Browse Source

【2025】【Home】创建文件逻辑串接完善

niehaoyu 4 months ago
parent
commit
b21a138412

+ 192 - 0
PDF Office/PDF Master/KMClass/KMHomeViewController/KMNHomeViewController.swift

@@ -11,6 +11,7 @@ import KMComponentLibrary
 class KMNHomeViewController: NSViewController {
 
     @IBOutlet var leftContendBox: NSBox!
+    @IBOutlet var leftDivider: ComponentDivider!
     @IBOutlet var homeOpenView: KMHomeOpenView!
     @IBOutlet var homeRecommondView: KMHomeRecommondView!
    
@@ -48,6 +49,8 @@ class KMNHomeViewController: NSViewController {
         
         leftContendBox.fillColor = ComponentLibrary.shared.getComponentColorFromKey("colorBg/layout-middle")
         
+        leftDivider.properties = ComponentDividerProperty(type: .vertical, dash: false)
+        
         homeOpenView.delegate = self
         
         self.homeRecommondView.reloadData()
@@ -129,6 +132,22 @@ extension KMNHomeViewController: KMHomeOpenViewDelegate {
     func homeOpenViewDidChooseFileURL(_ view: KMHomeOpenView?, _ url: URL) {
         self.openFile(withFilePath: url)
     }
+    
+    func homeOpenViewDidChooseImageURLs(_ view: KMHomeOpenView?, _ urls: [URL]) {
+        self.openImageToPdfWindow(urls: urls)
+    }
+    
+    func homeOpenViewDidChooseCreateFromClipboard(_ view: KMHomeOpenView?) {
+        var error: NSError?
+        let pboard = NSPasteboard.general
+        var document = openDocumentWithImageFromPasteboard(pboard, error: &error)
+        
+        if document == nil{
+            document = openDocument(withURLFromPasteboard: pboard, showNotes: false, error: &error)
+        }
+        
+    }
+    
 }
 
 //MARK: - KMHomeRightViewDelegate
@@ -417,6 +436,129 @@ extension KMNHomeViewController {
         }
     }
     
+    func openImageToPdfWindow(urls: Array<URL>) {
+        var arr: Array<KMBatchOperateFile> = Array()
+        for fileURL in urls {
+            let img = NSImage(contentsOfFile: fileURL.path)
+            if self.isDamageImage(image: img, path: fileURL.path) {
+                let alert = NSAlert()
+                alert.alertStyle = .critical
+                alert.messageText = String(format: KMLocalizedString("The file \"%@\" could not be opened."), fileURL.path.lastPathComponent)
+                alert.informativeText = NSLocalizedString("It may be damaged or use a file format that PDF Reader Pro doesn’t recognize.", comment: "")
+                alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
+                alert.beginSheetModal(for: NSApp.mainWindow!) { (response) in
+                    if response == .alertFirstButtonReturn {
+                        // Handle cancel action
+                    }
+                }
+                continue
+            }
+            let file = KMBatchOperateFile(filePath: fileURL.path, type: .CreatePDF)
+            arr.append(file)
+        }
+        let baseWindowController = KMBatchOperateBaseWindowController(windowNibName: "KMBatchOperateBaseWindowController")
+        if #available(macOS 10.13, *) {
+            baseWindowController.window?.makeKeyAndOrderFront(nil)
+        } else {
+            baseWindowController.showWindow(nil)
+        }
+        if arr.count > 0 {
+            baseWindowController.checkNeedPasswordSwitchToOperateType(operateType: .CreatePDF, files: arr)
+        }
+    }
+    
+    
+    func openDocumentWithImageFromPasteboard(_ pboard: NSPasteboard, error outError: AutoreleasingUnsafeMutablePointer<NSError?>?) -> Any? {
+        var document: CPDFDocument? = nil
+        var data: Data? = nil
+        
+        if pboard.canReadItem(withDataConformingToTypes: [NSPasteboard.PasteboardType.pdf.rawValue]) {
+            // pboard.types
+            data = pboard.data(forType: NSPasteboard.PasteboardType.pdf)
+        } else if pboard.canReadItem(withDataConformingToTypes: [NSPasteboard.PasteboardType.postScript.rawValue]) {
+            // pboard.types
+            data = pboard.data(forType: NSPasteboard.PasteboardType.postScript)
+        } else if pboard.canReadItem(withDataConformingToTypes: [NSPasteboard.PasteboardType.tiff.rawValue]) {
+            // pboard.types
+            data = convertTIFFDataToPDF(pboard.data(forType: NSPasteboard.PasteboardType.tiff) ?? Data())
+        } else {
+            let images = pboard.readObjects(forClasses: [NSImage.self], options: [:])
+            let strings = pboard.readObjects(forClasses: [NSAttributedString.self], options: [:])
+            if images?.count ?? 0 > 0 {
+                data = convertTIFFDataToPDF((images![0] as AnyObject).tiffRepresentation!)
+            } else if strings?.count ?? 0 > 0 {
+                data = KMOCTool.convertStringsToPDF(withString: strings ?? [""]) // convertStringsToPDF(strings!)
+            }
+        }
+        
+        if let data = data {
+            _ = NSDocumentController.shared
+
+            document = CPDFDocument(data: data)
+            
+            let fileName: NSString = String(format: "%@.pdf", NSLocalizedString("Untitled", comment: "")) as NSString
+            let savePath = fetchUniquePath(fileName.kUrlToPDFFolderPath() as String)
+            let filePath = savePath.deletingLastPathComponent
+            if FileManager.default.fileExists(atPath: filePath) == false {
+                try?FileManager.default.createDirectory(atPath: filePath, withIntermediateDirectories: false)
+            }
+             
+            document?.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
+                    }
+                }
+            }
+        } else if let outError = outError {
+            outError.pointee = NSError(domain: "SKDocumentErrorDomain", code: 3, userInfo: [NSLocalizedDescriptionKey: NSLocalizedString("Unable to load data from clipboard", comment: "Error description")])
+           
+        }
+    
+        return document
+    }
+    func openDocument(withURLFromPasteboard pboard: NSPasteboard, showNotes: Bool, error outError: inout NSError?) -> Any? {
+        let theURLs = NSURL.readURLs(from: pboard)
+        let url = theURLs?.count ?? 0 > 0 ? theURLs?[0] : nil
+        let theURL: NSURL? = url as? NSURL
+        let documentC = NSDocumentController.shared
+        var document: NSDocument? = nil
+        if (theURL as AnyObject).isFileURL == true {
+            var _: NSError? = nil
+            let type = try? documentC.typeForContents(of: theURL as! URL)//ForContents(ofURL: theURL, error: &error)
+            
+            if showNotes == false || NSDocument.readableTypes.contains(type ?? "") {
+                documentC.openDocument(withContentsOf: theURL as! URL, display: true, completionHandler: { resultDocument, success, err in
+                    document = resultDocument
+                })
+            } else if NSDocument.readableTypes.contains(type ?? "") {
+                for doc in documentC.documents {
+                    let sel = NSSelectorFromString("sourceFileURL")
+                    if doc.responds(to: sel) && doc.fileURL == theURL as? URL {
+                        document = doc
+                        break
+                    }
+                }
+                if let document: NSDocument = document {
+                    document.showWindows()
+                } else {
+                    if let document = try? documentC.makeUntitledDocument(ofType: KMNotesDocumentType) {
+                        document.fileURL = URL(fileURLWithPath: theURL?.path ?? "")
+                        
+                        documentC.addDocument(document)
+                        document.makeWindowControllers()
+                        document.showWindows()
+                    }
+                }
+            }
+        }
+        return document
+    }
+    
     func showLimitWindowAlert(url: URL?) {
         if !KMDataManager.default.isTabbingWin{
             KMDataManager.default.isTabbingWin = true
@@ -493,5 +635,55 @@ extension KMNHomeViewController {
         return resultFilePath;
     }
     
+    func isDamageImage(image: NSImage?, path: String) -> Bool {
+        if (image == nil) {
+            return true
+        }
+        let addImageAnnotation = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).last!.appendingPathComponent(Bundle.main.bundleIdentifier!).appendingPathComponent("addImageAnnotation")
+         if !FileManager.default.fileExists(atPath: addImageAnnotation.path) {
+            try? FileManager.default.createDirectory(atPath: addImageAnnotation.path, withIntermediateDirectories: false, attributes: nil)
+        }
+        guard let data = image!.tiffRepresentation else { return false }
+        guard let imageRep = NSBitmapImageRep(data: data) else { return false }
+        imageRep.size = image!.size
+        var imageData: Data?
+        if path.lowercased() == "png" {
+            imageData = imageRep.representation(using: .png, properties: [:])
+        } else {
+            imageData = imageRep.representation(using: .jpeg, properties: [:])
+        }
+        let rPath: URL = addImageAnnotation.appendingPathComponent(tagString()).appendingPathExtension("png")
+        if let data = imageData {
+            try?data.write(to: rPath)
+            return false
+        } else {
+            return true
+        }
+    }
+    
+    func tagString() -> String {
+        let dateFormatter = DateFormatter()
+        dateFormatter.dateFormat = "yyMMddHHmmss"
+        let currentDate = Date()
+        let randomNum = Int(arc4random_uniform(10000))
+        let str = String(format: "%@%04d", dateFormatter.string(from: Date()),randomNum)
+        return str
+    }
+    
+    func convertTIFFDataToPDF(_ tiffData: Data) -> Data? {
+        guard let imsrc = CGImageSourceCreateWithData(tiffData as CFData, [kCGImageSourceTypeIdentifierHint: kUTTypeTIFF] as CFDictionary), CGImageSourceGetCount(imsrc) > 0, let cgImage = CGImageSourceCreateImageAtIndex(imsrc, 0, nil) else { return nil }
+        let pdfData = NSMutableData(capacity: tiffData.count)
+        let consumer = CGDataConsumer(data: pdfData! as CFMutableData)!
+        
+        var rect = CGRect(x: 0, y: 0, width: CGFloat(cgImage.width), height: CGFloat(cgImage.height))
+        let ctxt = CGContext(consumer: consumer, mediaBox: &rect, nil)
+        ctxt!.beginPDFPage(nil)
+        ctxt!.draw(cgImage, in: rect)
+        ctxt!.endPDFPage()
+        ctxt!.closePDF()
+        
+        return pdfData as? Data
+    }
+    
     
 }

