KMHomeViewController+Action.swift 94 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170
  1. //
  2. // KMHomeViewController+Action.swift
  3. // PDF Reader Pro
  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. break
  58. case .Home:
  59. homeButtonAction()
  60. break
  61. case .PDFTools:
  62. pdfToolsButtonAction()
  63. break
  64. case .FavoriteDocuments:
  65. favoriteDocumentsButtonAction()
  66. break
  67. case .CloudDocuments:
  68. cloudDocumentsButtonAction()
  69. break
  70. default:
  71. KMPrint("error: 错误的传入枚举")
  72. break
  73. }
  74. }
  75. func fastToolItemAction(_ type: DataNavigationViewButtonActionType) {
  76. print("fastToolItemAction + \(type.rawValue)")
  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. fastTool_FileCompare()
  152. break
  153. case .equity:
  154. break
  155. case .PrintMultipage:
  156. self.fastTool_printMultple()
  157. break
  158. case .PrintPoster:
  159. self.fastTool_printPoster()
  160. break
  161. case .PrintBooklet:
  162. self.fastTool_printBooklet()
  163. break
  164. }
  165. }
  166. func openPDFButtonAction() {
  167. NSPanel.km_open_pdf_multi_success(self.view.window!, panel: nil) { urls in
  168. for url in urls {
  169. NSDocumentController.shared.km_safe_openDocument(withContentsOf: url, display: true) { _, _, _ in
  170. }
  171. }
  172. }
  173. }
  174. func openSupportPDFButtonAction() {
  175. var window = self.view.window
  176. if (window == nil) {
  177. window = NSApp.mainWindow
  178. }
  179. NSOpenPanel.km_open_multi(window!) { panel in
  180. // if let data = KMConvertPDFManager.supportFileType() as? [String], !data.isEmpty {
  181. panel.allowedFileTypes = KMTools.pdfExtensions + KMConvertPDFManager.supportFileType()
  182. // } else {
  183. // panel.allowedFileTypes = KMTools.pdfExtensions + KMTools.imageExtensions
  184. // }
  185. } completion: { [weak self] result , urls in
  186. if result == .OK {
  187. var imageUrl: [URL] = []
  188. for url in urls! {
  189. let type = url.pathExtension.lowercased()
  190. if (type == "pdf" || type == "PDF") {
  191. NSDocumentController.shared.km_safe_openDocument(withContentsOf: url, display: true) { _, _, _ in
  192. }
  193. } else if (type == "jpg") ||
  194. (type == "cur") ||
  195. (type == "bmp") ||
  196. (type == "jpeg") ||
  197. (type == "gif") ||
  198. (type == "png") ||
  199. (type == "tiff") ||
  200. (type == "tif") ||
  201. (type == "ico") ||
  202. (type == "icns") ||
  203. (type == "tga") ||
  204. (type == "psd") ||
  205. (type == "eps") ||
  206. (type == "hdr") ||
  207. (type == "jp2") ||
  208. (type == "jpc") ||
  209. (type == "pict") ||
  210. (type == "sgi") ||
  211. (type == "heic") {
  212. self?.openImageFile(url: url)
  213. } else if (type == "doc") ||
  214. (type == "docx") ||
  215. (type == "xls") ||
  216. (type == "xlsx") ||
  217. (type == "ppt") ||
  218. (type == "pptx") ||
  219. (type == "pptx") {
  220. self?.openOfficeFile(url: url)
  221. }
  222. }
  223. }
  224. }
  225. }
  226. func homeButtonAction() {
  227. refreshRightBoxUI(.Home)
  228. }
  229. func pdfToolsButtonAction() {
  230. refreshRightBoxUI(.PDFTools)
  231. }
  232. func favoriteDocumentsButtonAction() {
  233. KMPrint("Favorite Documents")
  234. }
  235. func cloudDocumentsButtonAction() {
  236. refreshRightBoxUI(.CloudDocuments)
  237. }
  238. func productPromotionClickAction(_ name: NSString) {
  239. var httpString: NSString = ""
  240. if name.isEqual(to: "Windows") {
  241. httpString = "https://www.pdfreaderpro.com/windows?utm_source=MacApp&utm_campaign=PDFProMac&utm_medium=pdfmac_promo"
  242. } else if name.isEqual(to: "iPhone / iPad") {
  243. #if VERSION_FREE
  244. #if VERSION_DMG
  245. httpString = "https://www.pdfreaderpro.com/product?utm_source=MacAppDmg&utm_campaign=ProductLinkLeftNav&utm_medium=PdfProduct"
  246. #else
  247. httpString = "https://www.pdfreaderpro.com/product?utm_source=MacAppLite&utm_campaign=ProductLinkLeftNav&utm_medium=PdfProduct"
  248. #endif
  249. #else
  250. httpString = "https://www.pdfreaderpro.com/product?utm_source=MacApp&utm_campaign=ProductLinkLeftNav&utm_medium=PdfProduct"
  251. #endif
  252. } else if name.isEqual(to: "Android") {
  253. httpString = "https://www.pdfreaderpro.com/pdfreaderpro-android?utm_source=MacAppDmg&utm_campaign=AndroidLink&utm_medium=PdfAndroid"
  254. } else if name.isEqual(to: "ComPDFKit") {
  255. httpString = "https://www.compdf.com?utm_source=macapp&utm_medium=pdfmac&utm_campaign=compdfkit-promp"
  256. } else if name.isEqual(to: "ComVideoKit") {
  257. httpString = "https://www.filmagepro.com/video-sdk?utm_source=macapp&utm_medium=pdfmac&utm_campaign=comvideosdk-promo"
  258. } else if name.isEqual(to: "SignFlow") {
  259. httpString = "https://apps.apple.com/app/apple-store/id1584624017?pt=118745145&ct=pdfmac-promo&mt=8"
  260. } else if name.isEqual(to: "FiImage Editor") {
  261. httpString = "https://apps.apple.com/app/apple-store/id1475051178?pt=118745145&ct=pdfmac-promo&mt=8"
  262. } else if name.isEqual(to: "FiImage Screen") {
  263. httpString = "https://apps.apple.com/app/apple-store/id1475049179?pt=118745145&ct=pdfmac-promo&mt=8"
  264. } else if name.isEqual(to: "Free PDF Templates") {
  265. httpString = "https://www.pdfreaderpro.com/templates?utm_source=MacApp&utm_campaign=PDFProMac&utm_medium=pdfmac_promo"
  266. }
  267. self.workSpaceOpenUrl(httpString)
  268. }
  269. func historyFile(deleteDocuments indexPaths: [URL]) {
  270. if UserDefaults.standard.bool(forKey: "kHistoryDeleteNOReminderKey") {
  271. historyFileDeleteAction(indexPaths)
  272. } else {
  273. let historyFileDeleteVC: KMHistoryFileDeleteWindowController = KMHistoryFileDeleteWindowController.init(windowNibName: NSNib.Name("KMHistoryFileDeleteWindowController"))
  274. historyFileDeleteVC.indexPaths = indexPaths
  275. self.currentWindowController = historyFileDeleteVC
  276. historyFileDeleteVC.deleteCallback = { [weak self](indexPaths: [URL], windowController: KMHistoryFileDeleteWindowController) -> Void in
  277. if self != nil {
  278. self?.currentWindowController = nil
  279. self!.historyFileDeleteAction(indexPaths)
  280. }
  281. }
  282. self.view.window?.beginSheet(historyFileDeleteVC.window!)
  283. }
  284. }
  285. func historyFileDeleteAction(_ indexPaths: [URL]) -> Void {
  286. let urls: Array<URL> = NSDocumentController.shared.recentDocumentURLs
  287. NSDocumentController.shared.clearRecentDocuments(nil)
  288. DispatchQueue.main.asyncAfter(deadline: .now()) { [self] in
  289. for (_, url) in urls.enumerated() {
  290. if !indexPaths.contains(url) {
  291. NSDocumentController.shared.noteNewRecentDocumentURL(url)
  292. }
  293. }
  294. self.homeContentView.historyListView.reloadData()
  295. }
  296. }
  297. func openNewWindowAlertV(){
  298. let preferenceNoteShow = UserDefaults.standard.bool(forKey: KMTabbingHintShowFlag)
  299. if preferenceNoteShow {
  300. menuItemAction_newTagPageToNewWindow("")
  301. } else {
  302. let window = NSWindow.currentWindow()
  303. if !KMTools.defaultManager.isTabbingWin{
  304. KMTools.defaultManager.isTabbingWin = true
  305. let tabbingWin: KMTabbingHintWindowController = KMTabbingHintWindowController()
  306. tabbingWin.selectCallBack = { continueOrNot in
  307. window.km_quick_endSheet()
  308. KMTools.defaultManager.isTabbingWin = false
  309. if continueOrNot {
  310. self.reopenDocument(forPaths: [])
  311. } else {
  312. }
  313. }
  314. window.km_beginSheet(windowC: tabbingWin)
  315. }
  316. }
  317. }
  318. func reopenDocument(forPaths paths: [String]) -> Void {
  319. let browser = KMBrowser.init() as KMBrowser
  320. browser.windowController = KMBrowserWindowController.init(browser: browser)
  321. browser.addHomeTabContents()
  322. browser.windowController.showWindow(self)
  323. }
  324. func openHistoryFilePath(url: URL) -> Void {
  325. if !url.path.isPDFValid() {
  326. let alert = NSAlert()
  327. alert.alertStyle = .critical
  328. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  329. alert.beginSheetModal(for: view.window!) { [unowned self] result in
  330. self.homeContentView.historyListView.reloadData()
  331. // self.historyFileViewController.reloadData()
  332. }
  333. return
  334. }
  335. if url.pathExtension.lowercased() == "pdf" {
  336. let pdfDoc = CPDFDocument.init(url: url)
  337. if pdfDoc != nil {
  338. let document = NSDocumentController.shared.document(for: url)
  339. var alreadyOpen = false
  340. for openDocument in NSDocumentController.shared.documents {
  341. if document == openDocument {
  342. alreadyOpen = true
  343. }
  344. }
  345. if !alreadyOpen {
  346. KMMainDocument().tryToUnlockDocument(pdfDoc!)
  347. var selectDocument: KMMainDocument? = nil
  348. if ((document?.isKind(of: KMMainDocument.self)) != nil) {
  349. selectDocument = (document as! KMMainDocument)
  350. }
  351. if selectDocument != nil {
  352. let currentIndex = selectDocument?.browser.tabStripModel.index(of: selectDocument)
  353. selectDocument?.browser.tabStripModel.selectTabContents(at: Int32(currentIndex!), userGesture: true)
  354. if (selectDocument?.browser.window.isVisible)! as Bool {
  355. selectDocument?.browser.window.orderFront(nil)
  356. } else if (selectDocument?.browser.window.isMiniaturized)! as Bool {
  357. selectDocument?.browser.window.orderFront(nil)
  358. }
  359. } else {
  360. NSDocumentController.shared.km_safe_openDocument(withContentsOf: url, display: true) { _, _, _ in
  361. }
  362. }
  363. } else {
  364. var selectDocument: KMMainDocument? = nil
  365. if ((document?.isKind(of: KMMainDocument.self)) != nil) {
  366. selectDocument = (document as! KMMainDocument)
  367. }
  368. if selectDocument != nil {
  369. if selectDocument?.browser != nil {
  370. let currentIndex = selectDocument?.browser.tabStripModel.index(of: selectDocument)
  371. selectDocument?.browser.tabStripModel.selectTabContents(at: Int32(currentIndex!), userGesture: true)
  372. if (selectDocument?.browser.window.isVisible)! as Bool {
  373. selectDocument?.browser.window.orderFront(nil)
  374. } else if (selectDocument?.browser.window.isMiniaturized)! as Bool {
  375. selectDocument?.browser.window.orderFront(nil)
  376. }
  377. }
  378. } else {
  379. NSDocumentController.shared.km_safe_openDocument(withContentsOf: url, display: true) { _, _, _ in
  380. }
  381. }
  382. }
  383. } else {
  384. let alert = NSAlert()
  385. alert.alertStyle = .critical
  386. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  387. alert.beginSheetModal(for: view.window!) { [unowned self] result in
  388. self.homeContentView.historyListView.reloadData()
  389. // self.historyFileViewController.reloadData()
  390. }
  391. }
  392. } else {
  393. NSWorkspace.shared.open(url)
  394. }
  395. }
  396. func openFile(withFilePath path: URL) -> Void {
  397. let type = path.pathExtension.lowercased()
  398. if (type == "pdf") {
  399. if !path.path.isPDFValid() {
  400. let alert = NSAlert()
  401. alert.alertStyle = .critical
  402. alert.messageText = NSLocalizedString("This file format is not supported, please drag in PDF, picture, Office format files", comment: "")
  403. alert.runModal()
  404. return
  405. }
  406. NSDocumentController.shared.openDocument(withContentsOf: path, display: true) { document, documentWasAlreadyOpen, error in
  407. if error != nil {
  408. NSApp.presentError(error!)
  409. return
  410. }
  411. }
  412. } else if (type == "jpg") ||
  413. (type == "cur") ||
  414. (type == "bmp") ||
  415. (type == "jpeg") ||
  416. (type == "gif") ||
  417. (type == "png") ||
  418. (type == "tiff") ||
  419. (type == "tif") ||
  420. (type == "ico") ||
  421. (type == "icns") ||
  422. (type == "tga") ||
  423. (type == "psd") ||
  424. (type == "eps") ||
  425. (type == "hdr") ||
  426. (type == "jp2") ||
  427. (type == "jpc") ||
  428. (type == "pict") ||
  429. (type == "sgi") ||
  430. (type == "heic") {
  431. openImageFile(url: path)
  432. } else if (type == "doc") ||
  433. (type == "docx") ||
  434. (type == "xls") ||
  435. (type == "xlsx") ||
  436. (type == "ppt") ||
  437. (type == "pptx") ||
  438. (type == "pptx") {
  439. let fileName: NSString = String(format: "%@.pdf", NSLocalizedString("Untitled", comment: "")) as NSString
  440. let savePath = fetchUniquePath(fileName.kUrlToPDFFolderPath() as String)
  441. openOfficeFile(url: path)
  442. }
  443. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.3) {
  444. self.homeContentView.historyListView.reloadData()
  445. }
  446. }
  447. func openImageFile(url: URL) -> Void {
  448. var filePath = url.path
  449. let fileName: NSString = url.lastPathComponent as NSString
  450. let savePath = fetchUniquePath(fileName.kUrlToPDFFolderPath() as String).deletingLastPathComponent
  451. let imageName = NSString(string: NSString(string: filePath).lastPathComponent).deletingPathExtension
  452. let path = self.fetchDifferentFilePath(filePath: savePath + "/" + imageName + ".pdf")
  453. if (!FileManager.default.fileExists(atPath: path.deletingLastPathComponent as String)) {
  454. try?FileManager.default.createDirectory(atPath: path.deletingLastPathComponent as String, withIntermediateDirectories: true, attributes: nil)
  455. }
  456. if (!FileManager.default.fileExists(atPath: path as String)) {
  457. FileManager.default.createFile(atPath: path as String, contents: nil)
  458. }
  459. let document = CPDFDocument.init()
  460. var success = false
  461. if NSString(string: NSString(string: filePath).lastPathComponent).pathExtension == "png" ||
  462. NSString(string: NSString(string: filePath).lastPathComponent).pathExtension == "PNG" {
  463. let jpgPath = self.fetchDifferentFilePath(filePath: savePath + "/" + imageName + ".jpg")
  464. if (!FileManager.default.fileExists(atPath: jpgPath as String)) {
  465. FileManager.default.createFile(atPath: jpgPath as String, contents: nil)
  466. }
  467. // 加载 PNG 图像
  468. guard let pngImage = NSImage(contentsOfFile: filePath) else {
  469. KMPrint("Failed to load PNG image")
  470. return
  471. }
  472. // 创建 NSBitmapImageRep 对象,并将 PNG 图像绘制到其中
  473. let bitmap = NSBitmapImageRep(data: pngImage.tiffRepresentation!)
  474. let rect = NSRect(origin: .zero, size: bitmap!.size)
  475. bitmap?.draw(in: rect)
  476. // 将 PNG 图像数据转换为 JPG 图像数据
  477. guard let jpgData = bitmap?.representation(using: .jpeg, properties: [:]) else {
  478. KMPrint("Failed to convert PNG to JPG")
  479. return
  480. }
  481. // 保存 JPG 图像数据到文件
  482. let fileURL = URL(fileURLWithPath: jpgPath)
  483. do {
  484. try jpgData.write(to: fileURL)
  485. filePath = fileURL.path
  486. KMPrint("JPG image saved successfully")
  487. } catch {
  488. KMPrint("Failed to save JPG image: \(error.localizedDescription)")
  489. }
  490. }
  491. //FIXME: 无法插入图片
  492. let image = NSImage(contentsOfFile: filePath)
  493. let insertPageSuccess = document?.insertPage(image!.size, withImage: filePath, at: document!.pageCount)
  494. if insertPageSuccess != nil {
  495. //信号量控制异步
  496. let semaphore = DispatchSemaphore(value: 0)
  497. DispatchQueue.global().async {
  498. success = ((document?.write(toFile: path)) != nil)
  499. semaphore.signal()
  500. }
  501. semaphore.wait()
  502. } else {
  503. }
  504. if success {
  505. NSDocumentController.shared.km_safe_openDocument(withContentsOf: URL(fileURLWithPath: path), display: true) { _, _, _ in
  506. }
  507. }
  508. }
  509. func openOfficeFile(url: URL) -> Void {
  510. let filePath = url.path
  511. let folderPath = "convertToPDF.pdf"
  512. let savePath: String? = folderPath.kUrlToPDFFolderPath() as String
  513. if (!FileManager.default.fileExists(atPath: savePath!.deletingLastPathComponent as String)) {
  514. try?FileManager.default.createDirectory(atPath: savePath!.deletingLastPathComponent as String, withIntermediateDirectories: true, attributes: nil)
  515. }
  516. if (!FileManager.default.fileExists(atPath: savePath! as String)) {
  517. FileManager.default.createFile(atPath: savePath! as String, contents: nil)
  518. }
  519. if savePath == nil {
  520. return
  521. }
  522. KMConvertPDFManager.convertFile(filePath, savePath: savePath!) { success, errorDic in
  523. if errorDic != nil || !success || !FileManager.default.fileExists(atPath: savePath!) {
  524. if FileManager.default.fileExists(atPath: savePath!) {
  525. try?FileManager.default.removeItem(atPath: savePath!)
  526. }
  527. let alert = NSAlert.init()
  528. alert.alertStyle = .critical
  529. var infoString = ""
  530. if errorDic != nil {
  531. for key in (errorDic! as Dictionary).keys {
  532. infoString = infoString.appendingFormat("%@\n", errorDic![key] as! CVarArg)
  533. }
  534. }
  535. alert.informativeText = NSLocalizedString("Please install Microsoft Office to create PDFs from Office files", comment: "")
  536. alert.messageText = NSLocalizedString("Failed to Create PDF", comment: "")
  537. alert.addButton(withTitle: NSLocalizedString("OK", comment: ""))
  538. alert.runModal()
  539. return
  540. }
  541. NSDocumentController.shared.km_safe_openDocument(withContentsOf: URL(fileURLWithPath: savePath!), display: true) { _, _, _ in
  542. }
  543. }
  544. }
  545. func aiTranslation(withFilePath path: String) -> Void {
  546. if !KMLightMemberManager.manager.isLogin() {
  547. KMLoginWindowController.show(window: NSApp.mainWindow!)
  548. return
  549. }
  550. let isExceedsLimit = self.isPDFPageCountExceedsLimit(filePath: path)
  551. if self.isFileGreaterThan10MB(atPath: path) {
  552. self.aiTranslationViewController.errorView.isHidden = false
  553. self.aiTranslationViewController.errorLabel.stringValue = NSLocalizedString("The uploaded file size cannot exceed 10MB", comment: "")
  554. } else if isExceedsLimit {
  555. self.aiTranslationViewController.errorView.isHidden = false
  556. self.aiTranslationViewController.errorLabel.stringValue = NSLocalizedString("Documents cannot exceed 30 pages", comment: "")
  557. } else {
  558. let url = URL(fileURLWithPath: path)
  559. if (url.pathExtension == "pdf") || url.pathExtension == "PDF" {
  560. if !path.isPDFValid() {
  561. let alert = NSAlert()
  562. alert.alertStyle = .critical
  563. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  564. alert.runModal()
  565. return
  566. }
  567. }
  568. let infoDictionary = Bundle .main.infoDictionary!
  569. let majorVersion = infoDictionary["CFBundleShortVersionString"]
  570. DispatchQueue.main.async {
  571. self.showProgressWindow()
  572. self.progressController?.maxValue = Double(100)
  573. }
  574. timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(timerTick), userInfo: nil, repeats: true)
  575. KMRequestServerManager.manager.aiTranslationFileUpload(file: path, version: majorVersion as! String) { [unowned self] success, result in
  576. if success {
  577. let result: NSDictionary = result!.result
  578. let fileKey = result["fileKey"]
  579. let fileName = result["fileName"]
  580. let pageCount = result["pageCount"]
  581. if fileKey != nil {
  582. self.fileTranslateHandle(fileKey as! String)
  583. }
  584. } else {
  585. let result: String = result!.message
  586. DispatchQueue.main.async {
  587. self.hiddenProgressWindow()
  588. self.aiTranslationViewController.errorView.isHidden = false
  589. self.aiTranslationViewController.errorLabel.stringValue = result
  590. }
  591. }
  592. }
  593. }
  594. }
  595. func fileTranslateHandle(_ fileKey: String) -> Void {
  596. let infoDictionary = Bundle .main.infoDictionary!
  597. let majorVersion = infoDictionary["CFBundleShortVersionString"]
  598. let languageArr = UserDefaults.standard.array(forKey: "KMAITranslationLanguageArrayKey1") as? [String] ?? [NSLocalizedString("Automatic", comment: ""), NSLocalizedString("English", comment: "")]
  599. let language1 = self.aiTranslationViewController.languageAbbreviation(languageArr[0])
  600. let language2 = self.aiTranslationViewController.languageAbbreviation(languageArr[1])
  601. KMRequestServerManager.manager.aiTranslationFileTranslateHandle(fileKey: fileKey, from: language1, to: language2, version: majorVersion as! String) { success, result in
  602. if success {
  603. let result: NSDictionary = result!.result
  604. let fileUrl: String = result["fileUrl"] as! String
  605. let downFileUrl: String = result["downFileUrl"] as! String
  606. let ossDownUrl: String = result["ossDownUrl"] as! String
  607. let fileName: String = result["fileName"] as! String
  608. let downFileName: String = result["downFileName"] as! String
  609. let from: String = result["from"] as! String
  610. let to: String = result["to"] as! String
  611. self.downloadFile(filePath: ossDownUrl, downFileName: downFileName)
  612. } else {
  613. let result: String = result!.message
  614. DispatchQueue.main.async {
  615. self.hiddenProgressWindow()
  616. self.aiTranslationViewController.errorView.isHidden = false
  617. self.aiTranslationViewController.errorLabel.stringValue = result
  618. }
  619. }
  620. }
  621. }
  622. func downloadFile(filePath: String, downFileName: String) -> Void {
  623. guard let fileURL = URL(string: filePath) else {
  624. let alert = NSAlert()
  625. alert.alertStyle = .critical
  626. alert.messageText = NSLocalizedString("Invalid file link", comment: "")
  627. alert.runModal()
  628. return
  629. }
  630. let destinationURL = FileManager.default.temporaryDirectory.appendingPathComponent(downFileName)
  631. if FileManager.default.fileExists(atPath: destinationURL.path) {
  632. do {
  633. try FileManager.default.removeItem(at: destinationURL)
  634. KMPrint("删除旧文件成功")
  635. } catch {
  636. KMPrint("删除旧文件失败:\(error)")
  637. }
  638. }
  639. let sessionConfiguration = URLSessionConfiguration.default
  640. let session = URLSession(configuration: sessionConfiguration)
  641. let downloadTask = session.downloadTask(with: fileURL) { (tempLocalURL, response, error) in
  642. if let error = error {
  643. let alert = NSAlert()
  644. alert.alertStyle = .critical
  645. alert.messageText = String(format: "%@:\(error)", NSLocalizedString("Download failed", comment: ""))
  646. alert.runModal()
  647. return
  648. }
  649. guard let tempLocalURL = tempLocalURL else {
  650. let alert = NSAlert()
  651. alert.alertStyle = .critical
  652. alert.messageText = NSLocalizedString("Invalid temporary directory", comment: "")
  653. alert.runModal()
  654. return
  655. }
  656. DispatchQueue.main.async {
  657. self.hiddenProgressWindow()
  658. }
  659. do {
  660. try FileManager.default.moveItem(at: tempLocalURL, to: destinationURL)
  661. NSDocumentController.shared.openDocument(withContentsOf: destinationURL, display: true) { document, documentWasAlreadyOpen, error in
  662. if error != nil {
  663. NSApp.presentError(error!)
  664. } else {
  665. }
  666. }
  667. } catch {
  668. let alert = NSAlert()
  669. alert.alertStyle = .critical
  670. alert.messageText = String(format: "%@:\(error)", NSLocalizedString("Failed to save file", comment: ""))
  671. alert.runModal()
  672. }
  673. }
  674. downloadTask.resume()
  675. }
  676. override func otherMouseDown(with event: NSEvent) {
  677. if historyFileViewController.selectFiles.count > 0 {
  678. let eventPoint = event.locationInWindow as NSPoint
  679. let x = eventPoint.x - 270.0
  680. if x >= 0 {
  681. let point = NSPoint(x: x, y: eventPoint.y)
  682. let historyPoint = historyFileViewController.historyFileCollectionView.convert(eventPoint, from: nil)
  683. var indexPath: IndexPath? = nil
  684. if historyFileViewController.showMode == .List {
  685. let rowIndex = historyFileViewController.historyFileTableView.row(at: historyPoint)
  686. // 查找列索引
  687. let columnIndex = historyFileViewController.historyFileTableView.column(at: point)
  688. // 使用行和列索引创建 indexPath
  689. if rowIndex != -1 {
  690. indexPath = IndexPath(item: columnIndex, section: rowIndex)
  691. }
  692. } else {
  693. indexPath = historyFileViewController.historyFileCollectionView.indexPathForItem(at: historyPoint)
  694. }
  695. if (historyFileViewController.historyFileCollectionView.frame.contains(point) ||
  696. historyFileViewController.historyFileTableView.frame.contains(point) ||
  697. historyFileViewController.deleteBox.frame.contains(point) ||
  698. historyFileViewController.listBox.frame.contains(point) ||
  699. historyFileViewController.thumbnailBox.frame.contains(point)) && indexPath != nil {
  700. } else {
  701. self.historyFileViewController.selectFiles.removeAll()
  702. self.historyFileViewController.selectFiles_shift.removeAll()
  703. if self.historyFileViewController.showMode == .Thumbnail {
  704. self.historyFileViewController.historyFileCollectionView.reloadData()
  705. } else {
  706. self.historyFileViewController.historyFileTableView.reloadData()
  707. }
  708. }
  709. } else {
  710. self.historyFileViewController.selectFiles.removeAll()
  711. self.historyFileViewController.selectFiles_shift.removeAll()
  712. if self.historyFileViewController.showMode == .Thumbnail {
  713. self.historyFileViewController.historyFileCollectionView.reloadData()
  714. } else {
  715. self.historyFileViewController.historyFileTableView.reloadData()
  716. }
  717. }
  718. }
  719. }
  720. // MARK: PDF Tools
  721. // 插入
  722. func insertPageAction(_ pdfDocument: CPDFDocument, _ password: String, _ pages: [CPDFPage], _ indexPage: Int) -> Void {
  723. if indexPage >= 0 {
  724. let insertPages: [CPDFPage] = pages
  725. for i in 0...insertPages.count-1 {
  726. let page = pages[i]
  727. // FIXME: 待底层库修改,使用 insertPageObject 插入,插入位置变为文档最后,暂用 insertPage 代替
  728. pdfDocument.insertPageObject(page, at: UInt(indexPage + i))
  729. }
  730. self.savePDFDocument(pdfDocument, password: password)
  731. }
  732. }
  733. func extractPageAction(_ pdfDocument: CPDFDocument, _ pages: [CPDFPage], _ oneDocumentPerPage: Bool, _ isDeletePage: Bool) -> Void {
  734. if pages.count < 1 {
  735. let alert = NSAlert()
  736. alert.alertStyle = .critical
  737. alert.messageText = NSLocalizedString("Please select two or more pages first to organize.", comment: "")
  738. alert.runModal()
  739. return
  740. }
  741. if !oneDocumentPerPage {
  742. let fileName = pdfDocument.getFileNameAccordingSelctPages(pages)
  743. let outputSavePanel = NSSavePanel()
  744. outputSavePanel.allowedFileTypes = ["pdf"]
  745. outputSavePanel.nameFieldStringValue = fileName
  746. outputSavePanel.beginSheetModal(for: self.view.window!) { result in
  747. if result == .OK {
  748. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  749. let saveFilePath = outputSavePanel.url?.path
  750. DispatchQueue.global().async {
  751. var pdf = CPDFDocument.init()
  752. let success = (pdf!.extractAsOneDocument(withPages: pages, savePath: saveFilePath)) as Bool
  753. DispatchQueue.main.async {
  754. if success {
  755. let workspace = NSWorkspace.shared
  756. let url = URL(fileURLWithPath: saveFilePath!)
  757. workspace.activateFileViewerSelecting([url])
  758. if isDeletePage {
  759. for page in pages {
  760. let indexPage = pdfDocument.index(for: page)
  761. pdfDocument.removePage(at: indexPage)
  762. }
  763. }
  764. }
  765. }
  766. }
  767. }
  768. }
  769. }
  770. } else {
  771. let panel = NSOpenPanel()
  772. panel.canChooseFiles = false
  773. panel.canChooseDirectories = true
  774. panel.canCreateDirectories = true
  775. panel.allowsMultipleSelection = false
  776. panel.beginSheetModal(for: self.view.window!) { result in
  777. if result == .OK {
  778. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  779. let outputURL = panel.url
  780. DispatchQueue.global().async {
  781. let folderName = String(pdfDocument.documentURL!.lastPathComponent.split(separator: ".")[0]) + "_extract"
  782. var filePath = URL(fileURLWithPath: outputURL!.path).appendingPathComponent(folderName).path
  783. var i = 1
  784. let testFilePath = filePath
  785. while FileManager.default.fileExists(atPath: filePath) {
  786. filePath = testFilePath + "\(i)"
  787. i += 1
  788. }
  789. try? FileManager.default.createDirectory(atPath: filePath, withIntermediateDirectories: false, attributes: nil)
  790. let successArray = pdfDocument.extractPerPageDocument(withPages: pages, folerPath: filePath)
  791. DispatchQueue.main.async {
  792. if successArray!.count > 0 {
  793. NSWorkspace.shared.activateFileViewerSelecting(successArray!)
  794. if !isDeletePage {
  795. for page in pages {
  796. let indexPage = pdfDocument.index(for: page)
  797. pdfDocument.removePage(at: indexPage)
  798. }
  799. }
  800. }
  801. }
  802. }
  803. }
  804. }
  805. }
  806. }
  807. }
  808. // MARK: 快捷工具 Action
  809. func fastToolDidSelectAllTools() {
  810. // 首页 快捷工具 Tools按钮
  811. refreshRightBoxUI(.PDFTools)
  812. }
  813. func fastTool_Batch() { // Batch
  814. // KMBatchWindowController.openFile(nil, .Batch)
  815. if !IAPProductsManager.default().isAvailableAllFunction(){
  816. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  817. return
  818. }
  819. let batchWindowController = KMBatchOperateWindowController.sharedWindowController
  820. batchWindowController.window?.makeKeyAndOrderFront("")
  821. }
  822. func fastTool_OCR() { // OCR
  823. // KMOCRWindowController.openFiles(window: self.view.window!)
  824. if !IAPProductsManager.default().isAvailableAllFunction(){
  825. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  826. return
  827. }
  828. let openPanel = NSOpenPanel()
  829. var arr = KMImageToPDFMethod.supportedImageTypes()
  830. arr.append("pdf")
  831. openPanel.allowedFileTypes = arr
  832. //MARK: 允许多选还是单选,如果是付费用户允许多选
  833. openPanel.allowsMultipleSelection = false
  834. openPanel.beginSheetModal(for: NSWindow.currentWindow()) { [self] (result) in
  835. if result == NSApplication.ModalResponse.OK {
  836. quickOcr(urls: openPanel.urls)
  837. }
  838. }
  839. }
  840. func quickOcr(urls: Array<URL>) {
  841. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.3) {
  842. var document: CPDFDocument?
  843. for fileURL in urls {
  844. if fileURL.lastPathComponent.pathExtension == "pdf"{
  845. document = CPDFDocument(url: fileURL)
  846. }else{
  847. document = CPDFDocument()
  848. let image = NSImage(contentsOfFile: fileURL.path)
  849. _ = document?.km_insertPage(image!.size, withImage: fileURL.path, at: 0)
  850. }
  851. break
  852. }
  853. if document == nil{
  854. let alert = NSAlert()
  855. alert.alertStyle = .critical
  856. alert.messageText = KMLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", nil)
  857. alert.beginSheetModal(for: NSApp.mainWindow!) { (response) in
  858. if response == .alertFirstButtonReturn {
  859. // Handle cancel action
  860. }
  861. }
  862. return
  863. }
  864. let com = KMOCRPDFWindowController(cpdfDocument: document!, pwd: document!.password)
  865. self.km_beginSheet(windowC: com)
  866. }
  867. }
  868. func fastTool_ConvertPDF() { // 转换PDF
  869. // KMBatchWindowController.openFile(nil, .ConvertPDF)
  870. let openPanel = NSOpenPanel()
  871. var arr = KMImageToPDFMethod.supportedImageTypes()
  872. arr.append("pdf")
  873. openPanel.allowedFileTypes = ["pdf","PDF"]
  874. //MARK: 允许多选还是单选,如果是付费用户允许多选
  875. openPanel.allowsMultipleSelection = false
  876. openPanel.beginSheetModal(for: self.view.window!) { [self] (result) in
  877. if result == NSApplication.ModalResponse.OK {
  878. quickConvertPdf(urls: openPanel.urls, type: .WordAdvance)
  879. }
  880. }
  881. }
  882. func quickConvertPdf(urls: Array<URL>, type: KMConvertWithPDFType) {
  883. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.3) {
  884. var arr: Array<KMBatchOperateFile> = Array()
  885. for fileURL in urls {
  886. let img = NSImage(contentsOfFile: fileURL.path)
  887. if self.isDamageImage(image: img, path: fileURL.path) {
  888. let alert = NSAlert()
  889. alert.alertStyle = .critical
  890. alert.messageText = String(format: KMLocalizedString("The file \"%@\" could not be opened.", nil), fileURL.path.lastPathComponent)
  891. alert.informativeText = NSLocalizedString("It may be damaged or use a file format that PDF Reader Pro doesn’t recognize.", comment: "")
  892. alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  893. alert.beginSheetModal(for: NSApp.mainWindow!) { (response) in
  894. if response == .alertFirstButtonReturn {
  895. // Handle cancel action
  896. }
  897. }
  898. continue
  899. }
  900. let file = KMBatchOperateFile(filePath: fileURL.path, type: .Convert)
  901. arr.append(file)
  902. }
  903. let baseWindowController = KMBatchOperateBaseWindowController(windowNibName: "KMBatchOperateBaseWindowController")
  904. if #available(macOS 10.13, *) {
  905. baseWindowController.window?.makeKeyAndOrderFront(nil)
  906. } else {
  907. baseWindowController.showWindow(nil)
  908. }
  909. if arr.count > 0 {
  910. baseWindowController.checkNeedPasswordSwitchToOperateType(operateType: .Convert, files: arr)
  911. }
  912. baseWindowController.switchToConvertType(convertType: type)
  913. }
  914. }
  915. func fastTool_ImageToPDF() { // 图片转PDF
  916. // KMImageToPDFWindowController.openFiles(window: NSApp.mainWindow!)
  917. let openPanel = NSOpenPanel()
  918. openPanel.allowedFileTypes = KMImageToPDFMethod.supportedImageTypes()
  919. //MARK: 允许多选还是单选,如果是付费用户允许多选
  920. openPanel.allowsMultipleSelection = true
  921. openPanel.message = KMLocalizedString("Select images to create a new document. To select multiple files press cmd ⌘ button on keyboard and click on the target files one by one.", nil)
  922. // openPanel.canChooseFiles = false
  923. // openPanel.canChooseDirectories = true
  924. // openPanel.canCreateDirectories = true
  925. if IAPProductsManager.default().isAvailableAllFunction(){
  926. openPanel.allowsMultipleSelection = true
  927. }else{
  928. openPanel.allowsMultipleSelection = false
  929. }
  930. openPanel.beginSheetModal(for: NSWindow.currentWindow()) { [self] (result) in
  931. if result == NSApplication.ModalResponse.OK {
  932. openImageToPdfWindow(urls: openPanel.urls)
  933. }
  934. }
  935. }
  936. func openImageToPdfWindow(urls: Array<URL>) {
  937. var arr: Array<KMBatchOperateFile> = Array()
  938. for fileURL in urls {
  939. let img = NSImage(contentsOfFile: fileURL.path)
  940. if self.isDamageImage(image: img, path: fileURL.path) {
  941. let alert = NSAlert()
  942. alert.alertStyle = .critical
  943. alert.messageText = String(format: KMLocalizedString("The file \"%@\" could not be opened.", nil), fileURL.path.lastPathComponent)
  944. alert.informativeText = NSLocalizedString("It may be damaged or use a file format that PDF Reader Pro doesn’t recognize.", comment: "")
  945. alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  946. alert.beginSheetModal(for: NSApp.mainWindow!) { (response) in
  947. if response == .alertFirstButtonReturn {
  948. // Handle cancel action
  949. }
  950. }
  951. continue
  952. }
  953. let file = KMBatchOperateFile(filePath: fileURL.path, type: .CreatePDF)
  954. arr.append(file)
  955. }
  956. let baseWindowController = KMBatchOperateBaseWindowController(windowNibName: "KMBatchOperateBaseWindowController")
  957. if #available(macOS 10.13, *) {
  958. baseWindowController.window?.makeKeyAndOrderFront(nil)
  959. } else {
  960. baseWindowController.showWindow(nil)
  961. }
  962. if arr.count > 0 {
  963. baseWindowController.checkNeedPasswordSwitchToOperateType(operateType: .CreatePDF, files: arr)
  964. }
  965. }
  966. func isDamageImage(image: NSImage?, path: String) -> Bool {
  967. if (image == nil) {
  968. return true
  969. }
  970. let addImageAnnotation = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).last!.appendingPathComponent(Bundle.main.bundleIdentifier!).appendingPathComponent("addImageAnnotation")
  971. // let addImageAnnotation = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.applicationSupportDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).last?.stringByAppendingPathComponent(Bundle.main.bundleIdentifier!).stringByAppendingPathComponent("addImageAnnotation")
  972. if !FileManager.default.fileExists(atPath: addImageAnnotation.path) {
  973. try? FileManager.default.createDirectory(atPath: addImageAnnotation.path, withIntermediateDirectories: false, attributes: nil)
  974. }
  975. guard let data = image!.tiffRepresentation else { return false }
  976. guard let imageRep = NSBitmapImageRep(data: data) else { return false }
  977. imageRep.size = image!.size
  978. var imageData: Data?
  979. if path.lowercased() == "png" {
  980. imageData = imageRep.representation(using: .png, properties: [:])
  981. } else {
  982. imageData = imageRep.representation(using: .jpeg, properties: [:])
  983. }
  984. let rPath: URL = addImageAnnotation.appendingPathComponent(tagString()).appendingPathExtension("png")
  985. if let data = imageData {
  986. try?data.write(to: rPath)
  987. return false
  988. } else {
  989. return true
  990. }
  991. }
  992. func tagString() -> String {
  993. let dateFormatter = DateFormatter()
  994. dateFormatter.dateFormat = "yyMMddHHmmss"
  995. let currentDate = Date()
  996. let formattedDate = dateFormatter.string(from: currentDate)
  997. let randomNum = Int(arc4random_uniform(10000))
  998. let str = String(format: "%@%04d", dateFormatter.string(from: Date()),randomNum)
  999. return str//"(formattedDate)(String(format: "%04d", randomNum))"
  1000. }
  1001. func fastTool_MergePDF() { // MergePDF
  1002. Task { @MainActor in
  1003. self.km_open_pdf_merge()
  1004. }
  1005. }
  1006. func km_open_pdf_merge() {
  1007. DispatchQueue.main.async {
  1008. let windowController = KMMergeWindowController(windowNibName: "KMMergeWindowController")
  1009. self.currentWindowController = windowController
  1010. windowController.cancelAction = { [unowned self] controller in
  1011. self.view.window?.endSheet((self.currentWindowController!.window)!)
  1012. self.currentWindowController = nil
  1013. }
  1014. self.view.window?.beginSheet(windowController.window!)
  1015. }
  1016. }
  1017. func fastTool_Compression() { // 压缩
  1018. let openPanel = NSOpenPanel()
  1019. openPanel.allowedFileTypes = ["pdf","PDF"]
  1020. //MARK: 允许多选还是单选,如果是付费用户允许多选
  1021. openPanel.allowsMultipleSelection = false
  1022. openPanel.beginSheetModal(for: NSWindow.currentWindow()) { [self] (result) in
  1023. if result == NSApplication.ModalResponse.OK {
  1024. quickCompressPdf(urls: openPanel.urls)
  1025. }
  1026. }
  1027. }
  1028. func quickCompressPdf(urls: Array<URL>) {
  1029. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.3) {
  1030. var arr: Array<KMBatchOperateFile> = Array()
  1031. for fileURL in urls {
  1032. let file = KMBatchOperateFile(filePath: fileURL.path, type: .Compress)
  1033. arr.append(file)
  1034. }
  1035. let baseWindowController = KMBatchOperateBaseWindowController(windowNibName: "KMBatchOperateBaseWindowController")
  1036. if #available(macOS 10.13, *) {
  1037. baseWindowController.window?.makeKeyAndOrderFront(nil)
  1038. } else {
  1039. baseWindowController.showWindow(nil)
  1040. }
  1041. if arr.count > 0 {
  1042. baseWindowController.checkNeedPasswordSwitchToOperateType(operateType: .Compress, files: arr)
  1043. }
  1044. }
  1045. }
  1046. func km_secure_openPanel_compress() {
  1047. DispatchQueue.main.async {
  1048. NSOpenPanel.km_secure_openPanel(window: self.view.window!) { url, result, passowrd in
  1049. if (url == nil) {
  1050. return
  1051. }
  1052. if (result != nil && result! == .cancel) {
  1053. return
  1054. }
  1055. self.showCompressWindow(url!, passowrd)
  1056. }
  1057. }
  1058. }
  1059. func showCompressWindow(_ url: URL, _ password: String?) {
  1060. // Task { @MainActor in
  1061. // let windowController = KMCompressWindowController(windowNibName: "KMCompressWindowController")
  1062. // windowController.documentURL = url
  1063. // windowController.password = password
  1064. //
  1065. // windowController.itemClick = { [weak self] _ in
  1066. // self?.km_endSheet()
  1067. // }
  1068. //
  1069. // windowController.resultCallback = { [weak self] result, openDocument, fileURL, _ in
  1070. // if result {
  1071. // self?.km_endSheet()
  1072. // if openDocument {
  1073. // NSDocumentController.shared.km_safe_openDocument(withContentsOf: fileURL, display: true) { _, _, _ in
  1074. //
  1075. // }
  1076. // } else {
  1077. // NSWorkspace.shared.activateFileViewerSelecting([fileURL])
  1078. // }
  1079. // } else {
  1080. // let alert = NSAlert()
  1081. // alert.messageText = NSLocalizedString("Compress Faild", comment: "")
  1082. // alert.runModal()
  1083. // }
  1084. // }
  1085. // self.km_beginSheet(windowC: windowController)
  1086. // }
  1087. }
  1088. func fastTool_Security() { // 安全
  1089. if !IAPProductsManager.default().isAvailableAllFunction(){
  1090. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  1091. return
  1092. }
  1093. let openPanel = NSOpenPanel()
  1094. openPanel.allowedFileTypes = ["pdf","PDF"]
  1095. //MARK: 允许多选还是单选,如果是付费用户允许多选
  1096. openPanel.allowsMultipleSelection = true
  1097. openPanel.message = KMLocalizedString("To select multiple files press cmd ⌘ button on keyboard and click on the target files one by one.", nil)
  1098. openPanel.beginSheetModal(for: NSWindow.currentWindow()) { [self] (result) in
  1099. if result == NSApplication.ModalResponse.OK {
  1100. quickPassword(urls: openPanel.urls)
  1101. }
  1102. }
  1103. }
  1104. func quickPassword(urls: Array<URL>) {
  1105. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.3) {
  1106. var arr: Array<KMBatchOperateFile> = Array()
  1107. for fileURL in urls {
  1108. let file = KMBatchOperateFile(filePath: fileURL.path, type: KMBatchQuickActionManager.defaultManager.actionType == .add ? .AddPassword : .RemovePassword)
  1109. arr.append(file)
  1110. }
  1111. let baseWindowController = KMBatchOperateBaseWindowController(windowNibName: "KMBatchOperateBaseWindowController")
  1112. if #available(macOS 10.13, *) {
  1113. baseWindowController.window?.makeKeyAndOrderFront(nil)
  1114. } else {
  1115. baseWindowController.showWindow(nil)
  1116. }
  1117. if arr.count > 0 {
  1118. baseWindowController.checkNeedPasswordSwitchToOperateType(operateType: KMBatchQuickActionManager.defaultManager.actionType == .add ? .AddPassword : .RemovePassword, files: arr)
  1119. }
  1120. }
  1121. }
  1122. func fastTool_FileCompare() { // 文件对比
  1123. if !IAPProductsManager.default().isAvailableAllFunction(){
  1124. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  1125. return
  1126. }
  1127. let openPanel = NSOpenPanel()
  1128. openPanel.allowsMultipleSelection = false
  1129. openPanel.allowedFileTypes = ["pdf"]
  1130. openPanel.beginSheetModal(for: NSApp.mainWindow!) { result in
  1131. if result == .cancel {
  1132. return
  1133. }
  1134. if !openPanel.url!.path.isPDFValid() {
  1135. let alert = NSAlert()
  1136. alert.alertStyle = .critical
  1137. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  1138. alert.runModal()
  1139. return
  1140. }
  1141. KMBaseWindowController.checkPassword(url: URL(fileURLWithPath: openPanel.url!.path)) { [unowned self] success, resultPassword in
  1142. if success {
  1143. DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
  1144. let controller = KMCompareWindowController(windowNibName: "KMCompareWindowController")
  1145. self.currentWindowController = controller
  1146. controller.password = resultPassword
  1147. controller.filePath = openPanel.url!.path
  1148. controller.cancelAction = { [unowned self] contr in
  1149. self.view.window?.endSheet((controller.window)!)
  1150. // self.currentWindowController = nil
  1151. }
  1152. controller.contentComplete = { [unowned self] controller, pdfCompareContent, result, oldDocument, document in
  1153. DispatchQueue.main.async {
  1154. self.view.window?.endSheet((controller.window)!)
  1155. // self.currentWindowController = nil
  1156. self.openContentCompareVC(with: pdfCompareContent, results: result, oldDocument: oldDocument, document: document)
  1157. }
  1158. }
  1159. controller.coveringComplete = { [unowned self] controller, document in
  1160. self.view.window?.endSheet((controller.window)!)
  1161. // self.currentWindowController = nil
  1162. self.openCoveringCompareVC(with: document)
  1163. }
  1164. // if index == 1 {
  1165. controller.fileType = .content
  1166. // } else {
  1167. // controller.fileType = .coverting
  1168. // }
  1169. NSWindow.currentWindow().beginSheet(controller.window!)
  1170. }
  1171. } else {
  1172. }
  1173. }
  1174. }
  1175. }
  1176. func fastTool_PDFToPPT() {
  1177. // self.showConvertWindow(type: .ppt)
  1178. let openPanel = NSOpenPanel()
  1179. openPanel.allowedFileTypes = ["pdf","PDF"]
  1180. //MARK: 允许多选还是单选,如果是付费用户允许多选
  1181. openPanel.allowsMultipleSelection = false
  1182. openPanel.beginSheetModal(for: NSWindow.currentWindow()) { [self] (result) in
  1183. if result == NSApplication.ModalResponse.OK {
  1184. quickConvertPdf(urls: openPanel.urls, type: .PowerPoint)
  1185. }
  1186. }
  1187. }
  1188. func fastTool_PDFToExcel() {
  1189. // self.showConvertWindow(type: .excel)
  1190. let openPanel = NSOpenPanel()
  1191. openPanel.allowedFileTypes = ["pdf","PDF"]
  1192. //MARK: 允许多选还是单选,如果是付费用户允许多选
  1193. openPanel.allowsMultipleSelection = false
  1194. openPanel.beginSheetModal(for: NSWindow.currentWindow()) { [self] (result) in
  1195. if result == NSApplication.ModalResponse.OK {
  1196. quickConvertPdf(urls: openPanel.urls, type: .Excel)
  1197. }
  1198. }
  1199. }
  1200. func fastTool_PDFToWord() { // PDF转Word
  1201. // self.showConvertWindow(type: .word)
  1202. fastTool_ConvertPDF()
  1203. }
  1204. func fastTool_PDFToImage() { // PDF转图片
  1205. self.showConvertWindow(type: .image)
  1206. }
  1207. func fastTool_Watermark() { // 水印
  1208. // KMBatchWindowController.openFile(nil, .Watermark)
  1209. if !IAPProductsManager.default().isAvailableAllFunction(){
  1210. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  1211. return
  1212. }
  1213. let openPanel = NSOpenPanel()
  1214. openPanel.allowedFileTypes = ["pdf","PDF"]
  1215. //MARK: 允许多选还是单选,如果是付费用户允许多选
  1216. openPanel.allowsMultipleSelection = false
  1217. openPanel.beginSheetModal(for: NSWindow.currentWindow()) { [self] (result) in
  1218. if result == NSApplication.ModalResponse.OK {
  1219. quickWaterMark(urls: openPanel.urls)
  1220. }
  1221. }
  1222. }
  1223. func quickWaterMark(urls: Array<URL>) {
  1224. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.3) {
  1225. var arr: Array<KMBatchOperateFile> = Array()
  1226. for fileURL in urls {
  1227. let pdf = CPDFDocument(url: fileURL)
  1228. if !pdf!.allowsPrinting || !pdf!.allowsCopying {
  1229. let alert = NSAlert()
  1230. alert.alertStyle = .critical
  1231. alert.messageText = NSLocalizedString("This is a secured document. Editing is not permitted.", comment: "")
  1232. alert.runModal()
  1233. return
  1234. }
  1235. let file = KMBatchOperateFile(filePath: fileURL.path, type: KMBatchQuickActionManager.defaultManager.actionType == .add ? .AddWatermark : .RemoveWatermark)
  1236. arr.append(file)
  1237. }
  1238. let baseWindowController = KMBatchOperateBaseWindowController(windowNibName: "KMBatchOperateBaseWindowController")
  1239. if #available(macOS 10.13, *) {
  1240. baseWindowController.window?.makeKeyAndOrderFront(nil)
  1241. } else {
  1242. baseWindowController.showWindow(nil)
  1243. }
  1244. if arr.count > 0 {
  1245. baseWindowController.checkNeedPasswordSwitchToOperateType(operateType: KMBatchQuickActionManager.defaultManager.actionType == .add ? .AddWatermark : .RemoveWatermark, files: arr)
  1246. }
  1247. }
  1248. }
  1249. func fastTool_Background() { // 背景
  1250. // KMBatchWindowController.openFile(nil, .Background)
  1251. if !IAPProductsManager.default().isAvailableAllFunction(){
  1252. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  1253. return
  1254. }
  1255. let openPanel = NSOpenPanel()
  1256. openPanel.allowedFileTypes = ["pdf","PDF"]
  1257. //MARK: 允许多选还是单选,如果是付费用户允许多选
  1258. openPanel.allowsMultipleSelection = false
  1259. openPanel.beginSheetModal(for: NSWindow.currentWindow()) { [self] (result) in
  1260. if result == NSApplication.ModalResponse.OK {
  1261. quickBackgroudMark(urls: openPanel.urls)
  1262. }
  1263. }
  1264. }
  1265. func quickBackgroudMark(urls: Array<URL>) {
  1266. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.3) {
  1267. var arr: Array<KMBatchOperateFile> = Array()
  1268. for fileURL in urls {
  1269. let pdf = CPDFDocument(url: fileURL)
  1270. if !pdf!.allowsPrinting || !pdf!.allowsCopying {
  1271. let alert = NSAlert()
  1272. alert.alertStyle = .critical
  1273. alert.messageText = NSLocalizedString("This is a secured document. Editing is not permitted.", comment: "")
  1274. alert.runModal()
  1275. return
  1276. }
  1277. let file = KMBatchOperateFile(filePath: fileURL.path, type: KMBatchQuickActionManager.defaultManager.actionType == .add ? .AddBackground : .RemoveBackground)
  1278. arr.append(file)
  1279. }
  1280. let baseWindowController = KMBatchOperateBaseWindowController(windowNibName: "KMBatchOperateBaseWindowController")
  1281. if #available(macOS 10.13, *) {
  1282. baseWindowController.window?.makeKeyAndOrderFront(nil)
  1283. } else {
  1284. baseWindowController.showWindow(nil)
  1285. }
  1286. if arr.count > 0 {
  1287. baseWindowController.checkNeedPasswordSwitchToOperateType(operateType: KMBatchQuickActionManager.defaultManager.actionType == .add ? .AddBackground : .RemoveBackground, files: arr)
  1288. }
  1289. }
  1290. }
  1291. func fastTool_HeaderAndFooter() { // 页眉页脚
  1292. // KMBatchWindowController.openFile(nil, .HeaderAndFooter)
  1293. if !IAPProductsManager.default().isAvailableAllFunction(){
  1294. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  1295. return
  1296. }
  1297. let openPanel = NSOpenPanel()
  1298. openPanel.allowedFileTypes = ["pdf","PDF"]
  1299. //MARK: 允许多选还是单选,如果是付费用户允许多选
  1300. openPanel.allowsMultipleSelection = false
  1301. openPanel.beginSheetModal(for: NSWindow.currentWindow()) { [self] (result) in
  1302. if result == NSApplication.ModalResponse.OK {
  1303. quickHeaderAndFooterMark(urls: openPanel.urls)
  1304. }
  1305. }
  1306. }
  1307. func quickHeaderAndFooterMark(urls: Array<URL>) {
  1308. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.3) {
  1309. var arr: Array<KMBatchOperateFile> = Array()
  1310. for fileURL in urls {
  1311. let pdf = CPDFDocument(url: fileURL)
  1312. if !pdf!.allowsPrinting || !pdf!.allowsCopying {
  1313. let alert = NSAlert()
  1314. alert.alertStyle = .critical
  1315. alert.messageText = NSLocalizedString("This is a secured document. Editing is not permitted.", comment: "")
  1316. alert.runModal()
  1317. return
  1318. }
  1319. let file = KMBatchOperateFile(filePath: fileURL.path, type: KMBatchQuickActionManager.defaultManager.actionType == .add ? .AddHeaderFooter : .RemoveHeaderFooter)
  1320. arr.append(file)
  1321. }
  1322. let baseWindowController = KMBatchOperateBaseWindowController(windowNibName: "KMBatchOperateBaseWindowController")
  1323. if #available(macOS 10.13, *) {
  1324. baseWindowController.window?.makeKeyAndOrderFront(nil)
  1325. } else {
  1326. baseWindowController.showWindow(nil)
  1327. }
  1328. if arr.count > 0 {
  1329. baseWindowController.checkNeedPasswordSwitchToOperateType(operateType: KMBatchQuickActionManager.defaultManager.actionType == .add ? .AddHeaderFooter : .RemoveHeaderFooter, files: arr)
  1330. }
  1331. }
  1332. }
  1333. func fastTool_BatesCode() { // 贝茨码
  1334. // KMBatchWindowController.openFile(nil, .BatesCode)
  1335. if !IAPProductsManager.default().isAvailableAllFunction(){
  1336. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  1337. return
  1338. }
  1339. let openPanel = NSOpenPanel()
  1340. openPanel.allowedFileTypes = ["pdf","PDF"]
  1341. //MARK: 允许多选还是单选,如果是付费用户允许多选
  1342. openPanel.allowsMultipleSelection = false
  1343. openPanel.beginSheetModal(for: NSWindow.currentWindow()) { [self] (result) in
  1344. if result == NSApplication.ModalResponse.OK {
  1345. quickBatesNumberMark(urls: openPanel.urls)
  1346. }
  1347. }
  1348. }
  1349. func quickBatesNumberMark(urls: Array<URL>) {
  1350. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.3) {
  1351. var arr: Array<KMBatchOperateFile> = Array()
  1352. for fileURL in urls {
  1353. let pdf = CPDFDocument(url: fileURL)
  1354. if !pdf!.allowsPrinting || !pdf!.allowsCopying {
  1355. let alert = NSAlert()
  1356. alert.alertStyle = .critical
  1357. alert.messageText = NSLocalizedString("This is a secured document. Editing is not permitted.", comment: "")
  1358. alert.runModal()
  1359. return
  1360. }
  1361. let file = KMBatchOperateFile(filePath: fileURL.path, type: KMBatchQuickActionManager.defaultManager.actionType == .add ? .AddBates : .RemoveBates)
  1362. arr.append(file)
  1363. }
  1364. let baseWindowController = KMBatchOperateBaseWindowController(windowNibName: "KMBatchOperateBaseWindowController")
  1365. if #available(macOS 10.13, *) {
  1366. baseWindowController.window?.makeKeyAndOrderFront(nil)
  1367. } else {
  1368. baseWindowController.showWindow(nil)
  1369. }
  1370. if arr.count > 0 {
  1371. baseWindowController.checkNeedPasswordSwitchToOperateType(operateType: KMBatchQuickActionManager.defaultManager.actionType == .add ? .AddBates : .RemoveBates, files: arr)
  1372. }
  1373. }
  1374. }
  1375. func fastTool_Print() { // 打印
  1376. KMPrintWindowController.openFiles(window: self.view.window!)
  1377. }
  1378. func fastTool_BatchRemove() { // 批量移除
  1379. // KMBatchWindowController.openFile(nil, .BatchRemove)
  1380. }
  1381. func fastTool_Insert() { // 插入
  1382. if !IAPProductsManager.default().isAvailableAllFunction(){
  1383. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  1384. return
  1385. }
  1386. let openPanel = NSOpenPanel()
  1387. openPanel.prompt = NSLocalizedString("Insert", comment: "")
  1388. openPanel.allowsMultipleSelection = false
  1389. openPanel.allowedFileTypes = ["pdf"]
  1390. openPanel.beginSheetModal(for: NSApp.mainWindow!) { result in
  1391. if result == .OK {
  1392. // DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
  1393. // let insertWindowController: KMPDFInsertPageWindow = KMPDFInsertPageWindow.init(documentPath: openPanel.url!, toolType: .Insert)
  1394. // insertWindowController.beginSheetModal(for: self.view.window!) { pdfDocument, password, pages, indexPage in
  1395. // self.insertPageAction(pdfDocument, password, pages, indexPage)
  1396. // }
  1397. // }
  1398. // }
  1399. let windowC = KMPDFInsertWindowController(fileURL: openPanel.url!)
  1400. // [com beginSheetModalForWindow:[NSApp mainWindow] completionHandler:^(PDFDocument *pdfDocument, NSString *password, NSMutableArray<PDFPage *> *pages, NSInteger indexPage) {
  1401. // if (pdfDocument && indexPage >= 0) {
  1402. // [pdfDocument insertWithInsertPages:pages insertPageIndex:indexPage];
  1403. // [self savePDFDocument:pdfDocument password:password];
  1404. // }
  1405. // }];
  1406. windowC.callback = { [unowned self] idx, params in
  1407. if params.count >= 4 {
  1408. if let doc = params.first as? CPDFDocument {
  1409. // doc.insertWithInsertPages((params[2] as? [CPDFPage]) ?? [], insertPageIndex: params[3] as! Int)
  1410. self.savePDFDocument(doc, password: params[1] as? String ?? "")
  1411. }
  1412. }
  1413. self.km_endSheet()
  1414. }
  1415. self.km_beginSheet(windowC: windowC)
  1416. }
  1417. }
  1418. }
  1419. // func savePDFDocument(_ pdf: CPDFDocument, password: String?) {
  1420. //// KMProgressWindowController * vc = [[KMProgressWindowController alloc] init];
  1421. //// [NSApp beginSheet:[vc window] modalForWindow:[NSApp mainWindow] modalDelegate:nil didEndSelector:nil contextInfo:NULL];
  1422. //
  1423. // DispatchQueue.global().async {
  1424. // var isSuccessfully = false
  1425. // if (pdf.isEncrypted) {
  1426. // isSuccessfully = pdf.write(to: pdf.documentURL, withOptions: [.userPasswordOption : password ?? "", .ownerPasswordOption : password ?? ""])
  1427. // } else {
  1428. // isSuccessfully = pdf.write(to: pdf.documentURL)
  1429. // }
  1430. // if (!isSuccessfully) {
  1431. //// isSuccessfully = [pdf.dataRepresentation writeToURL:pdf.documentURL atomically:YES];
  1432. // try?pdf.dataRepresentation().write(to: pdf.documentURL)
  1433. // }
  1434. //
  1435. // Task { @MainActor in
  1436. //// [NSApp endSheet:vc.window];
  1437. //// [vc close];
  1438. //
  1439. // if (isSuccessfully) {
  1440. //// BOOL autoOpen = [[NSUserDefaults standardUserDefaults] boolForKey:KMAutoOpenDocumentKey];
  1441. //// if (autoOpen) {
  1442. //// [[NSDocumentController sharedDocumentController] openDocumentWithContentsOfURL:pdf.documentURL display:YES completionHandler:^(NSDocument * _Nullable document, BOOL documentWasAlreadyOpen, NSError * _Nullable error) {
  1443. ////
  1444. //// }];
  1445. //// } else {
  1446. // let workspace = NSWorkspace.shared
  1447. // let url = URL(fileURLWithPath: pdf.documentURL.path)
  1448. // workspace.activateFileViewerSelecting([url])
  1449. //// }
  1450. // } else {
  1451. // _ = await KMAlertTool.runModel(message: KMLocalizedString("Failed to insert page(s)!", nil))
  1452. // }
  1453. // }
  1454. // }
  1455. // }
  1456. func fastTool_BreakUp() { // 拆分
  1457. // [[FMTrackEventManager manager] trackEvent:@"Onbrd" withProperties:@{@"HP_Tools":@"Split"}];
  1458. //
  1459. // if (![IAPProductsManager defaultManager].isAvailableAllFunction) {
  1460. // [[KMPurchaseCompareWindowController sharedInstance] showWindow:nil];
  1461. // return;
  1462. // }
  1463. // self.isDragEntered = YES;
  1464. if !IAPProductsManager.default().isAvailableAllFunction(){
  1465. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  1466. return
  1467. }
  1468. let openPanel = NSOpenPanel()
  1469. openPanel.allowedFileTypes = ["pdf"]
  1470. openPanel.allowsMultipleSelection = false
  1471. openPanel.beginSheetModal(for: NSApp.mainWindow!) { result in
  1472. // self.isDragEntered = NO;
  1473. if result == .OK {
  1474. DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
  1475. let com = SplitWindowController(fileURL: openPanel.url!)
  1476. self.km_beginSheet(windowC: com)
  1477. }
  1478. }
  1479. }
  1480. }
  1481. func fastTool_Extract() { // 提取
  1482. let openPanel = NSOpenPanel()
  1483. openPanel.prompt = "提取"
  1484. openPanel.allowsMultipleSelection = false
  1485. openPanel.allowedFileTypes = ["pdf"]
  1486. openPanel.beginSheetModal(for: NSApp.mainWindow!) { result in
  1487. if result == .OK {
  1488. DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
  1489. let insertWindowController: KMPDFInsertPageWindow = KMPDFInsertPageWindow.init(documentPath: openPanel.url!, toolType: .Extract)
  1490. insertWindowController.beginSheetExtractModal(for: self.view.window!) { pdfDocument, pages, oneDocumentPerPage, isDeletePage in
  1491. self.extractPageAction(pdfDocument, pages, oneDocumentPerPage, isDeletePage)
  1492. }
  1493. }
  1494. }
  1495. }
  1496. }
  1497. func fastTool_MarkCipher() { // 标记密文
  1498. if !IAPProductsManager.default().isAvailableAllFunction(){
  1499. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  1500. return
  1501. }
  1502. let openPanel = NSOpenPanel()
  1503. openPanel.allowsMultipleSelection = false
  1504. openPanel.allowedFileTypes = ["pdf"]
  1505. openPanel.beginSheetModal(for: NSApp.mainWindow!) { result in
  1506. if result == .cancel {
  1507. return
  1508. }
  1509. if !openPanel.url!.path.isPDFValid() {
  1510. let alert = NSAlert()
  1511. alert.alertStyle = .critical
  1512. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  1513. alert.runModal()
  1514. return
  1515. }
  1516. DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
  1517. NSDocumentController.shared.openDocument(withContentsOf: openPanel.url!, display: true) { document, result, error in
  1518. if (error != nil) {
  1519. NSApp.presentError(error!)
  1520. return
  1521. }
  1522. let toolbar = (document as! KMMainDocument).mainViewController?.toolbarController
  1523. toolbar?.enterRedact()
  1524. }
  1525. }
  1526. }
  1527. }
  1528. func fastTool_AutomaticFormRecognition() { // 表单自动识别
  1529. let openPanel = NSOpenPanel()
  1530. openPanel.prompt = "表单自动识别"
  1531. openPanel.allowsMultipleSelection = false
  1532. openPanel.allowedFileTypes = ["pdf"]
  1533. openPanel.beginSheetModal(for: NSApp.mainWindow!) { result in
  1534. if result == .OK {
  1535. }
  1536. }
  1537. }
  1538. func fastTool_PageEdit() { // 页面编辑
  1539. let openPanel = NSOpenPanel()
  1540. openPanel.allowsMultipleSelection = false
  1541. openPanel.allowedFileTypes = ["pdf"]
  1542. openPanel.beginSheetModal(for: NSApp.mainWindow!) { result in
  1543. if result == .cancel {
  1544. return
  1545. }
  1546. if !openPanel.url!.path.isPDFValid() {
  1547. let alert = NSAlert()
  1548. alert.alertStyle = .critical
  1549. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  1550. alert.runModal()
  1551. return
  1552. }
  1553. if let pdf = CPDFDocument(url: openPanel.url!) {
  1554. if pdf.allowsCopying == false || pdf.allowsPrinting == false {
  1555. Task {
  1556. _ = await KMAlertTool.runModel(message: KMLocalizedString("This is a secured document. Editing is not permitted.", nil))
  1557. }
  1558. return
  1559. }
  1560. }
  1561. let windowC = KMPDFEditWindowController(filepath: openPanel.url!.path, password: nil)
  1562. windowC.startModal(nil)
  1563. }
  1564. }
  1565. func fastTool_printBooklet() {
  1566. if !IAPProductsManager.default().isAvailableAllFunction(){
  1567. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  1568. return
  1569. }
  1570. let openPanel = NSOpenPanel()
  1571. openPanel.allowsMultipleSelection = false
  1572. openPanel.allowedFileTypes = ["pdf"]
  1573. openPanel.beginSheetModal(for: NSApp.mainWindow!) { result in
  1574. if result == .cancel {
  1575. return
  1576. }
  1577. if !openPanel.url!.path.isPDFValid() {
  1578. let alert = NSAlert()
  1579. alert.alertStyle = .critical
  1580. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  1581. alert.runModal()
  1582. return
  1583. }
  1584. if let pdf = CPDFDocument(url: openPanel.url!) {
  1585. if pdf.allowsCopying == false || pdf.allowsPrinting == false {
  1586. Task {
  1587. _ = await KMAlertTool.runModel(message: KMLocalizedString("This is a secured document. Editing is not permitted.", nil))
  1588. }
  1589. return
  1590. }
  1591. }
  1592. DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
  1593. let pdfDocument = CPDFDocument(url: openPanel.url!)
  1594. KMPrintWindowController.showNewPrintWindowControll(inputDocument: pdfDocument, inputPageRange: KMPrintPageRange(), printType: .pamphlet)
  1595. }
  1596. }
  1597. }
  1598. func fastTool_printPoster() {
  1599. if !IAPProductsManager.default().isAvailableAllFunction(){
  1600. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  1601. return
  1602. }
  1603. let openPanel = NSOpenPanel()
  1604. openPanel.allowsMultipleSelection = false
  1605. openPanel.allowedFileTypes = ["pdf"]
  1606. openPanel.beginSheetModal(for: NSApp.mainWindow!) { result in
  1607. if result == .cancel {
  1608. return
  1609. }
  1610. if !openPanel.url!.path.isPDFValid() {
  1611. let alert = NSAlert()
  1612. alert.alertStyle = .critical
  1613. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  1614. alert.runModal()
  1615. return
  1616. }
  1617. if let pdf = CPDFDocument(url: openPanel.url!) {
  1618. if pdf.allowsCopying == false || pdf.allowsPrinting == false {
  1619. Task {
  1620. _ = await KMAlertTool.runModel(message: KMLocalizedString("This is a secured document. Editing is not permitted.", nil))
  1621. }
  1622. return
  1623. }
  1624. }
  1625. DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
  1626. let pdfDocument = CPDFDocument(url: openPanel.url!)
  1627. KMPrintWindowController.showNewPrintWindowControll(inputDocument: pdfDocument, inputPageRange: KMPrintPageRange(), printType: .poster)
  1628. }
  1629. }
  1630. }
  1631. func fastTool_printMultple() {
  1632. if !IAPProductsManager.default().isAvailableAllFunction(){
  1633. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  1634. return
  1635. }
  1636. let openPanel = NSOpenPanel()
  1637. openPanel.allowsMultipleSelection = false
  1638. openPanel.allowedFileTypes = ["pdf"]
  1639. openPanel.beginSheetModal(for: NSApp.mainWindow!) { result in
  1640. if result == .cancel {
  1641. return
  1642. }
  1643. if !openPanel.url!.path.isPDFValid() {
  1644. let alert = NSAlert()
  1645. alert.alertStyle = .critical
  1646. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  1647. alert.runModal()
  1648. return
  1649. }
  1650. if let pdf = CPDFDocument(url: openPanel.url!) {
  1651. if pdf.allowsCopying == false || pdf.allowsPrinting == false {
  1652. Task {
  1653. _ = await KMAlertTool.runModel(message: KMLocalizedString("This is a secured document. Editing is not permitted.", nil))
  1654. }
  1655. return
  1656. }
  1657. }
  1658. DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
  1659. let pdfDocument = CPDFDocument(url: openPanel.url!)
  1660. KMPrintWindowController.showNewPrintWindowControll(inputDocument: pdfDocument, inputPageRange: KMPrintPageRange(), printType: .multipage)
  1661. }
  1662. }
  1663. }
  1664. @IBAction func escButtonAction(_ sender: Any) {
  1665. // self.historyFileViewController.selectFiles.removeAll()
  1666. // if self.historyFileViewController.showMode == .Thumbnail {
  1667. // self.historyFileViewController.historyFileCollectionView.reloadData()
  1668. // } else {
  1669. // self.historyFileViewController.historyFileTableView.reloadData()
  1670. // }
  1671. }
  1672. @IBAction func importFromFile(_ sender: Any) {
  1673. self.openSupportPDFButtonAction()
  1674. }
  1675. @IBAction func menuItemClick_mergePDF(_ sender: Any) {
  1676. fastTool_MergePDF()
  1677. }
  1678. @IBAction func menuItemClick_Compress(_ sender: Any) {
  1679. fastTool_Compression()
  1680. }
  1681. @IBAction func menuItemClick_Convert(_ sender: Any) {
  1682. fastTool_ConvertPDF()
  1683. }
  1684. @IBAction func menuItemClick_SettingPassword(_ sender: Any) {
  1685. KMBatchQuickActionManager.defaultManager.actionType = .add
  1686. fastTool_Security()
  1687. }
  1688. @IBAction func menuItemClick_RemovePassword(_ sender: Any) {
  1689. KMBatchQuickActionManager.defaultManager.actionType = .add
  1690. fastTool_Security()
  1691. }
  1692. func fetchUniquePath(_ originalPath: String) -> String {
  1693. var path = originalPath
  1694. let dManager = FileManager.default
  1695. if !dManager.fileExists(atPath: path) {
  1696. if path.extension.count < 1 {
  1697. path = path.stringByAppendingPathExtension("pdf")
  1698. }
  1699. return path
  1700. } else {
  1701. let originalFullFileName = path.lastPathComponent
  1702. let originalFileName = path.lastPathComponent.deletingPathExtension.lastPathComponent
  1703. let originalExtension = path.extension
  1704. let startIndex: Int = 0
  1705. let endIndex: Int = startIndex + originalPath.count - originalFullFileName.count - 1
  1706. let fileLocatePath = originalPath.substring(to: endIndex)
  1707. var i = 1
  1708. while (1 != 0) {
  1709. var newName = String(format: "%@%ld", originalFileName, i)
  1710. newName = String(format: "%@%@", newName, originalExtension)
  1711. let newPath = fileLocatePath.stringByAppendingPathComponent(newName)
  1712. if !dManager.fileExists(atPath: newPath) {
  1713. return newPath
  1714. } else {
  1715. i+=1
  1716. continue
  1717. }
  1718. }
  1719. }
  1720. }
  1721. // func kNewDocumentTempSavePath(_ fileName: String) -> String {
  1722. // let searchPath = NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory, .userDomainMask, true).last
  1723. //// let append1 = searchPath?.stringByAppendingPathComponent(Bundle.main.bundleIdentifier!)
  1724. // let append2 = searchPath!.stringByAppendingPathComponent(String(format: "%@", fileName))
  1725. // return append2
  1726. // }
  1727. // MARK: Notification
  1728. @objc func homeFileRectChange(_ notification: Notification) -> Void {
  1729. let window = notification.object
  1730. self.historyFileViewController.reloadData()
  1731. }
  1732. }
  1733. // MARK: window Menu
  1734. extension KMHomeViewController {
  1735. @IBAction func menuItemAction_showForwardTagPage(_ sender: Any) {
  1736. (self.myDocument as! KMMainDocument).browser.selectPreviousTab()
  1737. }
  1738. @IBAction func menuItemAction_showNextTagPage(_ sender: Any) {
  1739. (self.myDocument as! KMMainDocument).browser.selectNextTab()
  1740. }
  1741. @IBAction func menuItemAction_newTagPageToNewWindow(_ sender: Any) {
  1742. let browser = (self.myDocument as! KMMainDocument).browser
  1743. ((browser as! KMBrowser).windowController as? KMBrowserWindowController)?.openNewWindow(sender)
  1744. }
  1745. @IBAction func menuItemAction_mergeAllWindow(_ sender: Any) {
  1746. ((self.myDocument as? KMMainDocument)?.browser.windowController as? KMBrowserWindowController)?.mergeAllWindow(sender)
  1747. }
  1748. @IBAction func menuItemAction_currentWindowName(_ sender: Any) {
  1749. }
  1750. }
  1751. // MARK: file Menu
  1752. extension KMHomeViewController {
  1753. @IBAction func menuItemAction_closeWindow(_ sender: Any) {
  1754. self.view.window?.close()
  1755. }
  1756. @IBAction func menuItemAction_closeAllWindows(_ sender: Any) {
  1757. for window in NSApp.windows {
  1758. window.close()
  1759. }
  1760. }
  1761. @IBAction func menuItemAction_ConvertToWord(_ sender: Any) {
  1762. self.fastTool_PDFToWord()
  1763. }
  1764. @IBAction func menuItemAction_ConvertToExcel(_ sender: Any) {
  1765. self.fastTool_PDFToExcel()
  1766. }
  1767. @IBAction func menuItemAction_ConvertToPPT(_ sender: Any) {
  1768. self.fastTool_PDFToPPT()
  1769. }
  1770. @IBAction func menuItemAction_ConvertToRTF(_ sender: Any) {
  1771. self.showConvertWindow(type: .rtf)
  1772. }
  1773. @IBAction func menuItemAction_ConvertToHTML(_ sender: Any) {
  1774. self.showConvertWindow(type: .html)
  1775. }
  1776. @IBAction func menuItemAction_ConvertToText(_ sender: Any) {
  1777. self.showConvertWindow(type: .text)
  1778. }
  1779. @IBAction func menuItemAction_ConvertToCSV(_ sender: Any) {
  1780. self.showConvertWindow(type: .csv)
  1781. }
  1782. @IBAction func menuItemAction_ConvertToImage(_ sender: Any) {
  1783. self.fastTool_PDFToImage()
  1784. }
  1785. }
  1786. // MARK: help Menu
  1787. extension KMHomeViewController {
  1788. // @IBAction func menuItemAction_search(_ sender: Any) {
  1789. //
  1790. // }
  1791. }
  1792. // MARK: - Analytics (埋点)
  1793. extension KMHomeViewController {
  1794. func trackEvent_ai(eventName: String) -> Void {
  1795. KMAnalytics.trackEvent(eventName: eventName, parameters: [
  1796. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.home,
  1797. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.ai_Btn], platform: .AppCenter, appTarget: .all)
  1798. }
  1799. func trackEvent_create(eventName: String) -> Void {
  1800. KMAnalytics.trackEvent(eventName: eventName, parameters: [
  1801. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.home,
  1802. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.create_Btn], platform: .AppCenter, appTarget: .all)
  1803. }
  1804. }
  1805. extension KMHomeViewController {
  1806. //文件对比
  1807. func openContentCompareVC(with pdfCompareContent: CPDFCompareContent?, results: [CPDFCompareResults], oldDocument: CPDFDocument, document: CPDFDocument) {
  1808. let compareContentController = KMCompareContentWindowController(document: document, oldDocument: oldDocument, results: results)
  1809. self.currentController = compareContentController
  1810. // let compareContentView = KMCompareContentView()
  1811. // compareContentView.oldDocument = oldDocument
  1812. // compareContentView.document = document
  1813. // compareContentView.compareResults = results
  1814. compareContentController.saveHandle = { [unowned self] view in
  1815. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.25) { [unowned self] in
  1816. let saveController = KMCompareSaveWindow(windowNibName: "KMCompareSaveWindow")
  1817. self.currentWindowController = saveController
  1818. saveController.cancelHandle = { [unowned self] controller in
  1819. NSWindow.currentWindow().endSheet(controller.window!)
  1820. self.currentWindowController = nil
  1821. }
  1822. saveController.saveHandle = { [unowned self] controller, saveType in
  1823. let folderPath = controller.fileSaveFolderPath
  1824. if folderPath != nil {
  1825. if !FileManager.default.fileExists(atPath: folderPath) {
  1826. try? FileManager.default.createDirectory(atPath: folderPath, withIntermediateDirectories: true, attributes: nil)
  1827. }
  1828. var savePath: String
  1829. switch saveType {
  1830. case 0:
  1831. let filePath = oldDocument.documentURL.path
  1832. let fileName = filePath.deletingPathExtension.lastPathComponent
  1833. savePath = "\(folderPath)/\(fileName)_compare\(filePath.extension)"
  1834. savePath = self.getValidFilePath(savePath)
  1835. oldDocument.write(to: URL(fileURLWithPath: savePath))
  1836. NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: savePath)])
  1837. case 1:
  1838. let filePath = document.documentURL.path
  1839. let fileName = filePath.deletingPathExtension.lastPathComponent
  1840. savePath = "\(folderPath)/\(fileName)_compare\(filePath.extension)"
  1841. savePath = self.getValidFilePath(savePath)
  1842. document.write(to: URL(fileURLWithPath: savePath))
  1843. NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: savePath)])
  1844. case 2:
  1845. let filePath = oldDocument.documentURL.path
  1846. let fileName = filePath.deletingPathExtension.lastPathComponent
  1847. savePath = "\(folderPath)/MergedCompareFile\(filePath.extension)"
  1848. savePath = self.getValidFilePath(savePath)
  1849. pdfCompareContent!.saveAsComparisonDocument(withFilePath: savePath)
  1850. NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: savePath)])
  1851. default:
  1852. break
  1853. }
  1854. }
  1855. NSWindow.currentWindow().endSheet(controller.window!)
  1856. self.currentWindowController = nil
  1857. }
  1858. NSWindow.currentWindow().beginSheet(saveController.window!)
  1859. }
  1860. }
  1861. compareContentController.closeHandle = { [unowned self] controller in
  1862. self.view.window!.endSheet(controller.window!)
  1863. self.currentController = nil
  1864. // view.removeFromSuperview()
  1865. }
  1866. NSWindow.currentWindow().beginSheet(compareContentController.window!)
  1867. // self.PDFContendView.addSubview(compareContentView)
  1868. // compareContentView.frame = self.PDFContendView.bounds
  1869. // compareContentView.autoresizingMask = [.width,.height]
  1870. }
  1871. func getValidFilePath(_ oldPath: String) -> String {
  1872. let fileManager = FileManager.default
  1873. do {
  1874. let fileAttributes = try fileManager.attributesOfItem(atPath: oldPath)
  1875. guard let fileType = fileAttributes[FileAttributeKey.type] as? String else {
  1876. return oldPath
  1877. }
  1878. var i = 1
  1879. var newPath = oldPath
  1880. while fileManager.fileExists(atPath: newPath) {
  1881. if fileType == FileAttributeType.typeDirectory.rawValue {
  1882. newPath = oldPath + "(\(i))"
  1883. } else {
  1884. let fileExtension = (oldPath as NSString).pathExtension
  1885. newPath = ((oldPath as NSString).deletingPathExtension as NSString).appendingFormat("(\(i)).\(fileExtension)" as NSString) as String
  1886. }
  1887. i += 1
  1888. }
  1889. return newPath
  1890. } catch {
  1891. print("Error getting file attributes: \(error)")
  1892. return oldPath
  1893. }
  1894. }
  1895. func openCoveringCompareVC(with pdfDocument: CPDFDocument) {
  1896. let controller = KMCompareCoveringWindowController(document: pdfDocument)
  1897. self.currentWindowController = controller
  1898. // let coveringView = KMCompareCoveringView()
  1899. // coveringView.pdfDocument = pdfDocument
  1900. controller.closeHandle = { [unowned self] controller in
  1901. // view.removeFromSuperview()
  1902. self.view.window!.endSheet(controller.window!)
  1903. self.currentController = nil
  1904. }
  1905. controller.saveHandle = { [unowned self] controller in
  1906. let savePanel = NSSavePanel()
  1907. savePanel.nameFieldStringValue = "untitled"
  1908. savePanel.allowedFileTypes = ["pdf"]
  1909. savePanel.beginSheetModal(for: NSWindow.currentWindow()) { result in
  1910. if result == .OK {
  1911. pdfDocument.write(to: savePanel.url!)
  1912. NSWorkspace.shared.activateFileViewerSelecting([savePanel.url!])
  1913. }
  1914. }
  1915. }
  1916. // self.view.window!.endSheet(controller.window!)
  1917. NSWindow.currentWindow().beginSheet(controller.window!)
  1918. // self.PDFContendView.addSubview(coveringView)
  1919. // coveringView.frame = self.PDFContendView.bounds
  1920. // coveringView.autoresizingMask = [.width,.height]
  1921. }
  1922. }