KMHomeViewController+Action.swift 71 KB

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