Browse Source

【通用】OCR结果缺一页问题修正

niehaoyu 7 months ago
parent
commit
35eed90739

+ 146 - 125
PDF Office/PDF Master/Class/PDFTools/OCRNew/Controller/KMOCRPDFWindowController.swift

@@ -9,20 +9,7 @@ import Cocoa
 import PDFKit
 
 class KMOCRPDFWindowController: NSWindowController, NSWindowDelegate, KMGOCRManagerDelegate, NSPopoverDelegate,NSTextFieldDelegate{
-    var resultString: String = ""
-    var ocrDictionary: NSMutableDictionary?
-    var currentIndexPage: Int = 0
-//    {
-//        didSet {
-//            if PDFView.document.pageCount > currentIndexPage {
-//                currentIndexPage = 0
-//                self.currentPageLabel.stringValue = "\(currentIndexPage + 1)"
-//                //                let page = self.PDFView.document.page(at: UInt(currentIndexPage))
-//                self.PDFView.go(toPageIndex: currentIndexPage, animated: true)
-//            }
-//        }
-//    }
-    var PDFView: CPDFView!
+
     
     @IBOutlet var prePdfBGView: NSView!
     @IBOutlet var currentPageLabel: NSTextField!
@@ -56,21 +43,24 @@ class KMOCRPDFWindowController: NSWindowController, NSWindowDelegate, KMGOCRMana
     
     @IBOutlet var emptyLabel: NSTextField!
     
+    @IBOutlet var saveButton: NSButton!
+    @IBOutlet var box1: NSBox!
+    @IBOutlet var boxLabel1: NSTextField!
+    @IBOutlet var previewLabel: NSTextField!
+    @IBOutlet var savePDFButton: NSButton!
+    
+    var resultString: String = ""
+    var ocrDictionary: NSMutableDictionary?
+    var currentIndexPage: Int = 0
+    var PDFView: CPDFView!
     var errorOCRArrays: Array<Any>?
     
     var pageIndexs: Array<Any>?
     
-    var  password: String = ""
+    var password: String = ""
     var pathFile: String = ""
     
     var pdfDocument: CPDFDocument?
-    
-    @IBOutlet var saveButton: NSButton!
-    @IBOutlet var box1: NSBox!
-    @IBOutlet var boxLabel1: NSTextField!
-    @IBOutlet var previewLabel: NSTextField!
-    @IBOutlet var savePDFButton: NSButton!
-    
     var ocrCurrentIndex: Int = 0
     var appleOCRManger: KMGOCRManager?
     var googleOCRManger: KMGOCRManager?
@@ -93,6 +83,15 @@ class KMOCRPDFWindowController: NSWindowController, NSWindowDelegate, KMGOCRMana
         return path!
     }
     
+    func releaseSomething() {
+        KMGOCRManager.default().delegate = nil
+        appleOCRManger?.cancelRecognition()
+        appleOCRManger?.delegate = nil
+        googleOCRManger?.cancelRecognition()
+        googleOCRManger?.delegate = nil
+        self.PDFView.document = nil
+    }
+    
     convenience init(cpdfDocument: CPDFDocument, pwd: String?) {
         self.init(windowNibName: "KMOCRPDFWindowController")
         self.pdfDocument = cpdfDocument
@@ -138,19 +137,12 @@ class KMOCRPDFWindowController: NSWindowController, NSWindowDelegate, KMGOCRMana
         self._fileAttri?.password = self.pdfDocument?.password ?? ""
         self._fileAttri?.filePath = self.pdfDocument?.documentURL.path ?? ""
     }
+    
     deinit {
         NotificationCenter.default.removeObserver(self)
         releaseSomething()
     }
     
