Przeglądaj źródła

Merge branch 'develop_2025' of git.kdan.cc:Mac_PDF/PDF_Office into develop_2025

niehaoyu 2 miesięcy temu
rodzic
commit
c4ebe3f64d

+ 1 - 1
PDF Office/PDF Master/Class/OC/OCR/KMGOCRManager.h

@@ -42,7 +42,7 @@ extern NSString * KMGOCRLanguageStringKey;
 
 @interface KMGOCRManager : NSObject
 
-@property (nonatomic,assign) id<KMGOCRManagerDelegate> delegate;
+@property (nonatomic, weak) id<KMGOCRManagerDelegate> delegate;
 
 @property (nonatomic,readonly) NSMutableArray *images;
 

+ 32 - 23
PDF Office/PDF Master/Class/OC/OCR/KMGOCRManager.m

@@ -315,6 +315,7 @@ static inline NSFont * FontWithSize(NSString *strChar, CGSize size) {
         NSData *imageData = [NSData dataWithContentsOfFile:path];
         CGImageSourceRef imageSource = CGImageSourceCreateWithData((CFDataRef)imageData, NULL);
         CGImageRef imageRef = CGImageSourceCreateImageAtIndex(imageSource, 0, NULL);
+        CFRelease(imageSource); // 添加这行
         CGContextSaveGState(pdfContext);
         CGContextDrawImage(pdfContext, pageRect, imageRef);
         CGContextRestoreGState(pdfContext);
@@ -407,6 +408,7 @@ static inline NSFont * FontWithSize(NSString *strChar, CGSize size) {
         NSData *imageData = image.TIFFRepresentation;
         CGImageSourceRef imageSource = CGImageSourceCreateWithData((CFDataRef)imageData, NULL);
         CGImageRef imageRef = CGImageSourceCreateImageAtIndex(imageSource, 0, NULL);
+        CFRelease(imageSource); // 添加这行
         CGContextSaveGState(pdfContext);
         CGContextDrawImage(pdfContext, pageRect, imageRef);
         CGContextRestoreGState(pdfContext);
@@ -554,11 +556,16 @@ static inline NSFont * FontWithSize(NSString *strChar, CGSize size) {
 
 - (void)recognitionAppleImage:(NSImage *)image {
     dispatch_async(dispatch_get_global_queue(0, 0), ^{
-    __block typeof(self) blockSelf = self;
-        _appleRequest = [[VNRecognizeTextRequest alloc] initWithCompletionHandler:^(VNRequest * _Nonnull request, NSError * _Nullable error) {
+        if(self->_appleRequest) {
+            [self->_appleRequest cancel];
+            self->_appleRequest = nil;
+        }
+        __weak typeof(self) weakSelf = self;
+        self->_appleRequest = [[VNRecognizeTextRequest alloc] initWithCompletionHandler:^(VNRequest * _Nonnull request, NSError * _Nullable error) {
+            __strong typeof(weakSelf) strongSelf = weakSelf;
             NSArray *results = nil;
             if (request.results.count > 0) {
-                results = [blockSelf responseDataRequest:request dictionary:nil imageSize:image.size];
+                results = [strongSelf responseDataRequest:request dictionary:nil imageSize:image.size];
             }
 
             NSMutableArray *resultArray = [[NSMutableArray alloc] init];
@@ -574,21 +581,21 @@ static inline NSFont * FontWithSize(NSString *strChar, CGSize size) {
             
             dispatch_async(dispatch_get_main_queue(), ^{
                 if (error || !results) {
-                    if (self.delegate && [blockSelf.delegate respondsToSelector:@selector(GOCRManager:didFailureOCRImageAtIndex:error:)]) {
-                        [blockSelf.delegate GOCRManager:blockSelf didFailureOCRImageAtIndex:blockSelf.finishIndex error:error];
+                    if (strongSelf.delegate && [strongSelf.delegate respondsToSelector:@selector(GOCRManager:didFailureOCRImageAtIndex:error:)]) {
+                        [strongSelf.delegate GOCRManager:strongSelf didFailureOCRImageAtIndex:strongSelf.finishIndex error:error];
                     }
                 } else {
-                    if (self.delegate && [blockSelf.delegate respondsToSelector:@selector(GOCRManager:didFinishOCRImageAtIndex:results:)]) {
-                        [blockSelf.delegate GOCRManager:blockSelf didFinishOCRImageAtIndex:blockSelf.finishIndex results:results];
+                    if (strongSelf.delegate && [strongSelf.delegate respondsToSelector:@selector(GOCRManager:didFinishOCRImageAtIndex:results:)]) {
+                        [strongSelf.delegate GOCRManager:strongSelf didFinishOCRImageAtIndex:strongSelf.finishIndex results:results];
                     }
                 }
-                [blockSelf recognitionAppleImageAtIndex:blockSelf.finishIndex+1];
+                [strongSelf recognitionAppleImageAtIndex:strongSelf.finishIndex+1];
             });
         }];
         self->_appleRequest.usesCPUOnly = YES;
         self->_appleRequest.recognitionLevel = self.appleRecognitionMode;
         if (self.languages.count > 0) {
-            NSMutableArray *array = [[NSMutableArray alloc] initWithArray:blockSelf.languages];
+            NSMutableArray *array = [[NSMutableArray alloc] initWithArray:self.languages];
             if ([self.languages containsObject:@"zh-Hant"]) {
                 [array removeObject:@"zh-Hant"];
                 [array insertObject:@"zh-Hant" atIndex:0];
@@ -603,10 +610,12 @@ static inline NSFont * FontWithSize(NSString *strChar, CGSize size) {
             self->_appleRequest.recognitionLanguages = @[@"zh-Hans",@"zh-Hant"];
         }
         NSError *error = nil;
-        VNImageRequestHandler *handle = [[VNImageRequestHandler alloc] initWithCGImage:[self nsImageToCGImageRef:image] options:@{}];
+        CGImageRef imageRef = [self nsImageToCGImageRef:image];
+        VNImageRequestHandler *handle = [[VNImageRequestHandler alloc] initWithCGImage:imageRef options:@{}];
         if (self->_appleRequest){
             [handle performRequests:@[self->_appleRequest] error:&error];
         }
+        CGImageRelease(imageRef);
     });
 }
 
@@ -840,19 +849,19 @@ static inline NSFont * FontWithSize(NSString *strChar, CGSize size) {
     return results;
 }
 
-- (CGImageRef)nsImageToCGImageRef:(NSImage*)image;
-{
-    NSData * imageData = [image TIFFRepresentation];
-    CGImageRef imageRef;
-    if(imageData)
-    {
-        CGImageSourceRef imageSource =
-                  CGImageSourceCreateWithData(
-                            (CFDataRef)imageData,  NULL);
-        imageRef = CGImageSourceCreateImageAtIndex(
-                               imageSource, 0, NULL);
-    }
-    return imageRef;
+- (CGImageRef)nsImageToCGImageRef:(NSImage*)image {
+    NSData *imageData = [image TIFFRepresentation];
+    CGImageRef imageRef = NULL;
+    
+    if (imageData) {
+        CGImageSourceRef imageSource = CGImageSourceCreateWithData((CFDataRef)imageData, NULL);
+        if (imageSource) {
+            imageRef = CGImageSourceCreateImageAtIndex(imageSource, 0, NULL);
+            CFRelease(imageSource); // 释放 imageSource
+        }
+    }
+    
+    return imageRef; // 调用者负责释放
 }
 
 @end

+ 79 - 21
PDF Office/PDF Master/Class/PDFTools/OCRNew/Model/KMGOCROperation.swift

@@ -170,41 +170,99 @@ let KMGOC_API_KEY = "AIzaSyCJuqJ9YvtkFKMl1mW3Yq-av3mmI9ScbRY"
         }
         task?.resume()
     }
+    
     func base64EncodeImage(_ image: NSImage) -> String? {
+        // 获取 TIFF 数据
         guard let data = image.tiffRepresentation else { return nil }
-        let imageRep = NSBitmapImageRep(data: data)!
+        
+        // 创建位图表示
+        guard let imageRep = NSBitmapImageRep(data: data) else { return nil }
         imageRep.size = image.size
-        let imageData = imageRep.representation(using: .png, properties: [:])
-        // Resize the image if it exceeds the 4MB API limit
-        if imageData?.count ?? 0 > 4194304 {
-            let compressedData = compressImageData(imageData!, toMaxFileSize: 4194304)
-            if let data = compressedData {
-                return data.base64EncodedString(options: .endLineWithCarriageReturn)
-            }
-        }
         
-        if let data = imageData {
-            if #available(macOS 10.9, *) {
-                return data.base64EncodedString(options: .endLineWithCarriageReturn)
-            } else {
-                return data.base64EncodedString(options: [])
+        // 转换为 PNG 数据
+        guard let imageData = imageRep.representation(using: .png, properties: [:]) else { return nil }
+        
+        // 如果数据大小超过限制,尝试压缩
+        let finalData: Data
+        if imageData.count > 4194304 {
+            guard let compressedData = compressImageData(imageData, toMaxFileSize: 4194304) else {
+                return nil // 压缩失败时返回 nil
             }
+            finalData = compressedData
+        } else {
+            finalData = imageData
         }
         
-        return nil
+        // 返回 Base64 编码字符串
+        return finalData.base64EncodedString(options: .lineLength64Characters)
     }
+
     func compressImageData(_ imageData: Data, toMaxFileSize maxFileSize: Int) -> Data? {
+        // 初始压缩比
         var compression: CGFloat = 0.9
         let maxCompression: CGFloat = 0.1
-        var compressImageData = imageData
-        while compressImageData.count > maxFileSize && compression > maxCompression {
+        
+        // 循环压缩
+        var currentData = imageData
+        while currentData.count > maxFileSize && compression > maxCompression {
             compression -= 0.1
-            let imageRep = NSBitmapImageRep(data: compressImageData)!
-            compressImageData = imageRep.representation(using: .jpeg, properties: [NSBitmapImageRep.PropertyKey.compressionFactor: NSNumber(value: Float(compression))])!
+            
+            // 创建位图表示
+            guard let imageRep = NSBitmapImageRep(data: currentData) else {
+                return nil // 解码失败时返回 nil
+            }
+            
+            // 尝试压缩为 JPEG 数据
+            guard let compressedData = imageRep.representation(
+                using: .jpeg,
+                properties: [.compressionFactor: NSNumber(value: Float(compression))]
+            ) else {
+                return nil // 压缩失败时返回 nil
+            }
+            
+            currentData = compressedData
         }
-        return compressImageData
+        
+        return currentData.count <= maxFileSize ? currentData : nil
     }
-    func responseDataResults(_ dictionary: NSDictionary) -> [Any]? { 
+//
+//    func base64EncodeImage(_ image: NSImage) -> String? {
+//        guard let data = image.tiffRepresentation else { return nil }
+//        let imageRep = NSBitmapImageRep(data: data)!
+//        imageRep.size = image.size
+//        let imageData = imageRep.representation(using: .png, properties: [:])
+//        // Resize the image if it exceeds the 4MB API limit
+//        if imageData?.count ?? 0 > 4194304 {
+//            let compressedData = compressImageData(imageData!, toMaxFileSize: 4194304)
+//            if let data = compressedData {
+//                return data.base64EncodedString(options: .endLineWithCarriageReturn)
+//            }
+//        }
+//        
+//        if let data = imageData {
+//            if #available(macOS 10.9, *) {
+//                return data.base64EncodedString(options: .endLineWithCarriageReturn)
+//            } else {
+//                return data.base64EncodedString(options: [])
+//            }
+//        }
+//        
+//        return nil
+//    }
+//    
+//    func compressImageData(_ imageData: Data, toMaxFileSize maxFileSize: Int) -> Data? {
+//        var compression: CGFloat = 0.9
+//        let maxCompression: CGFloat = 0.1
+//        var compressImageData = imageData
+//        while compressImageData.count > maxFileSize && compression > maxCompression {
+//            compression -= 0.1
+//            let imageRep = NSBitmapImageRep(data: compressImageData)!
+//            compressImageData = imageRep.representation(using: .jpeg, properties: [NSBitmapImageRep.PropertyKey.compressionFactor: NSNumber(value: Float(compression))])!
+//        }
+//        return compressImageData
+//    }
+    
+    func responseDataResults(_ dictionary: NSDictionary) -> [Any]? {
         let responses = dictionary["responses"] as? [Any]
         if responses == nil {
             return nil

+ 7 - 4
PDF Office/PDF Master/KMClass/KMNPDFPageEdit/KMNPDFSplit/KMNSplitPDFWindowController.swift

@@ -36,6 +36,8 @@ class KMNSplitPDFWindowController: KMNBaseWindowController {
     
     @IBOutlet var cancelButton: ComponentButton!
     @IBOutlet var splitButton: ComponentButton!
+    
+    @IBOutlet var splitRangeHeightButton:NSLayoutConstraint!
 
     @IBOutlet var cancelWidthButton:NSLayoutConstraint!
     @IBOutlet var splitWidthButton:NSLayoutConstraint!
@@ -414,7 +416,7 @@ class KMNSplitPDFWindowController: KMNBaseWindowController {
                     fileAttribute.pagesType = .PagesString
                     fileAttribute.pagesString = splitRangeSelect.properties.text ?? ""
                 } else {
-                    if(pageRangeSelectIndex == 2) {
+                    if(pageRangeSelectIndex == 1) {
                         fileAttribute.pagesType = .OnlyEven
                     } else {
                         fileAttribute.pagesType = .PagesString
@@ -427,7 +429,8 @@ class KMNSplitPDFWindowController: KMNBaseWindowController {
                 
                 splitRangeSelect.properties.isError = true
                 splitRangeSelect.properties.errorText = KMLocalizedString("Invalid page range or the page number is out of range. Please try again.")
-                splitRangeSelect.reloadData()
+                splitRangeSelect.properties = splitRangeSelect.properties
+                splitRangeHeightButton.constant = splitRangeSelect.properties.propertyInfo.viewHeight
                 return
             }
         }
@@ -674,8 +677,8 @@ extension KMNSplitPDFWindowController: ComponentSelectDelegate {
     func componentSelectTextDidChange(_ view: ComponentSelect) {
         splitRangeSelect.properties.isError = false
         splitRangeSelect.properties.errorText = ""
-        splitRangeSelect.reloadData()
-
+        splitRangeSelect.properties = splitRangeSelect.properties
+        splitRangeHeightButton.constant = splitRangeSelect.properties.propertyInfo.viewHeight
     }
 
 }

+ 24 - 24
PDF Office/PDF Master/KMClass/KMNPDFPageEdit/KMNPDFSplit/KMNSplitPDFWindowController.xib

@@ -28,6 +28,7 @@
                 <outlet property="separatorCheckWidthButton" destination="Abe-jb-3iL" id="ATb-a1-i7X"/>
                 <outlet property="separatorInput" destination="TZS-vp-GuO" id="mxR-rj-mIO"/>
                 <outlet property="splitButton" destination="lHU-2j-0SQ" id="EVK-mi-vLS"/>
+                <outlet property="splitRangeHeightButton" destination="t2F-JL-BWZ" id="kAq-bO-NCv"/>
                 <outlet property="splitRangeRadio" destination="OQ5-6X-OjQ" id="gXR-cC-nkK"/>
                 <outlet property="splitRangeRadioWidthButton" destination="b6x-Js-9ra" id="MVw-Mh-bel"/>
                 <outlet property="splitRangeSelect" destination="VNh-Qe-w42" id="wSP-pe-T3n"/>
@@ -43,21 +44,20 @@
         <customObject id="-3" userLabel="Application" customClass="NSObject"/>
         <window allowsToolTipsWhenApplicationIsInactive="NO" autorecalculatesKeyViewLoop="NO" releasedWhenClosed="NO" visibleAtLaunch="NO" animationBehavior="default" titlebarAppearsTransparent="YES" titleVisibility="hidden" id="F0z-JX-Cv5">
             <windowStyleMask key="styleMask" titled="YES" fullSizeContentView="YES"/>
-            <windowPositionMask key="initialPositionMask" leftStrut="YES" rightStrut="YES" topStrut="YES" bottomStrut="YES"/>
-            <rect key="contentRect" x="196" y="240" width="480" height="270"/>
+            <rect key="contentRect" x="434" y="322" width="480" height="270"/>
             <rect key="screenRect" x="0.0" y="0.0" width="2560" height="1415"/>
-            <view key="contentView" id="se5-gp-TjO">
-                <rect key="frame" x="0.0" y="0.0" width="480" height="494"/>
+            <view key="contentView" misplaced="YES" id="se5-gp-TjO">
+                <rect key="frame" x="0.0" y="0.0" width="480" height="482"/>
                 <autoresizingMask key="autoresizingMask"/>
                 <subviews>
                     <box boxType="custom" borderWidth="0.0" cornerRadius="4" title="Box" translatesAutoresizingMaskIntoConstraints="NO" id="J6U-4A-QXu">
-                        <rect key="frame" x="24" y="16" width="432" height="462"/>
+                        <rect key="frame" x="24" y="16" width="432" height="454"/>
                         <view key="contentView" id="GOc-Px-FVN">
-                            <rect key="frame" x="0.0" y="0.0" width="432" height="462"/>
+                            <rect key="frame" x="0.0" y="0.0" width="432" height="454"/>
                             <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
                             <subviews>
                                 <textField horizontalHuggingPriority="251" verticalHuggingPriority="750" translatesAutoresizingMaskIntoConstraints="NO" id="jDk-6k-wPg">
-                                    <rect key="frame" x="-2" y="446" width="436" height="16"/>
+                                    <rect key="frame" x="-2" y="438" width="436" height="16"/>
                                     <textFieldCell key="cell" lineBreakMode="clipping" title="Split" id="cYm-fs-fJs">
                                         <font key="font" usesAppearanceFont="YES"/>
                                         <color key="textColor" name="labelColor" catalog="System" colorSpace="catalog"/>
@@ -65,27 +65,27 @@
                                     </textFieldCell>
                                 </textField>
                                 <box boxType="custom" borderWidth="0.0" title="Box" translatesAutoresizingMaskIntoConstraints="NO" id="Q6A-RB-Ma1">
-                                    <rect key="frame" x="0.0" y="264" width="432" height="166"/>
+                                    <rect key="frame" x="0.0" y="252" width="432" height="170"/>
                                     <view key="contentView" id="bHe-mF-VFs">
-                                        <rect key="frame" x="0.0" y="0.0" width="432" height="166"/>
+                                        <rect key="frame" x="0.0" y="0.0" width="432" height="170"/>
                                         <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
                                         <subviews>
                                             <customView translatesAutoresizingMaskIntoConstraints="NO" id="QNR-bY-o0a" customClass="ComponentRadio" customModule="KMComponentLibrary">
-                                                <rect key="frame" x="0.0" y="94" width="98" height="32"/>
+                                                <rect key="frame" x="0.0" y="98" width="98" height="32"/>
                                                 <constraints>
                                                     <constraint firstAttribute="height" constant="32" id="eN4-vv-2FB"/>
                                                     <constraint firstAttribute="width" constant="98" id="g2O-rM-rg3"/>
                                                 </constraints>
                                             </customView>
                                             <customView translatesAutoresizingMaskIntoConstraints="NO" id="tUV-il-jUA" customClass="ComponentRadio" customModule="KMComponentLibrary">
-                                                <rect key="frame" x="0.0" y="54" width="100" height="32"/>
+                                                <rect key="frame" x="0.0" y="58" width="100" height="32"/>
                                                 <constraints>
                                                     <constraint firstAttribute="width" constant="100" id="0Ip-y2-bce"/>
                                                     <constraint firstAttribute="height" constant="32" id="gdP-n3-RdE"/>
                                                 </constraints>
                                             </customView>
                                             <textField horizontalHuggingPriority="251" verticalHuggingPriority="750" translatesAutoresizingMaskIntoConstraints="NO" id="UQm-9R-ufX">
-                                                <rect key="frame" x="-2" y="138" width="436" height="16"/>
+                                                <rect key="frame" x="-2" y="142" width="436" height="16"/>
                                                 <textFieldCell key="cell" lineBreakMode="clipping" title="Split Method" id="cI1-Kj-hfi">
                                                     <font key="font" usesAppearanceFont="YES"/>
                                                     <color key="textColor" name="labelColor" catalog="System" colorSpace="catalog"/>
@@ -93,27 +93,27 @@
                                                 </textFieldCell>
                                             </textField>
                                             <customView translatesAutoresizingMaskIntoConstraints="NO" id="OQ5-6X-OjQ" customClass="ComponentRadio" customModule="KMComponentLibrary">
-                                                <rect key="frame" x="0.0" y="14" width="90" height="32"/>
+                                                <rect key="frame" x="0.0" y="18" width="90" height="32"/>
                                                 <constraints>
                                                     <constraint firstAttribute="height" constant="32" id="W7t-AF-CBU"/>
                                                     <constraint firstAttribute="width" constant="90" id="b6x-Js-9ra"/>
                                                 </constraints>
                                             </customView>
                                             <customView translatesAutoresizingMaskIntoConstraints="NO" id="VNh-Qe-w42" customClass="ComponentSelect" customModule="KMComponentLibrary">
-                                                <rect key="frame" x="98" y="14" width="334" height="32"/>
+                                                <rect key="frame" x="98" y="18" width="334" height="32"/>
                                                 <constraints>
                                                     <constraint firstAttribute="height" constant="32" id="t2F-JL-BWZ"/>
                                                 </constraints>
                                             </customView>
                                             <customView translatesAutoresizingMaskIntoConstraints="NO" id="VtK-QB-kfV" customClass="ComponentInputNumber" customModule="KMComponentLibrary">
-                                                <rect key="frame" x="106" y="94" width="96" height="32"/>
+                                                <rect key="frame" x="106" y="98" width="96" height="32"/>
                                                 <constraints>
                                                     <constraint firstAttribute="width" constant="96" id="JPd-DV-TKo"/>
                                                     <constraint firstAttribute="height" constant="32" id="wWO-v0-kf7"/>
                                                 </constraints>
                                             </customView>
                                             <textField horizontalHuggingPriority="251" verticalHuggingPriority="750" translatesAutoresizingMaskIntoConstraints="NO" id="taE-wg-hAl">
-                                                <rect key="frame" x="208" y="102" width="226" height="16"/>
+                                                <rect key="frame" x="208" y="106" width="226" height="16"/>
                                                 <textFieldCell key="cell" lineBreakMode="clipping" title="page(s) split into a PDF file" id="Xjj-Vz-9HY">
                                                     <font key="font" metaFont="system"/>
                                                     <color key="textColor" name="labelColor" catalog="System" colorSpace="catalog"/>
@@ -121,14 +121,14 @@
                                                 </textFieldCell>
                                             </textField>
                                             <customView translatesAutoresizingMaskIntoConstraints="NO" id="URa-ZG-kvD" customClass="ComponentInputNumber" customModule="KMComponentLibrary">
-                                                <rect key="frame" x="108" y="54" width="96" height="32"/>
+                                                <rect key="frame" x="108" y="58" width="96" height="32"/>
                                                 <constraints>
                                                     <constraint firstAttribute="width" constant="96" id="80b-Kw-yF3"/>
                                                     <constraint firstAttribute="height" constant="32" id="xt9-QO-Oc7"/>
                                                 </constraints>
                                             </customView>
                                             <textField horizontalHuggingPriority="251" verticalHuggingPriority="750" translatesAutoresizingMaskIntoConstraints="NO" id="hSV-Fh-E6f">
-                                                <rect key="frame" x="210" y="62" width="224" height="16"/>
+                                                <rect key="frame" x="210" y="66" width="224" height="16"/>
                                                 <textFieldCell key="cell" lineBreakMode="clipping" title="PDF files" id="uMu-7j-jve">
                                                     <font key="font" metaFont="system"/>
                                                     <color key="textColor" name="labelColor" catalog="System" colorSpace="catalog"/>
@@ -138,6 +138,7 @@
                                         </subviews>
                                         <constraints>
                                             <constraint firstItem="URa-ZG-kvD" firstAttribute="centerY" secondItem="tUV-il-jUA" secondAttribute="centerY" id="1sb-4R-bHQ"/>
+                                            <constraint firstItem="VNh-Qe-w42" firstAttribute="firstBaseline" secondItem="OQ5-6X-OjQ" secondAttribute="firstBaseline" id="2rq-KF-pvs"/>
                                             <constraint firstItem="URa-ZG-kvD" firstAttribute="leading" secondItem="tUV-il-jUA" secondAttribute="trailing" constant="8" id="2yC-7S-Y0P"/>
                                             <constraint firstItem="hSV-Fh-E6f" firstAttribute="centerY" secondItem="tUV-il-jUA" secondAttribute="centerY" id="2z7-DF-9e0"/>
                                             <constraint firstAttribute="trailing" secondItem="taE-wg-hAl" secondAttribute="trailing" id="37M-qP-a9U"/>
@@ -155,11 +156,10 @@
                                             <constraint firstAttribute="trailing" secondItem="UQm-9R-ufX" secondAttribute="trailing" id="cJ6-5g-Dcj"/>
                                             <constraint firstItem="UQm-9R-ufX" firstAttribute="leading" secondItem="bHe-mF-VFs" secondAttribute="leading" id="cgr-GO-8o7"/>
                                             <constraint firstAttribute="trailing" secondItem="VNh-Qe-w42" secondAttribute="trailing" id="dJz-XK-r6x"/>
-                                            <constraint firstAttribute="bottom" secondItem="OQ5-6X-OjQ" secondAttribute="bottom" constant="14" id="i5j-gK-Yez"/>
                                             <constraint firstItem="taE-wg-hAl" firstAttribute="leading" secondItem="VtK-QB-kfV" secondAttribute="trailing" constant="8" id="k0X-V6-nr0"/>
                                             <constraint firstItem="VNh-Qe-w42" firstAttribute="leading" secondItem="OQ5-6X-OjQ" secondAttribute="trailing" constant="8" id="rZW-vU-IEJ"/>
-                                            <constraint firstItem="VNh-Qe-w42" firstAttribute="centerY" secondItem="OQ5-6X-OjQ" secondAttribute="centerY" id="te3-86-2yJ"/>
                                             <constraint firstItem="UQm-9R-ufX" firstAttribute="top" secondItem="bHe-mF-VFs" secondAttribute="top" constant="12" id="xn4-HL-y7R"/>
+                                            <constraint firstAttribute="bottom" secondItem="OQ5-6X-OjQ" secondAttribute="bottom" constant="18" id="y33-u0-ixw"/>
                                         </constraints>
                                     </view>
                                 </box>
@@ -194,7 +194,7 @@
                                     </view>
                                 </box>
                                 <box boxType="custom" borderWidth="0.0" title="Box" translatesAutoresizingMaskIntoConstraints="NO" id="tdg-uu-noc">
-                                    <rect key="frame" x="0.0" y="184" width="432" height="64"/>
+                                    <rect key="frame" x="0.0" y="176" width="432" height="64"/>
                                     <view key="contentView" id="VRw-3a-f98">
                                         <rect key="frame" x="0.0" y="0.0" width="432" height="64"/>
                                         <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
@@ -304,12 +304,12 @@
                                 </box>
                             </subviews>
                             <constraints>
-                                <constraint firstItem="tdg-uu-noc" firstAttribute="top" secondItem="Q6A-RB-Ma1" secondAttribute="bottom" constant="16" id="0fm-5c-iuR"/>
+                                <constraint firstItem="tdg-uu-noc" firstAttribute="top" secondItem="Q6A-RB-Ma1" secondAttribute="bottom" constant="12" id="0fm-5c-iuR"/>
                                 <constraint firstAttribute="trailing" secondItem="DNb-ku-BLc" secondAttribute="trailing" id="4GG-Cn-xuW"/>
                                 <constraint firstItem="jDk-6k-wPg" firstAttribute="leading" secondItem="GOc-Px-FVN" secondAttribute="leading" id="4zz-30-R3i"/>
                                 <constraint firstItem="Q6A-RB-Ma1" firstAttribute="leading" secondItem="GOc-Px-FVN" secondAttribute="leading" id="6Tn-tz-TQ1"/>
                                 <constraint firstAttribute="trailing" secondItem="Q6A-RB-Ma1" secondAttribute="trailing" id="7IZ-P2-tJO"/>
-                                <constraint firstItem="1WY-FC-FjB" firstAttribute="top" secondItem="tdg-uu-noc" secondAttribute="bottom" constant="8" id="7pL-ec-mTz"/>
+                                <constraint firstItem="1WY-FC-FjB" firstAttribute="top" secondItem="tdg-uu-noc" secondAttribute="bottom" id="7pL-ec-mTz"/>
                                 <constraint firstItem="DNb-ku-BLc" firstAttribute="top" secondItem="1WY-FC-FjB" secondAttribute="bottom" constant="16" id="A1L-lz-yhs"/>
                                 <constraint firstAttribute="trailing" secondItem="tdg-uu-noc" secondAttribute="trailing" id="Fu2-y9-sHw"/>
                                 <constraint firstItem="DNb-ku-BLc" firstAttribute="leading" secondItem="GOc-Px-FVN" secondAttribute="leading" id="LBX-sb-7oQ"/>
@@ -327,7 +327,7 @@
                         </constraints>
                     </box>
                     <progressIndicator maxValue="100" indeterminate="YES" style="spinning" translatesAutoresizingMaskIntoConstraints="NO" id="TiY-FI-9RS">
-                        <rect key="frame" x="224" y="231" width="32" height="32"/>
+                        <rect key="frame" x="224" y="227" width="32" height="32"/>
                     </progressIndicator>
                 </subviews>
                 <constraints>

+ 5 - 0
PDF Office/PDF Master/KMClass/KMPDFViewController/KMMainViewController.swift

@@ -3491,6 +3491,11 @@ extension KMMainViewController {
             }
             self?.hiddenProgressWindow()
         }
+        
+        self.progressC?.closeBlock = {
+            print("手动取消中")
+            KMOCRManager.manager.cancelRecognition()
+        }
     }
     
     func convertOCRSaveAsTXT(text: String) {

+ 33 - 46
PDF Office/PDF Master/KMClass/KMPDFViewController/RightSideController/Views/OCR/Tool/Manager/KMOCRManager.swift

@@ -30,7 +30,7 @@ class KMOCRManager: NSObject {
     //Tool OCR
     private var OCRManger: KMGOCRManager?
     private var ocrDictionary:[NSNumber: Any] = [:]
-    private var pageImages: [NSImage] = []
+//    private var pageImages: [NSImage] = []
     
     private var OCRComplete: KMOCRManagerOCRComplete?
     private var progress: KMOCRManagerOCRProgress?
@@ -68,9 +68,9 @@ class KMOCRManager: NSObject {
 //        }
 //        return isContainsImagePage
 //    }
-    func cancel() {
-        self.converter?.cancel()
-    }
+//    func cancel() {
+//        self.converter?.cancel()
+//    }
 }
 
 //MARK: Tool OCR
@@ -130,29 +130,28 @@ extension KMOCRManager: KMGOCRManagerDelegate {
         self.document = document
         self.pageIndexs = indexs
         
-        //获取缩图
-        var selctPageImages: [NSImage] = []
-        for i in 0..<indexs.count {
-            autoreleasepool {
-                let index = indexs[i]
-                let page = document.page(at: UInt(index))
-                var image = page?.thumbnail(of: CGSize(width: (page?.size.width ?? 0) * maxImageScale, height: (page?.size.height ?? 0) * maxImageScale))
-                if (image != nil) {
-                    image = self.dealImage(image: image!, isCorrection: model.imageCorrection, isEnhancement: model.imageEnhancement)
-                    if image != nil {
-                        selctPageImages.append(image!)
+        DispatchQueue.main.async { [unowned self] in
+            //获取缩图
+            var selctPageImages: [NSImage] = []
+            for i in 0..<indexs.count {
+                autoreleasepool {
+                    let index = indexs[i]
+                    let page = document.page(at: UInt(index))
+                    var image = page?.thumbnail(of: CGSize(width: (page?.size.width ?? 0) * maxImageScale, height: (page?.size.height ?? 0) * maxImageScale))
+                    if (image != nil) {
+                        image = self.dealImage(image: image!, isCorrection: self.model.imageCorrection, isEnhancement: self.model.imageEnhancement)
+                        if image != nil {
+                            selctPageImages.append(image!)
+                        }
                     }
                 }
             }
-        }
-        
-        self.pageImages = selctPageImages
-        
-        if (selctPageImages.count == 0) {
-            fail()
-        } else {
-//            self.cancelRecognition()
-            DispatchQueue.main.async {
+            
+            //        self.pageImages = selctPageImages
+            
+            if (selctPageImages.count == 0) {
+                fail()
+            } else {
                 self.OCRManger = KMGOCRManager()
                 if type == .google {
                     self.OCRManger?.ocrType = .google
@@ -195,13 +194,13 @@ extension KMOCRManager: KMGOCRManagerDelegate {
         
         KMGOCRManager.default().delegate = nil
         OCRManger?.cancelRecognition()
+        
+        self.converter?.cancel()
     }
     
     
     //MARK: - KMGOCRManagerDelegate
     func gocrManagerDidFinishOCR(_ manager: KMGOCRManager!) {
-//        self.batchesOCR()
-//        KMGOCRManager.default().createPDFFile(savePDFPath, imagePaths: self.pageImages, results: resultArrays, scale: KMImageScale)
         var resultArrays: Array<Any> = []
         var ocrIndexArrays: Array<Any> = []
         let sortedKeys = self.ocrDictionary.keys.sorted(by: { $0.compare(($1)) == .orderedAscending })
@@ -214,20 +213,26 @@ extension KMOCRManager: KMGOCRManagerDelegate {
         if model.showType == .page {
             if model.saveAsPDF {
                 if model.saveType == .PDF {
-                    KMGOCRManager.default().createPDFFile(manager.saveFilePath, images: self.pageImages, results: resultArrays, scale: maxImageScale)
+                    let images: [NSImage] = manager.images as? [NSImage] ?? []
+                    KMGOCRManager.default().createPDFFile(manager.saveFilePath, images: images, results: resultArrays, scale: maxImageScale)
+                    NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: manager.saveFilePath ?? "")])
+                    self.OCRComplete?(nil, nil, nil)
                 } else {
                     self.saveTXT()
                 }
             } else {
                 let foler = self.fetchOutputFolderPath()
                 let outputPath = foler + "/temp_OCR.pdf";
-                KMGOCRManager.default().createPDFFile(outputPath, images: self.pageImages, results: resultArrays, scale: maxImageScale)
+                let images: [NSImage] = manager.images as? [NSImage] ?? []
+                KMGOCRManager.default().createPDFFile(outputPath, images: images, results: resultArrays, scale: maxImageScale)
                 
                 guard let document = self.document else {
                     self.fail()
                     return }
                 self.insertPDF(currentDocument: document, pageIndexs: self.pageIndexs, outputPath: outputPath)
             }
+            manager.cancelRecognition()
+            self.OCRManger = nil
         } else if model.showType == .area {
             let string = self.fetchTXT(ocrDictionary: ocrDictionary)
             self.OCRComplete?(nil, string, nil)
@@ -240,24 +245,6 @@ extension KMOCRManager: KMGOCRManagerDelegate {
         workspace.activateFileViewerSelecting([url])
     }
     
-//    KMGOCRManager.default().createPDFFile(savePDFPath, imagePaths: imagePath, results: resultArrays, scale: KMImageScale)
-//    if saveAccessCtr.openAutomaticButton.state == .on {
-//        self.cancelButtonAction("")
-//        NSDocumentController.shared.openDocument(withContentsOf: URL(fileURLWithPath: savePDFPath), display: true, completionHandler: {document,documentWasAlreadyOpen,error in
-//            
-//        })
-//    } else {
-//        self.viewFileAtFinder(savePDFPath)
-//    }
-//}
-//}
-//}
-//
-//func viewFileAtFinder(_ fileName: String) {
-//let workspace = NSWorkspace.shared
-//let url = URL(fileURLWithPath: fileName)
-//workspace.activateFileViewerSelecting([url])
-//}
     func gocrManager(_ manager: KMGOCRManager!, didCancelOCRImageAt index: Int) {
         
     }

+ 2 - 2
PDF Office/PDF Master/KMClass/KMPDFViewController/RightSideController/Views/OCR/Tool/View/Page/KMOCRPageView.swift

@@ -177,7 +177,7 @@ class KMOCRPageView: BaseXibView {
         self.OCRPlan2Button.reloadData()
         
         
-        self.saveAsPDFButton.properties.state = model.saveAsPDF ? .pressed : .normal
+        self.saveAsPDFButton.properties.checkboxType = model.saveAsPDF ? .selected : .normal
         self.enhancementSwitch.properties.open = model.imageEnhancement
         self.correctionSwitch.properties.open = model.imageCorrection
         
@@ -277,7 +277,7 @@ extension KMOCRPageView {
     
     func saveAsPDFAction(_ sender: ComponentCheckBox) {
         model.saveAsPDF = (sender.properties.checkboxType == .normal) ? false : true
-//        self.reloadData()
+        self.reloadData()
         
         guard let callBack = changeAction else { return }