123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595 |
- //
- // KMSnapshotPDFView.swift
- // PDF Master
- //
- // Created by tangchao on 2023/12/12.
- //
- import Cocoa
- class KMSnapshotPDFView: CPDFView {
-
- private var _scalePopUpButton: NSPopUpButton?
- var scalePopUpButton: NSPopUpButton? {
- get {
- if (self._scalePopUpButton == nil) {
-
- let scrollView = self.enclosingScrollView
- scrollView?.hasHorizontalScroller = true
-
- // create it
- 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 {
- label = Bundle.main.localizedString(forKey: self._SKDefaultScaleMenuLabels[i], value: "", table: "ZoomValues")
- 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(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)
- // Drawing code here.
- }
-
-
- /*
- #define SKPDFContentViewChangedNotification @"SKPDFContentViewChangedNotification"
- - (void)handlePDFViewFrameChangedNotification:(NSNotification *)notification {
- if ([self autoFits]) {
- NSView *clipView = [[self scrollView] contentView];
- NSRect clipRect = [self convertRect:[clipView visibleRect] fromView:clipView];
- NSRect rect = [self convertRect:autoFitRect fromPage:autoFitPage];
- CGFloat factor = fmin(NSWidth(clipRect) / NSWidth(rect), NSHeight(clipRect) / NSHeight(rect));
- rect = [self convertRect:NSInsetRect(rect, 0.5 * (NSWidth(rect) - NSWidth(clipRect) / factor), 0.5 * (NSHeight(rect) - NSHeight(clipRect) / factor)) toPage:autoFitPage];
- [super setScaleFactor:factor * [self scaleFactor]];
- [self goToRect:rect onPage:autoFitPage];
- }
- }
- - (void)handlePDFContentViewFrameChangedDelayedNotification:(NSNotification *)notification {
- if ([self inLiveResize] == NO && [[self window] isZoomed] == NO)
- [self resetAutoFitRectIfNeeded];
- }
- - (void)handlePDFContentViewFrameChangedNotification:(NSNotification *)notification {
- if ([self inLiveResize] == NO && [[self window] isZoomed] == NO) {
- NSNotification *note = [NSNotification notificationWithName:SKPDFContentViewChangedNotification object:self];
- [[NSNotificationQueue defaultQueue] enqueueNotification:note postingStyle:NSPostWhenIdle coalesceMask:NSNotificationCoalescingOnName forModes:nil];
- }
- }
- - (void)handlePDFViewScaleChangedNotification:(NSNotification *)notification {
- if ([self autoFits] == NO)
- [self setScaleFactor:fmax([self scaleFactor], SKMinDefaultScaleMenuFactor) adjustPopup:YES];
- }
- - (void)setAutoScales:(BOOL)newAuto {}
- - (IBAction)zoomIn:(id)sender{
- if([self autoFits]){
- [super zoomIn:sender];
- [self setAutoFits:NO adjustPopup:YES];
- }else{
- NSUInteger numberOfDefaultItems = SKDefaultScaleMenuFactorsCount;
- NSUInteger i = [self lowerIndexForScaleFactor:[self scaleFactor]];
- if (i < numberOfDefaultItems - 1) i++;
- [self setScaleFactor:SKDefaultScaleMenuFactors[i]];
- }
- }
- - (IBAction)zoomOut:(id)sender{
- if([self autoFits]){
- [super zoomOut:sender];
- [self setAutoFits:NO adjustPopup:YES];
- }else{
- NSUInteger i = [self upperIndexForScaleFactor:[self scaleFactor]];
- if (i > 1) i--;
- [self setScaleFactor:SKDefaultScaleMenuFactors[i]];
- }
- }
- - (BOOL)canZoomIn{
- if ([super canZoomIn] == NO)
- return NO;
- NSUInteger numberOfDefaultItems = SKDefaultScaleMenuFactorsCount;
- NSUInteger i = [self lowerIndexForScaleFactor:[self scaleFactor]];
- return i < numberOfDefaultItems - 1;
- }
- - (BOOL)canZoomOut{
- if ([super canZoomOut] == NO)
- return NO;
- NSUInteger i = [self upperIndexForScaleFactor:[self scaleFactor]];
- return i > 1;
- }
- - (BOOL)canGoBack {
- if ([self respondsToSelector:@selector(currentHistoryIndex)] && minHistoryIndex > 0)
- return minHistoryIndex < [self currentHistoryIndex];
- else
- return [super canGoBack];
- }
- - (void)goToPage:(PDFPage *)aPage {
- [super goToPage:aPage];
- [self resetAutoFitRectIfNeeded];
- }
- - (void)doAutoFit:(id)sender {
- [self setAutoFits:YES];
- }
- - (void)doActualSize:(id)sender {
- [self setScaleFactor:1.0];
- }
- - (void)doPhysicalSize:(id)sender {
- [self setPhysicalScaleFactor:1.0];
- }
- // we don't want to steal the printDocument: action from the responder chain
- - (void)printDocument:(id)sender{}
- - (BOOL)respondsToSelector:(SEL)aSelector {
- return aSelector != @selector(printDocument:) && [super respondsToSelector:aSelector];
- }
- - (NSMenu *)menuForEvent:(NSEvent *)theEvent {
- static NSSet *selectionActions = nil;
- if (selectionActions == nil)
- selectionActions = [[NSSet alloc] initWithObjects:@"copy:", @"_searchInSpotlight:", @"_searchInGoogle:", @"_searchInDictionary:", @"_revealSelection:", nil];
- NSMenu *menu = [super menuForEvent:theEvent];
-
- [menu insertItem:[NSMenuItem separatorItem] atIndex:0];
- [menu insertItemWithTitle:NSLocalizedString(@"Print", @"Menu item title") action:@selector(menuItemClick_Print:) target:self atIndex:0];
-
- NSMenuItem * item = [menu insertItemWithTitle:NSLocalizedString(@"Export", @"Menu item title") action:nil target:self atIndex:0];
- NSMenu *subMenu = [NSMenu menu];
-
- [subMenu addItemWithTitle:NSLocalizedString(@"PNG", @"Menu item title") action:@selector(menuItemClick_ExportPNG:) target:self];
- [subMenu addItemWithTitle:NSLocalizedString(@"JPG", @"Menu item title") action:@selector(menuItemClick_ExportJPG:) target:self];
- [subMenu addItemWithTitle:NSLocalizedString(@"PDF", @"Menu item title") action:@selector(menuItemClick_ExportPDF:) target:self];
- item.submenu = subMenu;
- [menu insertItem:[NSMenuItem separatorItem] atIndex:0];
- [menu insertItemWithTitle:NSLocalizedString(@"Copy", @"Menu item title") action:@selector(menuItemClick_Copy:) target:self atIndex:0];
-
- [self setCurrentSelection:RUNNING_AFTER(10_11) ? [[[PDFSelection alloc] initWithDocument:[self document]] autorelease] : nil];
- while ([menu numberOfItems]) {
- NSMenuItem *item = [menu itemAtIndex:0];
- if ([item isSeparatorItem] || [self validateMenuItem:item] == NO || [selectionActions containsObject:NSStringFromSelector([item action])])
- [menu removeItemAtIndex:0];
- else
- break;
- }
-
- NSInteger i = [menu indexOfItemWithTarget:self andAction:NSSelectorFromString(@"_setAutoSize:")];
- if (i != -1)
- [[menu itemAtIndex:i] setAction:@selector(doAutoFit:)];
- i = [menu indexOfItemWithTarget:self andAction:NSSelectorFromString(@"_setActualSize:")];
- if (i != -1) {
- [[menu itemAtIndex:i] setAction:@selector(doActualSize:)];
- NSMenuItem *item = [menu insertItemWithTitle:NSLocalizedString(@"Physical Size", @"Menu item title") action:@selector(doPhysicalSize:) target:self atIndex:i + 1];
- [item setKeyEquivalentModifierMask:NSAlternateKeyMask];
- [item setAlternate:YES];
- }
-
- return menu;
- }
- - (BOOL)validateMenuItem:(NSMenuItem *)menuItem {
- if ([menuItem action] == @selector(doAutoFit:)) {
- [menuItem setState:[self autoFits] ? NSOnState : NSOffState];
- return YES;
- } else if ([menuItem action] == @selector(doActualSize:)) {
- [menuItem setState:fabs([self scaleFactor] - 1.0) < 0.1 ? NSOnState : NSOffState];
- return YES;
- } else if ([menuItem action] == @selector(doPhysicalSize:)) {
- [menuItem setState:([self autoScales] || fabs([self physicalScaleFactor] - 1.0 ) > 0.01) ? NSOffState : NSOnState];
- return YES;
- } else if ([[SKSnapshotPDFView superclass] instancesRespondToSelector:_cmd]) {
- return [super validateMenuItem:menuItem];
- }
- return YES;
- }
- #pragma mark Gestures
- - (void)beginGestureWithEvent:(NSEvent *)theEvent {
- if ([[SKSnapshotPDFView superclass] instancesRespondToSelector:_cmd])
- [super beginGestureWithEvent:theEvent];
- startScale = [self scaleFactor];
- }
- - (void)endGestureWithEvent:(NSEvent *)theEvent {
- if (fabs(startScale - [self scaleFactor]) > 0.001)
- [self setScaleFactor:fmax([self scaleFactor], SKMinDefaultScaleMenuFactor) adjustPopup:YES];
- if ([[SKSnapshotPDFView superclass] instancesRespondToSelector:_cmd])
- [super endGestureWithEvent:theEvent];
- }
- - (void)magnifyWithEvent:(NSEvent *)theEvent {
- if ([[NSUserDefaults standardUserDefaults] boolForKey:SKDisablePinchZoomKey] == NO && [theEvent respondsToSelector:@selector(magnification)]) {
- if ([theEvent respondsToSelector:@selector(phase)] && [theEvent phase] == NSEventPhaseBegan)
- startScale = [self scaleFactor];
- CGFloat magnifyFactor = (1.0 + fmax(-0.5, fmin(1.0 , [theEvent magnification])));
- [super setScaleFactor:magnifyFactor * [self scaleFactor]];
- if ([theEvent respondsToSelector:@selector(phase)] && ([theEvent phase] == NSEventPhaseEnded || [theEvent phase] == NSEventPhaseCancelled) && fabs(startScale - [self scaleFactor]) > 0.001)
- [self setScaleFactor:fmax([self scaleFactor], SKMinDefaultScaleMenuFactor) adjustPopup:YES];
- }
- }
- #pragma mark Dragging
- - (void)mouseDown:(NSEvent *)theEvent{
- [[self window] makeFirstResponder:self];
-
- if ([theEvent standardModifierFlags] == (NSCommandKeyMask | NSShiftKeyMask)) {
-
- [self doPdfsyncWithEvent:theEvent];
-
- } else {
-
- [self doDragWithEvent:theEvent];
-
- }
- }
- - (void)setCursorForAreaOfInterest:(PDFAreaOfInterest)area {
- if ([NSEvent standardModifierFlags] == (NSCommandKeyMask | NSShiftKeyMask))
- [[NSCursor arrowCursor] set];
- else
- [[NSCursor openHandCursor] set];
- }
- - (NSImage *)thumbnailWithSize:(CGFloat)size {
- NSView *clipView = [[[self documentView] enclosingScrollView] contentView];
- NSRect bounds = [self convertRect:[clipView bounds] fromView:clipView];
- NSBitmapImageRep *imageRep = [self bitmapImageRepForCachingDisplayInRect:bounds];
- NSAffineTransform *transform = nil;
- NSSize thumbnailSize = thumbnailSize = bounds.size;
- CGFloat shadowBlurRadius = 0.0;
- CGFloat shadowOffset = 0.0;
- NSImage *image;
-
- [self cacheDisplayInRect:bounds toBitmapImageRep:imageRep];
-
- bounds.origin = NSZeroPoint;
-
- if (size > 0.0) {
- shadowBlurRadius = round(size / 32.0);
- shadowOffset = -ceil(shadowBlurRadius * 0.75);
- if (NSHeight(bounds) > NSWidth(bounds))
- thumbnailSize = NSMakeSize(round((size - 2.0 * shadowBlurRadius) * NSWidth(bounds) / NSHeight(bounds) + 2.0 * shadowBlurRadius), size);
- else
- thumbnailSize = NSMakeSize(size, round((size - 2.0 * shadowBlurRadius) * NSHeight(bounds) / NSWidth(bounds) + 2.0 * shadowBlurRadius));
- transform = [NSAffineTransform transform];
- [transform translateXBy:shadowBlurRadius yBy:shadowBlurRadius - shadowOffset];
- [transform scaleXBy:(thumbnailSize.width - 2.0 * shadowBlurRadius) / NSWidth(bounds) yBy:(thumbnailSize.height - 2.0 * shadowBlurRadius) / NSHeight(bounds)];
- }
-
- image = [[[NSImage alloc] initWithSize:thumbnailSize] autorelease];
-
- [image lockFocus];
- [[NSGraphicsContext currentContext] setImageInterpolation:NSImageInterpolationHigh];
- [transform concat];
- [NSGraphicsContext saveGraphicsState];
- [[PDFView defaultPageBackgroundColor] set];
- if (shadowBlurRadius > 0.0)
- [NSShadow setShadowWithColor:[NSColor colorWithCalibratedWhite:0.0 alpha:0.5] blurRadius:shadowBlurRadius yOffset:shadowOffset];
- NSRectFill(bounds);
- [[NSGraphicsContext currentContext] setImageInterpolation:NSImageInterpolationDefault];
- [NSGraphicsContext restoreGraphicsState];
- [imageRep drawInRect:bounds];
- [image unlockFocus];
-
- 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]];
- // }
- // }
- }
- 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-1
- 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)
- }
- }
- }
|