-    func releaseSomething() {
-        KMGOCRManager.default().delegate = nil
-        appleOCRManger?.cancelRecognition()
-        appleOCRManger?.delegate = nil
-        googleOCRManger?.cancelRecognition()
-        googleOCRManger?.delegate = nil
-        self.PDFView.document = nil
-    }
     override func windowDidLoad() {
         super.windowDidLoad()
         let preView: CPDFView = CPDFView(frame: self.prePdfBGView.bounds)
@@ -250,13 +242,13 @@ class KMOCRPDFWindowController: NSWindowController, NSWindowDelegate, KMGOCRMana
     override func close() {
         releaseSomething()
         if ((self.window?.isSheet) != nil) {
-//            self.km_endSheet()
             self.window?.sheetParent?.endSheet(self.window!)
         } else {
             super.close()
         }
     }
     
+    //MARK: - Public Method
     func reloadPDFData() { // 隐藏PDFView滑动条
         self.PDFView.documentView()?.enclosingScrollView?.hasVerticalScroller = false
         self.PDFView.documentView()?.enclosingScrollView?.hasHorizontalScroller = false
@@ -265,27 +257,6 @@ class KMOCRPDFWindowController: NSWindowController, NSWindowDelegate, KMGOCRMana
         self.currentPageLabel.stringValue = "\((currentPageIndex ?? 0) + 1)"
         self.totalPageLabel.stringValue = "/ \(pageCount)"
     }
-    //MARK: KMOCRSelectedLanguagesChangeNotification
-    @objc func OCRSelectedLanguagesChangeNotification(notification: NSNotification) {
-        if let selectedLanguages = notification.object as? [String] {
-            updateLanguageButton(selectedLanguages)
-        }
-    }
-    
-    @objc func OCRSelectedPlanChangeNotification(notification: NSNotification) {
-        let plan = UserDefaults.standard.integer(forKey: "KMOCRCurrentPlanKey")
-        if plan == 0 {
-            self.planComboBox.selectItem(at: 0)
-        } else {
-            self.planComboBox.selectItem(at: 1)
-        }
-        KMGOCRManager.default().selectedLanguages = NSMutableArray()
-        updateLanguageButton(KMGOCRManager.default().selectedLanguages?.value(forKeyPath: KMGOCRLanguageStringKey) as? [String])
-    }
-    @objc func PDFViewDocumentChangedNotification(notification: NSNotification) {
-        let pageIndex = self.PDFView.currentPageIndex+1
-        self.currentPageLabel.stringValue = "\(pageIndex)"
-    }
     
     func updateLanguageButton(_ languages: [String]?) {
         if languages?.count ?? 0 < 1 {
@@ -308,6 +279,7 @@ class KMOCRPDFWindowController: NSWindowController, NSWindowDelegate, KMGOCRMana
         
         self.languageButton.title = languageName ?? ""
     }
+    
     func imageRep(withSize size: NSSize, scale: CGFloat, drawingHandler: (NSRect) -> Void) -> Any? {
         let bmpImageRep = NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: Int(size.width * scale), pixelsHigh: Int(size.height * scale), bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false, colorSpaceName: .calibratedRGB, bitmapFormat: .alphaFirst, bytesPerRow: 0, bitsPerPixel: 0)
         //        bmpImageRep?.bitmapImageRepByRetaggingWithColorSpace = .sRGB
@@ -319,12 +291,14 @@ class KMOCRPDFWindowController: NSWindowController, NSWindowDelegate, KMGOCRMana
         NSGraphicsContext.restoreGraphicsState()
         return bmpImageRep
     }
+    
     func bitmapImage(withSize size: NSSize, drawingHandler: (NSRect) -> Void) -> NSImage? {
         let image = NSImage(size: size)
         let scale = KMImageScale
         image.addRepresentation(imageRep(withSize: size, scale: scale, drawingHandler: drawingHandler) as! NSBitmapImageRep)
         return image
     }
+    
     func thumbnail(with page: CPDFPage) -> NSImage? {
         let bounds = page.bounds(for: .cropBox)
         var pageSize = bounds.size
@@ -381,6 +355,7 @@ class KMOCRPDFWindowController: NSWindowController, NSWindowDelegate, KMGOCRMana
         
         return image
     }
+    
     func savedName() -> String {
         var resultArrays: Array<Any> = []
         var ocrIndexArrays: Array<Any> = []
@@ -419,6 +394,7 @@ class KMOCRPDFWindowController: NSWindowController, NSWindowDelegate, KMGOCRMana
         
         return returnName
     }
+    
     func savePDF() {
         var resultArrays: Array<Any> = []
         var ocrIndexArrays: Array<Any> = []
@@ -464,12 +440,14 @@ class KMOCRPDFWindowController: NSWindowController, NSWindowDelegate, KMGOCRMana
             }
         }
     }
