KMHomeViewController+Action.swift 96 KB

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