KMConvertBaseWindowController.swift 35 KB

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