+    
     func viewFileAtFinder(_ fileName: String) {
         let workspace = NSWorkspace.shared
         let url = URL(fileURLWithPath: fileName)
         workspace.activateFileViewerSelecting([url])
     }
-    func saveText() { 
+    
+    func saveText() {
         let sortedKeys = self.ocrDictionary?.allKeys.sorted(by: { ($0 as? String)?.compare($1 as? String ?? "") == .orderedAscending })
         let fileName = self.savedFileName
         
@@ -490,6 +468,7 @@ class KMOCRPDFWindowController: NSWindowController, NSWindowDelegate, KMGOCRMana
             }
         }
     }
+    
     func fileNameWithNums(_ nums: [NSNumber]) -> String {
         var fileName: String? = nil
         if nums.count > 0 {
@@ -548,60 +527,7 @@ class KMOCRPDFWindowController: NSWindowController, NSWindowDelegate, KMGOCRMana
         return ""
     }
     
-    @IBAction func cancelButtonAction(_ sender: Any) {
-        if FileManager.default.fileExists(atPath: getOCRResrultsFolderPath()) {
-            try? FileManager.default.removeItem(atPath: getOCRResrultsFolderPath())
-        }
-        KMGOCRManager.default().cancelRecognition()
-        self.close()
-    }
-    @IBAction func startButtonAction(_ sender: Any) {
-        self.ocrCurrentIndex = 0
-        txtTextView.string = ""
-        ocrDictionary = NSMutableDictionary()
-        let pdfDocument = self.pdfDocument
-        errorOCRArrays?.removeAll()
-        pageIndexs?.removeAll()
-        if self.pageRangeBox.indexOfSelectedItem == 0 {
-            for i in 0..<(pdfDocument?.pageCount ?? 0) {
-                pageIndexs?.append(NSNumber(value: i))
-            }
-        } else if self.pageRangeBox.indexOfSelectedItem == 1 {
-            let page = PDFView.currentPage()
-            let pageIndex = PDFView.document?.index(for: page)
-            pageIndexs?.append(NSNumber(value: pageIndex!))
-        } else if self.pageRangeBox.indexOfSelectedItem == 2 {
-            for i in 0..<(pdfDocument?.pageCount ?? 0) where i % 2 == 0 {
-                pageIndexs?.append(NSNumber(value: i))
-            }
-        } else if self.pageRangeBox.indexOfSelectedItem == 3 {
-            for i in 0..<(pdfDocument?.pageCount ?? 0) where i % 2 != 0 {
-                pageIndexs?.append(NSNumber(value: i))
-            }
-        } else {
-            var attribute = self._fileAttri
-            if attribute == nil {
-                attribute = KMFileAttribute()
-                self._fileAttri = attribute
-                
-                attribute?.password = self.pdfDocument?.password ?? ""
-                attribute?.filePath = self.pdfDocument?.documentURL.path ?? ""
-            }
-//            attribute.pdfDocument = pdfDocument
-            
-            attribute?.bAllPage = false
-            attribute?.pagesType = .custom
-            attribute?.pagesString = self.pageRangeBox.stringValue
-            let selectPages = attribute?.fetchSelectPages() ?? []
-            if selectPages.count > 0 {
-                for num in selectPages {
-                    pageIndexs?.append(NSNumber(value: num - 1))
-                }
-            }
-        }
-        batchesOCR()
-    }
-    func batchesOCR() { 
+    func batchesOCR() {
         savedFileName = savedName()
         let intervalOCR: UInt = 10
         let selctPageImages: NSMutableArray = NSMutableArray()
@@ -630,10 +556,6 @@ class KMOCRPDFWindowController: NSWindowController, NSWindowDelegate, KMGOCRMana
             }
         }
         
-        if selctPageImages.count < 1 {
-            return
-        }
-        
         if appleOCRManger != nil {
             appleOCRManger?.cancelRecognition()
             appleOCRManger?.delegate = nil
@@ -646,6 +568,10 @@ class KMOCRPDFWindowController: NSWindowController, NSWindowDelegate, KMGOCRMana
             googleOCRManger = nil
         }
         
+        if selctPageImages.count < 1 {
+            return
+        }
+        
         ocrCopyButton.isEnabled = false
         saveButton.isEnabled = false
         savePDFButton.isEnabled = false
@@ -671,6 +597,63 @@ class KMOCRPDFWindowController: NSWindowController, NSWindowDelegate, KMGOCRMana
             }
         }
     }
