KMConvertBaseWindowController.swift 29 KB

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