KMHomeViewController+Action.swift 93 KB

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