+    
+    //MARK: - IBAction
+    @IBAction func cancelButtonAction(_ sender: Any) {
+        if FileManager.default.fileExists(atPath: getOCRResrultsFolderPath()) {
+            try? FileManager.default.removeItem(atPath: getOCRResrultsFolderPath())
+        }
+        KMGOCRManager.default().cancelRecognition()
+        self.close()
+    }
+    
+    @IBAction func startButtonAction(_ sender: Any) {
+        self.ocrCurrentIndex = 0
+        txtTextView.string = ""
+        ocrDictionary = NSMutableDictionary()
+        let pdfDocument = self.pdfDocument
+        errorOCRArrays?.removeAll()
+        pageIndexs?.removeAll()
+        if self.pageRangeBox.indexOfSelectedItem == 0 {
+            for i in 0..<(pdfDocument?.pageCount ?? 0) {
+                pageIndexs?.append(NSNumber(value: i))
+            }
+        } else if self.pageRangeBox.indexOfSelectedItem == 1 {
+            let page = PDFView.currentPage()
+            let pageIndex = PDFView.document?.index(for: page)
+            pageIndexs?.append(NSNumber(value: pageIndex!))
+        } else if self.pageRangeBox.indexOfSelectedItem == 2 {
+            for i in 0..<(pdfDocument?.pageCount ?? 0) where i % 2 == 0 {
+                pageIndexs?.append(NSNumber(value: i))
+            }
+        } else if self.pageRangeBox.indexOfSelectedItem == 3 {
+            for i in 0..<(pdfDocument?.pageCount ?? 0) where i % 2 != 0 {
+                pageIndexs?.append(NSNumber(value: i))
+            }
+        } else {
+            var attribute = self._fileAttri
+            if attribute == nil {
+                attribute = KMFileAttribute()
+                self._fileAttri = attribute
+                
+                attribute?.password = self.pdfDocument?.password ?? ""
+                attribute?.filePath = self.pdfDocument?.documentURL.path ?? ""
+            }
+//            attribute.pdfDocument = pdfDocument
+            
+            attribute?.bAllPage = false
+            attribute?.pagesType = .custom
+            attribute?.pagesString = self.pageRangeBox.stringValue
+            let selectPages = attribute?.fetchSelectPages() ?? []
+            if selectPages.count > 0 {
+                for num in selectPages {
+                    pageIndexs?.append(NSNumber(value: num - 1))
+                }
+            }
+        }
+        batchesOCR()
+    }
+    
     @IBAction func planSelectButtonAction(_ sender: NSPopUpButton) {
         let plan = UserDefaults.standard.integer(forKey: "KMOCRCurrentPlanKey")
         if plan != sender.indexOfSelectedItem {
@@ -686,6 +669,7 @@ class KMOCRPDFWindowController: NSWindowController, NSWindowDelegate, KMGOCRMana
         }
         NotificationCenter.default.post(name: NSNotification.Name("KMOCRSelectedPlanChangeNotification"), object: nil)
     }