+ 14 - 0
PDF Office/PDF Master/KMClass/KMHomeViewController/KMNHomeViewController.xib

@@ -12,6 +12,7 @@
                 <outlet property="homeOpenView" destination="Bxr-Ds-C57" id="DCS-RO-SoJ"/>
                 <outlet property="homeRecommondView" destination="SUk-pI-GKI" id="QLA-2x-bdU"/>
                 <outlet property="leftContendBox" destination="YQl-na-PHq" id="1OU-uy-3MI"/>
+                <outlet property="leftDivider" destination="vK7-bd-jKI" id="5sp-R8-tLi"/>
                 <outlet property="rightInfoView" destination="HJs-kh-Hyh" id="4ha-vR-5Ow"/>
                 <outlet property="view" destination="Hz6-mo-xeY" id="0bl-1N-x8E"/>
             </connections>
@@ -33,6 +34,19 @@
                                     <view key="contentView" id="aZH-46-zgg">
                                         <rect key="frame" x="0.0" y="0.0" width="240" height="445"/>
                                         <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
+                                        <subviews>
+                                            <customView translatesAutoresizingMaskIntoConstraints="NO" id="vK7-bd-jKI" customClass="ComponentDivider" customModule="KMComponentLibrary">
+                                                <rect key="frame" x="239" y="0.0" width="1" height="445"/>
+                                                <constraints>
+                                                    <constraint firstAttribute="width" constant="1" id="tJ6-6g-mIZ"/>
+                                                </constraints>
+                                            </customView>
+                                        </subviews>
+                                        <constraints>
+                                            <constraint firstAttribute="trailing" secondItem="vK7-bd-jKI" secondAttribute="trailing" id="AKi-n9-6W1"/>
+                                            <constraint firstAttribute="bottom" secondItem="vK7-bd-jKI" secondAttribute="bottom" id="KIt-UR-B9g"/>
+                                            <constraint firstItem="vK7-bd-jKI" firstAttribute="top" secondItem="aZH-46-zgg" secondAttribute="top" id="i2e-2k-89T"/>
+                                        </constraints>
                                     </view>
                                 </box>
                                 <customView translatesAutoresizingMaskIntoConstraints="NO" id="Bxr-Ds-C57" customClass="KMHomeOpenView" customModule="PDF_Reader_Pro" customModuleProvider="target">

