KMSnapshotPDFView.swift 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595
  1. //
  2. // KMSnapshotPDFView.swift
  3. // PDF Master
  4. //
  5. // Created by tangchao on 2023/12/12.
  6. //
  7. import Cocoa
  8. class KMSnapshotPDFView: CPDFView {
  9. private var _scalePopUpButton: NSPopUpButton?
  10. var scalePopUpButton: NSPopUpButton? {
  11. get {
  12. if (self._scalePopUpButton == nil) {
  13. let scrollView = self.enclosingScrollView
  14. scrollView?.hasHorizontalScroller = true
  15. // create it
  16. let scalePopUpButton_ = NSPopUpButton(frame: NSMakeRect(0.0, 0.0, 1.0, 1.0), pullsDown: false)
  17. scalePopUpButton_.cell?.controlSize = .small
  18. self._scalePopUpButton = scalePopUpButton_
  19. scalePopUpButton_.isBordered = false
  20. scalePopUpButton_.isEnabled = true
  21. scalePopUpButton_.refusesFirstResponder = true
  22. (scalePopUpButton_.cell as? NSPopUpButtonCell)?.usesItemFromMenu = true
  23. // set a suitable font, the control size is 0, 1 or 2
  24. scalePopUpButton_.font = .toolTipsFont(ofSize: CONTROL_FONT_SIZE)
  25. var cnt = 0
  26. var numberOfDefaultItems = self._SKDefaultScaleMenuFactorsCount
  27. var curItem: AnyObject?
  28. var label = ""
  29. var width: CGFloat = 0.0
  30. var maxWidth: CGFloat = 0.0
  31. let size = NSMakeSize(1000.0, 1000.0)
  32. let attrs = [NSAttributedString.Key.font : scalePopUpButton_.font ?? .systemFont(ofSize: 13)]
  33. var maxIndex = 0
  34. // fill it
  35. for i in 0 ..< numberOfDefaultItems {
  36. label = Bundle.main.localizedString(forKey: self._SKDefaultScaleMenuLabels[i], value: "", table: "ZoomValues")
  37. width = NSWidth(label.boundingRect(with: size, options: NSString.DrawingOptions(rawValue: 0), attributes: attrs))
  38. if (width > maxWidth) {
  39. maxWidth = width
  40. maxIndex = i
  41. }
  42. scalePopUpButton_.addItem(withTitle: label)
  43. curItem = scalePopUpButton_.item(at: i)
  44. // [curItem setRepresentedObject:(SKDefaultScaleMenuFactors[cnt] > 0.0 ? [NSNumber numberWithDouble:SKDefaultScaleMenuFactors[cnt]] : nil)];
  45. let fac = self._SKDefaultScaleMenuFactors[i]
  46. if fac > 0.0 {
  47. (curItem as? NSMenuItem)?.representedObject = NSNumber(value: fac)
  48. } else {
  49. (curItem as? NSMenuItem)?.representedObject = nil
  50. }
  51. }
  52. // Make sure the popup is big enough to fit the largest cell
  53. scalePopUpButton_.selectItem(at: maxIndex)
  54. scalePopUpButton_.sizeToFit()
  55. scalePopUpButton_.setFrameSize(NSMakeSize(NSWidth(scalePopUpButton_.frame) - CONTROL_WIDTH_OFFSET, CONTROL_HEIGHT))
  56. //
  57. // // select the appropriate item, adjusting the scaleFactor if necessary
  58. if self.autoFits {
  59. self._setScaleFactor(0, adjustPopup: true)
  60. } else {
  61. self._setScaleFactor(self.scaleFactor, adjustPopup: true)
  62. }
  63. //
  64. // // hook it up
  65. scalePopUpButton_.target = self
  66. scalePopUpButton_.action = #selector(_scalePopUpAction)
  67. //
  68. // // don't let it become first responder
  69. scalePopUpButton_.refusesFirstResponder = true
  70. }
  71. return _scalePopUpButton
  72. }
  73. }
  74. var autoFitPage: CPDFPage?
  75. var autoFitRect: NSRect = .zero
  76. var autoFits = false
  77. var startScale: CGFloat = 0
  78. var minHistoryIndex = 0
  79. private let CONTROL_FONT_SIZE = 10.0
  80. private let CONTROL_HEIGHT = 15.0
  81. private let CONTROL_WIDTH_OFFSET = 20.0
  82. 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%"]
  83. 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]
  84. private let _SKMinDefaultScaleMenuFactor = 0.1
  85. private let _SKDefaultScaleMenuFactorsCount = 23
  86. deinit {
  87. KMPrint("KMSnapshotPDFView deinit.")
  88. NotificationCenter.default.removeObserver(self)
  89. }
  90. override init(frame frameRect: NSRect) {
  91. super.init(frame: frameRect)
  92. self._commonInitialization()
  93. }
  94. required init?(coder: NSCoder) {
  95. super.init(coder: coder)
  96. self._commonInitialization()
  97. }
  98. override func draw(_ dirtyRect: NSRect) {
  99. super.draw(dirtyRect)
  100. // Drawing code here.
  101. }
  102. /*
  103. #define SKPDFContentViewChangedNotification @"SKPDFContentViewChangedNotification"
  104. - (void)handlePDFViewFrameChangedNotification:(NSNotification *)notification {
  105. if ([self autoFits]) {
  106. NSView *clipView = [[self scrollView] contentView];
  107. NSRect clipRect = [self convertRect:[clipView visibleRect] fromView:clipView];
  108. NSRect rect = [self convertRect:autoFitRect fromPage:autoFitPage];
  109. CGFloat factor = fmin(NSWidth(clipRect) / NSWidth(rect), NSHeight(clipRect) / NSHeight(rect));
  110. rect = [self convertRect:NSInsetRect(rect, 0.5 * (NSWidth(rect) - NSWidth(clipRect) / factor), 0.5 * (NSHeight(rect) - NSHeight(clipRect) / factor)) toPage:autoFitPage];
  111. [super setScaleFactor:factor * [self scaleFactor]];
  112. [self goToRect:rect onPage:autoFitPage];
  113. }
  114. }
  115. - (void)handlePDFContentViewFrameChangedDelayedNotification:(NSNotification *)notification {
  116. if ([self inLiveResize] == NO && [[self window] isZoomed] == NO)
  117. [self resetAutoFitRectIfNeeded];
  118. }
  119. - (void)handlePDFContentViewFrameChangedNotification:(NSNotification *)notification {
  120. if ([self inLiveResize] == NO && [[self window] isZoomed] == NO) {
  121. NSNotification *note = [NSNotification notificationWithName:SKPDFContentViewChangedNotification object:self];
  122. [[NSNotificationQueue defaultQueue] enqueueNotification:note postingStyle:NSPostWhenIdle coalesceMask:NSNotificationCoalescingOnName forModes:nil];
  123. }
  124. }
  125. - (void)handlePDFViewScaleChangedNotification:(NSNotification *)notification {
  126. if ([self autoFits] == NO)
  127. [self setScaleFactor:fmax([self scaleFactor], SKMinDefaultScaleMenuFactor) adjustPopup:YES];
  128. }
  129. - (void)setAutoScales:(BOOL)newAuto {}
  130. - (IBAction)zoomIn:(id)sender{
  131. if([self autoFits]){
  132. [super zoomIn:sender];
  133. [self setAutoFits:NO adjustPopup:YES];
  134. }else{
  135. NSUInteger numberOfDefaultItems = SKDefaultScaleMenuFactorsCount;
  136. NSUInteger i = [self lowerIndexForScaleFactor:[self scaleFactor]];
  137. if (i < numberOfDefaultItems - 1) i++;
  138. [self setScaleFactor:SKDefaultScaleMenuFactors[i]];
  139. }
  140. }
  141. - (IBAction)zoomOut:(id)sender{
  142. if([self autoFits]){
  143. [super zoomOut:sender];
  144. [self setAutoFits:NO adjustPopup:YES];
  145. }else{
  146. NSUInteger i = [self upperIndexForScaleFactor:[self scaleFactor]];
  147. if (i > 1) i--;
  148. [self setScaleFactor:SKDefaultScaleMenuFactors[i]];
  149. }
  150. }
  151. - (BOOL)canZoomIn{
  152. if ([super canZoomIn] == NO)
  153. return NO;
  154. NSUInteger numberOfDefaultItems = SKDefaultScaleMenuFactorsCount;
  155. NSUInteger i = [self lowerIndexForScaleFactor:[self scaleFactor]];
  156. return i < numberOfDefaultItems - 1;
  157. }
  158. - (BOOL)canZoomOut{
  159. if ([super canZoomOut] == NO)
  160. return NO;
  161. NSUInteger i = [self upperIndexForScaleFactor:[self scaleFactor]];
  162. return i > 1;
  163. }
  164. - (BOOL)canGoBack {
  165. if ([self respondsToSelector:@selector(currentHistoryIndex)] && minHistoryIndex > 0)
  166. return minHistoryIndex < [self currentHistoryIndex];
  167. else
  168. return [super canGoBack];
  169. }
  170. - (void)goToPage:(PDFPage *)aPage {
  171. [super goToPage:aPage];
  172. [self resetAutoFitRectIfNeeded];
  173. }
  174. - (void)doAutoFit:(id)sender {
  175. [self setAutoFits:YES];
  176. }
  177. - (void)doActualSize:(id)sender {
  178. [self setScaleFactor:1.0];
  179. }
  180. - (void)doPhysicalSize:(id)sender {
  181. [self setPhysicalScaleFactor:1.0];
  182. }
  183. // we don't want to steal the printDocument: action from the responder chain
  184. - (void)printDocument:(id)sender{}
  185. - (BOOL)respondsToSelector:(SEL)aSelector {
  186. return aSelector != @selector(printDocument:) && [super respondsToSelector:aSelector];
  187. }
  188. - (NSMenu *)menuForEvent:(NSEvent *)theEvent {
  189. static NSSet *selectionActions = nil;
  190. if (selectionActions == nil)
  191. selectionActions = [[NSSet alloc] initWithObjects:@"copy:", @"_searchInSpotlight:", @"_searchInGoogle:", @"_searchInDictionary:", @"_revealSelection:", nil];
  192. NSMenu *menu = [super menuForEvent:theEvent];
  193. [menu insertItem:[NSMenuItem separatorItem] atIndex:0];
  194. [menu insertItemWithTitle:NSLocalizedString(@"Print", @"Menu item title") action:@selector(menuItemClick_Print:) target:self atIndex:0];
  195. NSMenuItem * item = [menu insertItemWithTitle:NSLocalizedString(@"Export", @"Menu item title") action:nil target:self atIndex:0];
  196. NSMenu *subMenu = [NSMenu menu];
  197. [subMenu addItemWithTitle:NSLocalizedString(@"PNG", @"Menu item title") action:@selector(menuItemClick_ExportPNG:) target:self];
  198. [subMenu addItemWithTitle:NSLocalizedString(@"JPG", @"Menu item title") action:@selector(menuItemClick_ExportJPG:) target:self];
  199. [subMenu addItemWithTitle:NSLocalizedString(@"PDF", @"Menu item title") action:@selector(menuItemClick_ExportPDF:) target:self];
  200. item.submenu = subMenu;
  201. [menu insertItem:[NSMenuItem separatorItem] atIndex:0];
  202. [menu insertItemWithTitle:NSLocalizedString(@"Copy", @"Menu item title") action:@selector(menuItemClick_Copy:) target:self atIndex:0];
  203. [self setCurrentSelection:RUNNING_AFTER(10_11) ? [[[PDFSelection alloc] initWithDocument:[self document]] autorelease] : nil];
  204. while ([menu numberOfItems]) {
  205. NSMenuItem *item = [menu itemAtIndex:0];
  206. if ([item isSeparatorItem] || [self validateMenuItem:item] == NO || [selectionActions containsObject:NSStringFromSelector([item action])])
  207. [menu removeItemAtIndex:0];
  208. else
  209. break;
  210. }
  211. NSInteger i = [menu indexOfItemWithTarget:self andAction:NSSelectorFromString(@"_setAutoSize:")];
  212. if (i != -1)
  213. [[menu itemAtIndex:i] setAction:@selector(doAutoFit:)];
  214. i = [menu indexOfItemWithTarget:self andAction:NSSelectorFromString(@"_setActualSize:")];
  215. if (i != -1) {
  216. [[menu itemAtIndex:i] setAction:@selector(doActualSize:)];
  217. NSMenuItem *item = [menu insertItemWithTitle:NSLocalizedString(@"Physical Size", @"Menu item title") action:@selector(doPhysicalSize:) target:self atIndex:i + 1];
  218. [item setKeyEquivalentModifierMask:NSAlternateKeyMask];
  219. [item setAlternate:YES];
  220. }
  221. return menu;
  222. }
  223. - (BOOL)validateMenuItem:(NSMenuItem *)menuItem {
  224. if ([menuItem action] == @selector(doAutoFit:)) {
  225. [menuItem setState:[self autoFits] ? NSOnState : NSOffState];
  226. return YES;
  227. } else if ([menuItem action] == @selector(doActualSize:)) {
  228. [menuItem setState:fabs([self scaleFactor] - 1.0) < 0.1 ? NSOnState : NSOffState];
  229. return YES;
  230. } else if ([menuItem action] == @selector(doPhysicalSize:)) {
  231. [menuItem setState:([self autoScales] || fabs([self physicalScaleFactor] - 1.0 ) > 0.01) ? NSOffState : NSOnState];
  232. return YES;
  233. } else if ([[SKSnapshotPDFView superclass] instancesRespondToSelector:_cmd]) {
  234. return [super validateMenuItem:menuItem];
  235. }
  236. return YES;
  237. }
  238. #pragma mark Gestures
  239. - (void)beginGestureWithEvent:(NSEvent *)theEvent {
  240. if ([[SKSnapshotPDFView superclass] instancesRespondToSelector:_cmd])
  241. [super beginGestureWithEvent:theEvent];
  242. startScale = [self scaleFactor];
  243. }
  244. - (void)endGestureWithEvent:(NSEvent *)theEvent {
  245. if (fabs(startScale - [self scaleFactor]) > 0.001)
  246. [self setScaleFactor:fmax([self scaleFactor], SKMinDefaultScaleMenuFactor) adjustPopup:YES];
  247. if ([[SKSnapshotPDFView superclass] instancesRespondToSelector:_cmd])
  248. [super endGestureWithEvent:theEvent];
  249. }
  250. - (void)magnifyWithEvent:(NSEvent *)theEvent {
  251. if ([[NSUserDefaults standardUserDefaults] boolForKey:SKDisablePinchZoomKey] == NO && [theEvent respondsToSelector:@selector(magnification)]) {
  252. if ([theEvent respondsToSelector:@selector(phase)] && [theEvent phase] == NSEventPhaseBegan)
  253. startScale = [self scaleFactor];
  254. CGFloat magnifyFactor = (1.0 + fmax(-0.5, fmin(1.0 , [theEvent magnification])));
  255. [super setScaleFactor:magnifyFactor * [self scaleFactor]];
  256. if ([theEvent respondsToSelector:@selector(phase)] && ([theEvent phase] == NSEventPhaseEnded || [theEvent phase] == NSEventPhaseCancelled) && fabs(startScale - [self scaleFactor]) > 0.001)
  257. [self setScaleFactor:fmax([self scaleFactor], SKMinDefaultScaleMenuFactor) adjustPopup:YES];
  258. }
  259. }
  260. #pragma mark Dragging
  261. - (void)mouseDown:(NSEvent *)theEvent{
  262. [[self window] makeFirstResponder:self];
  263. if ([theEvent standardModifierFlags] == (NSCommandKeyMask | NSShiftKeyMask)) {
  264. [self doPdfsyncWithEvent:theEvent];
  265. } else {
  266. [self doDragWithEvent:theEvent];
  267. }
  268. }
  269. - (void)setCursorForAreaOfInterest:(PDFAreaOfInterest)area {
  270. if ([NSEvent standardModifierFlags] == (NSCommandKeyMask | NSShiftKeyMask))
  271. [[NSCursor arrowCursor] set];
  272. else
  273. [[NSCursor openHandCursor] set];
  274. }
  275. - (NSImage *)thumbnailWithSize:(CGFloat)size {
  276. NSView *clipView = [[[self documentView] enclosingScrollView] contentView];
  277. NSRect bounds = [self convertRect:[clipView bounds] fromView:clipView];
  278. NSBitmapImageRep *imageRep = [self bitmapImageRepForCachingDisplayInRect:bounds];
  279. NSAffineTransform *transform = nil;
  280. NSSize thumbnailSize = thumbnailSize = bounds.size;
  281. CGFloat shadowBlurRadius = 0.0;
  282. CGFloat shadowOffset = 0.0;
  283. NSImage *image;
  284. [self cacheDisplayInRect:bounds toBitmapImageRep:imageRep];
  285. bounds.origin = NSZeroPoint;
  286. if (size > 0.0) {
  287. shadowBlurRadius = round(size / 32.0);
  288. shadowOffset = -ceil(shadowBlurRadius * 0.75);
  289. if (NSHeight(bounds) > NSWidth(bounds))
  290. thumbnailSize = NSMakeSize(round((size - 2.0 * shadowBlurRadius) * NSWidth(bounds) / NSHeight(bounds) + 2.0 * shadowBlurRadius), size);
  291. else
  292. thumbnailSize = NSMakeSize(size, round((size - 2.0 * shadowBlurRadius) * NSHeight(bounds) / NSWidth(bounds) + 2.0 * shadowBlurRadius));
  293. transform = [NSAffineTransform transform];
  294. [transform translateXBy:shadowBlurRadius yBy:shadowBlurRadius - shadowOffset];
  295. [transform scaleXBy:(thumbnailSize.width - 2.0 * shadowBlurRadius) / NSWidth(bounds) yBy:(thumbnailSize.height - 2.0 * shadowBlurRadius) / NSHeight(bounds)];
  296. }
  297. image = [[[NSImage alloc] initWithSize:thumbnailSize] autorelease];
  298. [image lockFocus];
  299. [[NSGraphicsContext currentContext] setImageInterpolation:NSImageInterpolationHigh];
  300. [transform concat];
  301. [NSGraphicsContext saveGraphicsState];
  302. [[PDFView defaultPageBackgroundColor] set];
  303. if (shadowBlurRadius > 0.0)
  304. [NSShadow setShadowWithColor:[NSColor colorWithCalibratedWhite:0.0 alpha:0.5] blurRadius:shadowBlurRadius yOffset:shadowOffset];
  305. NSRectFill(bounds);
  306. [[NSGraphicsContext currentContext] setImageInterpolation:NSImageInterpolationDefault];
  307. [NSGraphicsContext restoreGraphicsState];
  308. [imageRep drawInRect:bounds];
  309. [image unlockFocus];
  310. return image;
  311. }
  312. */
  313. func resetHistory() {
  314. // if ([self respondsToSelector:@selector(currentHistoryIndex)])
  315. // minHistoryIndex = [self currentHistoryIndex];
  316. if self.responds(to: NSSelectorFromString("currentHistoryIndex")) {
  317. // self.current
  318. }
  319. }
  320. // MARK: - Menu
  321. func menuItemClick_Print(_ sender: AnyObject?) {
  322. // NSImage * image = [self thumbnailWithSize:0.0];
  323. //
  324. // PDFPage *page = [[[PDFPage alloc] initWithImage:image] autorelease];
  325. //
  326. // PDFDocument *pdfDocument = [[[PDFDocument alloc] init] autorelease];
  327. // [pdfDocument insertPage:page atIndex:0];
  328. //
  329. // NSPrintInfo *printInfo = [NSPrintInfo sharedPrintInfo];
  330. //
  331. // NSPrintOperation *printOperation = nil;
  332. // if ([pdfDocument respondsToSelector:@selector(printOperationForPrintInfo:scalingMode:autoRotate:)]){
  333. // printOperation = [pdfDocument printOperationForPrintInfo:printInfo scalingMode:kPDFPrintPageScaleNone autoRotate:YES];
  334. // }
  335. //
  336. // [printOperation runOperationModalForWindow:self.window delegate:self didRunSelector:nil contextInfo:NULL];
  337. }
  338. func menuItemClick_ExportPDF(_ sender: NSMenuItem) {
  339. // NSImage * image = [self thumbnailWithSize:0.0];
  340. //
  341. // PDFPage *page = [[[PDFPage alloc] initWithImage:image] autorelease];
  342. // PDFDocument *pdfDocument = [[[PDFDocument alloc] init] autorelease];
  343. // [pdfDocument insertPage:page atIndex:0];
  344. //
  345. // NSSavePanel *savePanel = [NSSavePanel savePanel];
  346. // savePanel.allowedFileTypes = @[@"pdf"];
  347. // [savePanel beginSheetModalForWindow:self.window completionHandler:^(NSInteger result) {
  348. // if (result) {
  349. // if ([pdfDocument writeToURL:savePanel.URL]) {
  350. // [[NSWorkspace sharedWorkspace] selectFile:savePanel.URL.path
  351. // inFileViewerRootedAtPath:@""];
  352. // }
  353. // }
  354. // }];
  355. }
  356. func menuItemClick_ExportJPG(_ sender: NSMenuItem) {
  357. // NSImage * image = [self thumbnailWithSize:0.0];
  358. // NSData *data = image.TIFFRepresentation;
  359. // NSBitmapImageRep *imageRep = [NSBitmapImageRep imageRepWithData:data];
  360. // [imageRep setSize:image.size];
  361. // NSData *imageData = [imageRep representationUsingType:NSJPEGFileType properties:@{}];
  362. //
  363. // NSSavePanel *savePanel = [NSSavePanel savePanel];
  364. // savePanel.allowedFileTypes = @[@"jpg"];
  365. // [savePanel beginSheetModalForWindow:self.window completionHandler:^(NSInteger result) {
  366. // if (result) {
  367. // if ([imageData writeToURL:savePanel.URL atomically:YES]) {
  368. // [[NSWorkspace sharedWorkspace] selectFile:savePanel.URL.path
  369. // inFileViewerRootedAtPath:@""];
  370. // }
  371. // }
  372. // }];
  373. }
  374. func menuItemClick_Copy(_ sender: AnyObject?) {
  375. // NSPasteboardItem *pasteboardItem = [[[NSPasteboardItem alloc] init] autorelease];
  376. // NSImage * image = [self thumbnailWithSize:0.0];
  377. // NSData *tiffData = [image TIFFRepresentation];
  378. // if (tiffData) {
  379. // [pasteboardItem setData:tiffData forType:NSPasteboardTypeTIFF];
  380. // if (pasteboardItem){
  381. // NSPasteboard *pboard = [NSPasteboard generalPasteboard];
  382. // [pboard clearContents];
  383. //
  384. // [pboard writeObjects:[NSArray arrayWithObject:pasteboardItem]];
  385. // }
  386. // }
  387. }
  388. func menuItemClick_ExportPNG(_ sender: NSMenuItem) {
  389. // NSImage * image = [self thumbnailWithSize:0.0];
  390. //
  391. // NSData *data = image.TIFFRepresentation;
  392. // NSBitmapImageRep *imageRep = [NSBitmapImageRep imageRepWithData:data];
  393. // [imageRep setSize:image.size];
  394. // NSData *imageData = [imageRep representationUsingType:NSPNGFileType properties:@{}];
  395. //
  396. // NSSavePanel *savePanel = [NSSavePanel savePanel];
  397. // savePanel.allowedFileTypes = @[@"png"];
  398. // [savePanel beginSheetModalForWindow:self.window completionHandler:^(NSInteger result) {
  399. // if (result) {
  400. // if ([imageData writeToURL:savePanel.URL atomically:YES]) {
  401. // [[NSWorkspace sharedWorkspace] selectFile:savePanel.URL.path
  402. // inFileViewerRootedAtPath:@""];
  403. // }
  404. // }
  405. // }];
  406. }
  407. }
  408. // MARK: - Private Methods
  409. extension KMSnapshotPDFView {
  410. private func _commonInitialization() {
  411. self._scalePopUpButton = nil
  412. self.autoFitPage = nil
  413. self.autoFitRect = .zero
  414. // [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handlePDFViewFrameChangedNotification:)
  415. // name:NSViewFrameDidChangeNotification object:self];
  416. // [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handlePDFViewFrameChangedNotification:)
  417. // name:NSViewBoundsDidChangeNotification object:self];
  418. // [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handlePDFContentViewFrameChangedNotification:)
  419. // name:NSViewBoundsDidChangeNotification object:[[self scrollView] contentView]];
  420. // [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handlePDFContentViewFrameChangedDelayedNotification:)
  421. // name:SKPDFContentViewChangedNotification object:self];
  422. // if ([PDFView instancesRespondToSelector:@selector(magnifyWithEvent:)] == NO || [PDFView instanceMethodForSelector:@selector(magnifyWithEvent:)] == [NSView instanceMethodForSelector:@selector(magnifyWithEvent:)])
  423. // [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handlePDFViewScaleChangedNotification:)
  424. // name:PDFViewScaleChangedNotification object:self];
  425. }
  426. private func _setScaleFactor(_ newScaleFactor: CGFloat) {
  427. self._setScaleFactor(newScaleFactor, adjustPopup: true)
  428. }
  429. private func _setScaleFactor(_ newScaleFactor: CGFloat, adjustPopup flag: Bool) {
  430. var newValue = newScaleFactor
  431. if flag {
  432. let i = self._index(for: newScaleFactor)
  433. self.scalePopUpButton?.selectItem(at: Int(i))
  434. newValue = self._SKDefaultScaleMenuFactors[Int(i)]
  435. }
  436. if self.autoFits {
  437. self._setAutoFits(false, adjustPopup: false)
  438. }
  439. super.scaleFactor = newValue
  440. }
  441. private func _lowerIndex(for scaleFactor: CGFloat) -> UInt {
  442. var count = self._SKDefaultScaleMenuFactorsCount
  443. for i in 0 ..< count {
  444. let index = count-i-1
  445. if (scaleFactor * 1.01 > self._SKDefaultScaleMenuFactors[index]) {
  446. return UInt(index)
  447. }
  448. }
  449. return 1
  450. }
  451. private func _upperIndex(for scaleFactor: CGFloat) -> UInt {
  452. var count = self._SKDefaultScaleMenuFactorsCount
  453. for i in 1 ..< count {
  454. if (scaleFactor * 0.99 < self._SKDefaultScaleMenuFactors[i]) {
  455. return UInt(i)
  456. }
  457. }
  458. return UInt(count - 1)
  459. }
  460. private func _index(for scaleFactor: CGFloat) -> UInt {
  461. let lower = self._lowerIndex(for: scaleFactor)
  462. let upper = self._upperIndex(for: scaleFactor)
  463. if (upper > lower && scaleFactor < 0.5 * (self._SKDefaultScaleMenuFactors[Int(lower)] + self._SKDefaultScaleMenuFactors[Int(upper)])) {
  464. return lower
  465. }
  466. return upper
  467. }
  468. private func _setAutoFits(_ newAuto: Bool) {
  469. self._setAutoFits(newAuto, adjustPopup: true)
  470. }
  471. private func _setAutoFits(_ newAuto: Bool, adjustPopup flag: Bool) {
  472. if (self.autoFits != newAuto) {
  473. self.autoFits = newAuto;
  474. if (self.autoFits) {
  475. super.autoScales = false
  476. self._resetAutoFitRectIfNeeded()
  477. if (flag) {
  478. self.scalePopUpButton?.selectItem(at: 0)
  479. }
  480. } else {
  481. self.autoFitPage = nil
  482. self.autoFitRect = NSZeroRect
  483. if (flag) {
  484. self._setScaleFactor(self.scaleFactor, adjustPopup: flag)
  485. }
  486. }
  487. }
  488. }
  489. private func _resetAutoFitRectIfNeeded() {
  490. if self.autoFits {
  491. let clipView = self.enclosingScrollView?.contentView
  492. self.autoFitPage = self.currentPage()
  493. // autoFitRect = [self convertRect:[self convertRect:[clipView visibleRect] fromView:clipView] toPage:autoFitPage];
  494. let rect = self.convert(clipView?.visibleRect ?? .zero, from: clipView)
  495. self.autoFitRect = self.convert(rect, to: self.autoFitPage)
  496. }
  497. }
  498. @objc private func _scalePopUpAction(_ sender: AnyObject?) {
  499. // NSNumber *selectedFactorObject = [[sender selectedItem] representedObject];
  500. let selectedFactorObject = self.scalePopUpButton?.selectedItem?.representedObject
  501. if let data = selectedFactorObject as? NSNumber {
  502. self._setScaleFactor(data.doubleValue, adjustPopup: false)
  503. } else {
  504. self._setAutoFits(true, adjustPopup: false)
  505. }
  506. }
  507. }