KMHomeViewController+Action.swift 62 KB

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