KMHomeViewController+Action.swift 67 KB

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