KMHomeViewController+Action.swift 62 KB

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