KMAIOpenPDFFilesVC.swift 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  1. //
  2. // KMAIOpenPDFFilesVC.swift
  3. // PDF Master
  4. //
  5. // Created by wanjun on 2023/5/22.
  6. //
  7. import Cocoa
  8. class KMAIOpenPDFFilesVC: NSViewController {
  9. @IBOutlet weak var openPDFFilesLabel: NSTextField!
  10. @IBOutlet weak var openPDFFilesImageView: NSImageView!
  11. @IBOutlet weak var selectYourFilesBox: KMBox!
  12. @IBOutlet weak var selectYourFilesLabel: NSTextField!
  13. @IBOutlet weak var selectYourFilesImageView: NSImageView!
  14. @IBOutlet weak var orDropFilesHereToOpenLabel: NSTextField!
  15. @IBOutlet weak var creatPDFLabel: NSTextField!
  16. @IBOutlet weak var newFromFilesLabel: NSTextField!
  17. @IBOutlet weak var newFromFilesImageView: NSImageView!
  18. @IBOutlet weak var newBlankPageLabel: NSTextField!
  19. @IBOutlet weak var newBlankPageImageView: NSImageView!
  20. @IBOutlet weak var importFromScannerLabel: NSTextField!
  21. @IBOutlet weak var importFromScannerImageView: NSImageView!
  22. var deviceBrowserWC: KMDeviceBrowserWindowController?
  23. override func viewDidLoad() {
  24. super.viewDidLoad()
  25. // Do view setup here.
  26. self.initLocalization()
  27. self.initializeUI()
  28. }
  29. // MARK: initialize
  30. func initializeUI() -> Void {
  31. self.openPDFFilesLabel.textColor = NSColor(hex: "#252629")
  32. self.openPDFFilesLabel.font = NSFont.SFProTextSemibold(20.0)
  33. self.openPDFFilesImageView.image = NSImage(named: "icon_empty_addFiles")
  34. self.selectYourFilesBox.cornerRadius = 4.0
  35. self.selectYourFilesBox.fillColor = NSColor(hex: "#1770F4")
  36. self.selectYourFilesLabel.textColor = NSColor(hex: "#FFFFFF")
  37. self.selectYourFilesLabel.font = NSFont.SFProTextRegular(16.0)
  38. self.selectYourFilesImageView.image = NSImage(named: "icon_SelectYourFiles")
  39. self.orDropFilesHereToOpenLabel.textColor = NSColor(hex: "#616469")
  40. self.orDropFilesHereToOpenLabel.font = NSFont.SFProTextRegular(14.0)
  41. self.creatPDFLabel.textColor = NSColor(hex: "#252629")
  42. self.creatPDFLabel.font = NSFont.SFProTextSemibold(20.0)
  43. self.newFromFilesLabel.textColor = NSColor(hex: "#252629")
  44. self.newFromFilesLabel.font = NSFont.SFProTextRegular(16.0)
  45. self.newFromFilesImageView.image = NSImage(named: "icon_empty_NewFromFiles")
  46. self.newBlankPageLabel.textColor = NSColor(hex: "#252629")
  47. self.newBlankPageLabel.font = NSFont.SFProTextRegular(16.0)
  48. self.newBlankPageImageView.image = NSImage(named: "icon_empty_NewBlackPage")
  49. self.importFromScannerLabel.textColor = NSColor(hex: "#252629")
  50. self.importFromScannerLabel.font = NSFont.SFProTextRegular(16.0)
  51. self.importFromScannerImageView.image = NSImage(named: "icon_empty_ImportFromScanner")
  52. self.selectYourFilesBox.moveCallback = { [unowned self](mouseEntered: Bool, mouseBox: KMBox) -> Void in
  53. if mouseEntered {
  54. self.selectYourFilesBox.fillColor = NSColor(hex: "#3F8FF6")
  55. } else {
  56. self.selectYourFilesBox.fillColor = NSColor(hex: "#1770F4")
  57. }
  58. }
  59. self.selectYourFilesBox.downCallback = { [unowned self](downEntered: Bool, mouseBox: KMBox, event) -> Void in
  60. if downEntered {
  61. self.openPDFButtonAction()
  62. }
  63. }
  64. }
  65. func initLocalization() -> Void {
  66. self.openPDFFilesLabel.stringValue = NSLocalizedString("Open PDF Files", comment: "")
  67. self.selectYourFilesLabel.stringValue = NSLocalizedString("Select Your Files", comment: "")
  68. self.orDropFilesHereToOpenLabel.stringValue = NSLocalizedString("or drop files here to open", comment: "")
  69. self.creatPDFLabel.stringValue = NSLocalizedString("Create PDF", comment: "")
  70. self.newFromFilesLabel.stringValue = NSLocalizedString("New From Files", comment: "")
  71. self.newBlankPageLabel.stringValue = NSLocalizedString("New Blank Page", comment: "")
  72. self.importFromScannerLabel.stringValue = NSLocalizedString("Import From Scanner", comment: "")
  73. }
  74. // MARK: Private Methods
  75. func openImageFile(url: URL) -> Void {
  76. let filePath = url.path
  77. let fileName: NSString = url.lastPathComponent as NSString
  78. let savePath = fetchUniquePath(fileName.kUrlToPDFFolderPath()).deletingLastPathComponent
  79. let imageName = NSString(string: NSString(string: filePath).lastPathComponent).deletingPathExtension
  80. let path = self.fetchDifferentFilePath(filePath: savePath + "/" + imageName + ".pdf")
  81. if (!FileManager.default.fileExists(atPath: path.deletingLastPathComponent as String)) {
  82. try?FileManager.default.createDirectory(atPath: path.deletingLastPathComponent as String, withIntermediateDirectories: true, attributes: nil)
  83. }
  84. if (!FileManager.default.fileExists(atPath: path as String)) {
  85. FileManager.default.createFile(atPath: path as String, contents: nil)
  86. }
  87. let document = CPDFDocument.init()
  88. var success = false
  89. //FIXME: 无法插入图片
  90. let image = NSImage(contentsOfFile: filePath)
  91. let insertPageSuccess = document?.insertPage(image!.size, withImage: filePath, at: document!.pageCount)
  92. if insertPageSuccess != nil {
  93. //信号量控制异步
  94. let semaphore = DispatchSemaphore(value: 0)
  95. DispatchQueue.global().async {
  96. success = ((document?.write(toFile: path)) != nil)
  97. semaphore.signal()
  98. }
  99. semaphore.wait()
  100. } else {
  101. }
  102. if success {
  103. if !path.isPDFValid() {
  104. let alert = NSAlert()
  105. alert.alertStyle = .critical
  106. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  107. alert.runModal()
  108. return
  109. }
  110. NSDocumentController.shared.openDocument(withContentsOf: URL(fileURLWithPath: path), display: true) { document, documentWasAlreadyOpen, error in
  111. if error != nil {
  112. NSApp.presentError(error!)
  113. return
  114. }
  115. }
  116. }
  117. }
  118. func openOfficeFile(url: URL) -> Void {
  119. let filePath = url.path
  120. let folderPath = "convertToPDF.pdf"
  121. let savePath = folderPath.kUrlToPDFFolderPath()
  122. if (!FileManager.default.fileExists(atPath: savePath!.deletingLastPathComponent as String)) {
  123. try?FileManager.default.createDirectory(atPath: savePath!.deletingLastPathComponent as String, withIntermediateDirectories: true, attributes: nil)
  124. }
  125. if (!FileManager.default.fileExists(atPath: savePath! as String)) {
  126. FileManager.default.createFile(atPath: savePath! as String, contents: nil)
  127. }
  128. if savePath == nil {
  129. return
  130. }
  131. KMConvertPDFManagerOC.convertFile(filePath, savePath: savePath!) { success, errorDic in
  132. if errorDic != nil || !success || !FileManager.default.fileExists(atPath: savePath!) {
  133. if FileManager.default.fileExists(atPath: savePath!) {
  134. try?FileManager.default.removeItem(atPath: savePath!)
  135. }
  136. let alert = NSAlert.init()
  137. alert.alertStyle = .critical
  138. var infoString = ""
  139. if errorDic != nil {
  140. for key in (errorDic! as Dictionary).keys {
  141. infoString = infoString.appendingFormat("%@\n", errorDic![key] as! CVarArg)
  142. }
  143. }
  144. alert.informativeText = NSLocalizedString("Please install Microsoft Office to create PDFs from Office files", comment: "")
  145. alert.messageText = NSLocalizedString("Failed to Create PDF", comment: "")
  146. alert.addButton(withTitle: NSLocalizedString("OK", comment: ""))
  147. alert.runModal()
  148. return
  149. }
  150. if !savePath!.isPDFValid() {
  151. let alert = NSAlert()
  152. alert.alertStyle = .critical
  153. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  154. alert.runModal()
  155. return
  156. }
  157. NSDocumentController.shared.openDocument(withContentsOf: URL(fileURLWithPath: savePath!), display: true) { document, documentWasAlreadyOpen, error in
  158. if error != nil {
  159. NSApp.presentError(error!)
  160. return
  161. }
  162. }
  163. }
  164. }
  165. func fetchUniquePath(_ originalPath: String) -> String {
  166. var path = originalPath
  167. let dManager = FileManager.default
  168. if !dManager.fileExists(atPath: path) {
  169. if path.extension.count < 1 {
  170. path = path.stringByAppendingPathExtension("pdf")
  171. }
  172. return path
  173. } else {
  174. let originalFullFileName = path.lastPathComponent
  175. let originalFileName = path.lastPathComponent.deletingPathExtension.lastPathComponent
  176. let originalExtension = path.extension
  177. let startIndex: Int = 0
  178. let endIndex: Int = startIndex + originalPath.count - originalFullFileName.count - 1
  179. let fileLocatePath = originalPath.substring(to: endIndex)
  180. var i = 1
  181. while (1 != 0) {
  182. var newName = String(format: "%@%ld", originalFileName, i)
  183. newName = String(format: "%@%@", newName, originalExtension)
  184. let newPath = fileLocatePath.stringByAppendingPathComponent(newName)
  185. if !dManager.fileExists(atPath: newPath) {
  186. return newPath
  187. } else {
  188. i+=1
  189. continue
  190. }
  191. }
  192. }
  193. }
  194. func fetchDifferentFilePath(filePath: String) -> String {
  195. var resultFilePath = filePath
  196. var index: Int = 0
  197. while (FileManager.default.fileExists(atPath: resultFilePath)) {
  198. index += 1
  199. let path = NSString(string: filePath).deletingPathExtension + "(" + String(index) + ")"
  200. resultFilePath = NSString(string: path).appendingPathExtension(NSString(string: filePath).pathExtension)!
  201. }
  202. return resultFilePath;
  203. }
  204. func openFile(withFilePath path: URL) -> Void {
  205. let type = path.pathExtension.lowercased()
  206. if (type == "pdf") {
  207. if !path.path.isPDFValid() {
  208. let alert = NSAlert()
  209. alert.alertStyle = .critical
  210. alert.messageText = NSLocalizedString("This file format is not supported, please drag in PDF, picture, Office format files", comment: "")
  211. alert.runModal()
  212. return
  213. }
  214. NSDocumentController.shared.openDocument(withContentsOf: path, display: true) { document, documentWasAlreadyOpen, error in
  215. if error != nil {
  216. NSApp.presentError(error!)
  217. return
  218. }
  219. }
  220. } else if (type == "jpg") ||
  221. (type == "cur") ||
  222. (type == "bmp") ||
  223. (type == "jpeg") ||
  224. (type == "gif") ||
  225. (type == "png") ||
  226. (type == "tiff") ||
  227. (type == "tif") ||
  228. (type == "ico") ||
  229. (type == "icns") ||
  230. (type == "tga") ||
  231. (type == "psd") ||
  232. (type == "eps") ||
  233. (type == "hdr") ||
  234. (type == "jp2") ||
  235. (type == "jpc") ||
  236. (type == "pict") ||
  237. (type == "sgi") ||
  238. (type == "heic") {
  239. openImageFile(url: path)
  240. } else if (type == "doc") ||
  241. (type == "docx") ||
  242. (type == "xls") ||
  243. (type == "xlsx") ||
  244. (type == "ppt") ||
  245. (type == "pptx") ||
  246. (type == "pptx") {
  247. let fileName: NSString = String(format: "%@.pdf", NSLocalizedString("Untitled", comment: "")) as NSString
  248. let savePath = fetchUniquePath(fileName.kUrlToPDFFolderPath())
  249. openOfficeFile(url: path)
  250. }
  251. }
  252. // MARK: Action
  253. @IBAction func createPDFAction(_ sender: NSButton) {
  254. let tag = sender.tag;
  255. if tag == 0 {
  256. // New From Files
  257. self.openSupportPDFButtonAction()
  258. } else if tag == 1 {
  259. // New Blank Page
  260. self.openBlankPage("")
  261. } else if tag == 2 {
  262. // Import From Scanner
  263. self.importFromScanner("")
  264. }
  265. }
  266. func openPDFButtonAction() {
  267. let openPanel = NSOpenPanel()
  268. openPanel.allowedFileTypes = ["pdf", "PDF"]
  269. openPanel.allowsMultipleSelection = true
  270. openPanel.beginSheetModal(for: self.view.window!) { result in
  271. if result == .OK {
  272. for url in openPanel.urls {
  273. if !url.path.isPDFValid() {
  274. let alert = NSAlert()
  275. alert.alertStyle = .critical
  276. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  277. alert.runModal()
  278. } else {
  279. NSDocumentController.shared.openDocument(withContentsOf: url, display: true) { document, documentWasAlreadyOpen, error in
  280. if error != nil {
  281. NSApp.presentError(error!)
  282. } else {
  283. }
  284. }
  285. }
  286. }
  287. }
  288. }
  289. }
  290. func openSupportPDFButtonAction() {
  291. let openPanel = NSOpenPanel()
  292. openPanel.allowedFileTypes = ["pdf", "PDF", "jpg", "cur", "bmp", "jpeg", "gif", "png", "tiff", "tif", "ico", "icns", "tga", "psd", "eps", "hdr", "jp2", "jpc", "pict", "sgi", "heic", "doc", "docx", "xls", "xlsx", "ppt", "pptx", "pptx"]
  293. openPanel.allowsMultipleSelection = true
  294. var window = self.view.window
  295. if (window == nil) {
  296. window = NSApp.mainWindow
  297. }
  298. openPanel.beginSheetModal(for: window!) { [self] result in
  299. if result == .OK {
  300. var imageUrl: [URL] = []
  301. for url in openPanel.urls {
  302. let type = url.pathExtension.lowercased()
  303. if (type == "pdf" || type == "PDF") {
  304. if !url.path.isPDFValid() {
  305. let alert = NSAlert()
  306. alert.alertStyle = .critical
  307. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  308. alert.runModal()
  309. } else {
  310. NSDocumentController.shared.openDocument(withContentsOf: url, display: true) { document, documentWasAlreadyOpen, error in
  311. if error != nil {
  312. NSApp.presentError(error!)
  313. return
  314. }
  315. }
  316. }
  317. } else if (type == "jpg") ||
  318. (type == "cur") ||
  319. (type == "bmp") ||
  320. (type == "jpeg") ||
  321. (type == "gif") ||
  322. (type == "png") ||
  323. (type == "tiff") ||
  324. (type == "tif") ||
  325. (type == "ico") ||
  326. (type == "icns") ||
  327. (type == "tga") ||
  328. (type == "psd") ||
  329. (type == "eps") ||
  330. (type == "hdr") ||
  331. (type == "jp2") ||
  332. (type == "jpc") ||
  333. (type == "pict") ||
  334. (type == "sgi") ||
  335. (type == "heic") {
  336. openImageFile(url: url)
  337. } else if (type == "doc") ||
  338. (type == "docx") ||
  339. (type == "xls") ||
  340. (type == "xlsx") ||
  341. (type == "ppt") ||
  342. (type == "pptx") ||
  343. (type == "pptx") {
  344. self.openOfficeFile(url: url)
  345. }
  346. }
  347. }
  348. }
  349. }
  350. @IBAction func openBlankPage(_ sender: Any) {
  351. let fileName: NSString = String(format: "%@.pdf", NSLocalizedString("Untitled", comment: "")) as NSString
  352. let savePath = fetchUniquePath(fileName.kUrlToPDFFolderPath())
  353. if (!FileManager.default.fileExists(atPath: savePath.deletingLastPathComponent as String)) {
  354. try?FileManager.default.createDirectory(atPath: savePath.deletingLastPathComponent as String, withIntermediateDirectories: true, attributes: nil)
  355. }
  356. if (!FileManager.default.fileExists(atPath: savePath as String)) {
  357. FileManager.default.createFile(atPath: savePath as String, contents: nil)
  358. }
  359. let pdfDocument = CPDFDocument()
  360. pdfDocument?.insertPage(CGSize(width: 595, height: 842), at: 0)
  361. pdfDocument?.write(to: URL(fileURLWithPath: savePath))
  362. NSDocumentController.shared.openDocument(withContentsOf: URL(fileURLWithPath: savePath), display: true) { document, documentWasAlreadyOpen, error in
  363. if error != nil {
  364. NSApp.presentError(error!)
  365. } else {
  366. if document is KMMainDocument {
  367. let newDocument = document
  368. (newDocument as! KMMainDocument).isNewCreated = true
  369. }
  370. }
  371. }
  372. }
  373. @IBAction func importFromScanner(_ sender: Any) {
  374. deviceBrowserWC = KMDeviceBrowserWindowController.init(windowNibName: "KMDeviceBrowserWindowController")
  375. deviceBrowserWC!.type = .scanner
  376. deviceBrowserWC!.importScannerFileCallback = { [unowned self](url: NSURL) -> Void in
  377. openFile(withFilePath: url as URL)
  378. }
  379. deviceBrowserWC!.showWindow(NSApp.mainWindow)
  380. }
  381. }