Browse Source

综合 - DMG OCR资源分包下载逻辑补充

wanjun 1 year ago
parent
commit
6af5de4ed3

+ 0 - 18
PDF Office/PDF Master.xcodeproj/xcuserdata/kdanwj.xcuserdatad/xcdebugger/Breakpoints_v2.xcbkptlist

@@ -3,22 +3,4 @@
    uuid = "A8D1F77E-FE7C-4DEF-A02B-F317BAFFC2B6"
    type = "1"
    version = "2.0">
-   <Breakpoints>
-      <BreakpointProxy
-         BreakpointExtensionID = "Xcode.Breakpoint.FileBreakpoint">
-         <BreakpointContent
-            uuid = "AD344587-64A1-4F8E-8488-DE53BFAE67EE"
-            shouldBeEnabled = "Yes"
-            ignoreCount = "0"
-            continueAfterRunningActions = "No"
-            filePath = "PDF Master/Class/Resource Download/KMResourceDownload.m"
-            startingColumnNumber = "9223372036854775807"
-            endingColumnNumber = "9223372036854775807"
-            startingLineNumber = "28"
-            endingLineNumber = "28"
-            landmarkName = "-downloadFramework"
-            landmarkType = "7">
-         </BreakpointContent>
-      </BreakpointProxy>
-   </Breakpoints>
 </Bucket>

+ 5 - 1
PDF Office/PDF Master/Class/PDFTools/Convert/Controller/KMConvertBaseWindowController.swift

@@ -756,7 +756,11 @@ class KMConvertBaseWindowController: KMBaseWindowController {
                     self.showProgressWindow()
                     self.progressController?.maxValue = Double(convert.pages.count)
                 }