+    
     @IBAction func languageButtonAction(_ sender: Any) {
         let popover = NSPopover()
         popover.delegate = self
@@ -694,6 +678,7 @@ class KMOCRPDFWindowController: NSWindowController, NSWindowDelegate, KMGOCRMana
         popover.behavior = .transient
         popover.show(relativeTo: (sender as! NSView).bounds, of: sender as! NSView, preferredEdge: .minX)
     }
+    
     @IBAction func helpButtonAction(_ sender: Any) {
         let helpController = NSViewController()
         let textView = NSTextView(frame: NSRectToCGRect(NSMakeRect(0, 0, 300.0, 50.0)))
@@ -711,6 +696,7 @@ class KMOCRPDFWindowController: NSWindowController, NSWindowDelegate, KMGOCRMana
         popover.behavior = .transient
         popover.show(relativeTo: (sender as! NSView).bounds, of: sender as! NSView, preferredEdge: .minY)
     }
+    
     @IBAction func buttonItemClick_CopyTxt(_ sender: NSButton) {
         let pasteboard = NSPasteboard.general
         pasteboard.clearContents()
@@ -718,6 +704,7 @@ class KMOCRPDFWindowController: NSWindowController, NSWindowDelegate, KMGOCRMana
         pasteboard.writeObjects([str])
         let _ = CustomAlertView.alertView(message: NSLocalizedString("Copy successful!", comment: ""), fromView: sender.superview!, withStyle: .black)
     }
+    
     @IBAction func buttonItemClick_Delete(_ sender: NSButton) {
         ocrCopyButton.isEnabled = false
         saveButton.isEnabled = false
@@ -729,6 +716,7 @@ class KMOCRPDFWindowController: NSWindowController, NSWindowDelegate, KMGOCRMana
         txtTextView.string = ""
         ocrDictionary = NSMutableDictionary()
     }
+    
     @IBAction func boxItemClicked_PageRange(_ sender: NSButton) {
         if 4 != pageRangeBox.indexOfSelectedItem {
             self.window?.makeFirstResponder(self)
@@ -744,16 +732,21 @@ class KMOCRPDFWindowController: NSWindowController, NSWindowDelegate, KMGOCRMana
         self.PDFView.goToNextPage(nil)
         self.reloadPDFData()
     }
+    
     @IBAction func previousButtonAction(_ sender: NSButton) {
         self.PDFView.goToPreviousPage(nil)
         self.reloadPDFData()
     }
+    
     @IBAction func buttonClicked_SaveButton(_ sender: NSButton) {
         self.saveText()
     }
+    
     @IBAction func savePDFButtonAction(_ sender: NSButton) {
         self.savePDF()
     }
+    
+    //MARK: - ControlDelegate
     func controlTextDidEndEditing(_ notification: Notification) {
         guard let textField = notification.object as? NSTextField else { return }
         if textField == currentPageLabel {
@@ -768,6 +761,7 @@ class KMOCRPDFWindowController: NSWindowController, NSWindowDelegate, KMGOCRMana
             }
         }
     }
+    
     func controlTextDidChange(_ notification: Notification) {
         guard let textField = notification.object as? NSTextField else { return }
         if textField == currentPageLabel {
@@ -775,6 +769,7 @@ class KMOCRPDFWindowController: NSWindowController, NSWindowDelegate, KMGOCRMana
             textField.stringValue = string ?? ""
         }
     }
+    
     func popoverDidClose(_ notification: Notification) {
         
     }
