KMHomeViewController+Action.swift 62 KB

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