-                
+                if self.settingView?.ocrItemView?.checkVC?.state == .Checked {
+                    let resourcePath = Bundle.main.resourcePath
+                    let filePath = resourcePath?.stringByAppendingPathComponent("DocumentAI.bundle")
+                    CPDFConvertKit.setOCRModelPath(filePath)
+                }
                 DispatchQueue.global().async {
                     KMPDFConvertManager.defaultManager.convert(convert: convert, progress: { index in
                         DispatchQueue.main.async {

+ 4 - 2
PDF Office/PDF Master/Class/PDFTools/Convert/Controller/OC/SKProgressController.m

@@ -145,8 +145,10 @@
 }
 
 - (void)setDoubleValue:(double)doubleValue {
-    [[self progressBar] setDoubleValue:doubleValue];
-    [[self progressBar] displayIfNeeded];
+    dispatch_async(dispatch_get_main_queue(), ^{
+        [[self progressBar] setDoubleValue:doubleValue];
+        [[self progressBar] displayIfNeeded];
+    });
 }
 
 - (void)incrementBy:(double)delta {

+ 69 - 33
PDF Office/PDF Master/Class/PDFTools/Convert/View/KMConvertOCRSettingItemView.swift

@@ -17,7 +17,8 @@ class KMConvertOCRSettingItemView: KMConvertBaseView {
     }
     
     private var _languageVC: KMDesignSelect?
-    
+    var progressController: SKProgressController?
+
     private var _languageIndex: Int = 0
     var languageIndex: Int {
         get {
@@ -76,39 +77,48 @@ class KMConvertOCRSettingItemView: KMConvertBaseView {
     }
     
     @objc func checkBoxAction(sender: NSButton) {
-//        let isExist = KMResourceDownload().documentAIBundleIsExist()
-//        if isExist || self._checkVC?.state == .Checked {
-//            if let state = self._checkVC?.state {
-//                self._checkVC?.state = state == .Checked ? .Norm : .Checked
-//            }
-//            
-//            self._checkAction()
-//        } else {
-//            let alert = NSAlert()
-//            alert.messageText = NSLocalizedString("Do you want to download resources?", comment: "")
-//            alert.informativeText = NSLocalizedString("Additional resource pack download is required to use OCR. Do you want to continue?", comment: "")
-//            alert.addButton(withTitle: NSLocalizedString("Yes", comment: ""))
-//            alert.addButton(withTitle: NSLocalizedString("No", comment: ""))
-//            alert.beginSheetModal(for: self.window!) { [unowned self] result in
-//                if (result == .alertFirstButtonReturn) { /// 取消
-//                    KMResourceDownload().downloadFramework()
-//                    
-//                    if let state = self._checkVC?.state {
-//                        self._checkVC?.state = state == .Checked ? .Norm : .Checked
-//                    }
-//                    
-//                    self._checkAction()
-//                } else if result == .alertSecondButtonReturn {
-//                    return
-//                }
-//            }
-//        }
-        if let state = self._checkVC?.state {
-            self._checkVC?.state = state == .Checked ? .Norm : .Checked
+        let isExist = KMResourceDownload().documentAIBundleIsExist()
+        if isExist || self._checkVC?.state == .Checked {
+            if let state = self._checkVC?.state {
+                self._checkVC?.state = state == .Checked ? .Norm : .Checked
+            }
+            
+            self._checkAction()
+        } else {
+            let alert = NSAlert()
+            alert.messageText = NSLocalizedString("Do you want to download resources?", comment: "")
+            alert.informativeText = NSLocalizedString("Additional resource pack download is required to use OCR. Do you want to continue?", comment: "")
+            alert.addButton(withTitle: NSLocalizedString("Yes", comment: ""))
+            alert.addButton(withTitle: NSLocalizedString("No", comment: ""))
+            alert.beginSheetModal(for: self.window!) { [unowned self] result in
+                if (result == .alertFirstButtonReturn) { /// 取消
+                    DispatchQueue.main.async {
+                        self.showProgressWindow()
+                        self.progressController?.maxValue = Double(100)
+                    }
+                    KMResourceDownload().downloadFrameworkProgress { progress in
+                        self.progressController?.doubleValue = Double(progress*100)
+                    } result: { result in
+                        if result {
+                            if let state = self._checkVC?.state {
+                                self._checkVC?.state = state == .Checked ? .Norm : .Checked
+                            }
+                            
+                            self._checkAction()
+                            
+                            if let state = self._checkVC?.state {
+                                self._checkVC?.state = state == .Checked ? .Norm : .Checked
+                            }
+                            
+                            self._checkAction()
+                        }
+                        self.hiddenProgressWindow()
+                    }
+                } else if result == .alertSecondButtonReturn {
+                    return
+                }
+            }
         }
-        
-        self._checkAction()
-
     }
     
     public func checkAction() {
@@ -122,6 +132,32 @@ class KMConvertOCRSettingItemView: KMConvertBaseView {
         
         self._languageVC?.enabled = state == .Checked
     }
+    
+    func showProgressWindow() {
+        let progress = SKProgressController()
+        progress.message = NSLocalizedString("Download...", comment: "")
+        progress.window?.backgroundColor = NSColor.km_init(hex: "#36383B")
+        progress.window?.contentView?.wantsLayer = true
+        progress.window?.contentView?.layer?.backgroundColor = NSColor.km_init(hex: "#36383B").cgColor
+        progress.progressField.textColor = NSColor.white
+        
+        progress.closeBlock = { [unowned self] in
+            
+        }
+        
+        self.progressController = progress
+        self.window?.beginSheet(progress.window!)
+    }
+    
+    func hiddenProgressWindow() {
+        DispatchQueue.main.async {
+            self.progressController?.doubleValue = 100.0
+            if (self.progressController != nil) {
+                self.window?.endSheet((self.progressController?.window)!)
+                self.progressController = nil
+            }
+        }
+    }
 }
 
 extension KMConvertOCRSettingItemView: KMSelectPopButtonDelegate {

+ 8 - 1
PDF Office/PDF Master/Class/Resource Download/KMResourceDownload.h

@@ -9,9 +9,16 @@
 
 NS_ASSUME_NONNULL_BEGIN
 
+typedef void(^KMResourceDownloadResult)(BOOL isSuccessful);
+typedef void(^KMResourceDownloadProgress)(double progress);
+
 @interface KMResourceDownload : NSObject
 
-- (void)downloadFramework;
+@property(nonatomic, copy) KMResourceDownloadResult downloadResultBlock;
+
+@property(nonatomic, copy) KMResourceDownloadProgress progressBlock;
+
+- (void)downloadFrameworkProgress:(KMResourceDownloadProgress)currentProgress result:(KMResourceDownloadResult)result;
 
 - (BOOL)documentAIBundleIsExist;
 

+ 52 - 36
PDF Office/PDF Master/Class/Resource Download/KMResourceDownload.m

@@ -16,42 +16,17 @@
 
 @implementation KMResourceDownload
 
-- (void)downloadFramework {
+- (void)downloadFrameworkProgress:(KMResourceDownloadProgress)currentProgress result:(KMResourceDownloadResult)result {
+    self.downloadResultBlock = result;
+    self.progressBlock = currentProgress;
     
     NSString *urlString = @"http://test-pdf-pro.kdan.cn:3021/downloads/DocumentAI.bundle.zip";
     NSURL *url = [NSURL URLWithString:urlString];
     
     NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
-    NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration];
-    
-    NSURLSessionDownloadTask *downloadTask = [session downloadTaskWithURL:url completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
-        if (error) {
-            NSLog(@"Failed to download framework: %@", error);
-            return;
-        }
-        
-        // Move the downloaded file to APP Contents/Frameworks folder
-        NSFileManager *fileManager = [NSFileManager defaultManager];
-        NSString *frameworksDirectory = [[NSBundle mainBundle] privateFrameworksPath];
-        NSString *destinationPath = [frameworksDirectory stringByAppendingPathComponent:@"DocumentAI.bundle.zip"];
-        
-        NSError *moveError = nil;
-        [fileManager moveItemAtURL:location toURL:[NSURL fileURLWithPath:destinationPath] error:&moveError];
-        if (moveError) {
-            NSLog(@"Failed to move framework: %@", moveError);
-            return;
-        }
-        
-        NSLog(@"Framework downloaded and installed successfully!");
-        
-        // 解压 framework 文件
-        [self unzipFrameworkAtURL:[NSURL fileURLWithPath:destinationPath] toDestination:frameworksDirectory];
-        
-        // 加载 framework 文件
-        [self loadFramework:[frameworksDirectory stringByAppendingPathComponent:@"DocumentAI.bundle"]];
-
-    }];
-    
+    NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
+
+    NSURLSessionDownloadTask *downloadTask = [session downloadTaskWithURL:url];
     [downloadTask resume];
 
 }
@@ -104,14 +79,55 @@
 - (BOOL)documentAIBundleIsExist {
     NSError *error = nil;
 
-    NSString *frameworksDirectory = [[NSBundle mainBundle] privateFrameworksPath];
-    NSBundle *frameworkBundle = [NSBundle bundleWithPath:[frameworksDirectory stringByAppendingPathComponent:@"DocumentAI.bundle"]];
-    if (![frameworkBundle loadAndReturnError:&error]) {
-        NSLog(@"Error loading bundle: %@", error);
+//    NSString *frameworksDirectory = [[NSBundle mainBundle] privateFrameworksPath];
+//    NSBundle *frameworkBundle = [NSBundle bundleWithPath:[frameworksDirectory stringByAppendingPathComponent:@"DocumentAI.bundle"]];
+    NSString *resourcePath = [[NSBundle mainBundle] resourcePath];
+    NSString *filePath = [resourcePath stringByAppendingPathComponent:@"DocumentAI.bundle"];
+    
+    NSFileManager *fileManager = [NSFileManager defaultManager];
+    if ([fileManager fileExistsAtPath:filePath]) {
+        return YES;
+    } else {
         return NO;
     }
+}
 
-    return YES;
+#pragma mark - NSURLSessionDelegate
+
+- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite {
+    // 计算下载进度
+    double progress = (double)totalBytesWritten / (double)totalBytesExpectedToWrite;
+    
+    // 可以在这里更新UI或执行其他操作
+    NSLog(@"下载进度:%f", progress);
+    
+    if (self.progressBlock) {
+        self.progressBlock(progress);
+    }
+}
+
+- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location {
+    // Move the downloaded file to APP Contents/Frameworks folder
+    NSFileManager *fileManager = [NSFileManager defaultManager];
+//        NSString *frameworksDirectory = [[NSBundle mainBundle] privateFrameworksPath];
+    NSString *resourcePath = [[NSBundle mainBundle] resourcePath];
+    NSString *destinationPath = [resourcePath stringByAppendingPathComponent:@"DocumentAI.bundle.zip"];
+
+    NSError *moveError = nil;
+    [fileManager moveItemAtURL:location toURL:[NSURL fileURLWithPath:destinationPath] error:&moveError];
+    if (moveError) {
+        NSLog(@"Failed to move framework: %@", moveError);
+        return;
+    }
+    
+    NSLog(@"Framework downloaded and installed successfully!");
+    
+    // 解压 framework 文件
+    [self unzipFrameworkAtURL:[NSURL fileURLWithPath:destinationPath] toDestination:resourcePath];
+    
+    if (self.downloadResultBlock) {
+        self.downloadResultBlock(YES);
+    }
 }
 
 @end