KMConvertBaseWindowController.swift 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995
  1. //
  2. // KMConvertBaseWindowController.swift
  3. // PDF Master
  4. //
  5. // Created by tangchao on 2022/12/5.
  6. //
  7. import PDFKit
  8. typealias KMConvertBaseWindowControllerItemClick = (Int) -> ()
  9. class KMConvertBaseWindowController: KMBaseWindowController {
  10. @IBOutlet weak var titleLabel: NSTextField!
  11. @IBOutlet weak var leftBox: NSBox!
  12. @IBOutlet weak var prePDFView: KMCustomPDFView?
  13. @IBOutlet weak var numberBox: NSView!
  14. @IBOutlet weak var numberTextField: NSTextField!
  15. @IBOutlet weak var perLabel: NSTextField!
  16. @IBOutlet weak var totalNumberLabel: NSTextField!
  17. @IBOutlet weak var backBox: NSBox!
  18. @IBOutlet weak var nextBox: NSBox!
  19. @IBOutlet weak var rightScrollView: NSScrollView!
  20. @IBOutlet weak var batchButton: NSButton!
  21. @IBOutlet weak var canelBox: NSBox!
  22. @IBOutlet weak var convertBox: NSBox!
  23. @IBOutlet weak var rightBoxHeightConst: NSLayoutConstraint!
  24. var canelButtonVC: KMDesignButton?
  25. var convertButtonVC: KMDesignButton?
  26. var backButtonVC: KMDesignButton?
  27. var nextButtonVC: KMDesignButton?
  28. var itemClick: KMConvertBaseWindowControllerItemClick?
  29. var documentModel: KMDocumentModel?
  30. var currentPageIndex: Int = 1
  31. var pageRange = KMPageRange.all
  32. var pageRangeString: String = ""
  33. var settingView: KMConvertSettingView?
  34. var subType: Int = 0
  35. var fileExtension: String {
  36. get {
  37. return ""
  38. }
  39. }
  40. var progressController: SKProgressController?
  41. private var convert: KMPDFConvert?
  42. var limit = true
  43. // 是否限制次数
  44. var limitCount = true
  45. var oriDocumentUrl: URL?
  46. var subscribeWaterMarkType: KMSubscribeWaterMarkType?
  47. deinit {
  48. KMPrint("KMConvertBaseWindowController 已释放")
  49. self.prePDFView?.removeFromSuperview()
  50. self.prePDFView = nil
  51. #if VERSION_DMG
  52. NotificationCenter.default.removeObserver(self)
  53. #endif
  54. }
  55. convenience init() {
  56. self.init(windowNibName: "KMConvertBaseWindowController")
  57. }
  58. override func awakeFromNib() {
  59. super.awakeFromNib()
  60. DispatchQueue.main.async {
  61. self.window?.makeFirstResponder(nil)
  62. }
  63. }
  64. override func windowDidLoad() {
  65. super.windowDidLoad()
  66. // if (self.convertCountIsReach()) {
  67. // Swift.debugPrint("转档次数已达到限制. count: \(self.getConvertCount())")
  68. // }
  69. // #if VERSION_DMG
  70. NotificationCenter.default.addObserver(self, selector: #selector(km_windowWillCloseNotifation), name: NSWindow.willCloseNotification, object: nil)
  71. // #endif
  72. if (self.documentModel != nil) {
  73. let document = CPDFDocument(url: self.documentModel!.documentURL)
  74. if (document!.isLocked) {
  75. document?.unlock(withPassword: self.documentModel!.password)
  76. }
  77. self.prePDFView?.document = document!
  78. let number: Int = Int((self.prePDFView?.document.pageCount)!)
  79. let string = "\(number)"
  80. totalNumberLabel.stringValue = string
  81. self.prePDFView?.go(toPageIndex: self.documentModel!.currentIndex, animated: false)
  82. }
  83. if (self.prePDFView?.documentView() != nil) {
  84. self.prePDFView?.documentView().enclosingScrollView?.hasVerticalScroller = false
  85. self.prePDFView?.documentView().enclosingScrollView?.hasHorizontalScroller = false
  86. }
  87. if let pageCount = self.prePDFView?.document.pageCount {
  88. self.settingView?.pageCount = Int(pageCount)
  89. }
  90. batchButton.title = NSLocalizedString("Batch", comment: "")
  91. batchButton.isBordered = false
  92. batchButton.wantsLayer = true
  93. batchButton.layer?.borderWidth = 1
  94. batchButton.layer?.cornerRadius = 4
  95. batchButton.target = self
  96. batchButton.action = #selector(batchButtonAction)
  97. batchButton.isHidden = true
  98. self.updateBackAndNextButtonState()
  99. }
  100. override func initSubViews() {
  101. super.initSubViews()
  102. let view = self.initSettingView()
  103. // view?.frame = self.rightScrollView.bounds
  104. // view?.autoresizingMask = [.width, .height]
  105. self.settingView = view
  106. self.rightScrollView.documentView = view
  107. self.rightScrollView.verticalScrollElasticity = .none
  108. self.rightScrollView.horizontalScrollElasticity = .none
  109. view?.km_add_inset_constraint()
  110. view?.currentLanguage = self.getCurrentLanguage()
  111. view?.lanugageDidSelected = { [unowned self] value, _ in
  112. guard let index = value as? Int else {
  113. return
  114. }
  115. self.saveLanugageSelectedIndex(index: index)
  116. }
  117. view?.pageRangeDidChange = { [unowned self] pageRange in
  118. self.pageRange = pageRange
  119. if (pageRange != .custom) {
  120. self.updatePreView(pageRange: pageRange)
  121. }
  122. }
  123. view?.pageRangeDidInputFinishCallback = { [unowned self] string in
  124. self.pageRangeString = string
  125. let array = self.findSelectPage(pageRangeString: string)
  126. if array.count == 0 {
  127. let alert = NSAlert()
  128. alert.alertStyle = .warning
  129. alert.messageText = NSLocalizedString("Invalid page range or the page number is out of range. Please try again.", comment: "")
  130. alert.runModal()
  131. self.settingView?.pageRangeItemView?.pageSizeVC?.stringValue = ""
  132. } else {
  133. self.updatePreView(pageRange: .custom, pageString: string)
  134. }
  135. }
  136. view?.tipView?.itemClick = { [unowned self] _, _ in
  137. #if VERSION_DMG
  138. KMTools.openPurchaseProductWebsite()
  139. #else
  140. Task { @MainActor in
  141. if await (KMLightMemberManager.manager.canPayFunction() == false) {
  142. let _ = KMSubscribeWaterMarkWindowController.show(window: self.window!) { isSubscribeSuccess, isWaterMarkExport, isClose in
  143. if (isSubscribeSuccess) {
  144. self.refreshUI()
  145. }
  146. }
  147. }
  148. }
  149. #endif
  150. }
  151. self.settingView?.tipView?.isHidden = true
  152. Task { @MainActor in
  153. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  154. self.limitCount = true
  155. } else {
  156. self.limitCount = false
  157. }
  158. if await (KMLightMemberManager.manager.canPayFunction() == false) {
  159. #if VERSION_DMG
  160. if (self.limitCount) { // 未登录
  161. self.settingView?.tipView?.isHidden = true
  162. } else {
  163. self.settingView?.tipView?.isHidden = false
  164. }
  165. #else
  166. self.settingView?.tipView?.isHidden = false
  167. #endif
  168. } else {
  169. self.limit = false
  170. }
  171. }
  172. self.backButtonVC = KMDesignButton.init(withType: .Image)
  173. self.backBox.contentView = self.backButtonVC!.view
  174. self.nextButtonVC = KMDesignButton.init(withType: .Image)
  175. self.nextBox.contentView = self.nextButtonVC!.view
  176. self.canelButtonVC = KMDesignButton.init(withType: .Text)
  177. self.canelBox.contentView = self.canelButtonVC!.view
  178. self.convertButtonVC = KMDesignButton.init(withType: .Text)
  179. self.convertBox.contentView = self.convertButtonVC!.view
  180. }
  181. override func initDefaultValue() {
  182. super.initDefaultValue()
  183. self.totalNumberLabel.lineBreakMode = .byTruncatingTail
  184. self.prePDFView?.setDisplay(.singlePage)
  185. self.prePDFView?.layoutDocumentView()
  186. self.prePDFView?.autoScales = true
  187. self.prePDFView?.delegate = self
  188. self.backBox.fillColor = .clear
  189. self.backButtonVC?.target = self
  190. self.backButtonVC?.action = #selector(backButtonAction)
  191. self.backButtonVC?.image = NSImage(named: "KMImageNamePreviousPageImage")!
  192. self.backButtonVC?.image_disabled = NSImage(named: "KMImageNamePreviousPageImageDisable")!
  193. self.backButtonVC?.pagination()
  194. self.numberBox.wantsLayer = true
  195. self.numberBox.layer?.backgroundColor = NSColor.white.cgColor
  196. self.numberBox.layer?.borderWidth = 1
  197. self.numberBox.layer?.cornerRadius = 4
  198. self.numberTextField.focusRingType = .none
  199. self.numberTextField.delegate = self
  200. self.numberTextField.isBordered = false
  201. self.nextBox.fillColor = .clear
  202. self.nextButtonVC?.target = self
  203. self.nextButtonVC?.action = #selector(nextButtonAction)
  204. self.nextButtonVC?.image = NSImage(named: "KMImageNameNextPageImage")!
  205. self.nextButtonVC?.image_disabled = NSImage(named: "KMImageNameNextPageImageDisable")!
  206. self.nextButtonVC?.pagination()
  207. self.canelBox.fillColor = .clear
  208. self.canelButtonVC?.target = self
  209. self.canelButtonVC?.action = #selector(cancelButtonAction)
  210. self.canelButtonVC?.stringValue = NSLocalizedString("Cancel", comment: "")
  211. self.canelButtonVC?.button(type: .Sec, size: .m)
  212. self.canelButtonVC?.button.keyEquivalent = KMKeyEquivalent.esc.string()
  213. self.convertBox.fillColor = .clear
  214. self.convertButtonVC?.target = self
  215. self.convertButtonVC?.action = #selector(convertButtonAction)
  216. self.convertButtonVC?.stringValue = NSLocalizedString("Convert", comment: "")
  217. self.convertButtonVC?.button(type: .Cta, size: .m)
  218. // convertButtonVC.button.keyEquivalent = KMKeyEquivalent.enter
  219. self.rightScrollView.hasVerticalScroller = false
  220. self.rightScrollView.hasHorizontalScroller = false
  221. self.initUIProperty()
  222. }
  223. private func initUIProperty() {
  224. self.titleLabel.textColor = NSColor.titleColor()
  225. self.titleLabel.font = .SFProTextSemiboldFont(16)
  226. self.leftBox.fillColor = NSColor.km_init(hex: "#F7F8FA")
  227. self.prePDFView?.backgroundColor = NSColor.km_init(hex: "#F7F8FA")
  228. self.numberBox.layer?.borderColor = NSColor.km_init(hex: "#DFE1E5").cgColor
  229. self.perLabel.textColor = NSColor.titleColor()
  230. self.perLabel.font = .SFProTextRegularFont(12)
  231. self.totalNumberLabel.textColor = NSColor.titleColor()
  232. self.totalNumberLabel.font = .SFProTextRegularFont(12)
  233. self.batchButton.setTitleColor(NSColor.buttonTitleColor())
  234. self.batchButton.layer?.borderColor = NSColor.buttonBorderColor().cgColor
  235. self.batchButton.font = .SFProTextRegularFont(14)
  236. }
  237. func initSettingView() -> KMConvertSettingView? {
  238. let settingView = KMConvertSettingView.createFromNib()
  239. return settingView
  240. }
  241. public func initConvert() -> KMPDFConvert {
  242. return KMPDFConvert()
  243. }
  244. func setupContentHeight(height: CGFloat, animated: Bool = false) {
  245. if (animated) {
  246. self.rightBoxHeightConst.animator().constant = height
  247. } else {
  248. self.rightBoxHeightConst.constant = height
  249. }
  250. }
  251. func refreshUI() {
  252. }
  253. @objc func backButtonAction() {
  254. if let _ = self.prePDFView?.canGoToPreviousPage() {
  255. self.currentPageIndex -= 1
  256. self.prePDFView?.goToPreviousPage(nil)
  257. self.numberTextField.stringValue = "\(self.prePDFView!.currentPageIndex+1)"
  258. self.updateBackAndNextButtonState()
  259. }
  260. }
  261. @objc func nextButtonAction() {
  262. if let _ = self.prePDFView?.canGoToNextPage() {
  263. self.currentPageIndex += 1
  264. self.prePDFView?.goToNextPage(nil)
  265. self.numberTextField.stringValue = "\(self.prePDFView!.currentPageIndex+1)"
  266. self.updateBackAndNextButtonState()
  267. }
  268. }
  269. @objc func batchButtonAction() {
  270. guard let callback = itemClick else {
  271. return
  272. }
  273. callback(1)
  274. }
  275. @objc func cancelButtonAction() {
  276. self._clearData()
  277. guard let callback = itemClick else {
  278. return
  279. }
  280. callback(2)
  281. }
  282. @objc func convertButtonAction() {
  283. self.window?.makeFirstResponder(nil)
  284. if (self.pageRange == .custom) {
  285. let array = self.findSelectPage(pageRangeString: self.pageRangeString)
  286. if (array.count <= 0) {
  287. self.window?.makeFirstResponder(self.settingView?.pageRangeItemView?.pageSizeVC?.textField)
  288. return
  289. }
  290. }
  291. var pages: [Int] = []
  292. let filePath = self.getConvertFileSavePath()
  293. if (FileManager.default.fileExists(atPath: filePath)) {
  294. try?FileManager.default.removeItem(atPath: filePath)
  295. }
  296. if ((self.prePDFView?.document?.writeDecrypt(to: URL(fileURLWithPath: filePath)))!) {
  297. for i in 0 ..< self.prePDFView!.document.pageCount {
  298. pages.append(Int(i)+1)
  299. }
  300. }
  301. if (pages.count <= 0) {
  302. let alert = NSAlert()
  303. alert.alertStyle = .warning
  304. alert.messageText = NSLocalizedString("Invalid page range or the page number is out of range. Please try again.", comment: "")
  305. alert.runModal()
  306. return
  307. }
  308. Task { @MainActor in
  309. #if VERSION_DMG
  310. if (await (KMLightMemberManager.manager.canUseAdvanced() == false)) {
  311. let _ = KMComparativeTableViewController.show(window: self.window!, .convert)
  312. return
  313. }
  314. #endif
  315. if await (KMLightMemberManager.manager.canPayFunction() == false) {
  316. var isContinue = false
  317. if pages.count <= 10 {
  318. isContinue = true
  319. }
  320. var limit = self.convertCountIsReach()
  321. if (!self.limitCount) { // 登录
  322. limit = false
  323. }
  324. if (limit) {
  325. isContinue = false
  326. }
  327. let _ = KMSubscribeWaterMarkWindowController.show(window: self.window!, isContinue: isContinue, limit: limit, type: self.subscribeWaterMarkType!) { isSubscribeSuccess, isWaterMarkExport, isClose in
  328. if (isClose) {
  329. return
  330. }
  331. if (isSubscribeSuccess) {
  332. self._convertButtonAction()
  333. return
  334. }
  335. if (isWaterMarkExport && !limit) {
  336. self._convertButtonAction(limit: true)
  337. return
  338. }
  339. }
  340. return
  341. }
  342. self._convertButtonAction()
  343. }
  344. }
  345. func convertModelAppendParams(convert: KMPDFConvert) -> () {
  346. if let isAllowOCR = self.settingView?.ocrEnabled {
  347. convert.isAllowOCR = isAllowOCR
  348. if let idx = self.settingView?.ocrItemView?.languageIndex {
  349. convert.ocrLanguage = KMPDFConvertManager.defaultManager.languages_asc[idx]
  350. }
  351. } else {
  352. convert.isAllowOCR = false
  353. }
  354. }
  355. func getConvertFileSavePath() -> String {
  356. var path = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.applicationSupportDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).last
  357. path?.append("/")
  358. path?.append(Bundle.main.bundleIdentifier!)
  359. if (FileManager.default.fileExists(atPath: path!) == false) {
  360. try?FileManager.default.createDirectory(atPath: path!, withIntermediateDirectories: false)
  361. }
  362. path?.append("/")
  363. path?.append("convert.pdf")
  364. return path!
  365. }
  366. func isValidPagesString(pagesString: String)-> Bool {
  367. var valid = false
  368. for ch in pagesString {
  369. if ch != "0" && ch != "1" && ch != "2" && ch != "3" && ch != "4" && ch != "5" && ch != "6" && ch != "7" && ch != "8" && ch != "9" && ch != "," && ch != "-" {
  370. valid = false
  371. break
  372. } else {
  373. valid = true
  374. }
  375. }
  376. return valid
  377. }
  378. func findSelectPage(pageRangeString: String) -> ([Int]) {
  379. if !isValidPagesString(pagesString: pageRangeString) {
  380. return []
  381. }
  382. var result: [Int] = []
  383. let array = pageRangeString.components(separatedBy: ",")
  384. for string in array {
  385. if string.isEmpty {
  386. return []
  387. } else {
  388. let pages = string .components(separatedBy: "-")
  389. if pages.count > 2 {
  390. return []
  391. } else if pages.count == 1 {
  392. let page = pages[0]
  393. if page.isEmpty || Int(page)! > self.documentModel!.pageCount || Int(page)! == 0 {
  394. return []
  395. } else {
  396. var hasSame: Bool = false
  397. for i in result {
  398. if i == Int(page)! {
  399. hasSame = true
  400. return []
  401. }
  402. }
  403. if !hasSame {
  404. result.append(Int(page)!)
  405. }
  406. }
  407. } else if pages.count == 2 {
  408. let page1 = pages[0]
  409. let page2 = pages[1]
  410. if page1.isEmpty || page2.isEmpty || Int(page1)! >= Int(page2)! || Int(page2)! > self.documentModel!.pageCount || Int(page1)! == 0 {
  411. return []
  412. } else {
  413. var hasSame: Bool = false
  414. for i in Int(page1)! ... Int(page2)! {
  415. for j in result {
  416. if j == i {
  417. hasSame = true
  418. return []
  419. }
  420. }
  421. }
  422. if !hasSame {
  423. for i in Int(page1)! ... Int(page2)! {
  424. result.append(i)
  425. }
  426. }
  427. }
  428. }
  429. }
  430. }
  431. return result
  432. }
  433. // MARK: -
  434. // MARK: Private Methods
  435. private func updateBackAndNextButtonState() {
  436. var nextEnabled = false
  437. if let result = self.prePDFView?.canGoToNextPage() {
  438. nextEnabled = result
  439. }
  440. var backEnabled = false
  441. if let result = self.prePDFView?.canGoToPreviousPage() {
  442. backEnabled = result
  443. }
  444. if (Thread.isMainThread) {
  445. self.backButtonVC?.state = backEnabled ? .Norm : .Disabled
  446. self.nextButtonVC?.state = nextEnabled ? .Norm : .Disabled
  447. } else {
  448. DispatchQueue.main.async {
  449. self.backButtonVC?.state = backEnabled ? .Norm : .Disabled
  450. self.nextButtonVC?.state = nextEnabled ? .Norm : .Disabled
  451. }
  452. }
  453. }
  454. internal func updatePreView(pageRange: KMPageRange, pageString: String = "") {
  455. let pages = self.getPages(pageRange, pageString: pageString)
  456. if (pages == nil || pages!.isEmpty) {
  457. let alert = NSAlert()
  458. alert.alertStyle = .warning
  459. alert.messageText = NSLocalizedString("Invalid page range or the page number is out of range. Please try again.", comment: "")
  460. alert.runModal()
  461. return
  462. }
  463. var indexs = IndexSet()
  464. for i in 0 ..< self.prePDFView!.document.pageCount {
  465. indexs.insert(IndexSet.Element(i))
  466. }
  467. self.prePDFView?.document.removePage(at: indexs)
  468. #if DEBUG
  469. let pageIndexs = self.getPageIndexs(pageRange, pageString: pageString)
  470. if (pageIndexs != nil) {
  471. for i in pageIndexs! {
  472. KMPrint(i)
  473. }
  474. }
  475. #endif
  476. // self.prePDFView.document?.importPages(pageIndexs!, from: self.documentModel.document, at: 0)
  477. for page in pages! {
  478. self.prePDFView?.document.insertPageObject(page, at: self.prePDFView!.document.pageCount)
  479. }
  480. DispatchQueue.main.async {
  481. self.prePDFView?.layoutDocumentView()
  482. self.prePDFView?.setNeedsDisplayForVisiblePages()
  483. self.prePDFView?.goToFirstPage(nil)
  484. let number: Int = Int(self.prePDFView!.document!.pageCount)
  485. self.totalNumberLabel.stringValue = "\(number)"
  486. self.currentPageIndex = 1
  487. self.numberTextField.stringValue = "1"
  488. self.updateBackAndNextButtonState()
  489. }
  490. }
  491. private func getPageIndexs(_ pageRange: KMPageRange, pageString: String = "") -> IndexSet? {
  492. guard let pageCount = self.documentModel?.pageCount, pageCount > 0 else {
  493. return nil
  494. }
  495. var indexs = IndexSet()
  496. if (pageRange == .all) {
  497. for i in 0 ..< pageCount {
  498. indexs.insert(i)
  499. }
  500. } else if (pageRange == .odd) {
  501. for i in 0 ..< pageCount {
  502. if ((i % 2) == 1) {
  503. continue
  504. }
  505. indexs.insert(i)
  506. }
  507. } else if (pageRange == .even) {
  508. for i in 0 ..< pageCount {
  509. if ((i % 2) == 0) {
  510. continue
  511. }
  512. indexs.insert(i)
  513. }
  514. } else if (pageRange == .current) {
  515. if (self.currentPageIndex >= 1 && self.currentPageIndex <= pageCount) {
  516. indexs.insert(self.currentPageIndex-1)
  517. }
  518. } else if (pageRange == .custom) {
  519. let array = self.findSelectPage(pageRangeString: pageString)
  520. if array.count == 0 {
  521. } else {
  522. for i in 0 ..< array.count {
  523. let index = array[i]
  524. if (index > pageCount || index < 1) {
  525. continue
  526. }
  527. indexs.insert(index-1)
  528. }
  529. }
  530. }
  531. return indexs
  532. }
  533. private func getPages(_ pageRange: KMPageRange, pageString: String = "") -> [CPDFPage]? {
  534. guard let pageCount = self.documentModel?.pageCount, pageCount > 0 else {
  535. return nil
  536. }
  537. var pages: [CPDFPage] = []
  538. if (pageRange == .all) {
  539. for i in 0 ..< pageCount {
  540. let page = self.documentModel!.document?.page(at: UInt(i))
  541. if (page == nil) {
  542. continue
  543. }
  544. pages.append(page!)
  545. }
  546. } else if (pageRange == .odd) {
  547. for i in 0 ..< pageCount {
  548. if ((i % 2) == 1) {
  549. continue
  550. }
  551. let page = self.documentModel!.document?.page(at: UInt(i))
  552. if (page == nil) {
  553. continue
  554. }
  555. pages.append(page!)
  556. }
  557. } else if (pageRange == .even) {
  558. for i in 0 ..< pageCount {
  559. if ((i % 2) == 0) {
  560. continue
  561. }
  562. let page = self.documentModel!.document?.page(at: UInt(i))
  563. if (page == nil) {
  564. continue
  565. }
  566. pages.append(page!)
  567. }
  568. } else if (pageRange == .current) {
  569. let page = self.prePDFView?.currentPage()
  570. if (page != nil) {
  571. pages.append(page!)
  572. }
  573. } else if (pageRange == .custom) {
  574. let array = self.findSelectPage(pageRangeString: pageString)
  575. if array.count == 0 {
  576. } else {
  577. for i in 0 ..< array.count {
  578. let index = array[i]
  579. if (index > pageCount || index < 1) {
  580. continue
  581. }
  582. let page = self.documentModel?.document?.page(at: UInt(index-1))
  583. if (page == nil) {
  584. continue
  585. }
  586. pages.append(page!)
  587. }
  588. }
  589. }
  590. return pages
  591. }
  592. private func _convertButtonAction(limit: Bool = false) {
  593. var pages: [Int] = []
  594. let filePath = self.getConvertFileSavePath()
  595. if (FileManager.default.fileExists(atPath: filePath)) {
  596. try?FileManager.default.removeItem(atPath: filePath)
  597. }
  598. if (limit) {
  599. if let _ = KMTools.saveWatermarkDocument(document: self.prePDFView!.document, to: URL(fileURLWithPath: filePath), removePWD: true) {
  600. for i in 0 ..< self.prePDFView!.document.pageCount {
  601. if (i >= 10) {
  602. break
  603. }
  604. pages.append(Int(i)+1)
  605. }
  606. }
  607. } else {
  608. if ((self.prePDFView?.document?.writeDecrypt(to: URL(fileURLWithPath: filePath)))!) {
  609. for i in 0 ..< self.prePDFView!.document.pageCount {
  610. pages.append(Int(i)+1)
  611. }
  612. }
  613. }
  614. if (pages.count <= 0) {
  615. let alert = NSAlert()
  616. alert.alertStyle = .warning
  617. alert.messageText = NSLocalizedString("Invalid page range or the page number is out of range. Please try again.", comment: "")
  618. alert.runModal()
  619. return
  620. }
  621. DispatchQueue.main.async {
  622. NSPanel.savePanel(self.window!) { panel in
  623. var url: URL = self.prePDFView!.document.documentURL
  624. if (self.oriDocumentUrl != nil) {
  625. url = self.oriDocumentUrl!
  626. }
  627. let name = url.deletingPathExtension().lastPathComponent
  628. panel.nameFieldStringValue = name
  629. panel.allowedFileTypes = [self.fileExtension]
  630. } completion: { response, url in
  631. if (response == .cancel) {
  632. return
  633. }
  634. let outputFolderPath = url!.deletingLastPathComponent().path
  635. let convert = self.initConvert()
  636. self.convert = convert
  637. convert.password = self.documentModel!.password
  638. convert.outputFolderPath = outputFolderPath
  639. convert.filePath = filePath
  640. convert.pages = pages
  641. var fileName = url!.deletingPathExtension().lastPathComponent
  642. if (self.fileExtension.isEmpty) {
  643. fileName = url!.lastPathComponent
  644. }
  645. // if (fileName.isEmpty) {
  646. // fileName = NSLocalizedString("Untitled", comment: "")
  647. // }
  648. convert.outputFileName = fileName
  649. self.convertModelAppendParams(convert: convert)
  650. DispatchQueue.main.async {
  651. self.showProgressWindow()
  652. self.progressController?.maxValue = Double(convert.pages.count)
  653. }
  654. #if VERSION_DMG
  655. if self.settingView?.ocrItemView?.checkVC?.state == .Checked {
  656. let bundlePath = kResourcePath?.stringByAppendingPathComponent("DocumentAI.bundle")
  657. CPDFConvertKit.setOCRModelPath(bundlePath)
  658. }
  659. #else
  660. let bundlePath = Bundle.main.path(forResource: "DocumentAI", ofType: "bundle")
  661. CPDFConvertKit.setOCRModelPath(bundlePath)
  662. #endif
  663. DispatchQueue.global().async {
  664. KMPDFConvertManager.defaultManager.convert(convert: convert, progress: { index in
  665. DispatchQueue.main.async {
  666. self.progressController?.increment(by: 1.0)
  667. }
  668. }) { [unowned self] finished, error in
  669. self.hiddenProgressWindow()
  670. // 清除临时文件
  671. if (FileManager.default.fileExists(atPath: filePath)) {
  672. try?FileManager.default.removeItem(atPath: filePath)
  673. }
  674. if finished {
  675. self._clearData()
  676. self.recordConvertCount()
  677. cancelButtonAction()
  678. if FileManager.default.fileExists(atPath: convert.outputFilePath) {
  679. NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: convert.outputFilePath)])
  680. }
  681. } else {
  682. var errorString = ""
  683. let myError: NSError? = error as? NSError
  684. if myError?.code == 1 {
  685. errorString = NSLocalizedString("Password required or incorrect password. Please re-enter your password and try again", comment: "")
  686. } else if myError?.code == 2 {
  687. errorString = NSLocalizedString("The license doesn't allow the permission", comment: "")
  688. } else if myError?.code == 3 {
  689. errorString = NSLocalizedString("Malloc failure", comment: "")
  690. } else if myError?.code == 4 {
  691. errorString = NSLocalizedString("Unknown error in processing conversion. Please try again later", comment: "")
  692. } else if myError?.code == 5 {
  693. errorString = NSLocalizedString("Unknown error in processing PDF. Please try again later", comment: "")
  694. } else if myError?.code == 6 {
  695. errorString = NSLocalizedString("File not found or could not be opened. Check if your file exists or choose another file to convert", comment: "")
  696. } else if myError?.code == 7 {
  697. errorString = NSLocalizedString("File not in PDF format or corruptead. Change a PDF file and try again", comment: "")
  698. } else if myError?.code == 8 {
  699. errorString = NSLocalizedString("Unsupported security scheme", comment: "")
  700. } else if myError?.code == 9 {
  701. errorString = NSLocalizedString("Page not found or content error", comment: "")
  702. } else {
  703. errorString = NSLocalizedString("Table not found", comment: "")
  704. }
  705. let alert = NSAlert()
  706. alert.alertStyle = .critical
  707. alert.messageText = NSLocalizedString("Conversion Failed", comment: "")
  708. alert.informativeText = errorString
  709. alert.addButton(withTitle: NSLocalizedString("OK", comment: ""))
  710. alert.runModal()
  711. }
  712. }
  713. }
  714. }
  715. }
  716. }
  717. // MARK: - Notifation Methods
  718. @objc private func km_windowWillCloseNotifation() {
  719. Task { @MainActor in
  720. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  721. self.limitCount = true
  722. } else {
  723. self.limitCount = false
  724. }
  725. if await (KMLightMemberManager.manager.canPayFunction() == false) {
  726. #if VERSION_DMG
  727. if (self.limitCount) { // 未登录
  728. self.settingView?.tipView?.isHidden = true
  729. } else {
  730. self.settingView?.tipView?.isHidden = false
  731. }
  732. #else
  733. self.settingView?.tipView?.isHidden = false
  734. #endif
  735. } else {
  736. self.limit = false
  737. }
  738. }
  739. }
  740. // MARK: Progress
  741. func showProgressWindow() {
  742. self.hiddenProgressWindow()
  743. let progress = SKProgressController()
  744. progress.window?.backgroundColor = NSColor.km_init(hex: "#36383B")
  745. progress.window?.contentView?.wantsLayer = true
  746. progress.window?.contentView?.layer?.backgroundColor = NSColor.km_init(hex: "#36383B").cgColor
  747. progress.progressField.textColor = NSColor.white
  748. progress.message = NSLocalizedString("Converting...", comment: "")
  749. progress.closeBlock = { [weak self] in
  750. if let convert = self?.convert {
  751. KMPDFConvertManager.defaultManager.cancel(convert: convert)
  752. }
  753. }
  754. self.progressController = progress
  755. self.window?.beginSheet(progress.window!)
  756. }
  757. func hiddenProgressWindow() {
  758. if (self.progressController != nil) {
  759. self.window?.endSheet((self.progressController?.window)!)
  760. self.progressController = nil
  761. }
  762. }
  763. func getCurrentLanguage() -> String {
  764. // return Bundle.main.preferredLocalizations.first!
  765. let array: [String] = UserDefaults.standard.object(forKey: "AppleLanguages") as! [String]
  766. return array.first!
  767. }
  768. /// 存储用户的选择的语言
  769. func saveLanugageSelectedIndex(index: Int) {
  770. UserDefaults.standard.setValue("\(index)", forKey: kKMConvertLanugageSelectedIndex)
  771. UserDefaults.standard.synchronize()
  772. }
  773. private func _clearData() {
  774. if let _ = self.oriDocumentUrl {
  775. if let data = self.prePDFView?.document.documentURL.path, FileManager.default.fileExists(atPath: data) {
  776. try?FileManager.default.removeItem(atPath: data)
  777. }
  778. }
  779. }
  780. }
  781. extension KMConvertBaseWindowController: NSTextFieldDelegate {
  782. func controlTextDidChange(_ obj: Notification) {
  783. if numberTextField.isEqual(to: obj.object) {
  784. let textField: NSTextField = obj.object as! NSTextField
  785. var value: String = ""
  786. for ch in textField.stringValue {
  787. if ch != "0" && ch != "1" && ch != "2" && ch != "3" && ch != "4" && ch != "5" && ch != "6" && ch != "7" && ch != "8" && ch != "9" {
  788. } else {
  789. if value.isEmpty && ch == "0" {
  790. } else {
  791. value.append(ch)
  792. }
  793. }
  794. }
  795. if value.isEmpty {
  796. value.append("1")
  797. } else {
  798. if Int(value)! <= 0 {
  799. value = "1"
  800. } else if Int(value)! > self.prePDFView!.document!.pageCount {
  801. let number: Int = Int(self.prePDFView!.document!.pageCount)
  802. value = "\(number)"
  803. }
  804. }
  805. numberTextField.stringValue = value
  806. }
  807. }
  808. func controlTextDidEndEditing(_ obj: Notification) {
  809. if numberTextField.isEqual(to: obj.object) {
  810. if (numberTextField.stringValue.isEmpty) {
  811. numberTextField.stringValue = "1"
  812. self.prePDFView?.go(toPageIndex: 0, animated: false)
  813. self.currentPageIndex = 1
  814. self.updateBackAndNextButtonState()
  815. return
  816. }
  817. let number: Int = Int(numberTextField.stringValue)!
  818. if number > 0 && number <= self.prePDFView!.document!.pageCount {
  819. guard let page = self.prePDFView?.document?.page(at: UInt(number-1)) else {
  820. return
  821. }
  822. self.prePDFView?.go(to: page)
  823. currentPageIndex = number
  824. self.updateBackAndNextButtonState()
  825. }
  826. }
  827. }
  828. }
  829. extension KMConvertBaseWindowController: CPDFViewDelegate {
  830. func pdfViewCurrentPageDidChanged(_ pdfView: CPDFView!) {
  831. let currentIndex = pdfView.currentPageIndex
  832. currentPageIndex = currentIndex + 1
  833. numberTextField.stringValue = "\(currentIndex+1)"
  834. self.updateBackAndNextButtonState()
  835. }
  836. }
  837. private let kKMConvertCountKey = "KMConvertCountKey"
  838. private let kKMConvertCountMax = 2
  839. extension KMConvertBaseWindowController {
  840. func convertCountIsReach() -> Bool {
  841. #if VERSION_DMG
  842. return false
  843. #else
  844. let cnt = self.getConvertCount()
  845. if (cnt >= kKMConvertCountMax) {
  846. return true
  847. }
  848. return false
  849. #endif
  850. }
  851. func recordConvertCount() {
  852. let cnt = self.getConvertCount()
  853. UserDefaults.standard.setValue(cnt+1, forKey: kKMConvertCountKey)
  854. UserDefaults.standard.synchronize()
  855. }
  856. func clearConvertRecordCount() {
  857. UserDefaults.standard.setValue(0, forKey: kKMConvertCountKey)
  858. UserDefaults.standard.synchronize()
  859. }
  860. private func getConvertCount() -> Int {
  861. return UserDefaults.standard.integer(forKey: kKMConvertCountKey)
  862. }
  863. }