KMHomeViewController+Action.swift 64 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529
  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. // MARK: PDF Tools
  758. // 插入
  759. func insertPageAction(_ pdfDocument: CPDFDocument, _ password: String, _ pages: [CPDFPage], _ indexPage: Int) -> Void {
  760. if indexPage >= 0 {
  761. let insertPages: [CPDFPage] = pages
  762. for i in 0...insertPages.count-1 {
  763. let page = pages[i]
  764. // FIXME: 待底层库修改,使用 insertPageObject 插入,插入位置变为文档最后,暂用 insertPage 代替
  765. pdfDocument.insertPageObject(page, at: UInt(indexPage + i))
  766. }
  767. self.savePDFDocument(pdfDocument, password: password)
  768. }
  769. }
  770. func extractPageAction(_ pdfDocument: CPDFDocument, _ pages: [CPDFPage], _ oneDocumentPerPage: Bool, _ isDeletePage: Bool) -> Void {
  771. if pages.count < 1 {
  772. let alert = NSAlert()
  773. alert.alertStyle = .critical
  774. alert.messageText = NSLocalizedString("Please select two or more pages first to organize.", comment: "")
  775. alert.runModal()
  776. return
  777. }
  778. if !oneDocumentPerPage {
  779. let fileName = pdfDocument.getFileNameAccordingSelctPages(pages)
  780. let outputSavePanel = NSSavePanel()
  781. outputSavePanel.allowedFileTypes = ["pdf"]
  782. outputSavePanel.nameFieldStringValue = fileName
  783. outputSavePanel.beginSheetModal(for: self.view.window!) { result in
  784. if result == .OK {
  785. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  786. let saveFilePath = outputSavePanel.url?.path
  787. DispatchQueue.global().async {
  788. var pdf = CPDFDocument.init()
  789. let success = (pdf!.extractAsOneDocument(withPages: pages, savePath: saveFilePath)) as Bool
  790. DispatchQueue.main.async {
  791. if success {
  792. let workspace = NSWorkspace.shared
  793. let url = URL(fileURLWithPath: saveFilePath!)
  794. workspace.activateFileViewerSelecting([url])
  795. if isDeletePage {
  796. for page in pages {
  797. let indexPage = pdfDocument.index(for: page)
  798. pdfDocument.removePage(at: indexPage)
  799. }
  800. }
  801. }
  802. }
  803. }
  804. }
  805. }
  806. }
  807. } else {
  808. let panel = NSOpenPanel()
  809. panel.canChooseFiles = false
  810. panel.canChooseDirectories = true
  811. panel.canCreateDirectories = true
  812. panel.allowsMultipleSelection = false
  813. panel.beginSheetModal(for: self.view.window!) { result in
  814. if result == .OK {
  815. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  816. let outputURL = panel.url
  817. DispatchQueue.global().async {
  818. let folderName = String(pdfDocument.documentURL!.lastPathComponent.split(separator: ".")[0]) + "_extract"
  819. var filePath = URL(fileURLWithPath: outputURL!.path).appendingPathComponent(folderName).path
  820. var i = 1
  821. let testFilePath = filePath
  822. while FileManager.default.fileExists(atPath: filePath) {
  823. filePath = testFilePath + "\(i)"
  824. i += 1
  825. }
  826. try? FileManager.default.createDirectory(atPath: filePath, withIntermediateDirectories: false, attributes: nil)
  827. let successArray = pdfDocument.extractPerPageDocument(withPages: pages, folerPath: filePath)
  828. DispatchQueue.main.async {
  829. if successArray!.count > 0 {
  830. NSWorkspace.shared.activateFileViewerSelecting(successArray!)
  831. if !isDeletePage {
  832. for page in pages {
  833. let indexPage = pdfDocument.index(for: page)
  834. pdfDocument.removePage(at: indexPage)
  835. }
  836. }
  837. }
  838. }
  839. }
  840. }
  841. }
  842. }
  843. }
  844. }
  845. // MARK: 快捷工具 Action
  846. func fastToolDidSelectAllTools() {
  847. // 首页 快捷工具 Tools按钮
  848. refreshRightBoxUI(.PDFTools)
  849. }
  850. func fastTool_Batch() { // Batch
  851. // KMBatchWindowController.openFile(nil, .Batch)
  852. }
  853. func fastTool_OCR() { // OCR
  854. // KMOCRWindowController.openFiles(window: self.view.window!)
  855. }
  856. func fastTool_ConvertPDF() { // 转换PDF
  857. // KMBatchWindowController.openFile(nil, .ConvertPDF)
  858. }
  859. func fastTool_ImageToPDF() { // 图片转PDF
  860. KMImageToPDFWindowController.openFiles(window: NSApp.mainWindow!)
  861. }
  862. func fastTool_MergePDF() { // MergePDF
  863. Task { @MainActor in
  864. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  865. let _ = KMComparativeTableViewController.show(window: self.view.window!, .merge)
  866. return
  867. }
  868. NSPanel.km_open_pdf_multi_success(self.view.window!, panel: nil) { urls in
  869. DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
  870. var filepaths: Array<String> = []
  871. for url in urls {
  872. filepaths.append(url.path)
  873. }
  874. let windowController = KMPDFEditAppendWindow(filePaths: filepaths)
  875. self.currentWindowController = windowController
  876. windowController?.beginSheetModal(for: self.view.window, completionHandler: { result, indexs in
  877. })
  878. }
  879. }
  880. }
  881. }
  882. func fastTool_Compression() { // 压缩
  883. Task { @MainActor in
  884. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  885. let _ = KMComparativeTableViewController.show(window: self.view.window!, .compress)
  886. return
  887. }
  888. if await (KMLightMemberManager.manager.canPayFunction() == false) {
  889. let _ = KMSubscribeWaterMarkWindowController.show(window: self.view.window!) { isSubscribeSuccess, isWaterMarkExport, isClose in
  890. if (isClose) {
  891. return
  892. }
  893. self.km_secure_openPanel_compress()
  894. }
  895. return
  896. }
  897. self.km_secure_openPanel_compress()
  898. }
  899. }
  900. func km_secure_openPanel_compress() {
  901. DispatchQueue.main.async {
  902. NSOpenPanel.km_secure_openPanel(window: self.view.window!) { url, result, passowrd in
  903. if (url == nil) {
  904. return
  905. }
  906. if (result != nil && result! == .cancel) {
  907. return
  908. }
  909. self.showCompressWindow(url!, passowrd)
  910. }
  911. }
  912. }
  913. func showCompressWindow(_ url: URL, _ password: String?) {
  914. Task { @MainActor in
  915. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  916. let _ = KMComparativeTableViewController.show(window: self.view.window!, .compress)
  917. return
  918. }
  919. let windowController = KMCompressWindowController(windowNibName: "KMCompressWindowController")
  920. self.currentWindowController = windowController
  921. windowController.documentURL = url
  922. windowController.password = password
  923. windowController.itemClick = { [weak self] (index: Int) -> () in
  924. self!.view.window?.endSheet(self!.currentWindowController!.window!)
  925. self?.currentWindowController = nil
  926. }
  927. windowController.resultCallback = { [weak self] (result: Bool, openDocument: Bool, fileURL: URL, error: String) in
  928. if result {
  929. self!.view.window?.endSheet(self!.currentWindowController!.window!)
  930. self?.currentWindowController = nil
  931. if openDocument {
  932. if !fileURL.path.isPDFValid() {
  933. let alert = NSAlert()
  934. alert.alertStyle = .critical
  935. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  936. alert.runModal()
  937. return
  938. }
  939. NSDocumentController.shared.openDocument(withContentsOf: fileURL, display: true) { document, result, error in
  940. if error != nil {
  941. NSApp.presentError(error!)
  942. return
  943. }
  944. }
  945. } else {
  946. NSWorkspace.shared.activateFileViewerSelecting([fileURL])
  947. }
  948. } else {
  949. let alert = NSAlert()
  950. alert.messageText = NSLocalizedString("Compress Faild", comment: "")
  951. alert.runModal()
  952. }
  953. }
  954. await self.view.window?.beginSheet(windowController.window!)
  955. }
  956. }
  957. func fastTool_Security() { // 安全
  958. Task { @MainActor in
  959. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  960. let _ = KMComparativeTableViewController.show(window: self.view.window!, .secure)
  961. return
  962. }
  963. NSOpenPanel.km_secure_openPanel(window: self.view.window!, needOwner: true) { url, result, passowrd in
  964. if (url == nil) {
  965. return
  966. }
  967. if (result != nil && result! == .cancel) {
  968. return
  969. }
  970. let windowController = KMSecureEncryptWindowController(windowNibName: "KMSecureEncryptWindowController")
  971. windowController.documentURL = url!
  972. windowController.myDocument = CPDFDocument(url: url!)
  973. if (passowrd != nil) {
  974. windowController.myDocument.unlock(withPassword: passowrd)
  975. }
  976. self.currentWindowController = windowController
  977. let newDocument: CPDFDocument = CPDFDocument(url: url!)
  978. windowController.itemClick = { [weak self] (index: Int) -> () in
  979. self!.view.window?.endSheet((self?.currentWindowController?.window!)!)
  980. self?.currentWindowController = nil
  981. }
  982. windowController.resultCallback = { [weak self] (result: Bool) -> () in
  983. let windowController_secure: KMSecureEncryptWindowController = self?.currentWindowController as! KMSecureEncryptWindowController
  984. self!.view.window?.endSheet((self?.currentWindowController?.window!)!)
  985. self!.currentWindowController = nil
  986. if (passowrd != nil) {
  987. newDocument.unlock(withPassword: passowrd)
  988. }
  989. newDocument.setPasswordOptions(windowController_secure.options)
  990. let result = KMPasswordInputWindow.saveDocument(newDocument)
  991. if result {
  992. NSWorkspace.shared.activateFileViewerSelecting([newDocument.documentURL])
  993. } else {
  994. let alert = NSAlert()
  995. alert.messageText = NSLocalizedString("Failure", comment: "")
  996. alert.runModal()
  997. }
  998. }
  999. self.view.window?.beginSheet(windowController.window!)
  1000. }
  1001. }
  1002. }
  1003. func fastTool_FileCompare() { // 文件对比
  1004. print("选中 快捷工具 文件对比")
  1005. }
  1006. func fastTool_PDFToPPT() {
  1007. self.showConvertWindow(type: .ppt)
  1008. }
  1009. func fastTool_PDFToExcel() {
  1010. self.showConvertWindow(type: .excel)
  1011. }
  1012. func fastTool_PDFToWord() { // PDF转Word
  1013. self.showConvertWindow(type: .word)
  1014. }
  1015. func fastTool_PDFToImage() { // PDF转图片
  1016. self.showConvertWindow(type: .image)
  1017. }
  1018. func fastTool_Watermark() { // 水印
  1019. KMBatchWindowController.openFile(nil, .Watermark)
  1020. }
  1021. func fastTool_Background() { // 背景
  1022. KMBatchWindowController.openFile(nil, .Background)
  1023. }
  1024. func fastTool_HeaderAndFooter() { // 页眉页脚
  1025. KMBatchWindowController.openFile(nil, .HeaderAndFooter)
  1026. }
  1027. func fastTool_BatesCode() { // 贝茨码
  1028. KMBatchWindowController.openFile(nil, .BatesCode)
  1029. }
  1030. func fastTool_Print() { // 打印
  1031. KMPrintWindowController.openFiles(window: self.view.window!)
  1032. }
  1033. func fastTool_BatchRemove() { // 批量移除
  1034. KMBatchWindowController.openFile(nil, .BatchRemove)
  1035. }
  1036. func fastTool_Insert() { // 插入
  1037. let openPanel = NSOpenPanel()
  1038. openPanel.prompt = "插入"
  1039. openPanel.allowsMultipleSelection = false
  1040. openPanel.allowedFileTypes = ["pdf"]
  1041. openPanel.beginSheetModal(for: NSApp.mainWindow!) { result in
  1042. if result == .OK {
  1043. DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
  1044. let insertWindowController: KMPDFInsertPageWindow = KMPDFInsertPageWindow.init(documentPath: openPanel.url!, toolType: .Insert)
  1045. insertWindowController.beginSheetModal(for: self.view.window!) { pdfDocument, password, pages, indexPage in
  1046. self.insertPageAction(pdfDocument, password, pages, indexPage)
  1047. }
  1048. }
  1049. }
  1050. }
  1051. }
  1052. func fastTool_BreakUp() { // 拆分
  1053. let openPanel = NSOpenPanel()
  1054. openPanel.prompt = "提取"
  1055. openPanel.allowsMultipleSelection = false
  1056. openPanel.allowedFileTypes = ["pdf"]
  1057. openPanel.beginSheetModal(for: NSApp.mainWindow!) { result in
  1058. if result == .OK {
  1059. DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
  1060. let document = CPDFDocument(url: openPanel.url)
  1061. let model = KMPageEditSplitSettingModel()
  1062. model.documentURL = openPanel.url
  1063. model.fileName = model.documentURL.lastPathComponent
  1064. model.pathExtension = model.fileName.components(separatedBy: ".").last
  1065. let windowController = KMPageEditSplitWindowController(model)
  1066. windowController.hasPreView = true
  1067. self.view.window?.beginSheet(windowController.window!)
  1068. self.currentWindowController = windowController
  1069. windowController.itemClick = { [weak self] index, value in
  1070. if (index == 1) { /// 取消
  1071. self?.view.window?.endSheet((self?.currentWindowController!.window)!)
  1072. self?.currentWindowController = nil
  1073. return
  1074. }
  1075. /// 拆分
  1076. let windowController_split: KMPageEditSplitWindowController = self?.currentWindowController as! KMPageEditSplitWindowController
  1077. let outputModel: KMPageEditSplitSettingModel = windowController_split.model! as! KMPageEditSplitSettingModel
  1078. self?.view.window?.endSheet((self?.currentWindowController!.window)!)
  1079. self?.currentWindowController = nil
  1080. let panel = NSOpenPanel()
  1081. panel.canChooseFiles = false
  1082. panel.canChooseDirectories = true
  1083. panel.canCreateDirectories = true
  1084. panel.beginSheetModal(for: (self?.view.window)!) { response in
  1085. KMPageEditTools.split(document!, outputModel, panel.url!.path, outputModel.outputFileNameDeletePathExtension) { result, outputDocuments, error in
  1086. if (result) {
  1087. }
  1088. }
  1089. }
  1090. }
  1091. }
  1092. }
  1093. }
  1094. }
  1095. func fastTool_Extract() { // 提取
  1096. let openPanel = NSOpenPanel()
  1097. openPanel.prompt = "提取"
  1098. openPanel.allowsMultipleSelection = false
  1099. openPanel.allowedFileTypes = ["pdf"]
  1100. openPanel.beginSheetModal(for: NSApp.mainWindow!) { result in
  1101. if result == .OK {
  1102. DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
  1103. let insertWindowController: KMPDFInsertPageWindow = KMPDFInsertPageWindow.init(documentPath: openPanel.url!, toolType: .Extract)
  1104. insertWindowController.beginSheetExtractModal(for: self.view.window!) { pdfDocument, pages, oneDocumentPerPage, isDeletePage in
  1105. self.extractPageAction(pdfDocument, pages, oneDocumentPerPage, isDeletePage)
  1106. }
  1107. }
  1108. }
  1109. }
  1110. }
  1111. func fastTool_MarkCipher() { // 标记密文
  1112. let openPanel = NSOpenPanel()
  1113. openPanel.allowsMultipleSelection = false
  1114. openPanel.allowedFileTypes = ["pdf"]
  1115. openPanel.beginSheetModal(for: NSApp.mainWindow!) { result in
  1116. if result == .cancel {
  1117. return
  1118. }
  1119. if !openPanel.url!.path.isPDFValid() {
  1120. let alert = NSAlert()
  1121. alert.alertStyle = .critical
  1122. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  1123. alert.runModal()
  1124. return
  1125. }
  1126. DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
  1127. NSDocumentController.shared.openDocument(withContentsOf: openPanel.url!, display: true) { document, result, error in
  1128. if (error != nil) {
  1129. NSApp.presentError(error!)
  1130. return
  1131. }
  1132. let toolbar = (document as! KMMainDocument).mainViewController?.toolbarController
  1133. toolbar?.enterRedact()
  1134. }
  1135. }
  1136. }
  1137. }
  1138. func fastTool_AutomaticFormRecognition() { // 表单自动识别
  1139. let openPanel = NSOpenPanel()
  1140. openPanel.prompt = "表单自动识别"
  1141. openPanel.allowsMultipleSelection = false
  1142. openPanel.allowedFileTypes = ["pdf"]
  1143. openPanel.beginSheetModal(for: NSApp.mainWindow!) { result in
  1144. if result == .OK {
  1145. }
  1146. }
  1147. }
  1148. func fastTool_PageEdit() { // 页面编辑
  1149. let openPanel = NSOpenPanel()
  1150. openPanel.allowsMultipleSelection = false
  1151. openPanel.allowedFileTypes = ["pdf"]
  1152. openPanel.beginSheetModal(for: NSApp.mainWindow!) { result in
  1153. if result == .cancel {
  1154. return
  1155. }
  1156. if !openPanel.url!.path.isPDFValid() {
  1157. let alert = NSAlert()
  1158. alert.alertStyle = .critical
  1159. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  1160. alert.runModal()
  1161. return
  1162. }
  1163. DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
  1164. NSDocumentController.shared.openDocument(withContentsOf: openPanel.url!, display: true) { document, result, error in
  1165. if (error != nil) {
  1166. NSApp.presentError(error!)
  1167. return
  1168. }
  1169. let mainView = (document as! KMMainDocument).mainViewController
  1170. mainView?.enterPageEdit()
  1171. }
  1172. }
  1173. }
  1174. }
  1175. // MARK: MenuItem Action & PopoverItem Action
  1176. func popoverItemAction(_ count: String) {
  1177. if count == NSLocalizedString("New Blank Page", comment: "") {
  1178. openBlankPage("")
  1179. } else if count == NSLocalizedString("New From Web Page", comment: "") {
  1180. importFromWebPage("")
  1181. } else if count == NSLocalizedString("Import From Scanner", comment: "") {
  1182. importFromScanner("")
  1183. }
  1184. }
  1185. @IBAction func escButtonAction(_ sender: Any) {
  1186. self.historyFileViewController.selectFiles.removeAll()
  1187. if self.historyFileViewController.showMode == .Thumbnail {
  1188. self.historyFileViewController.historyFileCollectionView.reloadData()
  1189. } else {
  1190. self.historyFileViewController.historyFileTableView.reloadData()
  1191. }
  1192. }
  1193. @IBAction func importFromFile(_ sender: Any) {
  1194. self.openSupportPDFButtonAction()
  1195. }
  1196. @IBAction func openBlankPage(_ sender: Any) {
  1197. let fileName: NSString = String(format: "%@.pdf", NSLocalizedString("Untitled", comment: "")) as NSString
  1198. let savePath = fetchUniquePath(fileName.kUrlToPDFFolderPath())
  1199. let pdfDocument = CPDFDocument()
  1200. pdfDocument?.insertPage(CGSize(width: 595, height: 842), at: 0)
  1201. pdfDocument?.write(to: URL(fileURLWithPath: savePath))
  1202. NSDocumentController.shared.openDocument(withContentsOf: URL(fileURLWithPath: savePath), display: true) { document, documentWasAlreadyOpen, error in
  1203. if error != nil {
  1204. NSApp.presentError(error!)
  1205. } else {
  1206. if document is KMMainDocument {
  1207. let newDocument = document
  1208. (newDocument as! KMMainDocument).isNewCreated = true
  1209. }
  1210. }
  1211. }
  1212. }
  1213. @IBAction func importFromWebPage(_ sender: Any) {
  1214. self.urlToPDFWindowController = KMURLToPDFWindowController.init(windowNibName: NSNib.Name("KMURLToPDFWindowController"))
  1215. self.urlToPDFWindowController!.beginSheetModal(for: NSApp.mainWindow!) { filePath in
  1216. if filePath != nil && FileManager.default.fileExists(atPath: filePath) {
  1217. NSDocumentController.shared.openDocument(withContentsOf: URL(fileURLWithPath: filePath), display: true) { document, documentWasAlreadyOpen, error in
  1218. if error != nil {
  1219. NSApp.presentError(error!)
  1220. } else {
  1221. if document is KMMainDocument {
  1222. (document as! KMMainDocument).isNewCreated = true
  1223. }
  1224. }
  1225. }
  1226. }
  1227. }
  1228. }
  1229. @IBAction func importFromScanner(_ sender: Any) {
  1230. deviceBrowserWC = KMDeviceBrowserWindowController.shared
  1231. deviceBrowserWC?.type = .scanner
  1232. deviceBrowserWC?.importScannerFileCallback = { [weak self](url: NSURL) -> Void in
  1233. self?.openFile(withFilePath: url as URL)
  1234. }
  1235. deviceBrowserWC?.showWindow(NSApp.mainWindow)
  1236. }
  1237. @IBAction func menuItemClick_mergePDF(_ sender: Any) {
  1238. fastTool_MergePDF()
  1239. }
  1240. @IBAction func menuItemClick_Compress(_ sender: Any) {
  1241. fastTool_Compression()
  1242. }
  1243. @IBAction func menuItemClick_Convert(_ sender: Any) {
  1244. fastTool_ConvertPDF()
  1245. }
  1246. @IBAction func menuItemClick_SettingPassword(_ sender: Any) {
  1247. fastTool_Security()
  1248. }
  1249. @IBAction func menuItemClick_RemovePassword(_ sender: Any) {
  1250. fastTool_Security()
  1251. }
  1252. func fetchUniquePath(_ originalPath: String) -> String {
  1253. var path = originalPath
  1254. let dManager = FileManager.default
  1255. if !dManager.fileExists(atPath: path) {
  1256. if path.extension.count < 1 {
  1257. path = path.stringByAppendingPathExtension("pdf")
  1258. }
  1259. return path
  1260. } else {
  1261. let originalFullFileName = path.lastPathComponent
  1262. let originalFileName = path.lastPathComponent.deletingPathExtension.lastPathComponent
  1263. let originalExtension = path.extension
  1264. let startIndex: Int = 0
  1265. let endIndex: Int = startIndex + originalPath.count - originalFullFileName.count - 1
  1266. let fileLocatePath = originalPath.substring(to: endIndex)
  1267. var i = 1
  1268. while (1 != 0) {
  1269. var newName = String(format: "%@%ld", originalFileName, i)
  1270. newName = String(format: "%@%@", newName, originalExtension)
  1271. let newPath = fileLocatePath.stringByAppendingPathComponent(newName)
  1272. if !dManager.fileExists(atPath: newPath) {
  1273. return newPath
  1274. } else {
  1275. i+=1
  1276. continue
  1277. }
  1278. }
  1279. }
  1280. }
  1281. // func kNewDocumentTempSavePath(_ fileName: String) -> String {
  1282. // let searchPath = NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory, .userDomainMask, true).last
  1283. //// let append1 = searchPath?.stringByAppendingPathComponent(Bundle.main.bundleIdentifier!)
  1284. // let append2 = searchPath!.stringByAppendingPathComponent(String(format: "%@", fileName))
  1285. // return append2
  1286. // }
  1287. // MARK: Notification
  1288. @objc func homeFileRectChange(_ notification: Notification) -> Void {
  1289. let window = notification.object
  1290. self.historyFileViewController.reloadData()
  1291. }
  1292. }
  1293. // MARK: window Menu
  1294. extension KMHomeViewController {
  1295. @IBAction func menuItemAction_showForwardTagPage(_ sender: Any) {
  1296. (self.myDocument as! KMMainDocument).browser.selectPreviousTab()
  1297. }
  1298. @IBAction func menuItemAction_showNextTagPage(_ sender: Any) {
  1299. (self.myDocument as! KMMainDocument).browser.selectNextTab()
  1300. }
  1301. @IBAction func menuItemAction_newTagPageToNewWindow(_ sender: Any) {
  1302. let browser = (self.myDocument as! KMMainDocument).browser
  1303. ((browser as! KMBrowser).windowController as? KMBrowserWindowController)?.openNewWindow(sender)
  1304. }
  1305. @IBAction func menuItemAction_mergeAllWindow(_ sender: Any) {
  1306. ((self.myDocument as? KMMainDocument)?.browser.windowController as? KMBrowserWindowController)?.mergeAllWindow(sender)
  1307. }
  1308. @IBAction func menuItemAction_currentWindowName(_ sender: Any) {
  1309. }
  1310. }
  1311. // MARK: file Menu
  1312. extension KMHomeViewController {
  1313. @IBAction func menuItemAction_closeWindow(_ sender: Any) {
  1314. self.view.window?.close()
  1315. }
  1316. @IBAction func menuItemAction_closeAllWindows(_ sender: Any) {
  1317. for window in NSApp.windows {
  1318. window.close()
  1319. }
  1320. }
  1321. @IBAction func menuItemAction_ConvertToWord(_ sender: Any) {
  1322. self.fastTool_PDFToWord()
  1323. }
  1324. @IBAction func menuItemAction_ConvertToExcel(_ sender: Any) {
  1325. self.fastTool_PDFToExcel()
  1326. }
  1327. @IBAction func menuItemAction_ConvertToPPT(_ sender: Any) {
  1328. self.fastTool_PDFToPPT()
  1329. }
  1330. @IBAction func menuItemAction_ConvertToRTF(_ sender: Any) {
  1331. self.showConvertWindow(type: .rtf)
  1332. }
  1333. @IBAction func menuItemAction_ConvertToHTML(_ sender: Any) {
  1334. self.showConvertWindow(type: .html)
  1335. }
  1336. @IBAction func menuItemAction_ConvertToText(_ sender: Any) {
  1337. self.showConvertWindow(type: .text)
  1338. }
  1339. @IBAction func menuItemAction_ConvertToCSV(_ sender: Any) {
  1340. self.showConvertWindow(type: .csv)
  1341. }
  1342. @IBAction func menuItemAction_ConvertToImage(_ sender: Any) {
  1343. self.fastTool_PDFToImage()
  1344. }
  1345. }
  1346. // MARK: help Menu
  1347. extension KMHomeViewController {
  1348. // @IBAction func menuItemAction_search(_ sender: Any) {
  1349. //
  1350. // }
  1351. }