KMHomeViewController+Action.swift 70 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664
  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. }
  623. KMRequestServerManager.manager.aiTranslationFileUpload(file: path, version: "1.0.1") { [unowned self] success, result in
  624. if success {
  625. let result: NSDictionary = result!.result
  626. let fileKey = result["fileKey"]
  627. let fileName = result["fileName"]
  628. let pageCount = result["pageCount"]
  629. if fileKey != nil {
  630. self.fileTranslateHandle(fileKey as! String)
  631. }
  632. } else {
  633. let result: String = result!.message
  634. DispatchQueue.main.async {
  635. self.hiddenProgressWindow()
  636. self.aiTranslationViewController.errorView.isHidden = false
  637. self.aiTranslationViewController.errorLabel.stringValue = result
  638. }
  639. }
  640. }
  641. }
  642. }
  643. func fileTranslateHandle(_ fileKey: String) -> Void {
  644. let infoDictionary = Bundle .main.infoDictionary!
  645. let majorVersion = infoDictionary["CFBundleShortVersionString"]
  646. KMRequestServerManager.manager.aiTranslationFileTranslateHandle(fileKey: fileKey, from: self.aiTranslationViewController.fromStr, to: self.aiTranslationViewController.toStr, version: "1.0.1") { success, result in
  647. if success {
  648. let result: NSDictionary = result!.result
  649. let fileUrl: String = result["fileUrl"] as! String
  650. let downFileUrl: String = result["downFileUrl"] as! String
  651. let ossDownUrl: String = result["ossDownUrl"] as! String
  652. let fileName: String = result["fileName"] as! String
  653. let downFileName: String = result["downFileName"] as! String
  654. let from: String = result["from"] as! String
  655. let to: String = result["to"] as! String
  656. self.downloadFile(filePath: ossDownUrl, downFileName: downFileName)
  657. } else {
  658. let result: String = result!.message
  659. DispatchQueue.main.async {
  660. self.hiddenProgressWindow()
  661. self.aiTranslationViewController.errorView.isHidden = false
  662. self.aiTranslationViewController.errorLabel.stringValue = result
  663. }
  664. }
  665. }
  666. }
  667. func downloadFile(filePath: String, downFileName: String) -> Void {
  668. guard let fileURL = URL(string: filePath) else {
  669. let alert = NSAlert()
  670. alert.alertStyle = .critical
  671. alert.messageText = NSLocalizedString("Invalid file link", comment: "")
  672. alert.runModal()
  673. return
  674. }
  675. let destinationURL = FileManager.default.temporaryDirectory.appendingPathComponent(downFileName)
  676. if FileManager.default.fileExists(atPath: destinationURL.path) {
  677. do {
  678. try FileManager.default.removeItem(at: destinationURL)
  679. print("删除旧文件成功")
  680. } catch {
  681. print("删除旧文件失败:\(error)")
  682. }
  683. }
  684. let sessionConfiguration = URLSessionConfiguration.default
  685. let session = URLSession(configuration: sessionConfiguration)
  686. let downloadTask = session.downloadTask(with: fileURL) { (tempLocalURL, response, error) in
  687. if let error = error {
  688. let alert = NSAlert()
  689. alert.alertStyle = .critical
  690. alert.messageText = String(format: "%@:\(error)", NSLocalizedString("Download failed", comment: ""))
  691. alert.runModal()
  692. return
  693. }
  694. guard let tempLocalURL = tempLocalURL else {
  695. let alert = NSAlert()
  696. alert.alertStyle = .critical
  697. alert.messageText = NSLocalizedString("Invalid temporary directory", comment: "")
  698. alert.runModal()
  699. return
  700. }
  701. DispatchQueue.main.async {
  702. self.hiddenProgressWindow()
  703. }
  704. do {
  705. try FileManager.default.moveItem(at: tempLocalURL, to: destinationURL)
  706. NSDocumentController.shared.openDocument(withContentsOf: destinationURL, display: true) { document, documentWasAlreadyOpen, error in
  707. if error != nil {
  708. NSApp.presentError(error!)
  709. } else {
  710. }
  711. }
  712. } catch {
  713. let alert = NSAlert()
  714. alert.alertStyle = .critical
  715. alert.messageText = String(format: "%@:\(error)", NSLocalizedString("Failed to save file", comment: ""))
  716. alert.runModal()
  717. }
  718. }
  719. downloadTask.resume()
  720. }
  721. override func otherMouseDown(with event: NSEvent) {
  722. if historyFileViewController.selectFiles.count > 0 {
  723. let eventPoint = event.locationInWindow as NSPoint
  724. let x = eventPoint.x - 270.0
  725. if x >= 0 {
  726. let point = NSPoint(x: x, y: eventPoint.y)
  727. if historyFileViewController.historyFileCollectionView.frame.contains(point) ||
  728. historyFileViewController.historyFileTableView.frame.contains(point) ||
  729. historyFileViewController.deleteBox.frame.contains(point) ||
  730. historyFileViewController.listBox.frame.contains(point) ||
  731. historyFileViewController.thumbnailBox.frame.contains(point) {
  732. } else {
  733. self.historyFileViewController.selectFiles.removeAll()
  734. self.historyFileViewController.selectFiles_shift.removeAll()
  735. if self.historyFileViewController.showMode == .Thumbnail {
  736. self.historyFileViewController.historyFileCollectionView.reloadData()
  737. } else {
  738. self.historyFileViewController.historyFileTableView.reloadData()
  739. }
  740. }
  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. }
  751. }
  752. internal func showConvertWindow(type: KMPDFConvertType) {
  753. Task { @MainActor in
  754. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  755. let _ = KMComparativeTableViewController.show(window: self.view.window!)
  756. return
  757. }
  758. NSOpenPanel.km_secure_openPanel_success(window: self.view.window!) { url, password in
  759. var windowController: KMConvertBaseWindowController?
  760. if (type == .word) { /// Word
  761. windowController = KMConvertWordWindowController()
  762. } else if (type == .excel) {
  763. windowController = KMConvertExcelWindowController()
  764. } else if (type == .ppt || type == .rtf || type == .html || type == .text) {
  765. windowController = KMConvertPPTsWindowController()
  766. if (type == .ppt) {
  767. windowController?.subType = 1
  768. } else if (type == .rtf) {
  769. windowController?.subType = 2
  770. } else if (type == .html) {
  771. windowController?.subType = 3
  772. } else if (type == .text) {
  773. windowController?.subType = 4
  774. }
  775. } else if (type == .csv) {
  776. windowController = KMConvertCSVWindowController()
  777. } else if (type == .image) {
  778. windowController = KMConvertImageWindowController()
  779. }
  780. let model = KMDocumentModel(url: url)
  781. if (password != nil) {
  782. let _ = model.unlock(password!)
  783. }
  784. windowController?.documentModel = model
  785. windowController?.itemClick = { [weak self] index in
  786. if (self?.currentWindowController == nil) {
  787. return
  788. }
  789. self?.view.window?.endSheet((self?.currentWindowController?.window)!)
  790. self?.currentWindowController = nil
  791. }
  792. self.view.window?.beginSheet((windowController?.window)!)
  793. self.currentWindowController = windowController
  794. }
  795. }
  796. }
  797. // MARK: PDF Tools
  798. // 插入
  799. func insertPageAction(_ pdfDocument: CPDFDocument, _ password: String, _ pages: [CPDFPage], _ indexPage: Int) -> Void {
  800. if indexPage >= 0 {
  801. let insertPages: [CPDFPage] = pages
  802. for i in 0...insertPages.count-1 {
  803. let page = pages[i]
  804. // FIXME: 待底层库修改,使用 insertPageObject 插入,插入位置变为文档最后,暂用 insertPage 代替
  805. pdfDocument.insertPageObject(page, at: UInt(indexPage + i))
  806. }
  807. self.savePDFDocument(pdfDocument, password: password)
  808. }
  809. }
  810. func extractPageAction(_ pdfDocument: CPDFDocument, _ pages: [CPDFPage], _ oneDocumentPerPage: Bool, _ isDeletePage: Bool) -> Void {
  811. if pages.count < 1 {
  812. let alert = NSAlert()
  813. alert.alertStyle = .critical
  814. alert.messageText = NSLocalizedString("Please select two or more pages first to organize.", comment: "")
  815. alert.runModal()
  816. return
  817. }
  818. if !oneDocumentPerPage {
  819. let fileName = pdfDocument.getFileNameAccordingSelctPages(pages)
  820. let outputSavePanel = NSSavePanel()
  821. outputSavePanel.allowedFileTypes = ["pdf"]
  822. outputSavePanel.nameFieldStringValue = fileName
  823. outputSavePanel.beginSheetModal(for: self.view.window!) { result in
  824. if result == .OK {
  825. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  826. let saveFilePath = outputSavePanel.url?.path
  827. DispatchQueue.global().async {
  828. var pdf = CPDFDocument.init()
  829. let success = (pdf!.extractAsOneDocument(withPages: pages, savePath: saveFilePath)) as Bool
  830. DispatchQueue.main.async {
  831. if success {
  832. let workspace = NSWorkspace.shared
  833. let url = URL(fileURLWithPath: saveFilePath!)
  834. workspace.activateFileViewerSelecting([url])
  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. } else {
  848. let panel = NSOpenPanel()
  849. panel.canChooseFiles = false
  850. panel.canChooseDirectories = true
  851. panel.canCreateDirectories = true
  852. panel.allowsMultipleSelection = false
  853. panel.beginSheetModal(for: self.view.window!) { result in
  854. if result == .OK {
  855. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  856. let outputURL = panel.url
  857. DispatchQueue.global().async {
  858. let folderName = String(pdfDocument.documentURL!.lastPathComponent.split(separator: ".")[0]) + "_extract"
  859. var filePath = URL(fileURLWithPath: outputURL!.path).appendingPathComponent(folderName).path
  860. var i = 1
  861. let testFilePath = filePath
  862. while FileManager.default.fileExists(atPath: filePath) {
  863. filePath = testFilePath + "\(i)"
  864. i += 1
  865. }
  866. try? FileManager.default.createDirectory(atPath: filePath, withIntermediateDirectories: false, attributes: nil)
  867. let successArray = pdfDocument.extractPerPageDocument(withPages: pages, folerPath: filePath)
  868. DispatchQueue.main.async {
  869. if successArray!.count > 0 {
  870. NSWorkspace.shared.activateFileViewerSelecting(successArray!)
  871. if !isDeletePage {
  872. for page in pages {
  873. let indexPage = pdfDocument.index(for: page)
  874. pdfDocument.removePage(at: indexPage)
  875. }
  876. }
  877. }
  878. }
  879. }
  880. }
  881. }
  882. }
  883. }
  884. }
  885. // MARK: 快捷工具 Action
  886. func fastToolDidSelectAllTools() {
  887. // 首页 快捷工具 Tools按钮
  888. refreshRightBoxUI(.PDFTools)
  889. }
  890. func fastTool_Batch() { // Batch
  891. // KMBatchWindowController.openFile(nil, .Batch)
  892. }
  893. func fastTool_OCR() { // OCR
  894. // KMOCRWindowController.openFiles(window: self.view.window!)
  895. }
  896. func fastTool_ConvertPDF() { // 转换PDF
  897. // KMBatchWindowController.openFile(nil, .ConvertPDF)
  898. }
  899. func fastTool_ImageToPDF() { // 图片转PDF
  900. KMImageToPDFWindowController.openFiles(window: NSApp.mainWindow!)
  901. }
  902. func fastTool_MergePDF() { // MergePDF
  903. Task { @MainActor in
  904. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  905. let _ = KMComparativeTableViewController.show(window: self.view.window!)
  906. return
  907. }
  908. NSPanel.km_open_pdf_multi_success(self.view.window!, panel: nil) { urls in
  909. DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
  910. var filepaths: Array<String> = []
  911. for url in urls {
  912. filepaths.append(url.path)
  913. }
  914. let windowController = KMPDFEditAppendWindow(filePaths: filepaths)
  915. self.currentWindowController = windowController
  916. windowController?.beginSheetModal(for: self.view.window, completionHandler: { result, indexs in
  917. })
  918. }
  919. }
  920. }
  921. }
  922. func fastTool_Compression() { // 压缩
  923. Task { @MainActor in
  924. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  925. let _ = KMComparativeTableViewController.show(window: self.view.window!)
  926. return
  927. }
  928. NSOpenPanel.km_secure_openPanel(window: self.view.window!) { url, result, passowrd in
  929. if (url == nil) {
  930. return
  931. }
  932. if (result != nil && result! == .cancel) {
  933. return
  934. }
  935. self.showCompressWindow(url!, passowrd)
  936. }
  937. }
  938. }
  939. func showCompressWindow(_ url: URL, _ password: String?) {
  940. Task { @MainActor in
  941. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  942. let _ = KMComparativeTableViewController.show(window: self.view.window!)
  943. return
  944. }
  945. let windowController = KMCompressWindowController(windowNibName: "KMCompressWindowController")
  946. self.currentWindowController = windowController
  947. windowController.documentURL = url
  948. windowController.password = password
  949. windowController.itemClick = { [weak self] (index: Int) -> () in
  950. self!.view.window?.endSheet(self!.currentWindowController!.window!)
  951. self?.currentWindowController = nil
  952. }
  953. windowController.resultCallback = { [weak self] (result: Bool, openDocument: Bool, fileURL: URL, error: String) in
  954. if result {
  955. self!.view.window?.endSheet(self!.currentWindowController!.window!)
  956. self?.currentWindowController = nil
  957. if openDocument {
  958. if !fileURL.path.isPDFValid() {
  959. let alert = NSAlert()
  960. alert.alertStyle = .critical
  961. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  962. alert.runModal()
  963. return
  964. }
  965. NSDocumentController.shared.openDocument(withContentsOf: fileURL, display: true) { document, result, error in
  966. if error != nil {
  967. NSApp.presentError(error!)
  968. return
  969. }
  970. }
  971. } else {
  972. NSWorkspace.shared.activateFileViewerSelecting([fileURL])
  973. }
  974. } else {
  975. let alert = NSAlert()
  976. alert.messageText = NSLocalizedString("Compress Faild", comment: "")
  977. alert.runModal()
  978. }
  979. }
  980. await self.view.window?.beginSheet(windowController.window!)
  981. }
  982. }
  983. func fastTool_Security() { // 安全
  984. Task { @MainActor in
  985. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  986. let _ = KMComparativeTableViewController.show(window: self.view.window!)
  987. return
  988. }
  989. NSOpenPanel.km_secure_openPanel(window: self.view.window!, needOwner: true) { url, result, passowrd in
  990. if (url == nil) {
  991. return
  992. }
  993. if (result != nil && result! == .cancel) {
  994. return
  995. }
  996. let windowController = KMSecureEncryptWindowController(windowNibName: "KMSecureEncryptWindowController")
  997. windowController.documentURL = url!
  998. windowController.myDocument = CPDFDocument(url: url!)
  999. if (passowrd != nil) {
  1000. windowController.myDocument.unlock(withPassword: passowrd)
  1001. }
  1002. self.currentWindowController = windowController
  1003. let newDocument: CPDFDocument = CPDFDocument(url: url!)
  1004. windowController.itemClick = { [weak self] (index: Int) -> () in
  1005. self!.view.window?.endSheet((self?.currentWindowController?.window!)!)
  1006. self?.currentWindowController = nil
  1007. }
  1008. windowController.resultCallback = { [weak self] (result: Bool) -> () in
  1009. let windowController_secure: KMSecureEncryptWindowController = self?.currentWindowController as! KMSecureEncryptWindowController
  1010. self!.view.window?.endSheet((self?.currentWindowController?.window!)!)
  1011. self!.currentWindowController = nil
  1012. if (passowrd != nil) {
  1013. newDocument.unlock(withPassword: passowrd)
  1014. }
  1015. newDocument.setPasswordOptions(windowController_secure.options)
  1016. let result = KMPasswordInputWindow.saveDocument(newDocument)
  1017. if result {
  1018. NSWorkspace.shared.activateFileViewerSelecting([newDocument.documentURL])
  1019. } else {
  1020. let alert = NSAlert()
  1021. alert.messageText = NSLocalizedString("Failure", comment: "")
  1022. alert.runModal()
  1023. }
  1024. }
  1025. self.view.window?.beginSheet(windowController.window!)
  1026. }
  1027. }
  1028. }
  1029. func fastTool_FileCompare() { // 文件对比
  1030. print("选中 快捷工具 文件对比")
  1031. }
  1032. func fastTool_PDFToPPT() { // PDF转PPT
  1033. Task { @MainActor in
  1034. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  1035. let _ = KMComparativeTableViewController.show(window: self.view.window!)
  1036. return
  1037. }
  1038. NSOpenPanel.km_secure_openPanel_success(window: self.view.window!) { url, password in
  1039. let windowController = KMConvertPPTsWindowController(windowNibName: "KMConvertBaseWindowController")
  1040. let model = KMDocumentModel(url: url)
  1041. windowController.subType = 1
  1042. if (password != nil) {
  1043. let _ = model.unlock(password!)
  1044. }
  1045. windowController.documentModel = model
  1046. windowController.itemClick = { [weak self] (index: Int) in
  1047. if (self?.currentWindowController == nil) {
  1048. return
  1049. }
  1050. self?.view.window?.endSheet((self?.currentWindowController?.window)!)
  1051. self?.currentWindowController = nil
  1052. }
  1053. self.view.window?.beginSheet(windowController.window!)
  1054. self.currentWindowController = windowController
  1055. }
  1056. }
  1057. }
  1058. func fastTool_PDFToExcel() { // PDF转Excel
  1059. Task { @MainActor in
  1060. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  1061. let _ = KMComparativeTableViewController.show(window: self.view.window!)
  1062. return
  1063. }
  1064. NSOpenPanel.km_secure_openPanel_success(window: self.view.window!) { url, password in
  1065. let windowController = KMConvertExcelWindowController(windowNibName: "KMConvertBaseWindowController")
  1066. let model = KMDocumentModel(url: url)
  1067. if (password != nil) {
  1068. let _ = model.unlock(password!)
  1069. }
  1070. windowController.documentModel = model
  1071. windowController.itemClick = { [weak self] (index: Int) in
  1072. if (self?.currentWindowController == nil) {
  1073. return
  1074. }
  1075. self?.view.window?.endSheet((self?.currentWindowController?.window)!)
  1076. self?.currentWindowController = nil
  1077. }
  1078. self.view.window?.beginSheet(windowController.window!)
  1079. self.currentWindowController = windowController
  1080. }
  1081. }
  1082. }
  1083. func fastTool_PDFToWord() { // PDF转Word
  1084. Task { @MainActor in
  1085. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  1086. let _ = KMComparativeTableViewController.show(window: self.view.window!)
  1087. return
  1088. }
  1089. NSOpenPanel.km_secure_openPanel_success(window: self.view.window!) { url, password in
  1090. if (url.path.isPDFValid() == false) {
  1091. let alert = NSAlert()
  1092. alert.alertStyle = .critical
  1093. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  1094. alert.runModal()
  1095. return
  1096. }
  1097. let windowController = KMConvertWordWindowController(windowNibName: "KMConvertBaseWindowController")
  1098. let model = KMDocumentModel(url: url)
  1099. if (password != nil) {
  1100. let _ = model.unlock(password!)
  1101. }
  1102. windowController.documentModel = model
  1103. windowController.itemClick = { [weak self] (index: Int) in
  1104. if (self?.currentWindowController == nil) {
  1105. return
  1106. }
  1107. self?.view.window?.endSheet((self?.currentWindowController?.window)!)
  1108. self?.currentWindowController = nil
  1109. }
  1110. self.view.window?.beginSheet(windowController.window!)
  1111. self.currentWindowController = windowController
  1112. }
  1113. }
  1114. }
  1115. func fastTool_PDFToImage() { // PDF转图片
  1116. Task { @MainActor in
  1117. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  1118. let _ = KMComparativeTableViewController.show(window: self.view.window!)
  1119. return
  1120. }
  1121. NSOpenPanel.km_secure_openPanel_success(window: self.view.window!) { url, password in
  1122. let windowController = KMConvertImageWindowController(windowNibName: "KMConvertBaseWindowController")
  1123. let model = KMDocumentModel(url: url)
  1124. if (password != nil) {
  1125. let _ = model.unlock(password!)
  1126. }
  1127. windowController.documentModel = model
  1128. windowController.itemClick = { [weak self] (index: Int) in
  1129. if (self?.currentWindowController == nil) {
  1130. return
  1131. }
  1132. self?.view.window?.endSheet((self?.currentWindowController?.window)!)
  1133. self?.currentWindowController = nil
  1134. }
  1135. self.view.window?.beginSheet(windowController.window!)
  1136. self.currentWindowController = windowController
  1137. }
  1138. }
  1139. }
  1140. func fastTool_Watermark() { // 水印
  1141. KMBatchWindowController.openFile(nil, .Watermark)
  1142. }
  1143. func fastTool_Background() { // 背景
  1144. KMBatchWindowController.openFile(nil, .Background)
  1145. }
  1146. func fastTool_HeaderAndFooter() { // 页眉页脚
  1147. KMBatchWindowController.openFile(nil, .HeaderAndFooter)
  1148. }
  1149. func fastTool_BatesCode() { // 贝茨码
  1150. KMBatchWindowController.openFile(nil, .BatesCode)
  1151. }
  1152. func fastTool_Print() { // 打印
  1153. KMPrintWindowController.openFiles(window: self.view.window!)
  1154. }
  1155. func fastTool_BatchRemove() { // 批量移除
  1156. KMBatchWindowController.openFile(nil, .BatchRemove)
  1157. }
  1158. func fastTool_Insert() { // 插入
  1159. let openPanel = NSOpenPanel()
  1160. openPanel.prompt = "插入"
  1161. openPanel.allowsMultipleSelection = false
  1162. openPanel.allowedFileTypes = ["pdf"]
  1163. openPanel.beginSheetModal(for: NSApp.mainWindow!) { result in
  1164. if result == .OK {
  1165. DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
  1166. let insertWindowController: KMPDFInsertPageWindow = KMPDFInsertPageWindow.init(documentPath: openPanel.url!, toolType: .Insert)
  1167. insertWindowController.beginSheetModal(for: self.view.window!) { pdfDocument, password, pages, indexPage in
  1168. self.insertPageAction(pdfDocument, password, pages, indexPage)
  1169. }
  1170. }
  1171. }
  1172. }
  1173. }
  1174. func fastTool_BreakUp() { // 拆分
  1175. let openPanel = NSOpenPanel()
  1176. openPanel.prompt = "提取"
  1177. openPanel.allowsMultipleSelection = false
  1178. openPanel.allowedFileTypes = ["pdf"]
  1179. openPanel.beginSheetModal(for: NSApp.mainWindow!) { result in
  1180. if result == .OK {
  1181. DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
  1182. let document = CPDFDocument(url: openPanel.url)
  1183. let model = KMPageEditSplitSettingModel()
  1184. model.documentURL = openPanel.url
  1185. model.fileName = model.documentURL.lastPathComponent
  1186. model.pathExtension = model.fileName.components(separatedBy: ".").last
  1187. let windowController = KMPageEditSplitWindowController(model)
  1188. windowController.hasPreView = true
  1189. self.view.window?.beginSheet(windowController.window!)
  1190. self.currentWindowController = windowController
  1191. windowController.itemClick = { [weak self] index, value in
  1192. if (index == 1) { /// 取消
  1193. self?.view.window?.endSheet((self?.currentWindowController!.window)!)
  1194. self?.currentWindowController = nil
  1195. return
  1196. }
  1197. /// 拆分
  1198. let windowController_split: KMPageEditSplitWindowController = self?.currentWindowController as! KMPageEditSplitWindowController
  1199. let outputModel: KMPageEditSplitSettingModel = windowController_split.model! as! KMPageEditSplitSettingModel
  1200. self?.view.window?.endSheet((self?.currentWindowController!.window)!)
  1201. self?.currentWindowController = nil
  1202. let panel = NSOpenPanel()
  1203. panel.canChooseFiles = false
  1204. panel.canChooseDirectories = true
  1205. panel.canCreateDirectories = true
  1206. panel.beginSheetModal(for: (self?.view.window)!) { response in
  1207. KMPageEditTools.split(document!, outputModel, panel.url!.path, outputModel.outputFileNameDeletePathExtension) { result, outputDocuments, error in
  1208. if (result) {
  1209. }
  1210. }
  1211. }
  1212. }
  1213. }
  1214. }
  1215. }
  1216. }
  1217. func fastTool_Extract() { // 提取
  1218. let openPanel = NSOpenPanel()
  1219. openPanel.prompt = "提取"
  1220. openPanel.allowsMultipleSelection = false
  1221. openPanel.allowedFileTypes = ["pdf"]
  1222. openPanel.beginSheetModal(for: NSApp.mainWindow!) { result in
  1223. if result == .OK {
  1224. DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
  1225. let insertWindowController: KMPDFInsertPageWindow = KMPDFInsertPageWindow.init(documentPath: openPanel.url!, toolType: .Extract)
  1226. insertWindowController.beginSheetExtractModal(for: self.view.window!) { pdfDocument, pages, oneDocumentPerPage, isDeletePage in
  1227. self.extractPageAction(pdfDocument, pages, oneDocumentPerPage, isDeletePage)
  1228. }
  1229. }
  1230. }
  1231. }
  1232. }
  1233. func fastTool_MarkCipher() { // 标记密文
  1234. let openPanel = NSOpenPanel()
  1235. openPanel.allowsMultipleSelection = false
  1236. openPanel.allowedFileTypes = ["pdf"]
  1237. openPanel.beginSheetModal(for: NSApp.mainWindow!) { result in
  1238. if result == .cancel {
  1239. return
  1240. }
  1241. if !openPanel.url!.path.isPDFValid() {
  1242. let alert = NSAlert()
  1243. alert.alertStyle = .critical
  1244. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  1245. alert.runModal()
  1246. return
  1247. }
  1248. DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
  1249. NSDocumentController.shared.openDocument(withContentsOf: openPanel.url!, display: true) { document, result, error in
  1250. if (error != nil) {
  1251. NSApp.presentError(error!)
  1252. return
  1253. }
  1254. let toolbar = (document as! KMMainDocument).mainViewController?.toolbarController
  1255. toolbar?.enterRedact()
  1256. }
  1257. }
  1258. }
  1259. }
  1260. func fastTool_AutomaticFormRecognition() { // 表单自动识别
  1261. let openPanel = NSOpenPanel()
  1262. openPanel.prompt = "表单自动识别"
  1263. openPanel.allowsMultipleSelection = false
  1264. openPanel.allowedFileTypes = ["pdf"]
  1265. openPanel.beginSheetModal(for: NSApp.mainWindow!) { result in
  1266. if result == .OK {
  1267. }
  1268. }
  1269. }
  1270. func fastTool_PageEdit() { // 页面编辑
  1271. let openPanel = NSOpenPanel()
  1272. openPanel.allowsMultipleSelection = false
  1273. openPanel.allowedFileTypes = ["pdf"]
  1274. openPanel.beginSheetModal(for: NSApp.mainWindow!) { result in
  1275. if result == .cancel {
  1276. return
  1277. }
  1278. if !openPanel.url!.path.isPDFValid() {
  1279. let alert = NSAlert()
  1280. alert.alertStyle = .critical
  1281. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  1282. alert.runModal()
  1283. return
  1284. }
  1285. DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
  1286. NSDocumentController.shared.openDocument(withContentsOf: openPanel.url!, display: true) { document, result, error in
  1287. if (error != nil) {
  1288. NSApp.presentError(error!)
  1289. return
  1290. }
  1291. let mainView = (document as! KMMainDocument).mainViewController
  1292. mainView?.enterPageEdit()
  1293. }
  1294. }
  1295. }
  1296. }
  1297. // MARK: MenuItem Action & PopoverItem Action
  1298. func popoverItemAction(_ count: String) {
  1299. if count == NSLocalizedString("New Blank Page", comment: "") {
  1300. openBlankPage("")
  1301. } else if count == NSLocalizedString("New From Web Page", comment: "") {
  1302. importFromWebPage("")
  1303. } else if count == NSLocalizedString("Import From Scanner", comment: "") {
  1304. importFromScanner("")
  1305. }
  1306. }
  1307. @IBAction func escButtonAction(_ sender: Any) {
  1308. self.historyFileViewController.selectFiles.removeAll()
  1309. if self.historyFileViewController.showMode == .Thumbnail {
  1310. self.historyFileViewController.historyFileCollectionView.reloadData()
  1311. } else {
  1312. self.historyFileViewController.historyFileTableView.reloadData()
  1313. }
  1314. }
  1315. @IBAction func importFromFile(_ sender: Any) {
  1316. self.openSupportPDFButtonAction()
  1317. }
  1318. @IBAction func openBlankPage(_ sender: Any) {
  1319. let fileName: NSString = String(format: "%@.pdf", NSLocalizedString("Untitled", comment: "")) as NSString
  1320. let savePath = fetchUniquePath(fileName.kUrlToPDFFolderPath())
  1321. let pdfDocument = CPDFDocument()
  1322. pdfDocument?.insertPage(CGSize(width: 595, height: 842), at: 0)
  1323. pdfDocument?.write(to: URL(fileURLWithPath: savePath))
  1324. NSDocumentController.shared.openDocument(withContentsOf: URL(fileURLWithPath: savePath), display: true) { document, documentWasAlreadyOpen, error in
  1325. if error != nil {
  1326. NSApp.presentError(error!)
  1327. } else {
  1328. if document is KMMainDocument {
  1329. let newDocument = document
  1330. (newDocument as! KMMainDocument).isNewCreated = true
  1331. }
  1332. }
  1333. }
  1334. }
  1335. @IBAction func importFromWebPage(_ sender: Any) {
  1336. self.urlToPDFWindowController = KMURLToPDFWindowController.init(windowNibName: NSNib.Name("KMURLToPDFWindowController"))
  1337. self.urlToPDFWindowController!.beginSheetModal(for: NSApp.mainWindow!) { filePath in
  1338. if filePath != nil && FileManager.default.fileExists(atPath: filePath) {
  1339. NSDocumentController.shared.openDocument(withContentsOf: URL(fileURLWithPath: filePath), display: true) { document, documentWasAlreadyOpen, error in
  1340. if error != nil {
  1341. NSApp.presentError(error!)
  1342. } else {
  1343. if document is KMMainDocument {
  1344. (document as! KMMainDocument).isNewCreated = true
  1345. }
  1346. }
  1347. }
  1348. }
  1349. }
  1350. }
  1351. @IBAction func importFromScanner(_ sender: Any) {
  1352. deviceBrowserWC = KMDeviceBrowserWindowController.shared
  1353. deviceBrowserWC?.type = .scanner
  1354. deviceBrowserWC?.importScannerFileCallback = { [weak self](url: NSURL) -> Void in
  1355. self?.openFile(withFilePath: url as URL)
  1356. }
  1357. deviceBrowserWC?.showWindow(NSApp.mainWindow)
  1358. }
  1359. @IBAction func menuItemClick_mergePDF(_ sender: Any) {
  1360. fastTool_MergePDF()
  1361. }
  1362. @IBAction func menuItemClick_Compress(_ sender: Any) {
  1363. fastTool_Compression()
  1364. }
  1365. @IBAction func menuItemClick_Convert(_ sender: Any) {
  1366. fastTool_ConvertPDF()
  1367. }
  1368. @IBAction func menuItemClick_SettingPassword(_ sender: Any) {
  1369. fastTool_Security()
  1370. }
  1371. @IBAction func menuItemClick_RemovePassword(_ sender: Any) {
  1372. fastTool_Security()
  1373. }
  1374. func fetchUniquePath(_ originalPath: String) -> String {
  1375. var path = originalPath
  1376. let dManager = FileManager.default
  1377. if !dManager.fileExists(atPath: path) {
  1378. if path.extension.count < 1 {
  1379. path = path.stringByAppendingPathExtension("pdf")
  1380. }
  1381. return path
  1382. } else {
  1383. let originalFullFileName = path.lastPathComponent
  1384. let originalFileName = path.lastPathComponent.deletingPathExtension.lastPathComponent
  1385. let originalExtension = path.extension
  1386. let startIndex: Int = 0
  1387. let endIndex: Int = startIndex + originalPath.count - originalFullFileName.count - 1
  1388. let fileLocatePath = originalPath.substring(to: endIndex)
  1389. var i = 1
  1390. while (1 != 0) {
  1391. var newName = String(format: "%@%ld", originalFileName, i)
  1392. newName = String(format: "%@%@", newName, originalExtension)
  1393. let newPath = fileLocatePath.stringByAppendingPathComponent(newName)
  1394. if !dManager.fileExists(atPath: newPath) {
  1395. return newPath
  1396. } else {
  1397. i+=1
  1398. continue
  1399. }
  1400. }
  1401. }
  1402. }
  1403. // func kNewDocumentTempSavePath(_ fileName: String) -> String {
  1404. // let searchPath = NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory, .userDomainMask, true).last
  1405. //// let append1 = searchPath?.stringByAppendingPathComponent(Bundle.main.bundleIdentifier!)
  1406. // let append2 = searchPath!.stringByAppendingPathComponent(String(format: "%@", fileName))
  1407. // return append2
  1408. // }
  1409. // MARK: Notification
  1410. @objc func homeFileRectChange(_ notification: Notification) -> Void {
  1411. let window = notification.object
  1412. self.historyFileViewController.reloadData()
  1413. }
  1414. }
  1415. // MARK: window Menu
  1416. extension KMHomeViewController {
  1417. @IBAction func menuItemAction_showForwardTagPage(_ sender: Any) {
  1418. (self.myDocument as! KMMainDocument).browser.selectPreviousTab()
  1419. }
  1420. @IBAction func menuItemAction_showNextTagPage(_ sender: Any) {
  1421. (self.myDocument as! KMMainDocument).browser.selectNextTab()
  1422. }
  1423. @IBAction func menuItemAction_newTagPageToNewWindow(_ sender: Any) {
  1424. let browser = (self.myDocument as! KMMainDocument).browser
  1425. ((browser as! KMBrowser).windowController as? KMBrowserWindowController)?.openNewWindow(sender)
  1426. }
  1427. @IBAction func menuItemAction_mergeAllWindow(_ sender: Any) {
  1428. ((self.myDocument as? KMMainDocument)?.browser.windowController as? KMBrowserWindowController)?.mergeAllWindow(sender)
  1429. }
  1430. @IBAction func menuItemAction_currentWindowName(_ sender: Any) {
  1431. }
  1432. }
  1433. // MARK: file Menu
  1434. extension KMHomeViewController {
  1435. @IBAction func menuItemAction_closeWindow(_ sender: Any) {
  1436. self.view.window?.close()
  1437. }
  1438. @IBAction func menuItemAction_closeAllWindows(_ sender: Any) {
  1439. for window in NSApp.windows {
  1440. window.close()
  1441. }
  1442. }
  1443. @IBAction func menuItemAction_ConvertToWord(_ sender: Any) {
  1444. self.fastTool_PDFToWord()
  1445. }
  1446. @IBAction func menuItemAction_ConvertToExcel(_ sender: Any) {
  1447. self.fastTool_PDFToExcel()
  1448. }
  1449. @IBAction func menuItemAction_ConvertToPPT(_ sender: Any) {
  1450. self.fastTool_PDFToPPT()
  1451. }
  1452. @IBAction func menuItemAction_ConvertToRTF(_ sender: Any) {
  1453. self.showConvertWindow(type: .rtf)
  1454. }
  1455. @IBAction func menuItemAction_ConvertToHTML(_ sender: Any) {
  1456. self.showConvertWindow(type: .html)
  1457. }
  1458. @IBAction func menuItemAction_ConvertToText(_ sender: Any) {
  1459. self.showConvertWindow(type: .text)
  1460. }
  1461. @IBAction func menuItemAction_ConvertToCSV(_ sender: Any) {
  1462. self.showConvertWindow(type: .csv)
  1463. }
  1464. @IBAction func menuItemAction_ConvertToImage(_ sender: Any) {
  1465. self.fastTool_PDFToImage()
  1466. }
  1467. }
  1468. // MARK: help Menu
  1469. extension KMHomeViewController {
  1470. // @IBAction func menuItemAction_search(_ sender: Any) {
  1471. //
  1472. // }
  1473. }