KMHomeViewController+Action.swift 95 KB

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