KMConvertWindowController.swift 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073
  1. //
  2. // KMConvertWindowController.swift
  3. // PDF Reader Pro
  4. //
  5. // Created by liujiajie on 2023/11/8.
  6. //
  7. import Cocoa
  8. typealias convertBatchCallBack = () -> Void
  9. let kPreviewMaxWidth = 237.0
  10. let kPreviewMaxHeight = 325.0
  11. let kConvertFileSavePath = (kTempSavePath?.stringByAppendingPathComponent("convert.pdf"))
  12. @objcMembers class KMConvertWindowController: NSWindowController, NSTextFieldDelegate, NSWindowDelegate{
  13. @IBOutlet var prePDFViewHeight: NSLayoutConstraint!
  14. @IBOutlet var prePDFViewWidth: NSLayoutConstraint!
  15. var prePDFView: CPDFView!
  16. @IBOutlet var prePdfBGView: NSView!
  17. @IBOutlet var currentPageIndexTextField: NSTextField!
  18. @IBOutlet var totalPageCountLabel: NSTextField!
  19. @IBOutlet var formatLabel: NSTextField!
  20. @IBOutlet var formatSelectButton: NSPopUpButton!
  21. @IBOutlet var imageDPISelectButton: NSPopUpButton!
  22. @IBOutlet var moreButton: NSButton!
  23. @IBOutlet var buttonBottemOffset: NSLayoutConstraint!
  24. @IBOutlet var buttonTopOffset: NSLayoutConstraint!
  25. @IBOutlet var moreConvertBox: NSBox!
  26. @IBOutlet var moreConvertLabel: NSTextField!
  27. @IBOutlet var pageRangLabel: NSTextField!
  28. @IBOutlet var allPageButton: NSButton!
  29. @IBOutlet var currentPageButton: NSButton!
  30. @IBOutlet var oddPageButton: NSButton!
  31. @IBOutlet var evenPageButton: NSButton!
  32. @IBOutlet var handInputButton: NSButton!
  33. @IBOutlet var pageRangeTextField: NSTextField!
  34. @IBOutlet var convertButton: NSButton!
  35. @IBOutlet var cancelButton: NSButton!
  36. @IBOutlet var batchButton: NSButton!
  37. @IBOutlet var upgradeButton: NSButton!
  38. @IBOutlet var separateStypeTopOffset: NSLayoutConstraint!
  39. @IBOutlet var separateButton: NSButton!
  40. @IBOutlet var singleButton: NSButton!
  41. @IBOutlet var separateStypeBox: NSBox!
  42. @IBOutlet var extractTableButton: NSButton!
  43. @IBOutlet var extractTableTopOffset: NSLayoutConstraint!
  44. @IBOutlet var separateStypeLabel: NSTextField!
  45. @IBOutlet var excelStyleBox: NSBox!
  46. @IBOutlet var onlyTextBtn: NSButton!
  47. @IBOutlet var onlyTableBtn: NSButton!
  48. @IBOutlet var allContentBtn: NSButton!
  49. @IBOutlet var tableMenu1: NSMenuItem!
  50. @IBOutlet var tableMenu2: NSMenuItem!
  51. @IBOutlet var tableMenu3: NSMenuItem!
  52. @IBOutlet var allContentMenu2: NSMenuItem!
  53. @IBOutlet var allContentMenu3: NSMenuItem!
  54. @IBOutlet var tableMenu: NSPopUpButton!
  55. @IBOutlet var allContentMenu: NSPopUpButton!
  56. @IBOutlet var box: NSBox!
  57. var isAllInOneSheet = false
  58. var modalSession: NSApplication.ModalSession?
  59. var pdfDocument: CPDFDocument?
  60. var maskView: KMBookletMaskView?
  61. var convertType: KMConvertType = .Word
  62. var imageDPINumber: Int = 0
  63. var callBackBlock: convertBatchCallBack?
  64. var currentPage: CPDFPage?
  65. var savePath: String = ""
  66. var lockPassword: String = ""
  67. var tempPDFDocument: CPDFDocument?
  68. var excelContentOption: CPDFConvertExcelContentOptions?
  69. var excelWorksheetOption: CPDFConvertExcelWorksheetOptions?
  70. private var fileAttri_: KMFileAttribute?
  71. deinit {
  72. #if DEBUG
  73. NSLog("====KMConvertWindowController==deinit")
  74. #endif
  75. }
  76. convenience init(documemtV:CPDFDocument, currentPage:CPDFPage, convertT:KMConvertType, handle:@escaping convertBatchCallBack) {
  77. self.init(windowNibName: "KMConvertWindowController")
  78. if (documemtV.documentURL != nil) {
  79. let pageIndex = documemtV.index(for: currentPage)
  80. self.pdfDocument = CPDFDocument(url: documemtV.documentURL)
  81. let isLoc: Bool = self.pdfDocument!.isLocked
  82. if (!documemtV.isLocked && isLoc) {
  83. self.lockPassword = documemtV.password
  84. self.pdfDocument?.unlock(withPassword: self.lockPassword)
  85. }
  86. self.currentPage = self.pdfDocument?.page(at: pageIndex )
  87. } else {
  88. self.pdfDocument = documemtV
  89. self.currentPage = currentPage
  90. }
  91. self.callBackBlock = handle
  92. if convertT.rawValue > 15 || convertT.rawValue < 0 {
  93. self.convertType = .Word
  94. } else {
  95. self.convertType = convertT
  96. }
  97. }
  98. convenience init(localPath:String, handle:@escaping convertBatchCallBack) {
  99. self.init(windowNibName: "KMConvertWindowController")
  100. self.pdfDocument = CPDFDocument(url: URL(fileURLWithPath: localPath))
  101. self.callBackBlock = handle
  102. let isLoc: Bool = self.pdfDocument!.isLocked
  103. if (isLoc) {
  104. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.5) {
  105. let url = self.pdfDocument?.documentURL
  106. KMBaseWindowController.checkPassword(url: url!, type: .owner) { [weak self] success, resultPassword in
  107. if success {
  108. self?.lockPassword = resultPassword
  109. self?.pdfDocument?.unlock(withPassword: resultPassword)
  110. self?.currentPage = self?.pdfDocument?.page(at: 0)
  111. self?.convertType = .Word
  112. }
  113. }
  114. }
  115. }
  116. }
  117. override func windowDidLoad() {
  118. super.windowDidLoad()
  119. let preView: CPDFView = CPDFView(frame: self.prePdfBGView.bounds)
  120. self.prePdfBGView.addSubview(preView)
  121. self.prePDFView = preView
  122. self.box.fillColor = .gridColor
  123. localizedLanguage()
  124. self.currentPageIndexTextField.delegate = self;
  125. self.pageRangeTextField.delegate = self;
  126. let isLoc: Bool = self.pdfDocument!.isLocked
  127. if (isLoc) {
  128. self.showWaitting()
  129. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  130. let url = URL(fileURLWithPath: self.pdfDocument!.documentURL.path)
  131. KMBaseWindowController.checkPassword(url: url, type: .owner) { result, password in
  132. self.hideWaitting()
  133. if password.count > 0 {
  134. let unlockSuccess: Bool = ((self.pdfDocument?.unlock(withPassword: password)) != nil)
  135. self.lockPassword = password
  136. if unlockSuccess {
  137. self.currentPage = self.pdfDocument?.page(at: 0)
  138. }
  139. self.configuView()
  140. } else {
  141. self.buttonClicked_Cancel(self.cancelButton)
  142. }
  143. }
  144. }
  145. } else {
  146. self.configuView()
  147. }
  148. if #available(macOS 10.14, *) {
  149. let appearanceName = NSApp.effectiveAppearance.bestMatch(from: [.aqua, .darkAqua])
  150. if appearanceName == .darkAqua {
  151. moreConvertLabel.textColor = NSColor.white
  152. }
  153. }
  154. isAllInOneSheet = false
  155. separateButton.state = .on
  156. singleButton.state = .off
  157. allPageButton.state = .on
  158. allContentBtn.state = .on
  159. allContentMenu.isEnabled = true
  160. tableMenu.isEnabled = false
  161. excelContentOption = .allContent
  162. excelWorksheetOption = .forEachPage
  163. NotificationCenter.default.addObserver(self, selector: #selector(PDFViewDocumentChangedNotification(notification:)), name: NSNotification.Name.CPDFViewPageChanged, object: nil)
  164. }
  165. @objc func PDFViewDocumentChangedNotification(notification: NSNotification) {
  166. let pageIndex = self.prePDFView.currentPageIndex+1
  167. self.currentPageIndexTextField.stringValue = "\(pageIndex)"
  168. }
  169. func windowShouldClose(_ sender: NSWindow) -> Bool {
  170. self.dismissSheet()
  171. return true
  172. }
  173. func localizedLanguage() {
  174. formatLabel.stringValue = KMLocalizedString("Format:", nil)
  175. separateButton.title = KMLocalizedString("Convert each page to a separate worksheet", nil)
  176. singleButton.title = KMLocalizedString("Convert all pages to a single worksheet", nil)
  177. box.title = KMLocalizedString("Page Range:", nil)
  178. separateStypeLabel.stringValue = KMLocalizedString("Excel Worksheet Settings", nil)
  179. extractTableButton.title = KMLocalizedString("Extract Tables Only", nil)
  180. allPageButton.title = KMLocalizedString("All Pages", nil)
  181. currentPageButton.title = KMLocalizedString("Current Page", nil)
  182. oddPageButton.title = KMLocalizedString("Odd Pages Only", nil)
  183. evenPageButton.title = KMLocalizedString("Even Pages Only", nil)
  184. pageRangeTextField.placeholderString = KMLocalizedString("e.g. 1,3-5,10", nil)
  185. batchButton.title = KMLocalizedString("Batch", nil)
  186. cancelButton.title = KMLocalizedString("Cancel", nil)
  187. convertButton.title = KMLocalizedString("Convert", nil)
  188. upgradeButton.title = KMLocalizedString("Upgrade", nil)
  189. onlyTextBtn.title = KMLocalizedString("Only Text", nil)
  190. onlyTableBtn.title = KMLocalizedString("Only Table", nil)
  191. allContentBtn.title = KMLocalizedString("All Content", nil)
  192. tableMenu1.title = KMLocalizedString("Create Sheet for each Table", nil)
  193. tableMenu2.title = KMLocalizedString("Create Sheet for each Page", nil)
  194. allContentMenu2.title = KMLocalizedString("Create Sheet for each Page", nil)
  195. tableMenu3.title = KMLocalizedString("Create single Sheet for File", nil)
  196. allContentMenu3.title = KMLocalizedString("Create single Sheet for File", nil)
  197. }
  198. func hideWaitting() {
  199. maskView?.removeFromSuperview()
  200. }
  201. func showWaitting() {
  202. if maskView == nil {
  203. maskView = KMBookletMaskView(frame: CGRect(x: 0, y: 0, width: self.window?.frame.size.width ?? 0, height: self.window?.frame.size.height ?? 0))
  204. }
  205. self.window?.contentView?.addSubview(maskView!)
  206. }
  207. func configuView() {
  208. self.prePDFView.autoScales = true
  209. self.prePDFView.wantsLayer = true
  210. self.prePDFView.document = self.pdfDocument
  211. self.imageDPISelectButton.removeAllItems()
  212. self.formatSelectButton.removeAllItems()
  213. let dpiArray = ["50 dpi", "72 dpi", "96 dpi", "150 dpi", "300 dpi", "600 dpi"]
  214. let formArray = ["Excel (.xlsx)", "PowerPoint (.pptx)", "RTF (.rtf)", "CSV (.csv)", "Html (.html)", "Text (.txt)", "JPEG (.jpeg)", "JPG (.jpg)", "PNG (.png)", "GIF (.gif)", "TIFF (.tiff)", "TGA (.tga)", "BMP (.bmp)", "JPEG-2000 (.jp2)"]
  215. for (index, string) in formArray.enumerated() {
  216. let item = NSMenuItem()
  217. item.title = string
  218. item.target = self
  219. item.tag = index + 1
  220. self.formatSelectButton.menu?.addItem(item)
  221. }
  222. var isShowAdvanced = false
  223. let wordItem = NSMenuItem()
  224. wordItem.title = "Word (.docx)"
  225. wordItem.target = self
  226. var isShowUpgrade = false
  227. var convertSample: KMConvertType = .Word
  228. #if VERSION_FREE
  229. #if VERSION_DMG
  230. // 桌机版
  231. wordItem.tag = convertSample.rawValue
  232. isShowAdvanced = true
  233. if IAPProductsManager.default().isAvailableAllFunction() {
  234. if IAPProductsManager.default().isAvailableAdvancedPDFToOffice() {
  235. convertSample = .AdvancedWord
  236. wordItem.tag = convertSample.rawValue
  237. isShowAdvanced = false
  238. } else {
  239. isShowUpgrade = true
  240. }
  241. } else {
  242. isShowUpgrade = true
  243. }
  244. #else
  245. // 免费版
  246. convertSample = .Word
  247. wordItem.tag = convertSample.rawValue
  248. isShowAdvanced = true
  249. if IAPProductsManager.default().isAvailableAllFunction() {
  250. if IAPProductsManager.default().isAvailableAdvancedPDFToOffice() {
  251. convertSample = .AdvancedWord
  252. wordItem.tag = convertSample.rawValue
  253. isShowAdvanced = false
  254. } else {
  255. isShowUpgrade = true
  256. }
  257. } else {
  258. isShowUpgrade = true
  259. }
  260. #endif
  261. #else
  262. convertSample = .Word
  263. wordItem.tag = convertSample.rawValue
  264. // 付费版
  265. isShowAdvanced = true
  266. if IAPProductsManager.default().isAvailableAdvancedPDFToOffice() {
  267. isShowAdvanced = false
  268. convertSample = .AdvancedWord
  269. wordItem.tag = convertSample.rawValue
  270. } else {
  271. isShowUpgrade = true
  272. }
  273. #endif
  274. if wordItem.title != "" {
  275. if isShowAdvanced {
  276. let originStr = " \(KMLocalizedString("Standard", nil)) "
  277. let str = KMLocalizedString("Word (.docx)", nil)
  278. let attributedStr = NSMutableAttributedString(string: "\(str) \(originStr)")
  279. attributedStr.addAttribute(NSAttributedString.Key.backgroundColor, value: NSColor(red: 40/255.0, green: 193.0/255.0, blue: 107.0/255.0, alpha: 1.0), range: NSMakeRange(str.count + 2, originStr.count))
  280. attributedStr.addAttribute(NSAttributedString.Key.foregroundColor, value: NSColor.white, range: NSMakeRange(str.count + 2, originStr.count))
  281. let item = NSMenuItem()
  282. item.attributedTitle = attributedStr
  283. item.target = self
  284. item.tag = wordItem.tag
  285. self.formatSelectButton.menu?.insertItem(item, at: 0)
  286. } else {
  287. self.formatSelectButton.menu?.insertItem(wordItem, at: 0)
  288. }
  289. }
  290. if !isShowUpgrade {
  291. self.upgradeButton.isHidden = true
  292. }
  293. var selectIndex = 0
  294. if isShowAdvanced {
  295. let originStr = " \(NSLocalizedString("Advanced", comment: "")) "
  296. let str = NSLocalizedString("Word (.docx)", comment: "")
  297. let attributedStr = NSMutableAttributedString(string: "\(str) \(originStr)")
  298. attributedStr.addAttribute(NSAttributedString.Key.backgroundColor, value: NSColor(red: 245.0/255.0, green: 142.0/255.0, blue: 38.0/255.0, alpha: 1.0), range: NSMakeRange(str.count + 2, originStr.count))
  299. attributedStr.addAttribute(NSAttributedString.Key.foregroundColor, value: NSColor.white, range: NSMakeRange(str.count + 2, originStr.count))
  300. let item = NSMenuItem()
  301. item.attributedTitle = attributedStr
  302. item.target = self
  303. convertSample = .AdvancedWord
  304. item.tag = convertSample.rawValue
  305. self.formatSelectButton.menu?.insertItem(item, at: 0)
  306. }
  307. if self.convertType == .Word {
  308. selectIndex = 0
  309. } else {
  310. selectIndex = self.convertType.rawValue
  311. if isShowAdvanced {
  312. selectIndex += 1
  313. }
  314. if wordItem.title == "" {
  315. selectIndex -= 1
  316. }
  317. }
  318. self.formatSelectButton.selectItem(at: selectIndex)
  319. let item = self.formatSelectButton.selectedItem
  320. self.convertType = KMConvertType(rawValue: item?.tag ?? 0) ?? .Word
  321. self.imageDPISelectButton.isHidden = true
  322. self.buttonTopOffset.constant = -26
  323. self.imageDPISelectButton.addItems(withTitles: dpiArray)
  324. self.imageDPISelectButton.selectItem(at: 3)
  325. self.imageDPINumber = 150
  326. self.totalPageCountLabel.stringValue = " / \(self.pdfDocument?.pageCount ?? 1)"
  327. self.totalPageCountLabel.textColor = KMAppearance.Layout.h2Color()
  328. self.updataView()
  329. self.prePDFView.go(to: currentPage)
  330. let pageIndex = self.prePDFView.currentPageIndex+1
  331. self.currentPageIndexTextField.stringValue = "\(pageIndex)"
  332. if let documentURL = self.pdfDocument?.documentURL{
  333. self.pdfDocument = CPDFDocument(url: documentURL)
  334. if !lockPassword.isEmpty && lockPassword.count > 0{
  335. self.pdfDocument?.unlock(withPassword: lockPassword)
  336. }
  337. self.prePDFView.document = self.pdfDocument
  338. self.fileAttri_ = KMFileAttribute()
  339. self.fileAttri_?.filePath = documentURL.path
  340. }
  341. self.prePDFView.setDisplay(.singlePage)
  342. self.prePDFView.layoutDocumentView()
  343. }
  344. func updataView() {
  345. var moreLabelString: String = ""
  346. var offset: CGFloat = 0
  347. excelStyleBox.isHidden = true
  348. #if VERSION_FREE
  349. // 座机版
  350. if !IAPProductsManager.default().isAvailableAllFunction() {
  351. moreLabelString = String(format: "%@ %@", KMLocalizedString("The first 10 pages for free"), KMLocalizedString("Unlimited Convert"))
  352. } else {
  353. if !IAPProductsManager.default().isAvailableAdvancedPDFToOffice() {
  354. if .Word == self.convertType ||
  355. self.convertType == .AdvancedWord ||
  356. .Excel == self.convertType ||
  357. .PPT == self.convertType ||
  358. .CSV == self.convertType ||
  359. .RTF == self.convertType ||
  360. .GIF == self.convertType ||
  361. .TIFF == self.convertType ||
  362. .JP2 == self.convertType ||
  363. .BMP == self.convertType ||
  364. .TGA == self.convertType {
  365. moreLabelString = String(format: "%@ %@", KMLocalizedString("The first 10 pages for free"), KMLocalizedString("Unlimited Convert"))
  366. }
  367. }
  368. }
  369. #else
  370. // 付费版
  371. if !(IAPProductsManager.default().isAvailableAdvancedPDFToOffice()) {
  372. if .Word == self.convertType ||
  373. self.convertType == .AdvancedWord ||
  374. .Excel == self.convertType ||
  375. .PPT == self.convertType ||
  376. .CSV == self.convertType ||
  377. .RTF == self.convertType ||
  378. .GIF == self.convertType ||
  379. .TIFF == self.convertType ||
  380. .JP2 == self.convertType ||
  381. .BMP == self.convertType ||
  382. .TGA == self.convertType {
  383. moreLabelString = String(format: "%@ %@", KMLocalizedString("The first 10 pages for free"), KMLocalizedString("Unlimited Convert"))
  384. }
  385. }
  386. #endif
  387. if convertType.rawValue >= 7 && convertType.rawValue <= 14 {
  388. offset += imageDPISelectButton.frame.size.height
  389. imageDPISelectButton.isHidden = false
  390. buttonTopOffset.constant = 5
  391. } else {
  392. imageDPISelectButton.isHidden = true
  393. buttonTopOffset.constant = -26
  394. }
  395. if moreLabelString.count < 1 {
  396. offset += 5
  397. moreConvertBox.isHidden = true
  398. moreButton.isHidden = true
  399. } else {
  400. offset += (moreButton.frame.size.height + 5)
  401. moreConvertBox.isHidden = false
  402. moreButton.isHidden = false
  403. moreConvertLabel.stringValue = moreLabelString
  404. if let range = moreLabelString.range(of: NSLocalizedString("Unlimited Convert", comment: "")) {
  405. let newR: NSRange = moreLabelString.nsRange(from: range)!
  406. let attributedStr = NSMutableAttributedString(string: moreLabelString)
  407. attributedStr.addAttribute(.foregroundColor, value: NSColor.labelColor, range: NSRange(location: 0, length: newR.location - 1))
  408. attributedStr.addAttribute(.foregroundColor, value: NSColor(red: 8/255, green: 124/255, blue: 1, alpha: 1), range: newR)
  409. attributedStr.addAttribute(.underlineStyle, value: NSUnderlineStyle.single.rawValue, range: newR)
  410. moreConvertLabel.attributedStringValue = attributedStr
  411. }
  412. }
  413. if .Excel == convertType {
  414. separateStypeTopOffset.constant = separateStypeBox.frame.size.height + 58 + 16
  415. extractTableTopOffset.constant = separateStypeBox.frame.size.height + 50
  416. separateStypeBox.isHidden = true
  417. extractTableButton.isHidden = true
  418. excelStyleBox.isHidden = false
  419. separateStypeLabel.isHidden = false
  420. separateStypeLabel.stringValue = NSLocalizedString("Excel Worksheet Settings", comment: "")
  421. separateButton.title = NSLocalizedString("Convert each page to a separate worksheet", comment: "")
  422. singleButton.title = NSLocalizedString("Convert all pages to a single worksheet", comment: "")
  423. buttonClicked_extractTable(extractTableButton)
  424. } else if .AdvancedWord == convertType {
  425. singleButton.setTitleColor(NSColor.labelColor)
  426. separateButton.setTitleColor(NSColor.labelColor)
  427. separateStypeLabel.textColor = NSColor.labelColor
  428. separateButton.state = NSControl.StateValue.on
  429. singleButton.isEnabled = true
  430. separateButton.isEnabled = true
  431. isAllInOneSheet = false
  432. separateStypeTopOffset.constant = separateStypeBox.frame.size.height + 40
  433. extractTableButton.isHidden = true
  434. separateStypeBox.isHidden = false
  435. separateStypeLabel.isHidden = false
  436. separateStypeLabel.stringValue = NSLocalizedString("Layout Settings", comment: "")
  437. separateButton.title = NSLocalizedString("Retain Flowing Text", comment: "")
  438. singleButton.title = NSLocalizedString("Retain Page Layout", comment: "")
  439. } else if .CSV == convertType {
  440. separateStypeTopOffset.constant = extractTableButton.frame.size.height + 30
  441. extractTableTopOffset.constant = 12
  442. extractTableButton.isHidden = false
  443. separateStypeBox.isHidden = true
  444. separateStypeLabel.isHidden = true
  445. } else {
  446. separateStypeTopOffset.constant = 15
  447. separateStypeBox.isHidden = true
  448. extractTableButton.isHidden = true
  449. separateStypeLabel.isHidden = true
  450. }
  451. buttonBottemOffset.constant = offset
  452. }
  453. @IBAction func buttonClicked_extractTable(_ sender: NSButton) {
  454. if extractTableButton.state == .on {
  455. singleButton.setTitleColor(KMAppearance.Layout.b15_1Color())
  456. separateButton.setTitleColor(KMAppearance.Layout.b15_1Color())
  457. separateStypeLabel.textColor = KMAppearance.Layout.b15_1Color()
  458. singleButton.isEnabled = false
  459. separateButton.isEnabled = false
  460. separateButton.state = .off
  461. singleButton.state = .off
  462. } else {
  463. singleButton.setTitleColor(NSColor.labelColor)
  464. separateButton.setTitleColor(NSColor.labelColor)
  465. separateStypeLabel.textColor = NSColor.labelColor
  466. separateButton.state = .on
  467. singleButton.isEnabled = true
  468. separateButton.isEnabled = true
  469. isAllInOneSheet = false
  470. }
  471. }
  472. @IBAction func buttonClicked_Cancel(_ sender: NSButton) {
  473. dismissSheet()
  474. }
  475. func dismissSheet() {
  476. if FileManager.default.fileExists(atPath: kConvertFileSavePath ?? "") {
  477. do {
  478. try FileManager.default.removeItem(atPath: kConvertFileSavePath ?? "")
  479. } catch {
  480. print("Error removing item at path: (error.localizedDescription)")
  481. }
  482. }
  483. // if self.prePDFView.document != nil {
  484. // self.prePDFView.document = nil
  485. // }
  486. // if self.tempPDFDocument != nil {
  487. // self.tempPDFDocument = nil
  488. // }
  489. self.km_quick_endSheet()
  490. }
  491. func showCriticalAlert(_ alertMsg: String?) {
  492. let alert = NSAlert()
  493. alert.alertStyle = .critical
  494. if let msg = alertMsg {
  495. alert.informativeText = msg
  496. } else {
  497. let st = self.pdfDocument?.documentURL.lastPathComponent.count ?? 0 > 0 ? self.pdfDocument?.documentURL.lastPathComponent : KMLocalizedString("Untitled.pdf", nil)
  498. alert.messageText = String(format: "%@ %@", st!, KMLocalizedString("Invalid page range or the page number is out of range. Please try again.", nil))
  499. }
  500. alert.runModal()
  501. }
  502. func produceNewPDF(with pagesArray: [CPDFPage]) {
  503. tempPDFDocument = nil
  504. // if self.tempPDFDocument == nil || self.tempPDFDocument!.isLocked {
  505. self.tempPDFDocument = CPDFDocument()
  506. // }
  507. var indexs = IndexSet()
  508. let pageCount = self.pdfDocument?.pageCount ?? 0
  509. for addedPage in pagesArray {
  510. // tempPDFDocument?.insertPageObject(addedPage, at: tempPDFDocument!.pageCount)
  511. let idx = addedPage.pageIndex()
  512. if idx >= 0 && idx < pageCount {
  513. indexs.insert(IndexSet.Element(idx))
  514. }
  515. }
  516. // self.tempPDFDocument?.removePage(at: IndexSet(integersIn: 0..<(Int(self.tempPDFDocument?.pageCount ?? 0))))
  517. _ = self.tempPDFDocument?.importPages(indexs, from: self.pdfDocument, at: 0)
  518. self.prePDFView.document = self.tempPDFDocument
  519. self.prePDFView.layoutDocumentView()
  520. self.prePDFView.goToFirstPage(nil)
  521. self.currentPageIndexTextField.stringValue = "1"
  522. self.totalPageCountLabel.stringValue = " / \(self.tempPDFDocument!.pageCount)"
  523. }
  524. func pageRangeSetON(_ sender: NSButton) {
  525. allPageButton.state = .off
  526. oddPageButton.state = .off
  527. evenPageButton.state = .off
  528. handInputButton.state = .off
  529. currentPageButton.state = .off
  530. sender.state = .on
  531. if sender == handInputButton {
  532. pageRangeTextField.isEditable = true
  533. pageRangeTextField.isSelectable = true
  534. // self.pageRangeTextField.textColor = NSColor.textColor
  535. window?.makeFirstResponder(pageRangeTextField)
  536. } else {
  537. pageRangeTextField.isEditable = false
  538. pageRangeTextField.isSelectable = false
  539. // self.pageRangeTextField.textColor = NSColor.lightGrayColor
  540. window?.makeFirstResponder(self)
  541. }
  542. }
  543. @IBAction func buttonClicked_FormatSelect(_ sender: NSButton) {
  544. guard let item = self.formatSelectButton.selectedItem else { return }
  545. self.convertType = KMConvertType(rawValue: item.tag) ?? .Word
  546. updataView()
  547. }
  548. func transform(with string: String) {
  549. if string == KMLocalizedString("Create Sheet for each Table", nil) {
  550. self.excelWorksheetOption = .forEachTable
  551. } else if string == KMLocalizedString("Create Sheet for each Page", nil) {
  552. self.excelWorksheetOption = .forEachPage
  553. } else if string == KMLocalizedString("Create single Sheet for File", nil) {
  554. self.excelWorksheetOption = .forTheDocument
  555. }
  556. }
  557. @IBAction func buttonClicked_excelStyle(_ sender: NSButton) {
  558. if sender.isEqual(self.onlyTextBtn) {
  559. self.tableMenu.isEnabled = false
  560. self.allContentMenu.isEnabled = false
  561. self.excelContentOption = .onlyText
  562. self.excelWorksheetOption = .forEachTable
  563. } else if (sender.isEqual(self.onlyTableBtn)) {
  564. self.tableMenu.isEnabled = true
  565. self.allContentMenu.isEnabled = false
  566. self.excelContentOption = .onlyTable
  567. transform(with: self.tableMenu.selectedItem?.title ?? "")
  568. } else if (sender.isEqual(self.allContentBtn)) {
  569. self.tableMenu.isEnabled = false
  570. self.allContentMenu.isEnabled = true
  571. self.excelContentOption = .allContent
  572. transform(with: self.allContentMenu.selectedItem?.title ?? "")
  573. }
  574. }
  575. @IBAction func buttonClicked_tableMenu(_ sender: NSButton) {
  576. transform(with: self.tableMenu.selectedItem?.title ?? "")
  577. }
  578. @IBAction func buttonClicked_allContentMenu(_ sender: NSButton) {
  579. transform(with: self.allContentMenu.selectedItem?.title ?? "")
  580. }
  581. @IBAction func buttonClicked_PageSelect(_ sender: NSButton) {
  582. pageRangeSetON(sender)
  583. self.lockPassword = ""
  584. let pagesArray = NSMutableArray()
  585. for i in 0..<(self.pdfDocument?.pageCount ?? 0) {
  586. let copyPage = self.pdfDocument?.page(at: i)
  587. pagesArray.add(copyPage!)
  588. }
  589. if sender.isEqual(self.oddPageButton) {
  590. pagesArray.subArray(type: .Odd)
  591. } else if (sender.isEqual(self.evenPageButton)) {
  592. pagesArray.subArray(type: .Even)
  593. } else if (sender.isEqual(self.currentPageButton)) {
  594. pagesArray.removeAllObjects()
  595. let page = self.prePDFView.currentPage()
  596. if (page != nil) {
  597. pagesArray.add(page as Any)
  598. }
  599. }
  600. produceNewPDF(with: pagesArray as! [CPDFPage])
  601. // perform(#selector(produceNewPDF(with:)), with: pagesArray, afterDelay: 2)
  602. // performSelector(produceNewPDF(with:), withObject: pagesArray, afterDelay: 2)
  603. }
  604. @IBAction func buttonClicked_DpiSelect(_ sender: NSPopUpButton) {
  605. let index = sender.indexOfSelectedItem
  606. var dpi = 0
  607. if index == 0 {
  608. dpi = 50
  609. } else if index == 1 {
  610. dpi = 72
  611. } else if index == 2 {
  612. dpi = 96
  613. } else if index == 3 {
  614. dpi = 150
  615. } else if index == 4 {
  616. dpi = 300
  617. } else if index == 5 {
  618. dpi = 600
  619. }
  620. self.imageDPINumber = dpi
  621. }
  622. @IBAction func buttonClick_PreviousPage(_ sender: NSButton) {
  623. if self.prePDFView.canGoToPreviousPage() {
  624. self.prePDFView.goToPreviousPage(nil)
  625. let currentIndex = self.prePDFView.document?.index(for: self.prePDFView.currentPage()) ?? 0
  626. self.currentPageIndexTextField.stringValue = "\(currentIndex + 1)"
  627. }
  628. }
  629. @IBAction func buttonClicked_NextPage(_ sender: NSButton) {
  630. if self.prePDFView.canGoToNextPage() {
  631. self.prePDFView.goToNextPage(nil)
  632. let currentIndex = self.prePDFView.document?.index(for: self.prePDFView.currentPage())
  633. self.currentPageIndexTextField.stringValue = "\((currentIndex ?? 0) + 1)"
  634. }
  635. }
  636. @IBAction func buttonClicked_Batch(_ sender: NSButton) {
  637. if !IAPProductsManager.default().isAvailableAllFunction() {
  638. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  639. return
  640. }
  641. if self.pdfDocument?.documentURL == nil {
  642. NSSound.beep()
  643. return
  644. }
  645. if self.callBackBlock != nil {
  646. self.callBackBlock!()
  647. self.callBackBlock = nil
  648. }
  649. dismissSheet()
  650. }
  651. @IBAction func buttonClicked_Convert(_ sender: Any) {
  652. self.window?.makeFirstResponder(self.prePDFView)
  653. if self.handInputButton.state == .on {
  654. if self.fileAttri_ == nil {
  655. self.fileAttri_ = KMFileAttribute()
  656. self.fileAttri_?.filePath = self.pdfDocument?.documentURL.path ?? ""
  657. }
  658. // fileAttri_.pdfDocument = self.pdfDocument
  659. self.fileAttri_?.bAllPage = false
  660. self.fileAttri_?.pagesType = .custom
  661. self.fileAttri_?.pagesString = self.pageRangeTextField.stringValue
  662. let pages = self.fileAttri_?.fetchSelectPages() ?? []
  663. if pages.isEmpty {
  664. return
  665. }
  666. }
  667. let openPanel = NSOpenPanel()
  668. openPanel.canChooseFiles = false
  669. openPanel.canChooseDirectories = true
  670. openPanel.canCreateDirectories = true
  671. openPanel.beginSheetModal(for: self.window!) { result in
  672. if result == .OK {
  673. self.savePath = openPanel.url!.path
  674. self.beginConvert()
  675. }
  676. }
  677. }
  678. func beginConvert() {
  679. var isLimitConvert = false
  680. #if VERSION_FREE
  681. #if VERSION_DMG
  682. // 桌机版
  683. if IAPProductsManager.default().isAvailableAllFunction() {
  684. if IAPProductsManager.default().isAvailableAdvancedPDFToOffice() {
  685. isLimitConvert = false
  686. } else {
  687. if (.PNG == self.convertType ||
  688. .JPEG == self.convertType ||
  689. .JPG == self.convertType ||
  690. .HTML == self.convertType ||
  691. .Text == self.convertType ||
  692. .Word == self.convertType) {
  693. isLimitConvert = false
  694. } else {
  695. isLimitConvert = true
  696. }
  697. }
  698. } else {
  699. isLimitConvert = true
  700. }
  701. #else
  702. // 免费版
  703. if IAPProductsManager.default().isAvailableAdvancedPDFToOffice() == false {
  704. isLimitConvert = true
  705. }
  706. #endif
  707. #else
  708. // 付费版
  709. if IAPProductsManager.default().isAvailableAdvancedPDFToOffice() {
  710. isLimitConvert = false
  711. } else {
  712. if (.PNG == self.convertType ||
  713. .JPEG == self.convertType ||
  714. .JPG == self.convertType ||
  715. .HTML == self.convertType ||
  716. .Text == self.convertType ||
  717. .Word == self.convertType) {
  718. isLimitConvert = false
  719. } else {
  720. isLimitConvert = true
  721. }
  722. }
  723. #endif
  724. self.showWaitting()
  725. let pages = NSMutableArray()
  726. DispatchQueue.global(qos: .background).async { [self] in
  727. let filePath = getConvertFileSavePath()
  728. if (FileManager.default.fileExists(atPath: filePath)) {
  729. try?FileManager.default.removeItem(atPath: filePath)
  730. }
  731. if self.prePDFView.document.write(toFile: filePath) {
  732. for i in 0..<self.prePDFView.document.pageCount {
  733. pages.add(i + 1)
  734. }
  735. }
  736. DispatchQueue.main.async {
  737. if pages.count < 1 {
  738. self.hideWaitting()
  739. let alert = NSAlert()
  740. alert.alertStyle = .critical
  741. alert.messageText = "\(self.pdfDocument?.documentURL.path.lastPathComponent ?? NSLocalizedString("Untitled", comment: "")) \(NSLocalizedString("Invalid page range or the page number is out of range. Please try again.", comment: ""))"
  742. alert.runModal()
  743. return
  744. }
  745. let pageCount = pages.count
  746. var selectPages = [Int]()
  747. if isLimitConvert {
  748. if pageCount >= 10 {
  749. for i in 0..<10 {
  750. selectPages.append(pages[i] as! Int)
  751. }
  752. } else {
  753. selectPages = pages as! [Int]
  754. }
  755. } else {
  756. selectPages = pages as! [Int]
  757. }
  758. let convert = KMPDFConvert()
  759. convert.filePath = filePath
  760. convert.pages = selectPages
  761. convert.isAllInOneSheet = self.isAllInOneSheet
  762. if self.convertType == .Word {
  763. convert.type = 0
  764. } else {
  765. convert.type = 1
  766. }
  767. convert.isExtractTable = self.extractTableButton.state == .on
  768. convert.outputFolderPath = self.savePath
  769. convert.outputFileName = (self.pdfDocument?.documentURL.deletingPathExtension().lastPathComponent) ?? NSLocalizedString("Untitled", comment: "")
  770. if self.convertType == .AdvancedWord {
  771. convert.convertType = .word
  772. } else if self.convertType == .JPEG ||
  773. self.convertType == .JPG ||
  774. self.convertType == .PNG ||
  775. self.convertType == .GIF ||
  776. self.convertType == .TIFF ||
  777. self.convertType == .TGA ||
  778. self.convertType == .BMP ||
  779. self.convertType == .JP2 {
  780. convert.convertType = KMPDFConvertType(rawValue: self.convertType.rawValue) ?? .word
  781. convert.options = [KMPDFConvertOptionsKeyImageDPI : self.imageDPINumber,
  782. KMPDFConvertOptionsKeyImageWithAnnotation : true] as [String : Any]
  783. } else {
  784. convert.convertType = KMPDFConvertType(rawValue: self.convertType.rawValue) ?? .word
  785. }
  786. if self.convertType == .Excel {
  787. convert.excelContentOption = self.excelContentOption
  788. convert.excelWorksheetOption = self.excelWorksheetOption
  789. }
  790. convert.password = self.lockPassword
  791. KMPDFConvertManager.defaultManager.convert(convert: convert) { [weak self] (finished, error) in
  792. self?.hideWaitting()
  793. if finished {
  794. self?.dismissSheet()
  795. if FileManager.default.fileExists(atPath: convert.outputFilePath) {
  796. let workspace = NSWorkspace.shared
  797. let url = URL(fileURLWithPath: convert.outputFilePath)
  798. workspace.activateFileViewerSelecting([url])
  799. }
  800. } else if let error = error {
  801. let err: NSError = error as NSError
  802. var erroeString = ""
  803. switch err.code {
  804. case CPDFConverterEncryptError:
  805. erroeString = NSLocalizedString("Password required or incorrect password. Please re-enter your password and try again", comment: "")
  806. break
  807. case CPDFConverterPermissionError:
  808. erroeString = NSLocalizedString("The license doesn't allow the permission", comment: "")
  809. break
  810. case CPDFConverterMallocError:
  811. erroeString = NSLocalizedString("Malloc failure", comment: "")
  812. break
  813. case CPDFConverterUnknownError:
  814. erroeString = NSLocalizedString("Unknown error in processing conversion. Please try again later", comment: "")
  815. break
  816. case CPDFConverterPDFUnknownError:
  817. erroeString = NSLocalizedString("Unknown error in processing PDF. Please try again later", comment: "")
  818. break
  819. case CPDFConverterPDFFileError:
  820. erroeString = NSLocalizedString("File not found or could not be opened. Check if your file exists or choose another file to convert", comment: "")
  821. break
  822. case CPDFConverterPDFFormatError:
  823. erroeString = NSLocalizedString("File not in PDF format or corruptead. Change a PDF file and try again", comment: "")
  824. break
  825. case CPDFConverterPDFSecurityError:
  826. erroeString = NSLocalizedString("Unsupported security scheme", comment: "")
  827. break
  828. case CPDFConverterPDFPageError:
  829. erroeString = NSLocalizedString("Page not found or content error", comment: "")
  830. break
  831. default:
  832. erroeString = NSLocalizedString("Table not found", comment: "")
  833. break
  834. }
  835. let alert = NSAlert()
  836. alert.alertStyle = .critical
  837. alert.messageText = NSLocalizedString("Conversion Failed", comment: "")
  838. alert.informativeText = erroeString
  839. alert.addButton(withTitle: NSLocalizedString("OK", comment: ""))
  840. if #available(OSX 10.14, *) {
  841. alert.beginSheetModal(for: self?.window! ?? NSWindow.currentWindow(), completionHandler: nil)
  842. } else {
  843. alert.runModal()
  844. }
  845. }
  846. }
  847. }
  848. }
  849. }
  850. func getConvertFileSavePath() -> String {
  851. var path = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.applicationSupportDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).last
  852. path?.append("/")
  853. path?.append(Bundle.main.bundleIdentifier!)
  854. if (FileManager.default.fileExists(atPath: path!) == false) {
  855. try?FileManager.default.createDirectory(atPath: path!, withIntermediateDirectories: false)
  856. }
  857. path?.append("/")
  858. path?.append("convert.pdf")
  859. return path!
  860. }
  861. @IBAction func buttonClicked_MoreConvert(_ sender: NSButton) {
  862. if sender == self.moreButton {
  863. FMTrackEventManager.defaultManager.trackEvent(event: "PUW", withProperties: ["PUW_Btn": "Btn_PUW_Converter_Premium_UnlimitedConvertw"])
  864. } else if sender == self.upgradeButton {
  865. FMTrackEventManager.defaultManager.trackEvent(event: "PUW", withProperties: ["PUW_Btn": "Btn_PUW_Converter_Premium_Upgrade"])
  866. }
  867. #if VERSION_DMG
  868. if IAPProductsManager.default().isAvailableAllFunction() && !IAPProductsManager.default().isAvailableAdvancedPDFToOffice() {
  869. let limitWC = KMPurchaseLimitWindowController.currentLimitWC()
  870. limitWC.continueBlock = { windowController in
  871. }
  872. limitWC.window?.center()
  873. limitWC.showWindow(nil)
  874. } else {
  875. let winC = KMPurchaseCompareWindowController.sharedInstance()
  876. if convertType == .Word || convertType == .AdvancedWord {
  877. winC?.kEventName = "Reading_PDFtoWord_BuyNow"
  878. } else if convertType == .Excel {
  879. winC?.kEventName = "Reading_PDFtoExcel_BuyNow"
  880. } else if convertType == .PPT {
  881. winC?.kEventName = "Reading_PDFtoPPT_BuyNow"
  882. } else if convertType == .RTF {
  883. winC?.kEventName = "Reading_PDFtoRTF_BuyNow"
  884. } else if convertType == .CSV {
  885. winC?.kEventName = "Reading_PDFtoCSV_BuyNow"
  886. } else if convertType == .Text {
  887. winC?.kEventName = "Reading_PDFtoText_BuyNow"
  888. }
  889. if convertType == .JPEG || convertType == .JPG || convertType == .PNG || convertType == .GIF || convertType == .TIFF || convertType == .TGA || convertType == .BMP || convertType == .JP2 {
  890. winC?.kEventName = "Reading_PDFtoImage_BuyNow"
  891. }
  892. // else if convertType == . {
  893. // winC?.kEventName = "Reading_PDFtoExcel_BuyNow"
  894. // }
  895. winC?.showWindow(nil)
  896. }
  897. #else
  898. if IAPProductsManager.default().isAvailableAllFunction() {
  899. var vc: KMToolCompareWindowController? = nil
  900. if convertType == .Word || convertType == .AdvancedWord {
  901. // vc = KMToolCompareWindowController(toolType: .Convert, selectNum: 1)
  902. vc = KMToolCompareWindowController.toolCompare(toolType: .Convert, selectNum: 1)
  903. } else if convertType == .Excel {
  904. // vc = KMToolCompareWindowController(toolType: .Convert, selectNum: 2)
  905. vc = KMToolCompareWindowController.toolCompare(toolType: .Convert, selectNum: 2)
  906. } else if convertType == .PPT {
  907. // vc = KMToolCompareWindowController(toolType: .Convert, selectNum: 3)
  908. vc = KMToolCompareWindowController.toolCompare(toolType: .Convert, selectNum: 3)
  909. } else if convertType.rawValue < 15 && convertType.rawValue > 7 {
  910. // vc = KMToolCompareWindowController(toolType: .Convert, selectNum: 4)
  911. vc = KMToolCompareWindowController.toolCompare(toolType: .Convert, selectNum: 4)
  912. } else {
  913. // vc = KMToolCompareWindowController(toolType: .Convert, selectNum: 0)
  914. vc = KMToolCompareWindowController.toolCompare(toolType: .Convert, selectNum: 0)
  915. }
  916. vc?.showWindow(nil)
  917. } else {
  918. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  919. }
  920. #endif
  921. self.buttonClicked_Cancel(self.cancelButton)
  922. }
  923. @IBAction func buttonItemClick_SepSingle(_ sender: Any) {
  924. if .on == self.singleButton.state {
  925. self.isAllInOneSheet = true
  926. } else {
  927. self.isAllInOneSheet = false
  928. }
  929. }
  930. func controlTextDidEndEditing(_ obj: Notification) {
  931. let object = obj.object
  932. if (object as AnyObject).isEqual(self.currentPageIndexTextField) == true {
  933. let num: Int = Int(self.currentPageIndexTextField.stringValue) ?? 1
  934. let targetPage = self.prePDFView.document.page(at: UInt(num - 1))
  935. self.prePDFView.go(to: targetPage)
  936. } else if (object as AnyObject).isEqual(self.pageRangeTextField) == true {
  937. guard self.handInputButton.state == .on else { return }
  938. if self.fileAttri_ == nil {
  939. self.fileAttri_ = KMFileAttribute()
  940. self.fileAttri_?.filePath = self.pdfDocument?.documentURL.path ?? ""
  941. }
  942. // fileAttribute.pdfDocument = self.pdfDocument
  943. self.fileAttri_?.bAllPage = false
  944. self.fileAttri_?.pagesType = .custom
  945. self.fileAttri_?.pagesString = self.pageRangeTextField.stringValue
  946. let pages = self.fileAttri_?.fetchSelectPages() ?? []
  947. if pages.count > 0 {
  948. let pagesArray = NSMutableArray()
  949. for pageNum in pages {
  950. let tpage = self.pdfDocument?.page(at: UInt(pageNum - 1))
  951. pagesArray.add(tpage as Any)
  952. }
  953. self.produceNewPDF(with: pagesArray as! [CPDFPage])
  954. } else {
  955. self.showCriticalAlert(nil)
  956. }
  957. }
  958. }
  959. func controlTextDidChange(_ obj: Notification) {
  960. if let textField = obj.object as? NSTextField {
  961. if textField.isEqual(self.currentPageIndexTextField) {
  962. if let stringValue = self.currentPageIndexTextField.formatter?.string(for: NSNumber(value: Float(self.currentPageIndexTextField.stringValue) ?? 0)) {
  963. if let integerValue = Int(stringValue) {
  964. var string = stringValue
  965. if integerValue > self.prePDFView.document.pageCount {
  966. string = "(self.prePDFView.document.pageCount)"
  967. } else if integerValue <= 0 {
  968. string = "1"
  969. }
  970. self.currentPageIndexTextField.stringValue = string
  971. }
  972. }
  973. }
  974. }
  975. }
  976. }
  977. @objc enum KMSubArrayType: Int {
  978. case Odd = 0
  979. case Even
  980. }
  981. extension NSMutableArray{
  982. func subArray(type: KMSubArrayType) {
  983. if self.count == 0 { return }
  984. if type.rawValue > 1 || type.rawValue < 0 { return }
  985. let newArray = NSMutableArray()
  986. for i in 0..<self.count {
  987. if i % 2 == type.rawValue {
  988. newArray.add(self[i])
  989. }
  990. }
  991. self.removeAllObjects()
  992. self.addObjects(from: newArray as! [Any])
  993. }
  994. }