KMHomeViewController+Action.swift 63 KB

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