123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398 |
- //
- // KMAIOpenPDFFilesVC.swift
- // PDF Master
- //
- // Created by wanjun on 2023/5/22.
- //
- import Cocoa
- class KMAIOpenPDFFilesVC: NSViewController {
-
- @IBOutlet weak var openPDFFilesLabel: NSTextField!
- @IBOutlet weak var openPDFFilesImageView: NSImageView!
- @IBOutlet weak var selectYourFilesBox: KMBox!
- @IBOutlet weak var selectYourFilesLabel: NSTextField!
- @IBOutlet weak var selectYourFilesImageView: NSImageView!
- @IBOutlet weak var orDropFilesHereToOpenLabel: NSTextField!
- @IBOutlet weak var creatPDFLabel: NSTextField!
- @IBOutlet weak var newFromFilesLabel: NSTextField!
- @IBOutlet weak var newFromFilesImageView: NSImageView!
- @IBOutlet weak var newBlankPageLabel: NSTextField!
- @IBOutlet weak var newBlankPageImageView: NSImageView!
- @IBOutlet weak var importFromScannerLabel: NSTextField!
- @IBOutlet weak var importFromScannerImageView: NSImageView!
- var deviceBrowserWC: KMDeviceBrowserWindowController?
- override func viewDidLoad() {
- super.viewDidLoad()
- // Do view setup here.
-
- self.initLocalization()
- self.initializeUI()
- }
-
-
- // MARK: initialize
-
- func initializeUI() -> Void {
- self.openPDFFilesLabel.textColor = NSColor(hex: "#252629")
- self.openPDFFilesLabel.font = NSFont.SFProTextSemibold(20.0)
- self.openPDFFilesImageView.image = NSImage(named: "icon_empty_addFiles")
- self.selectYourFilesBox.cornerRadius = 4.0
- self.selectYourFilesBox.fillColor = NSColor(hex: "#1770F4")
- self.selectYourFilesLabel.textColor = NSColor(hex: "#FFFFFF")
- self.selectYourFilesLabel.font = NSFont.SFProTextRegular(16.0)
- self.selectYourFilesImageView.image = NSImage(named: "icon_SelectYourFiles")
- self.orDropFilesHereToOpenLabel.textColor = NSColor(hex: "#616469")
- self.orDropFilesHereToOpenLabel.font = NSFont.SFProTextRegular(14.0)
-
- self.creatPDFLabel.textColor = NSColor(hex: "#252629")
- self.creatPDFLabel.font = NSFont.SFProTextSemibold(20.0)
- self.newFromFilesLabel.textColor = NSColor(hex: "#252629")
- self.newFromFilesLabel.font = NSFont.SFProTextRegular(16.0)
- self.newFromFilesImageView.image = NSImage(named: "icon_empty_NewFromFiles")
- self.newBlankPageLabel.textColor = NSColor(hex: "#252629")
- self.newBlankPageLabel.font = NSFont.SFProTextRegular(16.0)
- self.newBlankPageImageView.image = NSImage(named: "icon_empty_NewBlackPage")
- self.importFromScannerLabel.textColor = NSColor(hex: "#252629")
- self.importFromScannerLabel.font = NSFont.SFProTextRegular(16.0)
- self.importFromScannerImageView.image = NSImage(named: "icon_empty_ImportFromScanner")
-
- self.selectYourFilesBox.moveCallback = { [unowned self](mouseEntered: Bool, mouseBox: KMBox) -> Void in
- if mouseEntered {
- self.selectYourFilesBox.fillColor = NSColor(hex: "#3F8FF6")
- } else {
- self.selectYourFilesBox.fillColor = NSColor(hex: "#1770F4")
- }
- }
- self.selectYourFilesBox.downCallback = { [unowned self](downEntered: Bool, mouseBox: KMBox, event) -> Void in
- if downEntered {
- self.openPDFButtonAction()
- }
- }
- }
-
- func initLocalization() -> Void {
- self.openPDFFilesLabel.stringValue = NSLocalizedString("Open PDF Files", comment: "")
- self.selectYourFilesLabel.stringValue = NSLocalizedString("Select Your Files", comment: "")
- self.orDropFilesHereToOpenLabel.stringValue = NSLocalizedString("or drop files here to open", comment: "")
- self.creatPDFLabel.stringValue = NSLocalizedString("Create PDF", comment: "")
- self.newFromFilesLabel.stringValue = NSLocalizedString("New From Files", comment: "")
- self.newBlankPageLabel.stringValue = NSLocalizedString("New Blank Page", comment: "")
- self.importFromScannerLabel.stringValue = NSLocalizedString("Import From Scanner", comment: "")
- }
-
- // MARK: Private Methods
-
- func openImageFile(url: URL) -> Void {
- let filePath = url.path
-
- let fileName: NSString = url.lastPathComponent as NSString
- let savePath = fetchUniquePath(fileName.kUrlToPDFFolderPath()).deletingLastPathComponent
- let imageName = NSString(string: NSString(string: filePath).lastPathComponent).deletingPathExtension
-
- let path = self.fetchDifferentFilePath(filePath: savePath + "/" + imageName + ".pdf")
- let document = CPDFDocument.init()
- var success = false
-
- //FIXME: 无法插入图片
- let image = NSImage(contentsOfFile: filePath)
- let insertPageSuccess = document?.insertPage(image!.size, withImage: filePath, at: document!.pageCount)
- if insertPageSuccess != nil {
- //信号量控制异步
- let semaphore = DispatchSemaphore(value: 0)
- DispatchQueue.global().async {
- success = ((document?.write(toFile: path)) != nil)
- semaphore.signal()
- }
- semaphore.wait()
- } else {
- }
- if success {
- if !path.isPDFValid() {
- let alert = NSAlert()
- alert.alertStyle = .critical
- alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
- alert.runModal()
- return
- }
- NSDocumentController.shared.openDocument(withContentsOf: URL(fileURLWithPath: path), display: true) { document, documentWasAlreadyOpen, error in
- if error != nil {
- NSApp.presentError(error!)
- return
- }
- }
- }
- }
-
- func openOfficeFile(url: URL) -> Void {
- let filePath = url.path
- let folderPath = "convertToPDF.pdf"
- let savePath = folderPath.kUrlToPDFFolderPath()
- if savePath == nil {
- return
- }
- KMConvertPDFManagerOC.convertFile(filePath, savePath: savePath!) { success, errorDic in
- if errorDic != nil || !success || !FileManager.default.fileExists(atPath: savePath!) {
- if FileManager.default.fileExists(atPath: savePath!) {
- try?FileManager.default.removeItem(atPath: savePath!)
- }
- let alert = NSAlert.init()
- alert.alertStyle = .critical
- var infoString = ""
- if errorDic != nil {
- for key in (errorDic! as Dictionary).keys {
- infoString = infoString.appendingFormat("%@\n", errorDic![key] as! CVarArg)
- }
- }
- alert.informativeText = NSLocalizedString("Please install Microsoft Office to create PDFs from Office files", comment: "")
- alert.messageText = NSLocalizedString("Failed to Create PDF", comment: "")
- alert.addButton(withTitle: NSLocalizedString("OK", comment: ""))
- alert.runModal()
- return
- }
-
- if !savePath!.isPDFValid() {
- let alert = NSAlert()
- alert.alertStyle = .critical
- alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
- alert.runModal()
- return
- }
- NSDocumentController.shared.openDocument(withContentsOf: URL(fileURLWithPath: savePath!), display: true) { document, documentWasAlreadyOpen, error in
- if error != nil {
- NSApp.presentError(error!)
- return
- }
- }
- }
- }
-
- func fetchUniquePath(_ originalPath: String) -> String {
- var path = originalPath
- let dManager = FileManager.default
- if !dManager.fileExists(atPath: path) {
- if path.extension.count < 1 {
- path = path.stringByAppendingPathExtension("pdf")
- }
- return path
- } else {
- let originalFullFileName = path.lastPathComponent
- let originalFileName = path.lastPathComponent.deletingPathExtension.lastPathComponent
- let originalExtension = path.extension
- let startIndex: Int = 0
- let endIndex: Int = startIndex + originalPath.count - originalFullFileName.count - 1
- let fileLocatePath = originalPath.substring(to: endIndex)
- var i = 1
- while (1 != 0) {
- var newName = String(format: "%@%ld", originalFileName, i)
- newName = String(format: "%@%@", newName, originalExtension)
- let newPath = fileLocatePath.stringByAppendingPathComponent(newName)
- if !dManager.fileExists(atPath: newPath) {
- return newPath
- } else {
- i+=1
- continue
- }
- }
- }
- }
-
- func fetchDifferentFilePath(filePath: String) -> String {
- var resultFilePath = filePath
- var index: Int = 0
- while (FileManager.default.fileExists(atPath: resultFilePath)) {
- index += 1
- let path = NSString(string: filePath).deletingPathExtension + "(" + String(index) + ")"
- resultFilePath = NSString(string: path).appendingPathExtension(NSString(string: filePath).pathExtension)!
- }
-
- return resultFilePath;
- }
-
- func openFile(withFilePath path: URL) -> Void {
- let type = path.pathExtension.lowercased()
- if (type == "pdf") {
- if !path.path.isPDFValid() {
- let alert = NSAlert()
- alert.alertStyle = .critical
- alert.messageText = NSLocalizedString("This file format is not supported, please drag in PDF, picture, Office format files", comment: "")
- alert.runModal()
- return
- }
- NSDocumentController.shared.openDocument(withContentsOf: path, display: true) { document, documentWasAlreadyOpen, error in
- if error != nil {
- NSApp.presentError(error!)
- return
- }
- }
- } else if (type == "jpg") ||
- (type == "cur") ||
- (type == "bmp") ||
- (type == "jpeg") ||
- (type == "gif") ||
- (type == "png") ||
- (type == "tiff") ||
- (type == "tif") ||
- (type == "ico") ||
- (type == "icns") ||
- (type == "tga") ||
- (type == "psd") ||
- (type == "eps") ||
- (type == "hdr") ||
- (type == "jp2") ||
- (type == "jpc") ||
- (type == "pict") ||
- (type == "sgi") ||
- (type == "heic") {
- openImageFile(url: path)
- } else if (type == "doc") ||
- (type == "docx") ||
- (type == "xls") ||
- (type == "xlsx") ||
- (type == "ppt") ||
- (type == "pptx") ||
- (type == "pptx") {
- let fileName: NSString = String(format: "%@.pdf", NSLocalizedString("Untitled", comment: "")) as NSString
- let savePath = fetchUniquePath(fileName.kUrlToPDFFolderPath())
- openOfficeFile(url: path)
- }
- }
-
- // MARK: Action
-
- @IBAction func createPDFAction(_ sender: NSButton) {
- let tag = sender.tag;
- if tag == 0 {
- // New From Files
- self.openSupportPDFButtonAction()
- } else if tag == 1 {
- // New Blank Page
- self.openBlankPage("")
- } else if tag == 2 {
- // Import From Scanner
- self.importFromScanner("")
- }
- }
-
- func openPDFButtonAction() {
- let openPanel = NSOpenPanel()
- openPanel.allowedFileTypes = ["pdf", "PDF"]
- openPanel.allowsMultipleSelection = true
- openPanel.beginSheetModal(for: self.view.window!) { result in
- if result == .OK {
- for url in openPanel.urls {
- if !url.path.isPDFValid() {
- let alert = NSAlert()
- alert.alertStyle = .critical
- alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
- alert.runModal()
- } else {
- NSDocumentController.shared.openDocument(withContentsOf: url, display: true) { document, documentWasAlreadyOpen, error in
- if error != nil {
- NSApp.presentError(error!)
- } else {
-
- }
- }
- }
- }
- }
- }
- }
-
- func openSupportPDFButtonAction() {
- let openPanel = NSOpenPanel()
- 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"]
- openPanel.allowsMultipleSelection = true
-
- var window = self.view.window
- if (window == nil) {
- window = NSApp.mainWindow
- }
- openPanel.beginSheetModal(for: window!) { [self] result in
- if result == .OK {
- var imageUrl: [URL] = []
- for url in openPanel.urls {
- let type = url.pathExtension.lowercased()
- if (type == "pdf" || type == "PDF") {
- if !url.path.isPDFValid() {
- let alert = NSAlert()
- alert.alertStyle = .critical
- alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
- alert.runModal()
- } else {
- NSDocumentController.shared.openDocument(withContentsOf: url, display: true) { document, documentWasAlreadyOpen, error in
- if error != nil {
- NSApp.presentError(error!)
- return
- }
- }
- }
- } else if (type == "jpg") ||
- (type == "cur") ||
- (type == "bmp") ||
- (type == "jpeg") ||
- (type == "gif") ||
- (type == "png") ||
- (type == "tiff") ||
- (type == "tif") ||
- (type == "ico") ||
- (type == "icns") ||
- (type == "tga") ||
- (type == "psd") ||
- (type == "eps") ||
- (type == "hdr") ||
- (type == "jp2") ||
- (type == "jpc") ||
- (type == "pict") ||
- (type == "sgi") ||
- (type == "heic") {
- openImageFile(url: url)
- } else if (type == "doc") ||
- (type == "docx") ||
- (type == "xls") ||
- (type == "xlsx") ||
- (type == "ppt") ||
- (type == "pptx") ||
- (type == "pptx") {
- self.openOfficeFile(url: url)
- }
- }
- }
- }
- }
-
- @IBAction func openBlankPage(_ sender: Any) {
- let fileName: NSString = String(format: "%@.pdf", NSLocalizedString("Untitled", comment: "")) as NSString
- let savePath = fetchUniquePath(fileName.kUrlToPDFFolderPath())
- let pdfDocument = CPDFDocument()
- pdfDocument?.insertPage(CGSize(width: 595, height: 842), at: 0)
- pdfDocument?.write(to: URL(fileURLWithPath: savePath))
- NSDocumentController.shared.openDocument(withContentsOf: URL(fileURLWithPath: savePath), display: true) { document, documentWasAlreadyOpen, error in
- if error != nil {
- NSApp.presentError(error!)
- } else {
- if document is KMMainDocument {
- let newDocument = document
- (newDocument as! KMMainDocument).isNewCreated = true
- }
- }
- }
- }
-
- @IBAction func importFromScanner(_ sender: Any) {
- deviceBrowserWC = KMDeviceBrowserWindowController.init(windowNibName: "KMDeviceBrowserWindowController")
- deviceBrowserWC!.type = .scanner
- deviceBrowserWC!.importScannerFileCallback = { [unowned self](url: NSURL) -> Void in
- openFile(withFilePath: url as URL)
- }
- deviceBrowserWC!.showWindow(NSApp.mainWindow)
- }
- }
|