+ 1 - 1
PDF Office/PDF Master/KMClass/KMHomeViewController/KMURLCreatePDFWindowController/KMURLToPDF.swift

@@ -49,7 +49,7 @@ class KMURLToPDF: NSObject, WKNavigationDelegate {
     }
     
     func stopLoading() {
-        self.webView.stopLoading()
+        self.webView?.stopLoading()
     }
      
     

+ 8 - 2
PDF Office/PDF Master/KMClass/KMHomeViewController/Views/KMHomeOpenView/KMHomeOpenView.swift

@@ -10,8 +10,13 @@ import KMComponentLibrary
 
 @objc protocol KMHomeOpenViewDelegate: AnyObject {
     
+    //选择文件
     @objc optional func homeOpenViewDidChooseFileURL(_ view: KMHomeOpenView?, _ url:URL)
  
+    //选择多个图片文件
+    @objc optional func homeOpenViewDidChooseImageURLs(_ view: KMHomeOpenView?, _ urls: [URL])
+    
+    @objc optional func homeOpenViewDidChooseCreateFromClipboard(_ view: KMHomeOpenView?)
 }
 
 class KMHomeOpenView: BaseXibView {
@@ -132,8 +137,9 @@ class KMHomeOpenView: BaseXibView {
         
         openPanel.beginSheetModal(for: NSWindow.currentWindow()) {[weak self] result in
             if result == NSApplication.ModalResponse.OK {
+                guard let weakSelf = self else { return }
                 let urls = openPanel.urls as [URL]
-//                self?.delegate?.homeOpenViewDidChooseFileURLs?(self, urls)
+                weakSelf.delegate?.homeOpenViewDidChooseImageURLs?(weakSelf, urls)
             }
         }
     }
@@ -164,7 +170,7 @@ class KMHomeOpenView: BaseXibView {
     }
     
     func newFromClipboard() {
-        
+        self.delegate?.homeOpenViewDidChooseCreateFromClipboard?(self)
     }
     
     func importFromScanner() {

+ 0 - 1
PDF Office/PDF Master/Strings/zh-Hans.lproj/Localizable.strings

@@ -3568,7 +3568,6 @@
 "Read Mode Off" = "关闭阅读模式";
 
 "New From File"="从文件新建PDF";
-"New From Images"="从图片新建PDF";
 "Set Passwords"="设置密码";
 "Remove Passwords"="移除密码";
 "Remove Password"="移除密码";