@@ -782,13 +777,16 @@ class KMOCRPDFWindowController: NSWindowController, NSWindowDelegate, KMGOCRMana
     func gocrManagerDidStartOCR(_ manager: KMGOCRManager!) {
         
     }
-    //MARK: KMGOCRManagerDelegate
+    
+    //MARK: - KMGOCRManagerDelegate
     func gocrManagerDidFinishOCR(_ manager: KMGOCRManager!) {
         self.batchesOCR()
     }
+    
     func gocrManager(_ manager: KMGOCRManager!, didCancelOCRImageAt index: Int) {
         
     }
+    
     func gocrManager(_ manager: KMGOCRManager!, didStartOCRImageAt index: Int) {
         DispatchQueue.main.async {
             self.pageRangeBox.isEnabled = false
@@ -796,9 +794,11 @@ class KMOCRPDFWindowController: NSWindowController, NSWindowDelegate, KMGOCRMana
             self.planComboBox.isEnabled = false
         }
     }
+    
     func gocrManager(_ manager: KMGOCRManager!, didFinishOCRImageAt index: Int, results: [KMGOCRResult]!) {
         self.dealWithResults(results, OCRImageAtIndex: index)
     }
+    
     func gocrManager(_ manager: KMGOCRManager!, didFailureOCRImageAt index: Int, error: Error!) {
         let pagenum = self.pageIndexs?[index] as! NSNumber
         if (error != nil) {
@@ -855,19 +855,19 @@ class KMOCRPDFWindowController: NSWindowController, NSWindowDelegate, KMGOCRMana
                 self.languageButton.isEnabled = true
                 self.planComboBox.isEnabled = true
             }
-            if appleOCRManger != nil {
-                appleOCRManger?.cancelRecognition()
-                appleOCRManger?.delegate = nil
-                appleOCRManger = nil
-            }
-            
-            if googleOCRManger != nil {
-                googleOCRManger?.cancelRecognition()
-                googleOCRManger?.delegate = nil
-                googleOCRManger = nil
-            }
-            
-            KMGOCRManager.default().delegate = nil
+//            if appleOCRManger != nil {
+//                appleOCRManger?.cancelRecognition()
+//                appleOCRManger?.delegate = nil
+//                appleOCRManger = nil
+//            }
+//            
+//            if googleOCRManger != nil {
+//                googleOCRManger?.cancelRecognition()
+//                googleOCRManger?.delegate = nil
+//                googleOCRManger = nil
+//            }
+//            
+//            KMGOCRManager.default().delegate = nil
             
             if self.errorOCRArrays?.count ?? 0 < 1 {
                 
@@ -918,5 +918,26 @@ class KMOCRPDFWindowController: NSWindowController, NSWindowDelegate, KMGOCRMana
         }
     }
     
+    //MARK: KMOCRSelectedLanguagesChangeNotification
+    @objc func OCRSelectedLanguagesChangeNotification(notification: NSNotification) {
+        if let selectedLanguages = notification.object as? [String] {
+            updateLanguageButton(selectedLanguages)
+        }
+    }
+    
+    @objc func OCRSelectedPlanChangeNotification(notification: NSNotification) {
+        let plan = UserDefaults.standard.integer(forKey: "KMOCRCurrentPlanKey")
+        if plan == 0 {
+            self.planComboBox.selectItem(at: 0)
+        } else {
+            self.planComboBox.selectItem(at: 1)
+        }
+        KMGOCRManager.default().selectedLanguages = NSMutableArray()
+        updateLanguageButton(KMGOCRManager.default().selectedLanguages?.value(forKeyPath: KMGOCRLanguageStringKey) as? [String])
+    }
     
+    @objc func PDFViewDocumentChangedNotification(notification: NSNotification) {
+        let pageIndex = self.PDFView.currentPageIndex+1
+        self.currentPageLabel.stringValue = "\(pageIndex)"
+    }
 }