KMHomeViewController+Action.swift 63 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484
  1. //
  2. // KMHomeViewController+Action.swift
  3. // PDF Master
  4. //
  5. // Created by wanjun on 2022/10/13.
  6. //
  7. import Foundation
  8. extension KMHomeViewController: NSMenuItemValidation {
  9. func validateMenuItem(_ menuItem: NSMenuItem) -> Bool {
  10. if (menuItem.action == #selector(menuItemAction_currentWindowName)) {
  11. menuItem.title = NSLocalizedString("Home", comment: "")
  12. return true
  13. }
  14. if (menuItem.action == #selector(menuItemAction_showForwardTagPage) ||
  15. menuItem.action == #selector(menuItemAction_showNextTagPage)) {
  16. if (self.myDocument != nil && (self.myDocument is KMMainDocument)) {
  17. let browser = (self.myDocument as! KMMainDocument).browser
  18. if (menuItem.action == #selector(menuItemAction_showForwardTagPage)) {
  19. return (browser as! KMBrowser).canSelectPreviousTab()
  20. }
  21. if (menuItem.action == #selector(menuItemAction_showNextTagPage)) {
  22. return (browser as! KMBrowser).canSelectNextTab()
  23. }
  24. }
  25. }
  26. return true
  27. }
  28. }
  29. extension KMHomeViewController {
  30. // MARK: Action
  31. @objc func homeToolAction(_ sender: NSButton) -> Void {
  32. if sender == homeButtonVC.button {
  33. homeToolAction(homeToolState: KMHomeToolState.Home)
  34. } else if sender == pdfToolsButtonVC.button {
  35. homeToolAction(homeToolState: KMHomeToolState.PDFTools)
  36. } else if sender == cloudDocumentsButtonVC.button {
  37. homeToolAction(homeToolState: KMHomeToolState.CloudDocuments)
  38. } else if sender == openPDFButtonVC.button {
  39. homeToolAction(homeToolState: KMHomeToolState.OpenPDF)
  40. } else if sender == createPDFButtonVC.button {
  41. openSupportPDFButtonAction()
  42. } else if sender == createPDFImage.button {
  43. homeToolAction(homeToolState: KMHomeToolState.CreatePDF)
  44. }
  45. }
  46. func homeToolAction(homeToolState: KMHomeToolState) {
  47. switch homeToolState {
  48. case .OpenPDF:
  49. openPDFButtonAction()
  50. break
  51. case .CreatePDF:
  52. createPDFButtonAction()
  53. break
  54. case .Home:
  55. homeButtonAction()
  56. break
  57. case .PDFTools:
  58. pdfToolsButtonAction()
  59. break
  60. case .FavoriteDocuments:
  61. favoriteDocumentsButtonAction()
  62. break
  63. case .CloudDocuments:
  64. cloudDocumentsButtonAction()
  65. break
  66. default:
  67. print("error: 错误的传入枚举")
  68. break
  69. }
  70. }
  71. func fastToolItemAction(_ type: DataNavigationViewButtonActionType) {
  72. switch type {
  73. case .Batch:
  74. fastTool_Batch()
  75. break
  76. case .OCR:
  77. fastTool_OCR()
  78. break
  79. case .ConvertPDF:
  80. fastTool_ConvertPDF()
  81. break
  82. case .ImageToPDF:
  83. fastTool_ImageToPDF()
  84. break
  85. case .MergePDF:
  86. fastTool_MergePDF()
  87. break
  88. case .Compression:
  89. fastTool_Compression()
  90. break
  91. case .Security:
  92. fastTool_Security()
  93. break
  94. case .FileCompare:
  95. fastTool_FileCompare()
  96. break
  97. case .PDFToPPT:
  98. fastTool_PDFToPPT()
  99. break
  100. case .PDFToExcel:
  101. fastTool_PDFToExcel()
  102. break
  103. case .PDFToWord:
  104. fastTool_PDFToWord()
  105. break
  106. case .PDFToImage:
  107. fastTool_PDFToImage()
  108. break
  109. case .Watermark:
  110. fastTool_Watermark()
  111. break
  112. case .Background:
  113. fastTool_Background()
  114. break
  115. case .HeaderAndFooter:
  116. fastTool_HeaderAndFooter()
  117. break
  118. case .BatesCode:
  119. fastTool_BatesCode()
  120. break
  121. case .Print:
  122. fastTool_Print()
  123. break
  124. case .BatchRemove:
  125. fastTool_BatchRemove()
  126. break
  127. case .Insert:
  128. fastTool_Insert()
  129. break
  130. case .BreakUp:
  131. fastTool_BreakUp()
  132. break
  133. case .Extract:
  134. fastTool_Extract()
  135. break
  136. case .MarkCipher:
  137. fastTool_MarkCipher()
  138. break
  139. case .AutomaticFormRecognition:
  140. fastTool_AutomaticFormRecognition()
  141. break
  142. case .PageEdit:
  143. fastTool_PageEdit()
  144. break
  145. }
  146. }
  147. func openPDFButtonAction() {
  148. let openPanel = NSOpenPanel()
  149. openPanel.allowedFileTypes = ["pdf", "PDF"]
  150. openPanel.allowsMultipleSelection = true
  151. openPanel.beginSheetModal(for: self.view.window!) { result in
  152. if result == .OK {
  153. for url in openPanel.urls {
  154. if !url.path.isPDFValid() {
  155. let alert = NSAlert()
  156. alert.alertStyle = .critical
  157. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  158. alert.runModal()
  159. } else {
  160. NSDocumentController.shared.openDocument(withContentsOf: url, display: true) { document, documentWasAlreadyOpen, error in
  161. if error != nil {
  162. NSApp.presentError(error!)
  163. } else {
  164. }
  165. }
  166. }
  167. }
  168. }
  169. }
  170. }
  171. func openSupportPDFButtonAction() {
  172. let openPanel = NSOpenPanel()
  173. openPanel.allowedFileTypes = ["pdf", "PDF", "jpg", "cur", "bmp", "jpeg", "gif", "png", "tiff", "tif", "ico", "icns", "tga", "psd", "eps", "hdr", "jp2", "jpc", "pict", "sgi", "heic", "doc", "docx", "xls", "xlsx", "ppt", "pptx", "pptx"]
  174. openPanel.allowsMultipleSelection = true
  175. var window = self.view.window
  176. if (window == nil) {
  177. window = NSApp.mainWindow
  178. }
  179. openPanel.beginSheetModal(for: window!) { [self] result in
  180. if result == .OK {
  181. var imageUrl: [URL] = []
  182. for url in openPanel.urls {
  183. let type = url.pathExtension.lowercased()
  184. if (type == "pdf" || type == "PDF") {
  185. if !url.path.isPDFValid() {
  186. let alert = NSAlert()
  187. alert.alertStyle = .critical
  188. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  189. alert.runModal()
  190. } else {
  191. NSDocumentController.shared.openDocument(withContentsOf: url, display: true) { document, documentWasAlreadyOpen, error in
  192. if error != nil {
  193. NSApp.presentError(error!)
  194. return
  195. }
  196. }
  197. }
  198. } else if (type == "jpg") ||
  199. (type == "cur") ||
  200. (type == "bmp") ||
  201. (type == "jpeg") ||
  202. (type == "gif") ||
  203. (type == "png") ||
  204. (type == "tiff") ||
  205. (type == "tif") ||
  206. (type == "ico") ||
  207. (type == "icns") ||
  208. (type == "tga") ||
  209. (type == "psd") ||
  210. (type == "eps") ||
  211. (type == "hdr") ||
  212. (type == "jp2") ||
  213. (type == "jpc") ||
  214. (type == "pict") ||
  215. (type == "sgi") ||
  216. (type == "heic") {
  217. openImageFile(url: url)
  218. } else if (type == "doc") ||
  219. (type == "docx") ||
  220. (type == "xls") ||
  221. (type == "xlsx") ||
  222. (type == "ppt") ||
  223. (type == "pptx") ||
  224. (type == "pptx") {
  225. self.openOfficeFile(url: url)
  226. }
  227. }
  228. }
  229. }
  230. }
  231. func createPDFButtonAction() {
  232. let popViewDataArr = [NSLocalizedString("New Blank Page", comment: ""),
  233. // NSLocalizedString("New From Web Page", comment: ""),
  234. NSLocalizedString("Import From Scanner", comment: "")]
  235. createPopoverAction(popViewDataArr)
  236. }
  237. func homeButtonAction() {
  238. refreshRightBoxUI(.Home)
  239. }
  240. func pdfToolsButtonAction() {
  241. refreshRightBoxUI(.PDFTools)
  242. }
  243. func favoriteDocumentsButtonAction() {
  244. print("Favorite Documents")
  245. }
  246. func cloudDocumentsButtonAction() {
  247. refreshRightBoxUI(.CloudDocuments)
  248. }
  249. // 产品推广
  250. func productPromotionFoldOrUnfold(_ sender: NSButton) {
  251. var arr1: [NSString] = []
  252. var arr2: [NSString] = []
  253. if sender.isEqual(to: pdfSeriesButtonVC.button) {
  254. if self.pdfProSeriesBoxHeightConstraint.constant == 0 {
  255. arr1 = self.productPromotionPDFProSeries as! [NSString]
  256. }
  257. if self.othersBoxHeightConstraint.constant > 0 {
  258. arr2 = self.productPromotionOthers as! [NSString]
  259. }
  260. }
  261. if sender.isEqual(to: self.pdfOthersButtonVC.button) {
  262. if self.pdfProSeriesBoxHeightConstraint.constant > 0 {
  263. arr1 = self.productPromotionPDFProSeries as! [NSString]
  264. }
  265. if self.othersBoxHeightConstraint.constant == 0 {
  266. arr2 = self.productPromotionOthers as! [NSString]
  267. }
  268. }
  269. self.productPromotionShow(arr1 as NSArray, withOthers: arr2 as NSArray, isInitialize: false)
  270. refreshProductActiveSpacing()
  271. }
  272. func productPromotionClickAction(_ name: NSString) {
  273. var httpString: NSString = ""
  274. if name.isEqual(to: "Windows") {
  275. httpString = "https://www.pdfreaderpro.com/windows?utm_source=MacApp&utm_campaign=PDFProMac&utm_medium=pdfmac_promo"
  276. } else if name.isEqual(to: "iPhone / iPad") {
  277. #if VERSION_FREE
  278. #if VERSION_DMG
  279. httpString = "https://www.pdfreaderpro.com/product?utm_source=MacAppDmg&utm_campaign=ProductLinkLeftNav&utm_medium=PdfProduct"
  280. #else
  281. httpString = "https://www.pdfreaderpro.com/product?utm_source=MacAppLite&utm_campaign=ProductLinkLeftNav&utm_medium=PdfProduct"
  282. #endif
  283. #else
  284. httpString = "https://www.pdfreaderpro.com/product?utm_source=MacApp&utm_campaign=ProductLinkLeftNav&utm_medium=PdfProduct"
  285. #endif
  286. } else if name.isEqual(to: "Android") {
  287. httpString = "https://www.pdfreaderpro.com/pdfreaderpro-android?utm_source=MacAppDmg&utm_campaign=AndroidLink&utm_medium=PdfAndroid"
  288. } else if name.isEqual(to: "ComPDFKit") {
  289. httpString = "https://www.compdf.com?utm_source=macapp&utm_medium=pdfmac&utm_campaign=compdfkit-promp"
  290. } else if name.isEqual(to: "ComVideoKit") {
  291. httpString = "https://www.filmagepro.com/video-sdk?utm_source=macapp&utm_medium=pdfmac&utm_campaign=comvideosdk-promo"
  292. } else if name.isEqual(to: "SignFlow") {
  293. httpString = "https://apps.apple.com/app/apple-store/id1584624017?pt=118745145&ct=pdfmac-promo&mt=8"
  294. } else if name.isEqual(to: "FiImage Editor") {
  295. httpString = "https://apps.apple.com/app/apple-store/id1475051178?pt=118745145&ct=pdfmac-promo&mt=8"
  296. } else if name.isEqual(to: "FiImage Screen") {
  297. httpString = "https://apps.apple.com/app/apple-store/id1475049179?pt=118745145&ct=pdfmac-promo&mt=8"
  298. } else if name.isEqual(to: "Free PDF Templates") {
  299. httpString = "https://www.pdfreaderpro.com/templates?utm_source=MacApp&utm_campaign=PDFProMac&utm_medium=pdfmac_promo"
  300. }
  301. self.workSpaceOpenUrl(httpString)
  302. }
  303. func historyFile(deleteDocuments indexPaths: [URL]) {
  304. if UserDefaults.standard.bool(forKey: "kHistoryDeleteNOReminderKey") {
  305. historyFileDeleteAction(indexPaths)
  306. } else {
  307. let historyFileDeleteVC: KMHistoryFileDeleteWindowController = KMHistoryFileDeleteWindowController.init(windowNibName: NSNib.Name("KMHistoryFileDeleteWindowController"))
  308. historyFileDeleteVC.indexPaths = indexPaths
  309. self.currentWindowController = historyFileDeleteVC
  310. historyFileDeleteVC.deleteCallback = { [weak self](indexPaths: [URL], windowController: KMHistoryFileDeleteWindowController) -> Void in
  311. if self != nil {
  312. self?.currentWindowController = nil
  313. self!.historyFileDeleteAction(indexPaths)
  314. }
  315. }
  316. self.view.window?.beginSheet(historyFileDeleteVC.window!)
  317. }
  318. }
  319. func historyFileDeleteAction(_ indexPaths: [URL]) -> Void {
  320. // NSDocumentController.shared.clearRecentDocuments(nil)
  321. let urls: Array<URL> = NSDocumentController.shared.recentDocumentURLs
  322. NSDocumentController.shared.clearRecentDocuments(nil)
  323. DispatchQueue.main.asyncAfter(deadline: .now()) { [self] in
  324. for (_, url) in urls.enumerated() {
  325. if !indexPaths.contains(url) {
  326. NSDocumentController.shared.noteNewRecentDocumentURL(url)
  327. }
  328. }
  329. }
  330. historyFileViewController.reloadData()
  331. }
  332. func openHistoryFilePath(url: URL) -> Void {
  333. if !url.path.isPDFValid() {
  334. let alert = NSAlert()
  335. alert.alertStyle = .critical
  336. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  337. alert.beginSheetModal(for: view.window!) { [unowned self] result in
  338. self.historyFileViewController.reloadData()
  339. }
  340. return
  341. }
  342. if url.pathExtension.lowercased() == "pdf" {
  343. let pdfDoc = CPDFDocument.init(url: url)
  344. if pdfDoc != nil {
  345. let document = NSDocumentController.shared.document(for: url)
  346. var alreadyOpen = false
  347. for openDocument in NSDocumentController.shared.documents {
  348. if document == openDocument {
  349. alreadyOpen = true
  350. }
  351. }
  352. if !alreadyOpen {
  353. KMMainDocument().tryToUnlockDocument(pdfDoc!)
  354. if ((pdfDoc?.isLocked)! == true) {
  355. KMPasswordInputWindow.openWindow(window: self.view.window!, url: url) { result, password in
  356. if result == .cancel { /// 关闭
  357. return
  358. }
  359. /// 解密成功
  360. var selectDocument: KMMainDocument? = nil
  361. if ((document?.isKind(of: KMMainDocument.self)) != nil) {
  362. selectDocument = (document as! KMMainDocument)
  363. }
  364. if selectDocument != nil {
  365. let currentIndex = selectDocument?.browser.tabStripModel.index(of: selectDocument)
  366. selectDocument?.browser.tabStripModel.selectTabContents(at: Int32(currentIndex!), userGesture: true)
  367. if (selectDocument?.browser.window.isVisible)! as Bool {
  368. selectDocument?.browser.window.orderFront(nil)
  369. } else if (selectDocument?.browser.window.isMiniaturized)! as Bool {
  370. selectDocument?.browser.window.orderFront(nil)
  371. }
  372. } else {
  373. NSDocumentController.shared.openDocument(withContentsOf: url, display: true) { document, documentWasAlreadyOpen, error in
  374. if error != nil {
  375. NSApp.presentError(error!)
  376. return
  377. }
  378. // (document as! KMMainDocument).mainViewController.listView.document.unlock(withPassword: password)
  379. (document as! KMMainDocument).mainViewController?.password = password
  380. }
  381. }
  382. }
  383. return
  384. } else {
  385. var selectDocument: KMMainDocument? = nil
  386. if ((document?.isKind(of: KMMainDocument.self)) != nil) {
  387. selectDocument = (document as! KMMainDocument)
  388. }
  389. if selectDocument != nil {
  390. let currentIndex = selectDocument?.browser.tabStripModel.index(of: selectDocument)
  391. selectDocument?.browser.tabStripModel.selectTabContents(at: Int32(currentIndex!), userGesture: true)
  392. if (selectDocument?.browser.window.isVisible)! as Bool {
  393. selectDocument?.browser.window.orderFront(nil)
  394. } else if (selectDocument?.browser.window.isMiniaturized)! as Bool {
  395. selectDocument?.browser.window.orderFront(nil)
  396. }
  397. } else {
  398. NSDocumentController.shared.openDocument(withContentsOf: url, display: true) { document, documentWasAlreadyOpen, error in
  399. if error != nil {
  400. NSApp.presentError(error!)
  401. return
  402. }
  403. }
  404. }
  405. }
  406. } else {
  407. var selectDocument: KMMainDocument? = nil
  408. if ((document?.isKind(of: KMMainDocument.self)) != nil) {
  409. selectDocument = (document as! KMMainDocument)
  410. }
  411. if selectDocument != nil {
  412. if selectDocument?.browser != nil {
  413. let currentIndex = selectDocument?.browser.tabStripModel.index(of: selectDocument)
  414. selectDocument?.browser.tabStripModel.selectTabContents(at: Int32(currentIndex!), userGesture: true)
  415. if (selectDocument?.browser.window.isVisible)! as Bool {
  416. selectDocument?.browser.window.orderFront(nil)
  417. } else if (selectDocument?.browser.window.isMiniaturized)! as Bool {
  418. selectDocument?.browser.window.orderFront(nil)
  419. }
  420. }
  421. } else {
  422. NSDocumentController.shared.openDocument(withContentsOf: url, display: true) { document, documentWasAlreadyOpen, error in
  423. if error != nil {
  424. NSApp.presentError(error!)
  425. return
  426. }
  427. }
  428. }
  429. }
  430. } else {
  431. let alert = NSAlert()
  432. alert.alertStyle = .critical
  433. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  434. alert.beginSheetModal(for: view.window!) { [unowned self] result in
  435. self.historyFileViewController.reloadData()
  436. }
  437. }
  438. } else {
  439. NSWorkspace.shared.open(url)
  440. }
  441. }
  442. func openFile(withFilePath path: URL) -> Void {
  443. let type = path.pathExtension.lowercased()
  444. if (type == "pdf") {
  445. if !path.path.isPDFValid() {
  446. let alert = NSAlert()
  447. alert.alertStyle = .critical
  448. alert.messageText = NSLocalizedString("This file format is not supported, please drag in PDF, picture, Office format files", comment: "")
  449. alert.runModal()
  450. return
  451. }
  452. NSDocumentController.shared.openDocument(withContentsOf: path, display: true) { document, documentWasAlreadyOpen, error in
  453. if error != nil {
  454. NSApp.presentError(error!)
  455. return
  456. }
  457. }
  458. } else if (type == "jpg") ||
  459. (type == "cur") ||
  460. (type == "bmp") ||
  461. (type == "jpeg") ||
  462. (type == "gif") ||
  463. (type == "png") ||
  464. (type == "tiff") ||
  465. (type == "tif") ||
  466. (type == "ico") ||
  467. (type == "icns") ||
  468. (type == "tga") ||
  469. (type == "psd") ||
  470. (type == "eps") ||
  471. (type == "hdr") ||
  472. (type == "jp2") ||
  473. (type == "jpc") ||
  474. (type == "pict") ||
  475. (type == "sgi") ||
  476. (type == "heic") {
  477. openImageFile(url: path)
  478. } else if (type == "doc") ||
  479. (type == "docx") ||
  480. (type == "xls") ||
  481. (type == "xlsx") ||
  482. (type == "ppt") ||
  483. (type == "pptx") ||
  484. (type == "pptx") {
  485. let fileName: NSString = String(format: "%@.pdf", NSLocalizedString("Untitled", comment: "")) as NSString
  486. let savePath = fetchUniquePath(fileName.kUrlToPDFFolderPath())
  487. openOfficeFile(url: path)
  488. }
  489. }
  490. func openImageFile(url: URL) -> Void {
  491. let filePath = url.path
  492. let fileName: NSString = url.lastPathComponent as NSString
  493. let savePath = fetchUniquePath(fileName.kUrlToPDFFolderPath()).deletingLastPathComponent
  494. let imageName = NSString(string: NSString(string: filePath).lastPathComponent).deletingPathExtension
  495. let path = self.fetchDifferentFilePath(filePath: savePath + "/" + imageName + ".pdf")
  496. let document = CPDFDocument.init()
  497. var success = false
  498. //FIXME: 无法插入图片
  499. let image = NSImage(contentsOfFile: filePath)
  500. let insertPageSuccess = document?.insertPage(image!.size, withImage: filePath, at: document!.pageCount)
  501. if insertPageSuccess != nil {
  502. //信号量控制异步
  503. let semaphore = DispatchSemaphore(value: 0)
  504. DispatchQueue.global().async {
  505. success = ((document?.write(toFile: path)) != nil)
  506. semaphore.signal()
  507. }
  508. semaphore.wait()
  509. } else {
  510. }
  511. if success {
  512. if !path.isPDFValid() {
  513. let alert = NSAlert()
  514. alert.alertStyle = .critical
  515. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  516. alert.runModal()
  517. return
  518. }
  519. NSDocumentController.shared.openDocument(withContentsOf: URL(fileURLWithPath: path), display: true) { document, documentWasAlreadyOpen, error in
  520. if error != nil {
  521. NSApp.presentError(error!)
  522. return
  523. }
  524. }
  525. }
  526. }
  527. func openOfficeFile(url: URL) -> Void {
  528. let filePath = url.path
  529. let folderPath = "convertToPDF.pdf"
  530. let savePath = folderPath.kUrlToPDFFolderPath()
  531. if savePath == nil {
  532. return
  533. }
  534. KMConvertPDFManagerOC.convertFile(filePath, savePath: savePath!) { success, errorDic in
  535. if errorDic != nil || !success || !FileManager.default.fileExists(atPath: savePath!) {
  536. if FileManager.default.fileExists(atPath: savePath!) {
  537. try?FileManager.default.removeItem(atPath: savePath!)
  538. }
  539. let alert = NSAlert.init()
  540. alert.alertStyle = .critical
  541. var infoString = ""
  542. if errorDic != nil {
  543. for key in (errorDic! as Dictionary).keys {
  544. infoString = infoString.appendingFormat("%@\n", errorDic![key] as! CVarArg)
  545. }
  546. }
  547. alert.informativeText = NSLocalizedString("Please install Microsoft Office to create PDFs from Office files", comment: "")
  548. alert.messageText = NSLocalizedString("Failed to Create PDF", comment: "")
  549. alert.addButton(withTitle: NSLocalizedString("OK", comment: ""))
  550. alert.runModal()
  551. return
  552. }
  553. if !savePath!.isPDFValid() {
  554. let alert = NSAlert()
  555. alert.alertStyle = .critical
  556. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  557. alert.runModal()
  558. return
  559. }
  560. NSDocumentController.shared.openDocument(withContentsOf: URL(fileURLWithPath: savePath!), display: true) { document, documentWasAlreadyOpen, error in
  561. if error != nil {
  562. NSApp.presentError(error!)
  563. return
  564. }
  565. }
  566. }
  567. }
  568. override func otherMouseDown(with event: NSEvent) {
  569. if historyFileViewController.selectFiles.count > 0 {
  570. let eventPoint = event.locationInWindow as NSPoint
  571. let x = eventPoint.x - 270.0
  572. if x >= 0 {
  573. let point = NSPoint(x: x, y: eventPoint.y)
  574. if historyFileViewController.historyFileCollectionView.frame.contains(point) ||
  575. historyFileViewController.historyFileTableView.frame.contains(point) ||
  576. historyFileViewController.deleteBox.frame.contains(point) ||
  577. historyFileViewController.listBox.frame.contains(point) ||
  578. historyFileViewController.thumbnailBox.frame.contains(point) {
  579. } else {
  580. self.historyFileViewController.selectFiles.removeAll()
  581. self.historyFileViewController.selectFiles_shift.removeAll()
  582. if self.historyFileViewController.showMode == .Thumbnail {
  583. self.historyFileViewController.historyFileCollectionView.reloadData()
  584. } else {
  585. self.historyFileViewController.historyFileTableView.reloadData()
  586. }
  587. }
  588. } else {
  589. self.historyFileViewController.selectFiles.removeAll()
  590. self.historyFileViewController.selectFiles_shift.removeAll()
  591. if self.historyFileViewController.showMode == .Thumbnail {
  592. self.historyFileViewController.historyFileCollectionView.reloadData()
  593. } else {
  594. self.historyFileViewController.historyFileTableView.reloadData()
  595. }
  596. }
  597. }
  598. }
  599. internal func showConvertWindow(type: KMPDFConvertType) {
  600. Task { @MainActor in
  601. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  602. let _ = KMComparativeTableViewController.show(window: self.view.window!)
  603. return
  604. }
  605. NSOpenPanel.km_secure_openPanel_success(window: self.view.window!) { url, password in
  606. var windowController: KMConvertBaseWindowController?
  607. if (type == .word) { /// Word
  608. windowController = KMConvertWordWindowController()
  609. } else if (type == .excel) {
  610. windowController = KMConvertExcelWindowController()
  611. } else if (type == .ppt || type == .rtf || type == .html || type == .text) {
  612. windowController = KMConvertPPTsWindowController()
  613. if (type == .ppt) {
  614. windowController?.subType = 1
  615. } else if (type == .rtf) {
  616. windowController?.subType = 2
  617. } else if (type == .html) {
  618. windowController?.subType = 3
  619. } else if (type == .text) {
  620. windowController?.subType = 4
  621. }
  622. } else if (type == .csv) {
  623. windowController = KMConvertCSVWindowController()
  624. } else if (type == .image) {
  625. windowController = KMConvertImageWindowController()
  626. }
  627. let model = KMDocumentModel(url: url)
  628. if (password != nil) {
  629. let _ = model.unlock(password!)
  630. }
  631. windowController?.documentModel = model
  632. windowController?.itemClick = { [weak self] index in
  633. if (self?.currentWindowController == nil) {
  634. return
  635. }
  636. self?.view.window?.endSheet((self?.currentWindowController?.window)!)
  637. self?.currentWindowController = nil
  638. }
  639. self.view.window?.beginSheet((windowController?.window)!)
  640. self.currentWindowController = windowController
  641. }
  642. }
  643. }
  644. // MARK: PDF Tools
  645. // 插入
  646. func insertPageAction(_ pdfDocument: CPDFDocument, _ password: String, _ pages: [CPDFPage], _ indexPage: Int) -> Void {
  647. if indexPage >= 0 {
  648. let insertPages: [CPDFPage] = pages
  649. for i in 0...insertPages.count-1 {
  650. let page = pages[i]
  651. // FIXME: 待底层库修改,使用 insertPageObject 插入,插入位置变为文档最后,暂用 insertPage 代替
  652. pdfDocument.insertPageObject(page, at: UInt(indexPage + i))
  653. }
  654. self.savePDFDocument(pdfDocument, password: password)
  655. }
  656. }
  657. func extractPageAction(_ pdfDocument: CPDFDocument, _ pages: [CPDFPage], _ oneDocumentPerPage: Bool, _ isDeletePage: Bool) -> Void {
  658. if pages.count < 1 {
  659. let alert = NSAlert()
  660. alert.alertStyle = .critical
  661. alert.messageText = NSLocalizedString("Please select two or more pages first to organize.", comment: "")
  662. alert.runModal()
  663. return
  664. }
  665. if !oneDocumentPerPage {
  666. let fileName = pdfDocument.getFileNameAccordingSelctPages(pages)
  667. let outputSavePanel = NSSavePanel()
  668. outputSavePanel.allowedFileTypes = ["pdf"]
  669. outputSavePanel.nameFieldStringValue = fileName
  670. outputSavePanel.beginSheetModal(for: self.view.window!) { result in
  671. if result == .OK {
  672. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  673. let saveFilePath = outputSavePanel.url?.path
  674. DispatchQueue.global().async {
  675. var pdf = CPDFDocument.init()
  676. let success = (pdf!.extractAsOneDocument(withPages: pages, savePath: saveFilePath)) as Bool
  677. DispatchQueue.main.async {
  678. if success {
  679. let workspace = NSWorkspace.shared
  680. let url = URL(fileURLWithPath: saveFilePath!)
  681. workspace.activateFileViewerSelecting([url])
  682. if isDeletePage {
  683. for page in pages {
  684. let indexPage = pdfDocument.index(for: page)
  685. pdfDocument.removePage(at: indexPage)
  686. }
  687. }
  688. }
  689. }
  690. }
  691. }
  692. }
  693. }
  694. } else {
  695. let panel = NSOpenPanel()
  696. panel.canChooseFiles = false
  697. panel.canChooseDirectories = true
  698. panel.canCreateDirectories = true
  699. panel.allowsMultipleSelection = false
  700. panel.beginSheetModal(for: self.view.window!) { result in
  701. if result == .OK {
  702. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  703. let outputURL = panel.url
  704. DispatchQueue.global().async {
  705. let folderName = String(pdfDocument.documentURL!.lastPathComponent.split(separator: ".")[0]) + "_extract"
  706. var filePath = URL(fileURLWithPath: outputURL!.path).appendingPathComponent(folderName).path
  707. var i = 1
  708. let testFilePath = filePath
  709. while FileManager.default.fileExists(atPath: filePath) {
  710. filePath = testFilePath + "\(i)"
  711. i += 1
  712. }
  713. try? FileManager.default.createDirectory(atPath: filePath, withIntermediateDirectories: false, attributes: nil)
  714. let successArray = pdfDocument.extractPerPageDocument(withPages: pages, folerPath: filePath)
  715. DispatchQueue.main.async {
  716. if successArray!.count > 0 {
  717. NSWorkspace.shared.activateFileViewerSelecting(successArray!)
  718. if !isDeletePage {
  719. for page in pages {
  720. let indexPage = pdfDocument.index(for: page)
  721. pdfDocument.removePage(at: indexPage)
  722. }
  723. }
  724. }
  725. }
  726. }
  727. }
  728. }
  729. }
  730. }
  731. }
  732. // MARK: 快捷工具 Action
  733. func fastToolDidSelectAllTools() {
  734. // 首页 快捷工具 Tools按钮
  735. refreshRightBoxUI(.PDFTools)
  736. }
  737. func fastTool_Batch() { // Batch
  738. // KMBatchWindowController.openFile(nil, .Batch)
  739. }
  740. func fastTool_OCR() { // OCR
  741. // KMOCRWindowController.openFiles(window: self.view.window!)
  742. }
  743. func fastTool_ConvertPDF() { // 转换PDF
  744. // KMBatchWindowController.openFile(nil, .ConvertPDF)
  745. }
  746. func fastTool_ImageToPDF() { // 图片转PDF
  747. print("选中 快捷工具 图片转PDF")
  748. KMImageToPDFWindowController.openFiles(window: NSApp.mainWindow!)
  749. }
  750. func fastTool_MergePDF() { // MergePDF
  751. Task { @MainActor in
  752. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  753. let _ = KMComparativeTableViewController.show(window: self.view.window!)
  754. return
  755. }
  756. let panel = NSOpenPanel()
  757. panel.allowedFileTypes = ["pdf"]
  758. panel.allowsMultipleSelection = true
  759. panel.beginSheetModal(for: self.view.window!) { response in
  760. if (response == .cancel) {
  761. return
  762. }
  763. DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
  764. var filepaths: Array<String> = []
  765. for url in panel.urls {
  766. filepaths.append(url.path)
  767. }
  768. let windowController = KMPDFEditAppendWindow(filePaths: filepaths)
  769. self.currentWindowController = windowController
  770. windowController?.beginSheetModal(for: self.view.window, completionHandler: { result, indexs in
  771. })
  772. }
  773. }
  774. }
  775. }
  776. func fastTool_Compression() { // 压缩
  777. Task { @MainActor in
  778. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  779. let _ = KMComparativeTableViewController.show(window: self.view.window!)
  780. return
  781. }
  782. NSOpenPanel.km_secure_openPanel(window: self.view.window!) { url, result, passowrd in
  783. if (url == nil) {
  784. return
  785. }
  786. if (result != nil && result! == .cancel) {
  787. return
  788. }
  789. self.showCompressWindow(url!, passowrd)
  790. }
  791. }
  792. }
  793. func showCompressWindow(_ url: URL, _ password: String?) {
  794. Task { @MainActor in
  795. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  796. let _ = KMComparativeTableViewController.show(window: self.view.window!)
  797. return
  798. }
  799. let windowController = KMCompressWindowController(windowNibName: "KMCompressWindowController")
  800. self.currentWindowController = windowController
  801. windowController.documentURL = url
  802. windowController.password = password
  803. windowController.itemClick = { [weak self] (index: Int) -> () in
  804. self!.view.window?.endSheet(self!.currentWindowController!.window!)
  805. self?.currentWindowController = nil
  806. }
  807. windowController.resultCallback = { [weak self] (result: Bool, openDocument: Bool, fileURL: URL, error: String) in
  808. if result {
  809. self!.view.window?.endSheet(self!.currentWindowController!.window!)
  810. self?.currentWindowController = nil
  811. if openDocument {
  812. if !fileURL.path.isPDFValid() {
  813. let alert = NSAlert()
  814. alert.alertStyle = .critical
  815. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  816. alert.runModal()
  817. return
  818. }
  819. NSDocumentController.shared.openDocument(withContentsOf: fileURL, display: true) { document, result, error in
  820. if error != nil {
  821. NSApp.presentError(error!)
  822. return
  823. }
  824. }
  825. } else {
  826. NSWorkspace.shared.activateFileViewerSelecting([fileURL])
  827. }
  828. } else {
  829. let alert = NSAlert()
  830. alert.messageText = NSLocalizedString("Compress Faild", comment: "")
  831. alert.runModal()
  832. }
  833. }
  834. await self.view.window?.beginSheet(windowController.window!)
  835. }
  836. }
  837. func fastTool_Security() { // 安全
  838. Task { @MainActor in
  839. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  840. let _ = KMComparativeTableViewController.show(window: self.view.window!)
  841. return
  842. }
  843. NSOpenPanel.km_secure_openPanel(window: self.view.window!, needOwner: true) { url, result, passowrd in
  844. if (url == nil) {
  845. return
  846. }
  847. if (result != nil && result! == .cancel) {
  848. return
  849. }
  850. let windowController = KMSecureEncryptWindowController(windowNibName: "KMSecureEncryptWindowController")
  851. windowController.documentURL = url!
  852. windowController.myDocument = CPDFDocument(url: url!)
  853. if (passowrd != nil) {
  854. windowController.myDocument.unlock(withPassword: passowrd)
  855. }
  856. self.currentWindowController = windowController
  857. let newDocument: CPDFDocument = CPDFDocument(url: url!)
  858. windowController.itemClick = { [weak self] (index: Int) -> () in
  859. self!.view.window?.endSheet((self?.currentWindowController?.window!)!)
  860. self?.currentWindowController = nil
  861. }
  862. windowController.resultCallback = { [weak self] (result: Bool) -> () in
  863. let windowController_secure: KMSecureEncryptWindowController = self?.currentWindowController as! KMSecureEncryptWindowController
  864. self!.view.window?.endSheet((self?.currentWindowController?.window!)!)
  865. self!.currentWindowController = nil
  866. if (passowrd != nil) {
  867. newDocument.unlock(withPassword: passowrd)
  868. }
  869. newDocument.setPasswordOptions(windowController_secure.options)
  870. let result = KMPasswordInputWindow.saveDocument(newDocument)
  871. if result {
  872. NSWorkspace.shared.activateFileViewerSelecting([newDocument.documentURL])
  873. } else {
  874. let alert = NSAlert()
  875. alert.messageText = NSLocalizedString("Failure", comment: "")
  876. alert.runModal()
  877. }
  878. }
  879. self.view.window?.beginSheet(windowController.window!)
  880. }
  881. }
  882. }
  883. func fastTool_FileCompare() { // 文件对比
  884. print("选中 快捷工具 文件对比")
  885. }
  886. func fastTool_PDFToPPT() { // PDF转PPT
  887. Task { @MainActor in
  888. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  889. let _ = KMComparativeTableViewController.show(window: self.view.window!)
  890. return
  891. }
  892. NSOpenPanel.km_secure_openPanel_success(window: self.view.window!) { url, password in
  893. let windowController = KMConvertPPTsWindowController(windowNibName: "KMConvertBaseWindowController")
  894. let model = KMDocumentModel(url: url)
  895. windowController.subType = 1
  896. if (password != nil) {
  897. let _ = model.unlock(password!)
  898. }
  899. windowController.documentModel = model
  900. windowController.itemClick = { [weak self] (index: Int) in
  901. if (self?.currentWindowController == nil) {
  902. return
  903. }
  904. self?.view.window?.endSheet((self?.currentWindowController?.window)!)
  905. self?.currentWindowController = nil
  906. }
  907. self.view.window?.beginSheet(windowController.window!)
  908. self.currentWindowController = windowController
  909. }
  910. }
  911. }
  912. func fastTool_PDFToExcel() { // PDF转Excel
  913. Task { @MainActor in
  914. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  915. let _ = KMComparativeTableViewController.show(window: self.view.window!)
  916. return
  917. }
  918. NSOpenPanel.km_secure_openPanel_success(window: self.view.window!) { url, password in
  919. let windowController = KMConvertExcelWindowController(windowNibName: "KMConvertBaseWindowController")
  920. let model = KMDocumentModel(url: url)
  921. if (password != nil) {
  922. let _ = model.unlock(password!)
  923. }
  924. windowController.documentModel = model
  925. windowController.itemClick = { [weak self] (index: Int) in
  926. if (self?.currentWindowController == nil) {
  927. return
  928. }
  929. self?.view.window?.endSheet((self?.currentWindowController?.window)!)
  930. self?.currentWindowController = nil
  931. }
  932. self.view.window?.beginSheet(windowController.window!)
  933. self.currentWindowController = windowController
  934. }
  935. }
  936. }
  937. func fastTool_PDFToWord() { // PDF转Word
  938. Task { @MainActor in
  939. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  940. let _ = KMComparativeTableViewController.show(window: self.view.window!)
  941. return
  942. }
  943. NSOpenPanel.km_secure_openPanel_success(window: self.view.window!) { url, password in
  944. let windowController = KMConvertWordWindowController(windowNibName: "KMConvertBaseWindowController")
  945. let model = KMDocumentModel(url: url)
  946. if (password != nil) {
  947. let _ = model.unlock(password!)
  948. }
  949. windowController.documentModel = model
  950. windowController.itemClick = { [weak self] (index: Int) in
  951. if (self?.currentWindowController == nil) {
  952. return
  953. }
  954. self?.view.window?.endSheet((self?.currentWindowController?.window)!)
  955. self?.currentWindowController = nil
  956. }
  957. self.view.window?.beginSheet(windowController.window!)
  958. self.currentWindowController = windowController
  959. }
  960. }
  961. }
  962. func fastTool_PDFToImage() { // PDF转图片
  963. Task { @MainActor in
  964. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  965. let _ = KMComparativeTableViewController.show(window: self.view.window!)
  966. return
  967. }
  968. NSOpenPanel.km_secure_openPanel_success(window: self.view.window!) { url, password in
  969. let windowController = KMConvertImageWindowController(windowNibName: "KMConvertBaseWindowController")
  970. let model = KMDocumentModel(url: url)
  971. if (password != nil) {
  972. let _ = model.unlock(password!)
  973. }
  974. windowController.documentModel = model
  975. windowController.itemClick = { [weak self] (index: Int) in
  976. if (self?.currentWindowController == nil) {
  977. return
  978. }
  979. self?.view.window?.endSheet((self?.currentWindowController?.window)!)
  980. self?.currentWindowController = nil
  981. }
  982. self.view.window?.beginSheet(windowController.window!)
  983. self.currentWindowController = windowController
  984. }
  985. }
  986. }
  987. func fastTool_Watermark() { // 水印
  988. KMBatchWindowController.openFile(nil, .Watermark)
  989. }
  990. func fastTool_Background() { // 背景
  991. KMBatchWindowController.openFile(nil, .Background)
  992. }
  993. func fastTool_HeaderAndFooter() { // 页眉页脚
  994. KMBatchWindowController.openFile(nil, .HeaderAndFooter)
  995. }
  996. func fastTool_BatesCode() { // 贝茨码
  997. KMBatchWindowController.openFile(nil, .BatesCode)
  998. }
  999. func fastTool_Print() { // 打印
  1000. KMPrintWindowController.openFiles(window: self.view.window!)
  1001. }
  1002. func fastTool_BatchRemove() { // 批量移除
  1003. KMBatchWindowController.openFile(nil, .BatchRemove)
  1004. }
  1005. func fastTool_Insert() { // 插入
  1006. let openPanel = NSOpenPanel()
  1007. openPanel.prompt = "插入"
  1008. openPanel.allowsMultipleSelection = false
  1009. openPanel.allowedFileTypes = ["pdf"]
  1010. openPanel.beginSheetModal(for: NSApp.mainWindow!) { result in
  1011. if result == .OK {
  1012. DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
  1013. let insertWindowController: KMPDFInsertPageWindow = KMPDFInsertPageWindow.init(documentPath: openPanel.url!, toolType: .Insert)
  1014. insertWindowController.beginSheetModal(for: self.view.window!) { pdfDocument, password, pages, indexPage in
  1015. self.insertPageAction(pdfDocument, password, pages, indexPage)
  1016. }
  1017. }
  1018. }
  1019. }
  1020. }
  1021. func fastTool_BreakUp() { // 拆分
  1022. let openPanel = NSOpenPanel()
  1023. openPanel.prompt = "提取"
  1024. openPanel.allowsMultipleSelection = false
  1025. openPanel.allowedFileTypes = ["pdf"]
  1026. openPanel.beginSheetModal(for: NSApp.mainWindow!) { result in
  1027. if result == .OK {
  1028. DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
  1029. let document = CPDFDocument(url: openPanel.url)
  1030. let model = KMPageEditSplitSettingModel()
  1031. model.documentURL = openPanel.url
  1032. model.fileName = model.documentURL.lastPathComponent
  1033. model.pathExtension = model.fileName.components(separatedBy: ".").last
  1034. let windowController = KMPageEditSplitWindowController(model)
  1035. windowController.hasPreView = true
  1036. self.view.window?.beginSheet(windowController.window!)
  1037. self.currentWindowController = windowController
  1038. windowController.itemClick = { [weak self] index, value in
  1039. if (index == 1) { /// 取消
  1040. self?.view.window?.endSheet((self?.currentWindowController!.window)!)
  1041. self?.currentWindowController = nil
  1042. return
  1043. }
  1044. /// 拆分
  1045. let windowController_split: KMPageEditSplitWindowController = self?.currentWindowController as! KMPageEditSplitWindowController
  1046. let outputModel: KMPageEditSplitSettingModel = windowController_split.model! as! KMPageEditSplitSettingModel
  1047. self?.view.window?.endSheet((self?.currentWindowController!.window)!)
  1048. self?.currentWindowController = nil
  1049. let panel = NSOpenPanel()
  1050. panel.canChooseFiles = false
  1051. panel.canChooseDirectories = true
  1052. panel.canCreateDirectories = true
  1053. panel.beginSheetModal(for: (self?.view.window)!) { response in
  1054. KMPageEditTools.split(document!, outputModel, panel.url!.path, outputModel.outputFileNameDeletePathExtension) { result, outputDocuments, error in
  1055. if (result) {
  1056. }
  1057. }
  1058. }
  1059. }
  1060. }
  1061. }
  1062. }
  1063. }
  1064. func fastTool_Extract() { // 提取
  1065. let openPanel = NSOpenPanel()
  1066. openPanel.prompt = "提取"
  1067. openPanel.allowsMultipleSelection = false
  1068. openPanel.allowedFileTypes = ["pdf"]
  1069. openPanel.beginSheetModal(for: NSApp.mainWindow!) { result in
  1070. if result == .OK {
  1071. DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
  1072. let insertWindowController: KMPDFInsertPageWindow = KMPDFInsertPageWindow.init(documentPath: openPanel.url!, toolType: .Extract)
  1073. insertWindowController.beginSheetExtractModal(for: self.view.window!) { pdfDocument, pages, oneDocumentPerPage, isDeletePage in
  1074. self.extractPageAction(pdfDocument, pages, oneDocumentPerPage, isDeletePage)
  1075. }
  1076. }
  1077. }
  1078. }
  1079. }
  1080. func fastTool_MarkCipher() { // 标记密文
  1081. let openPanel = NSOpenPanel()
  1082. openPanel.allowsMultipleSelection = false
  1083. openPanel.allowedFileTypes = ["pdf"]
  1084. openPanel.beginSheetModal(for: NSApp.mainWindow!) { result in
  1085. if result == .cancel {
  1086. return
  1087. }
  1088. if !openPanel.url!.path.isPDFValid() {
  1089. let alert = NSAlert()
  1090. alert.alertStyle = .critical
  1091. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  1092. alert.runModal()
  1093. return
  1094. }
  1095. DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
  1096. NSDocumentController.shared.openDocument(withContentsOf: openPanel.url!, display: true) { document, result, error in
  1097. if (error != nil) {
  1098. NSApp.presentError(error!)
  1099. return
  1100. }
  1101. let toolbar = (document as! KMMainDocument).mainViewController?.toolbarController
  1102. toolbar?.enterRedact()
  1103. }
  1104. }
  1105. }
  1106. }
  1107. func fastTool_AutomaticFormRecognition() { // 表单自动识别
  1108. let openPanel = NSOpenPanel()
  1109. openPanel.prompt = "表单自动识别"
  1110. openPanel.allowsMultipleSelection = false
  1111. openPanel.allowedFileTypes = ["pdf"]
  1112. openPanel.beginSheetModal(for: NSApp.mainWindow!) { result in
  1113. if result == .OK {
  1114. }
  1115. }
  1116. }
  1117. func fastTool_PageEdit() { // 页面编辑
  1118. let openPanel = NSOpenPanel()
  1119. openPanel.allowsMultipleSelection = false
  1120. openPanel.allowedFileTypes = ["pdf"]
  1121. openPanel.beginSheetModal(for: NSApp.mainWindow!) { result in
  1122. if result == .cancel {
  1123. return
  1124. }
  1125. if !openPanel.url!.path.isPDFValid() {
  1126. let alert = NSAlert()
  1127. alert.alertStyle = .critical
  1128. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  1129. alert.runModal()
  1130. return
  1131. }
  1132. DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
  1133. NSDocumentController.shared.openDocument(withContentsOf: openPanel.url!, display: true) { document, result, error in
  1134. if (error != nil) {
  1135. NSApp.presentError(error!)
  1136. return
  1137. }
  1138. let mainView = (document as! KMMainDocument).mainViewController
  1139. mainView?.enterPageEdit()
  1140. }
  1141. }
  1142. }
  1143. }
  1144. // MARK: MenuItem Action & PopoverItem Action
  1145. func popoverItemAction(_ count: String) {
  1146. if count == NSLocalizedString("New Blank Page", comment: "") {
  1147. openBlankPage("")
  1148. } else if count == NSLocalizedString("New From Web Page", comment: "") {
  1149. importFromWebPage("")
  1150. } else if count == NSLocalizedString("Import From Scanner", comment: "") {
  1151. importFromScanner("")
  1152. }
  1153. }
  1154. @IBAction func escButtonAction(_ sender: Any) {
  1155. self.historyFileViewController.selectFiles.removeAll()
  1156. if self.historyFileViewController.showMode == .Thumbnail {
  1157. self.historyFileViewController.historyFileCollectionView.reloadData()
  1158. } else {
  1159. self.historyFileViewController.historyFileTableView.reloadData()
  1160. }
  1161. }
  1162. @IBAction func importFromFile(_ sender: Any) {
  1163. self.openSupportPDFButtonAction()
  1164. }
  1165. @IBAction func openBlankPage(_ sender: Any) {
  1166. let fileName: NSString = String(format: "%@.pdf", NSLocalizedString("Untitled", comment: "")) as NSString
  1167. let savePath = fetchUniquePath(fileName.kUrlToPDFFolderPath())
  1168. let pdfDocument = CPDFDocument()
  1169. pdfDocument?.insertPage(CGSize(width: 595, height: 842), at: 0)
  1170. pdfDocument?.write(to: URL(fileURLWithPath: savePath))
  1171. NSDocumentController.shared.openDocument(withContentsOf: URL(fileURLWithPath: savePath), display: true) { document, documentWasAlreadyOpen, error in
  1172. if error != nil {
  1173. NSApp.presentError(error!)
  1174. } else {
  1175. if document is KMMainDocument {
  1176. let newDocument = document
  1177. (newDocument as! KMMainDocument).isNewCreated = true
  1178. }
  1179. }
  1180. }
  1181. }
  1182. @IBAction func importFromWebPage(_ sender: Any) {
  1183. self.urlToPDFWindowController = KMURLToPDFWindowController.init(windowNibName: NSNib.Name("KMURLToPDFWindowController"))
  1184. self.urlToPDFWindowController!.beginSheetModal(for: NSApp.mainWindow!) { filePath in
  1185. if filePath != nil && FileManager.default.fileExists(atPath: filePath) {
  1186. NSDocumentController.shared.openDocument(withContentsOf: URL(fileURLWithPath: filePath), display: true) { document, documentWasAlreadyOpen, error in
  1187. if error != nil {
  1188. NSApp.presentError(error!)
  1189. } else {
  1190. if document is KMMainDocument {
  1191. (document as! KMMainDocument).isNewCreated = true
  1192. }
  1193. }
  1194. }
  1195. }
  1196. }
  1197. }
  1198. @IBAction func importFromScanner(_ sender: Any) {
  1199. deviceBrowserWC = KMDeviceBrowserWindowController.init(windowNibName: "KMDeviceBrowserWindowController")
  1200. deviceBrowserWC!.type = .scanner
  1201. deviceBrowserWC!.importScannerFileCallback = { [unowned self](url: NSURL) -> Void in
  1202. openFile(withFilePath: url as URL)
  1203. }
  1204. deviceBrowserWC!.showWindow(NSApp.mainWindow)
  1205. }
  1206. @IBAction func menuItemClick_mergePDF(_ sender: Any) {
  1207. fastTool_MergePDF()
  1208. }
  1209. @IBAction func menuItemClick_Compress(_ sender: Any) {
  1210. fastTool_Compression()
  1211. }
  1212. @IBAction func menuItemClick_Convert(_ sender: Any) {
  1213. fastTool_ConvertPDF()
  1214. }
  1215. @IBAction func menuItemClick_SettingPassword(_ sender: Any) {
  1216. fastTool_Security()
  1217. }
  1218. @IBAction func menuItemClick_RemovePassword(_ sender: Any) {
  1219. fastTool_Security()
  1220. }
  1221. func fetchUniquePath(_ originalPath: String) -> String {
  1222. var path = originalPath
  1223. let dManager = FileManager.default
  1224. if !dManager.fileExists(atPath: path) {
  1225. if path.extension.count < 1 {
  1226. path = path.stringByAppendingPathExtension("pdf")
  1227. }
  1228. return path
  1229. } else {
  1230. let originalFullFileName = path.lastPathComponent
  1231. let originalFileName = path.lastPathComponent.deletingPathExtension.lastPathComponent
  1232. let originalExtension = path.extension
  1233. let startIndex: Int = 0
  1234. let endIndex: Int = startIndex + originalPath.count - originalFullFileName.count - 1
  1235. let fileLocatePath = originalPath.substring(to: endIndex)
  1236. var i = 1
  1237. while (1 != 0) {
  1238. var newName = String(format: "%@%ld", originalFileName, i)
  1239. newName = String(format: "%@%@", newName, originalExtension)
  1240. let newPath = fileLocatePath.stringByAppendingPathComponent(newName)
  1241. if !dManager.fileExists(atPath: newPath) {
  1242. return newPath
  1243. } else {
  1244. i+=1
  1245. continue
  1246. }
  1247. }
  1248. }
  1249. }
  1250. // func kNewDocumentTempSavePath(_ fileName: String) -> String {
  1251. // let searchPath = NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory, .userDomainMask, true).last
  1252. //// let append1 = searchPath?.stringByAppendingPathComponent(Bundle.main.bundleIdentifier!)
  1253. // let append2 = searchPath!.stringByAppendingPathComponent(String(format: "%@", fileName))
  1254. // return append2
  1255. // }
  1256. // MARK: Notification
  1257. @objc func homeFileRectChange(_ notification: Notification) -> Void {
  1258. let window = notification.object
  1259. self.historyFileViewController.reloadData()
  1260. }
  1261. }
  1262. // MARK: window Menu
  1263. extension KMHomeViewController {
  1264. @IBAction func menuItemAction_showForwardTagPage(_ sender: Any) {
  1265. (self.myDocument as! KMMainDocument).browser.selectPreviousTab()
  1266. }
  1267. @IBAction func menuItemAction_showNextTagPage(_ sender: Any) {
  1268. (self.myDocument as! KMMainDocument).browser.selectNextTab()
  1269. }
  1270. @IBAction func menuItemAction_newTagPageToNewWindow(_ sender: Any) {
  1271. let browser = (self.myDocument as! KMMainDocument).browser
  1272. ((browser as! KMBrowser).windowController as? KMBrowserWindowController)?.openNewWindow(sender)
  1273. }
  1274. @IBAction func menuItemAction_mergeAllWindow(_ sender: Any) {
  1275. let browser = (self.myDocument as! KMMainDocument).browser
  1276. ((browser as! KMBrowser).windowController as? KMBrowserWindowController)?.mergeAllWindow(sender)
  1277. }
  1278. @IBAction func menuItemAction_currentWindowName(_ sender: Any) {
  1279. }
  1280. }
  1281. // MARK: file Menu
  1282. extension KMHomeViewController {
  1283. @IBAction func menuItemAction_closeWindow(_ sender: Any) {
  1284. self.view.window?.close()
  1285. }
  1286. @IBAction func menuItemAction_closeAllWindows(_ sender: Any) {
  1287. for window in NSApp.windows {
  1288. window.close()
  1289. }
  1290. }
  1291. @IBAction func menuItemAction_ConvertToWord(_ sender: Any) {
  1292. self.fastTool_PDFToWord()
  1293. }
  1294. @IBAction func menuItemAction_ConvertToExcel(_ sender: Any) {
  1295. self.fastTool_PDFToExcel()
  1296. }
  1297. @IBAction func menuItemAction_ConvertToPPT(_ sender: Any) {
  1298. self.fastTool_PDFToPPT()
  1299. }
  1300. @IBAction func menuItemAction_ConvertToRTF(_ sender: Any) {
  1301. self.showConvertWindow(type: .rtf)
  1302. }
  1303. @IBAction func menuItemAction_ConvertToHTML(_ sender: Any) {
  1304. self.showConvertWindow(type: .html)
  1305. }
  1306. @IBAction func menuItemAction_ConvertToText(_ sender: Any) {
  1307. self.showConvertWindow(type: .text)
  1308. }
  1309. @IBAction func menuItemAction_ConvertToCSV(_ sender: Any) {
  1310. self.showConvertWindow(type: .csv)
  1311. }
  1312. @IBAction func menuItemAction_ConvertToImage(_ sender: Any) {
  1313. self.fastTool_PDFToImage()
  1314. }
  1315. }
  1316. // MARK: help Menu
  1317. extension KMHomeViewController {
  1318. // @IBAction func menuItemAction_search(_ sender: Any) {
  1319. //
  1320. // }
  1321. }