KMHomeViewController+Action.swift 62 KB

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