KMHomeViewController+Action.swift 62 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471
  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. 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. print("选中 快捷工具 图片转PDF")
  730. KMImageToPDFWindowController.openFiles(window: NSApp.mainWindow!)
  731. }
  732. func fastTool_MergePDF() { // MergePDF
  733. Task { @MainActor in
  734. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  735. let _ = KMComparativeTableViewController.show(window: self.view.window!)
  736. return
  737. }
  738. let panel = NSOpenPanel()
  739. panel.allowedFileTypes = ["pdf"]
  740. panel.allowsMultipleSelection = true
  741. panel.beginSheetModal(for: self.view.window!) { response in
  742. if (response == .cancel) {
  743. return
  744. }
  745. DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
  746. var filepaths: Array<String> = []
  747. for url in panel.urls {
  748. filepaths.append(url.path)
  749. }
  750. let windowController = KMPDFEditAppendWindow(filePaths: filepaths)
  751. self.currentWindowController = windowController
  752. windowController?.beginSheetModal(for: self.view.window, completionHandler: { result, indexs in
  753. })
  754. }
  755. }
  756. }
  757. }
  758. func fastTool_Compression() { // 压缩
  759. Task { @MainActor in
  760. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  761. let _ = KMComparativeTableViewController.show(window: self.view.window!)
  762. return
  763. }
  764. NSOpenPanel.km_secure_openPanel(window: self.view.window!) { url, result, passowrd in
  765. if (url == nil) {
  766. return
  767. }
  768. if (result != nil && result! == .cancel) {
  769. return
  770. }
  771. self.showCompressWindow(url!, passowrd)
  772. }
  773. }
  774. }
  775. func showCompressWindow(_ url: URL, _ password: String?) {
  776. Task { @MainActor in
  777. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  778. let _ = KMComparativeTableViewController.show(window: self.view.window!)
  779. return
  780. }
  781. let windowController = KMCompressWindowController(windowNibName: "KMCompressWindowController")
  782. self.currentWindowController = windowController
  783. windowController.documentURL = url
  784. windowController.password = password
  785. windowController.itemClick = { [weak self] (index: Int) -> () in
  786. self!.view.window?.endSheet(self!.currentWindowController!.window!)
  787. self?.currentWindowController = nil
  788. }
  789. windowController.resultCallback = { [weak self] (result: Bool, openDocument: Bool, fileURL: URL, error: String) in
  790. if result {
  791. self!.view.window?.endSheet(self!.currentWindowController!.window!)
  792. self?.currentWindowController = nil
  793. if openDocument {
  794. if !fileURL.path.isPDFValid() {
  795. let alert = NSAlert()
  796. alert.alertStyle = .critical
  797. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  798. alert.runModal()
  799. return
  800. }
  801. NSDocumentController.shared.openDocument(withContentsOf: fileURL, display: true) { document, result, error in
  802. if error != nil {
  803. NSApp.presentError(error!)
  804. return
  805. }
  806. }
  807. } else {
  808. NSWorkspace.shared.activateFileViewerSelecting([fileURL])
  809. }
  810. } else {
  811. let alert = NSAlert()
  812. alert.messageText = NSLocalizedString("Compress Faild", comment: "")
  813. alert.runModal()
  814. }
  815. }
  816. await self.view.window?.beginSheet(windowController.window!)
  817. }
  818. }
  819. func fastTool_Security() { // 安全
  820. Task { @MainActor in
  821. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  822. let _ = KMComparativeTableViewController.show(window: self.view.window!)
  823. return
  824. }
  825. NSOpenPanel.km_secure_openPanel(window: self.view.window!, needOwner: true) { url, result, passowrd in
  826. if (url == nil) {
  827. return
  828. }
  829. if (result != nil && result! == .cancel) {
  830. return
  831. }
  832. let windowController = KMSecureEncryptWindowController(windowNibName: "KMSecureEncryptWindowController")
  833. windowController.documentURL = url!
  834. windowController.myDocument = CPDFDocument(url: url!)
  835. if (passowrd != nil) {
  836. windowController.myDocument.unlock(withPassword: passowrd)
  837. }
  838. self.currentWindowController = windowController
  839. let newDocument: CPDFDocument = CPDFDocument(url: url!)
  840. windowController.itemClick = { [weak self] (index: Int) -> () in
  841. self!.view.window?.endSheet((self?.currentWindowController?.window!)!)
  842. self?.currentWindowController = nil
  843. }
  844. windowController.resultCallback = { [weak self] (result: Bool) -> () in
  845. let windowController_secure: KMSecureEncryptWindowController = self?.currentWindowController as! KMSecureEncryptWindowController
  846. self!.view.window?.endSheet((self?.currentWindowController?.window!)!)
  847. self!.currentWindowController = nil
  848. if (passowrd != nil) {
  849. newDocument.unlock(withPassword: passowrd)
  850. }
  851. newDocument.setPasswordOptions(windowController_secure.options)
  852. let result = KMPasswordInputWindow.saveDocument(newDocument)
  853. if result {
  854. NSWorkspace.shared.activateFileViewerSelecting([newDocument.documentURL])
  855. } else {
  856. let alert = NSAlert()
  857. alert.messageText = NSLocalizedString("Failure", comment: "")
  858. alert.runModal()
  859. }
  860. }
  861. self.view.window?.beginSheet(windowController.window!)
  862. }
  863. }
  864. }
  865. func fastTool_FileCompare() { // 文件对比
  866. print("选中 快捷工具 文件对比")
  867. }
  868. func fastTool_PDFToPPT() { // PDF转PPT
  869. Task { @MainActor in
  870. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  871. let _ = KMComparativeTableViewController.show(window: self.view.window!)
  872. return
  873. }
  874. NSOpenPanel.km_secure_openPanel_success(window: self.view.window!) { url, password in
  875. let windowController = KMConvertPPTsWindowController(windowNibName: "KMConvertBaseWindowController")
  876. let model = KMDocumentModel(url: url)
  877. windowController.subType = 1
  878. if (password != nil) {
  879. let _ = model.unlock(password!)
  880. }
  881. windowController.documentModel = model
  882. windowController.itemClick = { [weak self] (index: Int) in
  883. if (self?.currentWindowController == nil) {
  884. return
  885. }
  886. self?.view.window?.endSheet((self?.currentWindowController?.window)!)
  887. self?.currentWindowController = nil
  888. }
  889. self.view.window?.beginSheet(windowController.window!)
  890. self.currentWindowController = windowController
  891. }
  892. }
  893. }
  894. func fastTool_PDFToExcel() { // PDF转Excel
  895. Task { @MainActor in
  896. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  897. let _ = KMComparativeTableViewController.show(window: self.view.window!)
  898. return
  899. }
  900. NSOpenPanel.km_secure_openPanel_success(window: self.view.window!) { url, password in
  901. let windowController = KMConvertExcelWindowController(windowNibName: "KMConvertBaseWindowController")
  902. let model = KMDocumentModel(url: url)
  903. if (password != nil) {
  904. let _ = model.unlock(password!)
  905. }
  906. windowController.documentModel = model
  907. windowController.itemClick = { [weak self] (index: Int) in
  908. if (self?.currentWindowController == nil) {
  909. return
  910. }
  911. self?.view.window?.endSheet((self?.currentWindowController?.window)!)
  912. self?.currentWindowController = nil
  913. }
  914. self.view.window?.beginSheet(windowController.window!)
  915. self.currentWindowController = windowController
  916. }
  917. }
  918. }
  919. func fastTool_PDFToWord() { // PDF转Word
  920. Task { @MainActor in
  921. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  922. let _ = KMComparativeTableViewController.show(window: self.view.window!)
  923. return
  924. }
  925. NSOpenPanel.km_secure_openPanel_success(window: self.view.window!) { url, password in
  926. if (url.path.isPDFValid() == false) {
  927. let alert = NSAlert()
  928. alert.alertStyle = .critical
  929. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  930. alert.runModal()
  931. return
  932. }
  933. let windowController = KMConvertWordWindowController(windowNibName: "KMConvertBaseWindowController")
  934. let model = KMDocumentModel(url: url)
  935. if (password != nil) {
  936. let _ = model.unlock(password!)
  937. }
  938. windowController.documentModel = model
  939. windowController.itemClick = { [weak self] (index: Int) in
  940. if (self?.currentWindowController == nil) {
  941. return
  942. }
  943. self?.view.window?.endSheet((self?.currentWindowController?.window)!)
  944. self?.currentWindowController = nil
  945. }
  946. self.view.window?.beginSheet(windowController.window!)
  947. self.currentWindowController = windowController
  948. }
  949. }
  950. }
  951. func fastTool_PDFToImage() { // PDF转图片
  952. Task { @MainActor in
  953. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  954. let _ = KMComparativeTableViewController.show(window: self.view.window!)
  955. return
  956. }
  957. NSOpenPanel.km_secure_openPanel_success(window: self.view.window!) { url, password in
  958. let windowController = KMConvertImageWindowController(windowNibName: "KMConvertBaseWindowController")
  959. let model = KMDocumentModel(url: url)
  960. if (password != nil) {
  961. let _ = model.unlock(password!)
  962. }
  963. windowController.documentModel = model
  964. windowController.itemClick = { [weak self] (index: Int) in
  965. if (self?.currentWindowController == nil) {
  966. return
  967. }
  968. self?.view.window?.endSheet((self?.currentWindowController?.window)!)
  969. self?.currentWindowController = nil
  970. }
  971. self.view.window?.beginSheet(windowController.window!)
  972. self.currentWindowController = windowController
  973. }
  974. }
  975. }
  976. func fastTool_Watermark() { // 水印
  977. KMBatchWindowController.openFile(nil, .Watermark)
  978. }
  979. func fastTool_Background() { // 背景
  980. KMBatchWindowController.openFile(nil, .Background)
  981. }
  982. func fastTool_HeaderAndFooter() { // 页眉页脚
  983. KMBatchWindowController.openFile(nil, .HeaderAndFooter)
  984. }
  985. func fastTool_BatesCode() { // 贝茨码
  986. KMBatchWindowController.openFile(nil, .BatesCode)
  987. }
  988. func fastTool_Print() { // 打印
  989. KMPrintWindowController.openFiles(window: self.view.window!)
  990. }
  991. func fastTool_BatchRemove() { // 批量移除
  992. KMBatchWindowController.openFile(nil, .BatchRemove)
  993. }
  994. func fastTool_Insert() { // 插入
  995. let openPanel = NSOpenPanel()
  996. openPanel.prompt = "插入"
  997. openPanel.allowsMultipleSelection = false
  998. openPanel.allowedFileTypes = ["pdf"]
  999. openPanel.beginSheetModal(for: NSApp.mainWindow!) { result in
  1000. if result == .OK {
  1001. DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
  1002. let insertWindowController: KMPDFInsertPageWindow = KMPDFInsertPageWindow.init(documentPath: openPanel.url!, toolType: .Insert)
  1003. insertWindowController.beginSheetModal(for: self.view.window!) { pdfDocument, password, pages, indexPage in
  1004. self.insertPageAction(pdfDocument, password, pages, indexPage)
  1005. }
  1006. }
  1007. }
  1008. }
  1009. }
  1010. func fastTool_BreakUp() { // 拆分
  1011. let openPanel = NSOpenPanel()
  1012. openPanel.prompt = "提取"
  1013. openPanel.allowsMultipleSelection = false
  1014. openPanel.allowedFileTypes = ["pdf"]
  1015. openPanel.beginSheetModal(for: NSApp.mainWindow!) { result in
  1016. if result == .OK {
  1017. DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
  1018. let document = CPDFDocument(url: openPanel.url)
  1019. let model = KMPageEditSplitSettingModel()
  1020. model.documentURL = openPanel.url
  1021. model.fileName = model.documentURL.lastPathComponent
  1022. model.pathExtension = model.fileName.components(separatedBy: ".").last
  1023. let windowController = KMPageEditSplitWindowController(model)
  1024. windowController.hasPreView = true
  1025. self.view.window?.beginSheet(windowController.window!)
  1026. self.currentWindowController = windowController
  1027. windowController.itemClick = { [weak self] index, value in
  1028. if (index == 1) { /// 取消
  1029. self?.view.window?.endSheet((self?.currentWindowController!.window)!)
  1030. self?.currentWindowController = nil
  1031. return
  1032. }
  1033. /// 拆分
  1034. let windowController_split: KMPageEditSplitWindowController = self?.currentWindowController as! KMPageEditSplitWindowController
  1035. let outputModel: KMPageEditSplitSettingModel = windowController_split.model! as! KMPageEditSplitSettingModel
  1036. self?.view.window?.endSheet((self?.currentWindowController!.window)!)
  1037. self?.currentWindowController = nil
  1038. let panel = NSOpenPanel()
  1039. panel.canChooseFiles = false
  1040. panel.canChooseDirectories = true
  1041. panel.canCreateDirectories = true
  1042. panel.beginSheetModal(for: (self?.view.window)!) { response in
  1043. KMPageEditTools.split(document!, outputModel, panel.url!.path, outputModel.outputFileNameDeletePathExtension) { result, outputDocuments, error in
  1044. if (result) {
  1045. }
  1046. }
  1047. }
  1048. }
  1049. }
  1050. }
  1051. }
  1052. }
  1053. func fastTool_Extract() { // 提取
  1054. let openPanel = NSOpenPanel()
  1055. openPanel.prompt = "提取"
  1056. openPanel.allowsMultipleSelection = false
  1057. openPanel.allowedFileTypes = ["pdf"]
  1058. openPanel.beginSheetModal(for: NSApp.mainWindow!) { result in
  1059. if result == .OK {
  1060. DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
  1061. let insertWindowController: KMPDFInsertPageWindow = KMPDFInsertPageWindow.init(documentPath: openPanel.url!, toolType: .Extract)
  1062. insertWindowController.beginSheetExtractModal(for: self.view.window!) { pdfDocument, pages, oneDocumentPerPage, isDeletePage in
  1063. self.extractPageAction(pdfDocument, pages, oneDocumentPerPage, isDeletePage)
  1064. }
  1065. }
  1066. }
  1067. }
  1068. }
  1069. func fastTool_MarkCipher() { // 标记密文
  1070. let openPanel = NSOpenPanel()
  1071. openPanel.allowsMultipleSelection = false
  1072. openPanel.allowedFileTypes = ["pdf"]
  1073. openPanel.beginSheetModal(for: NSApp.mainWindow!) { result in
  1074. if result == .cancel {
  1075. return
  1076. }
  1077. if !openPanel.url!.path.isPDFValid() {
  1078. let alert = NSAlert()
  1079. alert.alertStyle = .critical
  1080. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  1081. alert.runModal()
  1082. return
  1083. }
  1084. DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
  1085. NSDocumentController.shared.openDocument(withContentsOf: openPanel.url!, display: true) { document, result, error in
  1086. if (error != nil) {
  1087. NSApp.presentError(error!)
  1088. return
  1089. }
  1090. let toolbar = (document as! KMMainDocument).mainViewController?.toolbarController
  1091. toolbar?.enterRedact()
  1092. }
  1093. }
  1094. }
  1095. }
  1096. func fastTool_AutomaticFormRecognition() { // 表单自动识别
  1097. let openPanel = NSOpenPanel()
  1098. openPanel.prompt = "表单自动识别"
  1099. openPanel.allowsMultipleSelection = false
  1100. openPanel.allowedFileTypes = ["pdf"]
  1101. openPanel.beginSheetModal(for: NSApp.mainWindow!) { result in
  1102. if result == .OK {
  1103. }
  1104. }
  1105. }
  1106. func fastTool_PageEdit() { // 页面编辑
  1107. let openPanel = NSOpenPanel()
  1108. openPanel.allowsMultipleSelection = false
  1109. openPanel.allowedFileTypes = ["pdf"]
  1110. openPanel.beginSheetModal(for: NSApp.mainWindow!) { result in
  1111. if result == .cancel {
  1112. return
  1113. }
  1114. if !openPanel.url!.path.isPDFValid() {
  1115. let alert = NSAlert()
  1116. alert.alertStyle = .critical
  1117. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  1118. alert.runModal()
  1119. return
  1120. }
  1121. DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
  1122. NSDocumentController.shared.openDocument(withContentsOf: openPanel.url!, display: true) { document, result, error in
  1123. if (error != nil) {
  1124. NSApp.presentError(error!)
  1125. return
  1126. }
  1127. let mainView = (document as! KMMainDocument).mainViewController
  1128. mainView?.enterPageEdit()
  1129. }
  1130. }
  1131. }
  1132. }
  1133. // MARK: MenuItem Action & PopoverItem Action
  1134. func popoverItemAction(_ count: String) {
  1135. if count == NSLocalizedString("New Blank Page", comment: "") {
  1136. openBlankPage("")
  1137. } else if count == NSLocalizedString("New From Web Page", comment: "") {
  1138. importFromWebPage("")
  1139. } else if count == NSLocalizedString("Import From Scanner", comment: "") {
  1140. importFromScanner("")
  1141. }
  1142. }
  1143. @IBAction func escButtonAction(_ sender: Any) {
  1144. self.historyFileViewController.selectFiles.removeAll()
  1145. if self.historyFileViewController.showMode == .Thumbnail {
  1146. self.historyFileViewController.historyFileCollectionView.reloadData()
  1147. } else {
  1148. self.historyFileViewController.historyFileTableView.reloadData()
  1149. }
  1150. }
  1151. @IBAction func importFromFile(_ sender: Any) {
  1152. self.openSupportPDFButtonAction()
  1153. }
  1154. @IBAction func openBlankPage(_ sender: Any) {
  1155. let fileName: NSString = String(format: "%@.pdf", NSLocalizedString("Untitled", comment: "")) as NSString
  1156. let savePath = fetchUniquePath(fileName.kUrlToPDFFolderPath())
  1157. let pdfDocument = CPDFDocument()
  1158. pdfDocument?.insertPage(CGSize(width: 595, height: 842), at: 0)
  1159. pdfDocument?.write(to: URL(fileURLWithPath: savePath))
  1160. NSDocumentController.shared.openDocument(withContentsOf: URL(fileURLWithPath: savePath), display: true) { document, documentWasAlreadyOpen, error in
  1161. if error != nil {
  1162. NSApp.presentError(error!)
  1163. } else {
  1164. if document is KMMainDocument {
  1165. let newDocument = document
  1166. (newDocument as! KMMainDocument).isNewCreated = true
  1167. }
  1168. }
  1169. }
  1170. }
  1171. @IBAction func importFromWebPage(_ sender: Any) {
  1172. self.urlToPDFWindowController = KMURLToPDFWindowController.init(windowNibName: NSNib.Name("KMURLToPDFWindowController"))
  1173. self.urlToPDFWindowController!.beginSheetModal(for: NSApp.mainWindow!) { filePath in
  1174. if filePath != nil && FileManager.default.fileExists(atPath: filePath) {
  1175. NSDocumentController.shared.openDocument(withContentsOf: URL(fileURLWithPath: filePath), display: true) { document, documentWasAlreadyOpen, error in
  1176. if error != nil {
  1177. NSApp.presentError(error!)
  1178. } else {
  1179. if document is KMMainDocument {
  1180. (document as! KMMainDocument).isNewCreated = true
  1181. }
  1182. }
  1183. }
  1184. }
  1185. }
  1186. }
  1187. @IBAction func importFromScanner(_ sender: Any) {
  1188. deviceBrowserWC = KMDeviceBrowserWindowController.init(windowNibName: "KMDeviceBrowserWindowController")
  1189. deviceBrowserWC?.type = .scanner
  1190. deviceBrowserWC?.importScannerFileCallback = { [weak self](url: NSURL) -> Void in
  1191. self?.openFile(withFilePath: url as URL)
  1192. }
  1193. deviceBrowserWC?.showWindow(NSApp.mainWindow)
  1194. }
  1195. @IBAction func menuItemClick_mergePDF(_ sender: Any) {
  1196. fastTool_MergePDF()
  1197. }
  1198. @IBAction func menuItemClick_Compress(_ sender: Any) {
  1199. fastTool_Compression()
  1200. }
  1201. @IBAction func menuItemClick_Convert(_ sender: Any) {
  1202. fastTool_ConvertPDF()
  1203. }
  1204. @IBAction func menuItemClick_SettingPassword(_ sender: Any) {
  1205. fastTool_Security()
  1206. }
  1207. @IBAction func menuItemClick_RemovePassword(_ sender: Any) {
  1208. fastTool_Security()
  1209. }
  1210. func fetchUniquePath(_ originalPath: String) -> String {
  1211. var path = originalPath
  1212. let dManager = FileManager.default
  1213. if !dManager.fileExists(atPath: path) {
  1214. if path.extension.count < 1 {
  1215. path = path.stringByAppendingPathExtension("pdf")
  1216. }
  1217. return path
  1218. } else {
  1219. let originalFullFileName = path.lastPathComponent
  1220. let originalFileName = path.lastPathComponent.deletingPathExtension.lastPathComponent
  1221. let originalExtension = path.extension
  1222. let startIndex: Int = 0
  1223. let endIndex: Int = startIndex + originalPath.count - originalFullFileName.count - 1
  1224. let fileLocatePath = originalPath.substring(to: endIndex)
  1225. var i = 1
  1226. while (1 != 0) {
  1227. var newName = String(format: "%@%ld", originalFileName, i)
  1228. newName = String(format: "%@%@", newName, originalExtension)
  1229. let newPath = fileLocatePath.stringByAppendingPathComponent(newName)
  1230. if !dManager.fileExists(atPath: newPath) {
  1231. return newPath
  1232. } else {
  1233. i+=1
  1234. continue
  1235. }
  1236. }
  1237. }
  1238. }
  1239. // func kNewDocumentTempSavePath(_ fileName: String) -> String {
  1240. // let searchPath = NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory, .userDomainMask, true).last
  1241. //// let append1 = searchPath?.stringByAppendingPathComponent(Bundle.main.bundleIdentifier!)
  1242. // let append2 = searchPath!.stringByAppendingPathComponent(String(format: "%@", fileName))
  1243. // return append2
  1244. // }
  1245. // MARK: Notification
  1246. @objc func homeFileRectChange(_ notification: Notification) -> Void {
  1247. let window = notification.object
  1248. self.historyFileViewController.reloadData()
  1249. }
  1250. }
  1251. // MARK: window Menu
  1252. extension KMHomeViewController {
  1253. @IBAction func menuItemAction_showForwardTagPage(_ sender: Any) {
  1254. (self.myDocument as! KMMainDocument).browser.selectPreviousTab()
  1255. }
  1256. @IBAction func menuItemAction_showNextTagPage(_ sender: Any) {
  1257. (self.myDocument as! KMMainDocument).browser.selectNextTab()
  1258. }
  1259. @IBAction func menuItemAction_newTagPageToNewWindow(_ sender: Any) {
  1260. let browser = (self.myDocument as! KMMainDocument).browser
  1261. ((browser as! KMBrowser).windowController as? KMBrowserWindowController)?.openNewWindow(sender)
  1262. }
  1263. @IBAction func menuItemAction_mergeAllWindow(_ sender: Any) {
  1264. let browser = (self.myDocument as! KMMainDocument).browser
  1265. ((browser as! KMBrowser).windowController as? KMBrowserWindowController)?.mergeAllWindow(sender)
  1266. }
  1267. @IBAction func menuItemAction_currentWindowName(_ sender: Any) {
  1268. }
  1269. }
  1270. // MARK: file Menu
  1271. extension KMHomeViewController {
  1272. @IBAction func menuItemAction_closeWindow(_ sender: Any) {
  1273. self.view.window?.close()
  1274. }
  1275. @IBAction func menuItemAction_closeAllWindows(_ sender: Any) {
  1276. for window in NSApp.windows {
  1277. window.close()
  1278. }
  1279. }
  1280. @IBAction func menuItemAction_ConvertToWord(_ sender: Any) {
  1281. self.fastTool_PDFToWord()
  1282. }
  1283. @IBAction func menuItemAction_ConvertToExcel(_ sender: Any) {
  1284. self.fastTool_PDFToExcel()
  1285. }
  1286. @IBAction func menuItemAction_ConvertToPPT(_ sender: Any) {
  1287. self.fastTool_PDFToPPT()
  1288. }
  1289. @IBAction func menuItemAction_ConvertToRTF(_ sender: Any) {
  1290. self.showConvertWindow(type: .rtf)
  1291. }
  1292. @IBAction func menuItemAction_ConvertToHTML(_ sender: Any) {
  1293. self.showConvertWindow(type: .html)
  1294. }
  1295. @IBAction func menuItemAction_ConvertToText(_ sender: Any) {
  1296. self.showConvertWindow(type: .text)
  1297. }
  1298. @IBAction func menuItemAction_ConvertToCSV(_ sender: Any) {
  1299. self.showConvertWindow(type: .csv)
  1300. }
  1301. @IBAction func menuItemAction_ConvertToImage(_ sender: Any) {
  1302. self.fastTool_PDFToImage()
  1303. }
  1304. }
  1305. // MARK: help Menu
  1306. extension KMHomeViewController {
  1307. // @IBAction func menuItemAction_search(_ sender: Any) {
  1308. //
  1309. // }
  1310. }