KMHomeViewController+Action.swift 63 KB

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