KMHomeViewController+Action.swift 64 KB

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