KMHomeViewController+Action.swift 63 KB

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