Browse Source

【快照】KMSnapshotPDFView OC转Swift

tangchao 1 year ago
parent
commit
a3a2213bfc

+ 325 - 325
PDF Office/PDF Master/Class/PDFTools/Snapshot/View/KMSnapshotPDFView.swift

@@ -8,36 +8,120 @@
 import Cocoa
 
 class KMSnapshotPDFView: CPDFView {
-
-    /*
-     NSPopUpButton *scalePopUpButton;
-     PDFPage *autoFitPage;
-     NSRect autoFitRect;
-     BOOL autoFits;
-     CGFloat startScale;
-     NSInteger minHistoryIndex;
- }
-
- @property (nonatomic) BOOL autoFits;
- @property (nonatomic, readonly) NSPopUpButton *scalePopUpButton;
-
- - (void)resetHistory;
-     */
     
-    /*
-     - (void)resetAutoFitRectIfNeeded;
-
-     - (void)scalePopUpAction:(id)sender;
-
-     - (void)setAutoFits:(BOOL)newAuto adjustPopup:(BOOL)flag;
-     - (void)setScaleFactor:(CGFloat)factor adjustPopup:(BOOL)flag;
-
-     - (void)handlePDFViewFrameChangedNotification:(NSNotification *)notification;
-     - (void)handlePDFContentViewFrameChangedNotification:(NSNotification *)notification;
-     - (void)handlePDFContentViewFrameChangedDelayedNotification:(NSNotification *)notification;
-
-     - (void)handlePDFViewScaleChangedNotification:(NSNotification *)notification;
-     */
+    private var _scalePopUpButton: NSPopUpButton?
+    var scalePopUpButton: NSPopUpButton? {
+        get {
+            if (self._scalePopUpButton == nil) {
+                
+//                NSScrollView *scrollView = [self scrollView];
+                let scrollView = self.enclosingScrollView
+                scrollView?.hasHorizontalScroller = true
+                
+                // create it
+//                scalePopUpButton = [[NSPopUpButton allocWithZone:[self zone]] initWithFrame:NSMakeRect(0.0, 0.0, 1.0, 1.0) pullsDown:NO];
+                let scalePopUpButton_ = NSPopUpButton(frame: NSMakeRect(0.0, 0.0, 1.0, 1.0), pullsDown: false)
+                scalePopUpButton_.cell?.controlSize = .small
+                self._scalePopUpButton = scalePopUpButton_
+                
+                scalePopUpButton_.isBordered = false
+                scalePopUpButton_.isEnabled = true
+                scalePopUpButton_.refusesFirstResponder = true
+                (scalePopUpButton_.cell as? NSPopUpButtonCell)?.usesItemFromMenu = true
+                
+                // set a suitable font, the control size is 0, 1 or 2
+                scalePopUpButton_.font = .toolTipsFont(ofSize: CONTROL_FONT_SIZE)
+                
+                var cnt = 0
+                var numberOfDefaultItems = self._SKDefaultScaleMenuFactorsCount
+                var curItem: AnyObject?
+                var label = ""
+                var width: CGFloat = 0.0
+                var maxWidth: CGFloat = 0.0
+                
+                let size = NSMakeSize(1000.0, 1000.0)
+                let attrs = [NSAttributedString.Key.font : scalePopUpButton_.font ?? .systemFont(ofSize: 13)]
+                var maxIndex = 0
+                
+                // fill it
+                for i in 0 ..< numberOfDefaultItems {
+//                for (cnt = 0; cnt < numberOfDefaultItems; cnt++) {
+                    label = Bundle.main.localizedString(forKey: self._SKDefaultScaleMenuLabels[i], value: "", table: "ZoomValues")
+//                    width = NSWidth([label boundingRectWithSize:size options:0 attributes:attrs]);
+                    width = NSWidth(label.boundingRect(with: size, options: NSString.DrawingOptions(rawValue: 0), attributes: attrs))
+                    if (width > maxWidth) {
+                        maxWidth = width
+                        maxIndex = i
+                    }
+                    scalePopUpButton_.addItem(withTitle: label)
+                    curItem = scalePopUpButton_.item(at: i)
+//                    [curItem setRepresentedObject:(SKDefaultScaleMenuFactors[cnt] > 0.0 ? [NSNumber numberWithDouble:SKDefaultScaleMenuFactors[cnt]] : nil)];
+                    let fac = self._SKDefaultScaleMenuFactors[i]
+                    if fac > 0.0 {
+                        (curItem as? NSMenuItem)?.representedObject = NSNumber(value: fac)
+                    } else {
+                        (curItem as? NSMenuItem)?.representedObject = nil
+                    }
+                }
+                
+                // Make sure the popup is big enough to fit the largest cell
+                scalePopUpButton_.selectItem(at: maxIndex)
+                scalePopUpButton_.sizeToFit()
+//                [scalePopUpButton setFrameSize:];
+                scalePopUpButton_.setFrameSize(NSMakeSize(NSWidth(scalePopUpButton_.frame) - CONTROL_WIDTH_OFFSET, CONTROL_HEIGHT))
+//
+//                // select the appropriate item, adjusting the scaleFactor if necessary
+                if self.autoFits {
+                    self._setScaleFactor(0, adjustPopup: true)
+                } else {
+                    self._setScaleFactor(self.scaleFactor, adjustPopup: true)
+                }
+//
+//                // hook it up
+                scalePopUpButton_.target = self
+                scalePopUpButton_.action = #selector(_scalePopUpAction)
+//
+//                // don't let it become first responder
+                scalePopUpButton_.refusesFirstResponder = true
+                
+            }
+            
+            return _scalePopUpButton
+        }
+    }
+    
+    var autoFitPage: CPDFPage?
+    var autoFitRect: NSRect = .zero
+    var autoFits = false
+    var startScale: CGFloat = 0
+    var minHistoryIndex = 0
+    
+    private let CONTROL_FONT_SIZE = 10.0
+    private let CONTROL_HEIGHT = 15.0
+    private let CONTROL_WIDTH_OFFSET = 20.0
+    
+    private let _SKDefaultScaleMenuLabels = ["Auto", "10%", "20%", "25%", "35%", "50%", "60%", "71%", "85%", "100%", "120%", "141%", "170%", "200%", "300%", "400%", "600%", "800%", "1000%", "1200%", "1400%", "1700%", "2000%"]
+    private let _SKDefaultScaleMenuFactors = [0.0, 0.1, 0.2, 0.25, 0.35, 0.5, 0.6, 0.71, 0.85, 1.0, 1.2, 1.41, 1.7, 2.0, 3.0, 4.0, 6.0, 8.0, 10.0, 12.0, 14.0, 17.0, 20.0]
+    private let _SKMinDefaultScaleMenuFactor = 0.1
+    private let _SKDefaultScaleMenuFactorsCount = 23
+    
+    deinit {
+        KMPrint("KMSnapshotPDFView deinit.")
+        
+        NotificationCenter.default.removeObserver(self)
+    }
+    
+    override init(frame frameRect: NSRect) {
+        super.init(frame: frameRect)
+        
+        self._commonInitialization()
+    }
+    
+    required init?(coder: NSCoder) {
+        super.init(coder: coder)
+        
+        self._commonInitialization()
+    }
     
     override func draw(_ dirtyRect: NSRect) {
         super.draw(dirtyRect)
@@ -45,124 +129,11 @@ class KMSnapshotPDFView: CPDFView {
         // Drawing code here.
     }
     
+
+    
     /*
      #define SKPDFContentViewChangedNotification @"SKPDFContentViewChangedNotification"
 
-     static NSString *SKDefaultScaleMenuLabels[] = {@"Auto", @"10%", @"20%", @"25%", @"35%", @"50%", @"60%", @"71%", @"85%", @"100%", @"120%", @"141%", @"170%", @"200%", @"300%", @"400%", @"600%", @"800%", @"1000%", @"1200%", @"1400%", @"1700%", @"2000%"};
-     static CGFloat SKDefaultScaleMenuFactors[] = {0.0, 0.1, 0.2, 0.25, 0.35, 0.5, 0.6, 0.71, 0.85, 1.0, 1.2, 1.41, 1.7, 2.0, 3.0, 4.0, 6.0, 8.0, 10.0, 12.0, 14.0, 17.0, 20.0};
-
-     #define SKMinDefaultScaleMenuFactor (SKDefaultScaleMenuFactors[1])
-     #define SKDefaultScaleMenuFactorsCount (sizeof(SKDefaultScaleMenuFactors) / sizeof(CGFloat))
-
-     #define CONTROL_FONT_SIZE 10.0
-     #define CONTROL_HEIGHT 15.0
-     #define CONTROL_WIDTH_OFFSET 20.0
-
-     #pragma mark Popup button
-
-     - (void)commonInitialization {
-         scalePopUpButton = nil;
-         autoFitPage = nil;
-         autoFitRect = NSZeroRect;
-         
-         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handlePDFViewFrameChangedNotification:)
-                                                      name:NSViewFrameDidChangeNotification object:self];
-         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handlePDFViewFrameChangedNotification:)
-                                                      name:NSViewBoundsDidChangeNotification object:self];
-         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handlePDFContentViewFrameChangedNotification:)
-                                                      name:NSViewBoundsDidChangeNotification object:[[self scrollView] contentView]];
-         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handlePDFContentViewFrameChangedDelayedNotification:)
-                                                      name:SKPDFContentViewChangedNotification object:self];
-         if ([PDFView instancesRespondToSelector:@selector(magnifyWithEvent:)] == NO || [PDFView instanceMethodForSelector:@selector(magnifyWithEvent:)] == [NSView instanceMethodForSelector:@selector(magnifyWithEvent:)])
-             [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handlePDFViewScaleChangedNotification:)
-                                                          name:PDFViewScaleChangedNotification object:self];
-     }
-
-     - (id)initWithFrame:(NSRect)frameRect {
-         self = [super initWithFrame:frameRect];
-         if (self) {
-             [self commonInitialization];
-         }
-         return self;
-     }
-
-     - (id)initWithCoder:(NSCoder *)decoder {
-         self = [super initWithCoder:decoder];
-         if (self) {
-             [self commonInitialization];
-         }
-         return self;
-     }
-
-     - (void)dealloc {
-         [[NSNotificationCenter defaultCenter] removeObserver:self];
-         SKDESTROY(scalePopUpButton);
-         [super dealloc];
-     }
-
-     - (NSPopUpButton *)scalePopUpButton {
-         
-         if (scalePopUpButton == nil) {
-             
-             NSScrollView *scrollView = [self scrollView];
-             [scrollView setHasHorizontalScroller:YES];
-             
-             // create it
-             scalePopUpButton = [[NSPopUpButton allocWithZone:[self zone]] initWithFrame:NSMakeRect(0.0, 0.0, 1.0, 1.0) pullsDown:NO];
-             
-             [[scalePopUpButton cell] setControlSize:NSSmallControlSize];
-             [scalePopUpButton setBordered:NO];
-             [scalePopUpButton setEnabled:YES];
-             [scalePopUpButton setRefusesFirstResponder:YES];
-             [[scalePopUpButton cell] setUsesItemFromMenu:YES];
-             
-             // set a suitable font, the control size is 0, 1 or 2
-             [scalePopUpButton setFont:[NSFont toolTipsFontOfSize:CONTROL_FONT_SIZE]];
-             
-             NSUInteger cnt, numberOfDefaultItems = SKDefaultScaleMenuFactorsCount;
-             id curItem;
-             NSString *label;
-             CGFloat width, maxWidth = 0.0;
-             NSSize size = NSMakeSize(1000.0, 1000.0);
-             NSDictionary *attrs = [NSDictionary dictionaryWithObjectsAndKeys:[scalePopUpButton font], NSFontAttributeName, nil];
-             NSUInteger maxIndex = 0;
-             
-             // fill it
-             for (cnt = 0; cnt < numberOfDefaultItems; cnt++) {
-                 label = [[NSBundle mainBundle] localizedStringForKey:SKDefaultScaleMenuLabels[cnt] value:@"" table:@"ZoomValues"];
-                 width = NSWidth([label boundingRectWithSize:size options:0 attributes:attrs]);
-                 if (width > maxWidth) {
-                     maxWidth = width;
-                     maxIndex = cnt;
-                 }
-                 [scalePopUpButton addItemWithTitle:label];
-                 curItem = [scalePopUpButton itemAtIndex:cnt];
-                 [curItem setRepresentedObject:(SKDefaultScaleMenuFactors[cnt] > 0.0 ? [NSNumber numberWithDouble:SKDefaultScaleMenuFactors[cnt]] : nil)];
-             }
-             
-             // Make sure the popup is big enough to fit the largest cell
-             [scalePopUpButton selectItemAtIndex:maxIndex];
-             [scalePopUpButton sizeToFit];
-             [scalePopUpButton setFrameSize:NSMakeSize(NSWidth([scalePopUpButton frame]) - CONTROL_WIDTH_OFFSET, CONTROL_HEIGHT)];
-             
-             // select the appropriate item, adjusting the scaleFactor if necessary
-             if([self autoFits])
-                 [self setScaleFactor:0.0 adjustPopup:YES];
-             else
-                 [self setScaleFactor:[self scaleFactor] adjustPopup:YES];
-             
-             // hook it up
-             [scalePopUpButton setTarget:self];
-             [scalePopUpButton setAction:@selector(scalePopUpAction:)];
-             
-             // don't let it become first responder
-             [scalePopUpButton setRefusesFirstResponder:YES];
-             
-         }
-         
-         return scalePopUpButton;
-     }
-
      - (void)handlePDFViewFrameChangedNotification:(NSNotification *)notification {
          if ([self autoFits]) {
              NSView *clipView = [[self scrollView] contentView];
@@ -191,84 +162,6 @@ class KMSnapshotPDFView: CPDFView {
          if ([self autoFits] == NO)
              [self setScaleFactor:fmax([self scaleFactor], SKMinDefaultScaleMenuFactor) adjustPopup:YES];
      }
-
-     - (void)resetAutoFitRectIfNeeded {
-         if ([self autoFits]) {
-             NSView *clipView = [[self scrollView] contentView];
-             autoFitPage = [self currentPage];
-             autoFitRect = [self convertRect:[self convertRect:[clipView visibleRect] fromView:clipView] toPage:autoFitPage];
-         }
-     }
-
-     - (void)scalePopUpAction:(id)sender {
-         NSNumber *selectedFactorObject = [[sender selectedItem] representedObject];
-         if(selectedFactorObject)
-             [self setScaleFactor:[selectedFactorObject doubleValue] adjustPopup:NO];
-         else
-             [self setAutoFits:YES adjustPopup:NO];
-     }
-
-     - (void)setAutoFits:(BOOL)newAuto {
-         [self setAutoFits:newAuto adjustPopup:YES];
-     }
-
-     - (void)setAutoFits:(BOOL)newAuto adjustPopup:(BOOL)flag {
-         if (autoFits != newAuto) {
-             autoFits = newAuto;
-             if (autoFits) {
-                 [super setAutoScales:NO];
-                 [self resetAutoFitRectIfNeeded];
-                 if (flag)
-                     [scalePopUpButton selectItemAtIndex:0];
-             } else {
-                 autoFitPage = nil;
-                 autoFitRect = NSZeroRect;
-                 if (flag)
-                     [self setScaleFactor:[self scaleFactor] adjustPopup:flag];
-             }
-         }
-     }
-
-     - (NSUInteger)lowerIndexForScaleFactor:(CGFloat)scaleFactor {
-         NSUInteger i, count = SKDefaultScaleMenuFactorsCount;
-         for (i = count - 1; i > 0; i--) {
-             if (scaleFactor * 1.01 > SKDefaultScaleMenuFactors[i])
-                 return i;
-         }
-         return 1;
-     }
-
-     - (NSUInteger)upperIndexForScaleFactor:(CGFloat)scaleFactor {
-         NSUInteger i, count = SKDefaultScaleMenuFactorsCount;
-         for (i = 1; i < count; i++) {
-             if (scaleFactor * 0.99 < SKDefaultScaleMenuFactors[i])
-                 return i;
-         }
-         return count - 1;
-     }
-
-     - (NSUInteger)indexForScaleFactor:(CGFloat)scaleFactor {
-         NSUInteger lower = [self lowerIndexForScaleFactor:scaleFactor], upper = [self upperIndexForScaleFactor:scaleFactor];
-         if (upper > lower && scaleFactor < 0.5 * (SKDefaultScaleMenuFactors[lower] + SKDefaultScaleMenuFactors[upper]))
-             return lower;
-         return upper;
-     }
-
-     - (void)setScaleFactor:(CGFloat)newScaleFactor {
-         [self setScaleFactor:newScaleFactor adjustPopup:YES];
-     }
-
-     - (void)setScaleFactor:(CGFloat)newScaleFactor adjustPopup:(BOOL)flag {
-         if (flag) {
-             NSUInteger i = [self indexForScaleFactor:newScaleFactor];
-             [scalePopUpButton selectItemAtIndex:i];
-             newScaleFactor = SKDefaultScaleMenuFactors[i];
-         }
-         if ([self autoFits])
-             [self setAutoFits:NO adjustPopup:NO];
-         [super setScaleFactor:newScaleFactor];
-     }
-
      - (void)setAutoScales:(BOOL)newAuto {}
 
      - (IBAction)zoomIn:(id)sender{
@@ -316,11 +209,6 @@ class KMSnapshotPDFView: CPDFView {
              return [super canGoBack];
      }
 
-     - (void)resetHistory {
-         if ([self respondsToSelector:@selector(currentHistoryIndex)])
-             minHistoryIndex = [self currentHistoryIndex];
-     }
-
      - (void)goToPage:(PDFPage *)aPage {
          [super goToPage:aPage];
          [self resetAutoFitRectIfNeeded];
@@ -496,105 +384,217 @@ class KMSnapshotPDFView: CPDFView {
          
          return image;
      }
+     */
+    
+    func resetHistory() {
+//        if ([self respondsToSelector:@selector(currentHistoryIndex)])
+//            minHistoryIndex = [self currentHistoryIndex];
+        if self.responds(to: NSSelectorFromString("currentHistoryIndex")) {
+//            self.current
+        }
+    }
+    
+    // MARK: - Menu
+    func menuItemClick_Print(_ sender: AnyObject?) {
+//        NSImage * image = [self thumbnailWithSize:0.0];
+//
+//        PDFPage *page = [[[PDFPage alloc] initWithImage:image] autorelease];
+//
+//        PDFDocument *pdfDocument = [[[PDFDocument alloc] init] autorelease];
+//        [pdfDocument insertPage:page atIndex:0];
+//
+//        NSPrintInfo *printInfo = [NSPrintInfo sharedPrintInfo];
+//
+//        NSPrintOperation *printOperation = nil;
+//        if ([pdfDocument respondsToSelector:@selector(printOperationForPrintInfo:scalingMode:autoRotate:)]){
+//            printOperation = [pdfDocument printOperationForPrintInfo:printInfo scalingMode:kPDFPrintPageScaleNone autoRotate:YES];
+//        }
+//
+//        [printOperation runOperationModalForWindow:self.window delegate:self didRunSelector:nil contextInfo:NULL];
+    }
+    
+    func menuItemClick_ExportPDF(_ sender: NSMenuItem) {
+//        NSImage * image = [self thumbnailWithSize:0.0];
+//
+//        PDFPage *page = [[[PDFPage alloc] initWithImage:image] autorelease];
+//        PDFDocument *pdfDocument = [[[PDFDocument alloc] init] autorelease];
+//        [pdfDocument insertPage:page atIndex:0];
+//
+//        NSSavePanel *savePanel = [NSSavePanel savePanel];
+//        savePanel.allowedFileTypes = @[@"pdf"];
+//        [savePanel beginSheetModalForWindow:self.window completionHandler:^(NSInteger result) {
+//            if (result) {
+//                if ([pdfDocument writeToURL:savePanel.URL]) {
+//                    [[NSWorkspace sharedWorkspace] selectFile:savePanel.URL.path
+//                                     inFileViewerRootedAtPath:@""];
+//                }
+//            }
+//        }];
+    }
+     
+    func menuItemClick_ExportJPG(_ sender: NSMenuItem) {
+//        NSImage * image = [self thumbnailWithSize:0.0];
+//        NSData *data = image.TIFFRepresentation;
+//        NSBitmapImageRep *imageRep = [NSBitmapImageRep imageRepWithData:data];
+//        [imageRep setSize:image.size];
+//        NSData *imageData = [imageRep representationUsingType:NSJPEGFileType properties:@{}];
+//
+//        NSSavePanel *savePanel = [NSSavePanel savePanel];
+//        savePanel.allowedFileTypes = @[@"jpg"];
+//        [savePanel beginSheetModalForWindow:self.window completionHandler:^(NSInteger result) {
+//            if (result) {
+//                if ([imageData writeToURL:savePanel.URL atomically:YES]) {
+//                    [[NSWorkspace sharedWorkspace] selectFile:savePanel.URL.path
+//                                     inFileViewerRootedAtPath:@""];
+//                }
+//            }
+//        }];
+    }
+    
+    func menuItemClick_Copy(_ sender: AnyObject?) {
+//        NSPasteboardItem *pasteboardItem = [[[NSPasteboardItem alloc] init] autorelease];
+//        NSImage * image = [self thumbnailWithSize:0.0];
+//        NSData *tiffData = [image TIFFRepresentation];
+//        if (tiffData) {
+//            [pasteboardItem setData:tiffData forType:NSPasteboardTypeTIFF];
+//            if (pasteboardItem){
+//                NSPasteboard *pboard = [NSPasteboard generalPasteboard];
+//                [pboard clearContents];
+//
+//                [pboard writeObjects:[NSArray arrayWithObject:pasteboardItem]];
+//            }
+//        }
+    }
 
-     #pragma mark - Menu
-     - (void)menuItemClick_Copy:(id)sender
-     {
-         NSPasteboardItem *pasteboardItem = [[[NSPasteboardItem alloc] init] autorelease];
-         NSImage * image = [self thumbnailWithSize:0.0];
-         NSData *tiffData = [image TIFFRepresentation];
-         if (tiffData) {
-             [pasteboardItem setData:tiffData forType:NSPasteboardTypeTIFF];
-             if (pasteboardItem){
-                 NSPasteboard *pboard = [NSPasteboard generalPasteboard];
-                 [pboard clearContents];
-                 
-                 [pboard writeObjects:[NSArray arrayWithObject:pasteboardItem]];
-             }
-         }
-     }
-
-     - (void)menuItemClick_ExportPNG:(NSMenuItem *)sender
-     {
-         NSImage * image = [self thumbnailWithSize:0.0];
-         
-         NSData *data = image.TIFFRepresentation;
-         NSBitmapImageRep *imageRep = [NSBitmapImageRep imageRepWithData:data];
-         [imageRep setSize:image.size];
-         NSData *imageData = [imageRep representationUsingType:NSPNGFileType properties:@{}];
-         
-         NSSavePanel *savePanel = [NSSavePanel savePanel];
-         savePanel.allowedFileTypes = @[@"png"];
-         [savePanel beginSheetModalForWindow:self.window completionHandler:^(NSInteger result) {
-             if (result) {
-                 if ([imageData writeToURL:savePanel.URL atomically:YES]) {
-                     [[NSWorkspace sharedWorkspace] selectFile:savePanel.URL.path
-                                      inFileViewerRootedAtPath:@""];
-                 }
-             }
-         }];
-     }
-
-     - (void)menuItemClick_ExportJPG:(NSMenuItem *)sender
-     {
-         NSImage * image = [self thumbnailWithSize:0.0];
-         NSData *data = image.TIFFRepresentation;
-         NSBitmapImageRep *imageRep = [NSBitmapImageRep imageRepWithData:data];
-         [imageRep setSize:image.size];
-         NSData *imageData = [imageRep representationUsingType:NSJPEGFileType properties:@{}];
-         
-         NSSavePanel *savePanel = [NSSavePanel savePanel];
-         savePanel.allowedFileTypes = @[@"jpg"];
-         [savePanel beginSheetModalForWindow:self.window completionHandler:^(NSInteger result) {
-             if (result) {
-                 if ([imageData writeToURL:savePanel.URL atomically:YES]) {
-                     [[NSWorkspace sharedWorkspace] selectFile:savePanel.URL.path
-                                      inFileViewerRootedAtPath:@""];
-                 }
-             }
-         }];
-     }
-
-     - (void)menuItemClick_ExportPDF:(NSMenuItem *)sender
-     {
-         NSImage * image = [self thumbnailWithSize:0.0];
-         
-         PDFPage *page = [[[PDFPage alloc] initWithImage:image] autorelease];
-         PDFDocument *pdfDocument = [[[PDFDocument alloc] init] autorelease];
-         [pdfDocument insertPage:page atIndex:0];
-         
-         NSSavePanel *savePanel = [NSSavePanel savePanel];
-         savePanel.allowedFileTypes = @[@"pdf"];
-         [savePanel beginSheetModalForWindow:self.window completionHandler:^(NSInteger result) {
-             if (result) {
-                 if ([pdfDocument writeToURL:savePanel.URL]) {
-                     [[NSWorkspace sharedWorkspace] selectFile:savePanel.URL.path
-                                      inFileViewerRootedAtPath:@""];
-                 }
-             }
-         }];
-     }
-
-
-     - (void)menuItemClick_Print:(id)sender
-     {
-         NSImage * image = [self thumbnailWithSize:0.0];
-         
-         PDFPage *page = [[[PDFPage alloc] initWithImage:image] autorelease];
-         
-         PDFDocument *pdfDocument = [[[PDFDocument alloc] init] autorelease];
-         [pdfDocument insertPage:page atIndex:0];
-         
-         NSPrintInfo *printInfo = [NSPrintInfo sharedPrintInfo];
-         
-         NSPrintOperation *printOperation = nil;
-         if ([pdfDocument respondsToSelector:@selector(printOperationForPrintInfo:scalingMode:autoRotate:)]){
-             printOperation = [pdfDocument printOperationForPrintInfo:printInfo scalingMode:kPDFPrintPageScaleNone autoRotate:YES];
-         }
-         
-         [printOperation runOperationModalForWindow:self.window delegate:self didRunSelector:nil contextInfo:NULL];
-     }
+    func menuItemClick_ExportPNG(_ sender: NSMenuItem) {
+//        NSImage * image = [self thumbnailWithSize:0.0];
+//
+//        NSData *data = image.TIFFRepresentation;
+//        NSBitmapImageRep *imageRep = [NSBitmapImageRep imageRepWithData:data];
+//        [imageRep setSize:image.size];
+//        NSData *imageData = [imageRep representationUsingType:NSPNGFileType properties:@{}];
+//
+//        NSSavePanel *savePanel = [NSSavePanel savePanel];
+//        savePanel.allowedFileTypes = @[@"png"];
+//        [savePanel beginSheetModalForWindow:self.window completionHandler:^(NSInteger result) {
+//            if (result) {
+//                if ([imageData writeToURL:savePanel.URL atomically:YES]) {
+//                    [[NSWorkspace sharedWorkspace] selectFile:savePanel.URL.path
+//                                     inFileViewerRootedAtPath:@""];
+//                }
+//            }
+//        }];
+    }
+}
 
-     */
+// MARK: - Private Methods
+
+extension KMSnapshotPDFView {
+    private func _commonInitialization() {
+        self._scalePopUpButton = nil
+        self.autoFitPage = nil
+        self.autoFitRect = .zero
+        
+//        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handlePDFViewFrameChangedNotification:)
+//                                                     name:NSViewFrameDidChangeNotification object:self];
+//        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handlePDFViewFrameChangedNotification:)
+//                                                     name:NSViewBoundsDidChangeNotification object:self];
+//        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handlePDFContentViewFrameChangedNotification:)
+//                                                     name:NSViewBoundsDidChangeNotification object:[[self scrollView] contentView]];
+//        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handlePDFContentViewFrameChangedDelayedNotification:)
+//                                                     name:SKPDFContentViewChangedNotification object:self];
+//        if ([PDFView instancesRespondToSelector:@selector(magnifyWithEvent:)] == NO || [PDFView instanceMethodForSelector:@selector(magnifyWithEvent:)] == [NSView instanceMethodForSelector:@selector(magnifyWithEvent:)])
+//            [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handlePDFViewScaleChangedNotification:)
+//                                                         name:PDFViewScaleChangedNotification object:self];
+    }
+    
+    private func _setScaleFactor(_ newScaleFactor: CGFloat) {
+        self._setScaleFactor(newScaleFactor, adjustPopup: true)
+    }
+    
+    private func _setScaleFactor(_ newScaleFactor: CGFloat, adjustPopup flag: Bool) {
+        var newValue = newScaleFactor
+        if flag {
+            let i = self._index(for: newScaleFactor)
+            self.scalePopUpButton?.selectItem(at: Int(i))
+            newValue = self._SKDefaultScaleMenuFactors[Int(i)]
+        }
+        if self.autoFits {
+            self._setAutoFits(false, adjustPopup: false)
+        }
+        super.scaleFactor = newValue
+    }
+    
+    private func _lowerIndex(for scaleFactor: CGFloat) -> UInt {
+        var count = self._SKDefaultScaleMenuFactorsCount
+        for i in 0 ..< count {
+            let index = count-i
+            if (scaleFactor * 1.01 > self._SKDefaultScaleMenuFactors[index]) {
+                return UInt(index)
+            }
+        }
+        return 1
+    }
+    
+    private func _upperIndex(for scaleFactor: CGFloat) -> UInt {
+        var count = self._SKDefaultScaleMenuFactorsCount
+        for i in 1 ..< count {
+            if (scaleFactor * 0.99 < self._SKDefaultScaleMenuFactors[i]) {
+                return UInt(i)
+            }
+        }
+        return UInt(count - 1)
+    }
     
+    private func _index(for scaleFactor: CGFloat) -> UInt {
+        let lower = self._lowerIndex(for: scaleFactor)
+        let upper = self._upperIndex(for: scaleFactor)
+        if (upper > lower && scaleFactor < 0.5 * (self._SKDefaultScaleMenuFactors[Int(lower)] + self._SKDefaultScaleMenuFactors[Int(upper)])) {
+            return lower
+        }
+        return upper
+    }
+    
+    private func _setAutoFits(_ newAuto: Bool) {
+        self._setAutoFits(newAuto, adjustPopup: true)
+    }
+    
+    private func _setAutoFits(_ newAuto: Bool, adjustPopup flag: Bool) {
+        if (self.autoFits != newAuto) {
+            self.autoFits = newAuto;
+            if (self.autoFits) {
+                super.autoScales = false
+                self._resetAutoFitRectIfNeeded()
+                if (flag) {
+                    self.scalePopUpButton?.selectItem(at: 0)
+                }
+            } else {
+                self.autoFitPage = nil
+                self.autoFitRect = NSZeroRect
+                if (flag) {
+                    self._setScaleFactor(self.scaleFactor, adjustPopup: flag)
+                }
+            }
+        }
+    }
+    
+    private func _resetAutoFitRectIfNeeded() {
+        if self.autoFits {
+            let clipView = self.enclosingScrollView?.contentView
+            self.autoFitPage = self.currentPage()
+//            autoFitRect = [self convertRect:[self convertRect:[clipView visibleRect] fromView:clipView] toPage:autoFitPage];
+            let rect = self.convert(clipView?.visibleRect ?? .zero, from: clipView)
+            self.autoFitRect = self.convert(rect, to: self.autoFitPage)
+        }
+    }
+    
+    @objc private func _scalePopUpAction(_ sender: AnyObject?) {
+//        NSNumber *selectedFactorObject = [[sender selectedItem] representedObject];
+        let selectedFactorObject = self.scalePopUpButton?.selectedItem?.representedObject
+        if let data = selectedFactorObject as? NSNumber {
+            self._setScaleFactor(data.doubleValue, adjustPopup: false)
+        } else {
+            self._setAutoFits(true, adjustPopup: false)
+        }
+    }
 }

+ 12 - 9
PDF Office/PDF Master/Class/PDFTools/Snapshot/Window/KMSnapshotWindowController.swift

@@ -9,6 +9,8 @@ import Cocoa
 
 class KMSnapshotWindowController: NSWindowController {
     
+    @IBOutlet var pdfView: KMSnapshotPDFView!
+    
     var hasWindow = false
     var forceOnTop = false
     
@@ -30,7 +32,7 @@ class KMSnapshotWindowController: NSWindowController {
          BOOL animating;
      }
 
-     @property (nonatomic, retain) IBOutlet SKSnapshotPDFView *pdfView;
+     @property (nonatomic, retain)   *;
      @property (nonatomic, assign) id <SKSnapshotWindowControllerDelegate> delegate;
      @property (nonatomic, retain) NSImage *thumbnail;
      @property (nonatomic, readonly) NSUInteger pageIndex;
@@ -639,16 +641,17 @@ class KMSnapshotWindowController: NSWindowController {
     func setPdfDocument(_ pdfDocument: CPDFDocument, goToPageNumber pageNum: Int, rect: NSRect, scaleFactor factor: CGFloat, autoFits: Bool) {
         let window = self.window
         
-//        [pdfView setScaleFactor:factor];
-//        [pdfView setAutoScales:NO];
-//        [pdfView setDisplaysPageBreaks:NO];
-//        [pdfView setDisplayBox:kPDFDisplayBoxCropBox];
-//        [pdfView setShouldAntiAlias:[[NSUserDefaults standardUserDefaults] floatForKey:SKShouldAntiAliasKey]];
-//        [pdfView setGreekingThreshold:[[NSUserDefaults standardUserDefaults] floatForKey:SKGreekingThresholdKey]];
-//        [pdfView setBackgroundColor:[[NSUserDefaults standardUserDefaults] colorForKey:SKBackgroundColorKey]];
+        self.pdfView.scaleFactor = factor
+        self.pdfView.autoScales = false
+        self.pdfView.displaysPageBreaks = false
+        self.pdfView.displayBox = .cropBox
+//        [pdfView setShouldAntiAlias:[[NSUserDefaults standardUserDefaults] floatForKey:]];
+        self.pdfView.setShouldAntiAlias(UserDefaults.standard.bool(forKey: SKShouldAntiAliasKey))
+        self.pdfView.setGreekingThreshold(UserDefaults.standard.float(forKey: SKGreekingThresholdKey).cgFloat)
+        self.pdfView.backgroundColor = UserDefaults.standard.color(forKey: SKBackgroundColorKey)
 //        [pdfView applyDefaultPageBackgroundColor];
 //        [pdfView applyDefaultInterpolationQuality];
-//        [pdfView setDocument:pdfDocument];
+        self.pdfView.document = pdfDocument
         
 //        [self setWindowFrameAutosaveNameOrCascade:SKSnapshotWindowFrameAutosaveName];
         

File diff suppressed because it is too large
+ 39 - 1060
PDF Office/PDF Master/Class/PDFTools/Snapshot/Window/SnapshotWindow.xib