KMSnapshotPDFView.swift 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612
  1. //
  2. // KMSnapshotPDFView.swift
  3. // PDF Reader Pro
  4. //
  5. // Created by tangchao on 2023/12/12.
  6. //
  7. import Cocoa
  8. class KMSnapshotPDFView: CPDFListView {
  9. private var _scalePopUpButton: NSPopUpButton?
  10. var scalePopUpButton: NSPopUpButton? {
  11. get {
  12. if (self._scalePopUpButton == nil) {
  13. let scrollView = self.documentView()
  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. private let SKPDFContentViewChangedNotification = "SKPDFContentViewChangedNotification"
  87. deinit {
  88. KMPrint("KMSnapshotPDFView deinit.")
  89. NotificationCenter.default.removeObserver(self)
  90. }
  91. override init(frame frameRect: NSRect) {
  92. super.init(frame: frameRect)
  93. self._commonInitialization()
  94. }
  95. required init?(coder: NSCoder) {
  96. super.init(coder: coder)
  97. self._commonInitialization()
  98. }
  99. override func layout() {
  100. super.layout()
  101. let scrollView = self.documentView()
  102. let clipView = scrollView?.contentView
  103. // KMPrint(scrollView?.frame)
  104. // KMPrint(clipView?.frame)
  105. scrollView?.frame = self.bounds
  106. }
  107. override func draw(_ dirtyRect: NSRect) {
  108. super.draw(dirtyRect)
  109. // Drawing code here.
  110. }
  111. @objc func handlePDFViewFrameChangedNotification(_ notification: NSNotification) {
  112. if self.autoFits {
  113. let clipView = self.documentView().contentView
  114. let clipRect = self.convert(clipView.visibleRect, from: clipView)
  115. var rect = self.convert(self.autoFitRect, from: self.autoFitPage)
  116. let factor = fmin(NSWidth(clipRect) / NSWidth(rect), NSHeight(clipRect) / NSHeight(rect))
  117. rect = self.convert(NSInsetRect(rect, 0.5 * (NSWidth(rect) - NSWidth(clipRect) / factor), 0.5 * (NSHeight(rect) - NSHeight(clipRect) / factor)), to: self.autoFitPage)
  118. super.scaleFactor = factor * self.scaleFactor
  119. self.go(to: rect, on: self.autoFitPage)
  120. }
  121. }
  122. @objc func handlePDFContentViewFrameChangedDelayedNotification(_ notification: NSNotification) {
  123. if self.inLiveResize == false && (self.window?.isZoomed ?? false) == false {
  124. self._resetAutoFitRectIfNeeded()
  125. }
  126. }
  127. @objc func handlePDFContentViewFrameChangedNotification(_ notification: NSNotification) {
  128. if self.inLiveResize == false && (self.window?.isZoomed ?? false) == false {
  129. let note = Notification(name: Notification.Name(SKPDFContentViewChangedNotification), object: self)
  130. NotificationQueue.default.enqueue(note, postingStyle: .whenIdle, coalesceMask: .onName, forModes: nil)
  131. }
  132. }
  133. @objc func handlePDFViewScaleChangedNotification(_ notification: NSNotification) {
  134. if self.autoFits == false {
  135. self._setScaleFactor(fmax(self.scaleFactor, _SKMinDefaultScaleMenuFactor), adjustPopup: true)
  136. }
  137. }
  138. func setAutoScales() {
  139. }
  140. @IBAction override func zoomIn(_ sender: Any?) {
  141. if self.autoFits {
  142. super.zoomIn(sender)
  143. self._setAutoFits(false, adjustPopup: true)
  144. } else {
  145. let numberOfDefaultItems = _SKDefaultScaleMenuFactorsCount
  146. var i = self._lowerIndex(for: self.scaleFactor)
  147. if i < numberOfDefaultItems-1 {
  148. i += 1
  149. }
  150. self._setScaleFactor(_SKDefaultScaleMenuFactors[Int(i)])
  151. }
  152. }
  153. @IBAction override func zoomOut(_ sender: Any?) {
  154. if self.autoFits {
  155. super.zoomOut(sender)
  156. self._setAutoFits(false, adjustPopup: true)
  157. } else {
  158. var i = self._upperIndex(for: self.scaleFactor)
  159. if i > 1 {
  160. i -= 1
  161. }
  162. self._setScaleFactor(_SKDefaultScaleMenuFactors[Int(i)])
  163. }
  164. }
  165. override var canZoomIn: Bool {
  166. if super.canZoomIn == false {
  167. return false
  168. }
  169. let numberOfDefaultItems = _SKDefaultScaleMenuFactorsCount
  170. let i = self._lowerIndex(for: self.scaleFactor)
  171. return i < numberOfDefaultItems - 1
  172. }
  173. override var canZoomOut: Bool {
  174. if super.canZoomOut == false {
  175. return false
  176. }
  177. let i = self._upperIndex(for: self.scaleFactor)
  178. return i > 1
  179. }
  180. override func go(to page: CPDFPage!) {
  181. super.go(to: page)
  182. self._resetAutoFitRectIfNeeded()
  183. }
  184. @objc func doAutoFit(_ sender: Any?) {
  185. self.autoFits = true
  186. }
  187. @objc func doActualSize(_ sender: Any?) {
  188. self.scaleFactor = 1.0
  189. }
  190. override func menu(for event: NSEvent) -> NSMenu? {
  191. let selectionActions: NSSet = NSSet(objects: ["copy:", "_searchInSpotlight:", "_searchInGoogle:", "_searchInDictionary:", "_revealSelection:"])
  192. var menu = super.menu(for: event)
  193. if menu == nil {
  194. menu = NSMenu()
  195. }
  196. menu?.insertItem(.separator(), at: 0)
  197. menu?.insertItem(withTitle: KMLocalizedString("Print", "Menu item title"), action: #selector(menuItemClick_Print), target: self, at: 0)
  198. var item = menu?.insertItem(withTitle: KMLocalizedString("Export", "Menu item title"), action: nil, target: self, at: 0)
  199. let subMenu = NSMenu()
  200. subMenu.addItem(title: KMLocalizedString("PNG", "Menu item title"), action: #selector(menuItemClick_ExportPNG), target: self)
  201. subMenu.addItem(title: KMLocalizedString("JPG", "Menu item title"), action: #selector(menuItemClick_ExportJPG), target: self)
  202. subMenu.addItem(title: KMLocalizedString("PDF", "Menu item title"), action: #selector(menuItemClick_ExportPDF), target: self)
  203. item?.submenu = subMenu
  204. menu?.insertItem(.separator(), at: 0)
  205. menu?.insertItem(withTitle: KMLocalizedString("Copy", "Menu item title"), action: #selector(menuItemClick_Copy), target: self, at: 0)
  206. // [self setCurrentSelection:RUNNING_AFTER(10_11) ? [[[PDFSelection alloc] initWithDocument:[self document]] autorelease] : nil];
  207. self.currentSelection = CPDFSelection(document: self.document)
  208. if let _menu = menu {
  209. while (_menu.numberOfItems > 0) {
  210. if let item = _menu.item(at: 0), item.action != nil {
  211. if item.isSeparatorItem || self.validate(item) == false || selectionActions.contains(NSStringFromSelector(item.action!)) {
  212. menu?.removeItem(at: 0)
  213. } else {
  214. break
  215. }
  216. } else {
  217. break
  218. }
  219. }
  220. }
  221. if let i = menu?.indexOfItem(withTarget: self, andAction: NSSelectorFromString("_setAutoSize:")), i != -1 {
  222. menu?.item(at: i)?.action = #selector(doAutoFit)
  223. }
  224. if let i = menu?.indexOfItem(withTarget: self, andAction: NSSelectorFromString("_setActualSize:")), i != -1 {
  225. menu?.item(at: i)?.action = #selector(doActualSize)
  226. var item = menu?.insertItem(withTitle: KMLocalizedString("Physical Size", "Menu item title"), action: #selector(doPhysicalSize), target: self, at: i + 1)
  227. // item?.keyEquivalentModifierMask = [.alternate]
  228. // [item setKeyEquivalentModifierMask:NSAlternateKeyMask];
  229. // [item setAlternate:YES];
  230. item?.isAlternate = true
  231. }
  232. return menu
  233. }
  234. @objc func doPhysicalSize(_ sender: Any?) {
  235. // [self setPhysicalScaleFactor:1.0];
  236. }
  237. override func magnify(with event: NSEvent) {
  238. if KMDataManager.ud_bool(forKey: SKDisablePinchZoomKey) == false && event.responds(to: NSSelectorFromString("magnification")) {
  239. if event.phase == .began {
  240. self.startScale = self.scaleFactor
  241. }
  242. let magnifyFactor = (1.0 + fmax(-0.5, fmin(1.0 , event.magnification)))
  243. super.scaleFactor = magnification * self.scaleFactor
  244. if event.phase == .ended || event.phase == .cancelled && (fabs(self.startScale-self.scaleFactor) > 0.001) {
  245. self._setScaleFactor(fmax(self.scaleFactor, _SKMinDefaultScaleMenuFactor), adjustPopup: true)
  246. }
  247. }
  248. }
  249. /*
  250. - (BOOL)canGoBack {
  251. if ([self respondsToSelector:@selector(currentHistoryIndex)] && minHistoryIndex > 0)
  252. return minHistoryIndex < [self currentHistoryIndex];
  253. else
  254. return [super canGoBack];
  255. }
  256. // we don't want to steal the printDocument: action from the responder chain
  257. - (void)printDocument:(id)sender{}
  258. - (BOOL)respondsToSelector:(SEL)aSelector {
  259. return aSelector != @selector(printDocument:) && [super respondsToSelector:aSelector];
  260. }
  261. #pragma mark Gestures
  262. - (void)beginGestureWithEvent:(NSEvent *)theEvent {
  263. if ([[SKSnapshotPDFView superclass] instancesRespondToSelector:_cmd])
  264. [super beginGestureWithEvent:theEvent];
  265. startScale = [self scaleFactor];
  266. }
  267. - (void)endGestureWithEvent:(NSEvent *)theEvent {
  268. if (fabs(startScale - [self scaleFactor]) > 0.001)
  269. [self setScaleFactor:fmax([self scaleFactor], SKMinDefaultScaleMenuFactor) adjustPopup:YES];
  270. if ([[SKSnapshotPDFView superclass] instancesRespondToSelector:_cmd])
  271. [super endGestureWithEvent:theEvent];
  272. }
  273. - (void)magnifyWithEvent:(NSEvent *)theEvent {
  274. }
  275. #pragma mark Dragging
  276. - (void)mouseDown:(NSEvent *)theEvent{
  277. [[self window] makeFirstResponder:self];
  278. if ([theEvent standardModifierFlags] == (NSCommandKeyMask | NSShiftKeyMask)) {
  279. [self doPdfsyncWithEvent:theEvent];
  280. } else {
  281. [self doDragWithEvent:theEvent];
  282. }
  283. }
  284. - (void)setCursorForAreaOfInterest:(PDFAreaOfInterest)area {
  285. if ([NSEvent standardModifierFlags] == (NSCommandKeyMask | NSShiftKeyMask))
  286. [[NSCursor arrowCursor] set];
  287. else
  288. [[NSCursor openHandCursor] set];
  289. }
  290. */
  291. func thumbnailWithSize(_ size: CGFloat) -> NSImage? {
  292. // NSView *clipView = [[[self documentView] enclosingScrollView] contentView];
  293. let clipView = self.documentView().contentView
  294. var bounds = self.convert(clipView.bounds, from: clipView)
  295. guard let imageRep = self.bitmapImageRepForCachingDisplay(in: bounds) else {
  296. return nil
  297. }
  298. var transform: NSAffineTransform?
  299. var thumbnailSize = bounds.size
  300. var shadowBlurRadius = 0.0
  301. var shadowOffset = 0.0
  302. var image: NSImage?
  303. self.cacheDisplay(in: bounds, to: imageRep)
  304. bounds.origin = .zero
  305. if (size > 0.0) {
  306. shadowBlurRadius = round(size / 32.0)
  307. shadowOffset = -ceil(shadowBlurRadius * 0.75)
  308. if (NSHeight(bounds) > NSWidth(bounds)) {
  309. thumbnailSize = NSMakeSize(round((size - 2.0 * shadowBlurRadius) * NSWidth(bounds) / NSHeight(bounds) + 2.0 * shadowBlurRadius), size)
  310. } else {
  311. thumbnailSize = NSMakeSize(size, round((size - 2.0 * shadowBlurRadius) * NSHeight(bounds) / NSWidth(bounds) + 2.0 * shadowBlurRadius))
  312. }
  313. transform = NSAffineTransform()
  314. transform?.translateX(by: shadowBlurRadius, yBy: shadowBlurRadius - shadowOffset)
  315. transform?.scaleX(by: (thumbnailSize.width - 2.0 * shadowBlurRadius) / NSWidth(bounds), yBy: (thumbnailSize.height - 2.0 * shadowBlurRadius) / NSHeight(bounds))
  316. }
  317. image = NSImage(size: thumbnailSize)
  318. image?.lockFocus()
  319. NSGraphicsContext.current?.imageInterpolation = .high
  320. transform?.concat()
  321. NSGraphicsContext.saveGraphicsState()
  322. // [[PDFView defaultPageBackgroundColor] set];
  323. // if (shadowBlurRadius > 0.0) {
  324. // [NSShadow setShadowWithColor:[NSColor colorWithCalibratedWhite:0.0 alpha:0.5] blurRadius:shadowBlurRadius yOffset:shadowOffset];
  325. // }
  326. __NSRectFill(bounds)
  327. NSGraphicsContext.current?.imageInterpolation = .default
  328. NSGraphicsContext.restoreGraphicsState()
  329. imageRep.draw(in: bounds)
  330. image?.unlockFocus()
  331. return image
  332. }
  333. func resetHistory() {
  334. // if ([self respondsToSelector:@selector(currentHistoryIndex)])
  335. // minHistoryIndex = [self currentHistoryIndex];
  336. if self.responds(to: NSSelectorFromString("currentHistoryIndex")) {
  337. // self.current
  338. }
  339. }
  340. // MARK: - Menu
  341. @objc func menuItemClick_Print(_ sender: AnyObject?) {
  342. // NSImage * image = [self thumbnailWithSize:0.0];
  343. //
  344. // PDFPage *page = [[[PDFPage alloc] initWithImage:image] autorelease];
  345. //
  346. // PDFDocument *pdfDocument = [[[PDFDocument alloc] init] autorelease];
  347. // [pdfDocument insertPage:page atIndex:0];
  348. //
  349. // NSPrintInfo *printInfo = [NSPrintInfo sharedPrintInfo];
  350. //
  351. // NSPrintOperation *printOperation = nil;
  352. // if ([pdfDocument respondsToSelector:@selector(printOperationForPrintInfo:scalingMode:autoRotate:)]){
  353. // printOperation = [pdfDocument printOperationForPrintInfo:printInfo scalingMode:kPDFPrintPageScaleNone autoRotate:YES];
  354. // }
  355. //
  356. // [printOperation runOperationModalForWindow:self.window delegate:self didRunSelector:nil contextInfo:NULL];
  357. }
  358. @objc func menuItemClick_ExportPDF(_ sender: NSMenuItem) {
  359. guard let image = self.thumbnailWithSize(0) else {
  360. return
  361. }
  362. let document = CPDFDocument()
  363. document?.km_insert(image: image, at: 0)
  364. NSPanel.savePanel_pdf_success(self.window!, document: document) { url in
  365. NSWorkspace.shared.selectFile(url.path, inFileViewerRootedAtPath: "")
  366. }
  367. }
  368. @objc func menuItemClick_ExportJPG(_ sender: NSMenuItem) {
  369. guard let image = self.thumbnailWithSize(0) else {
  370. return
  371. }
  372. NSPanel.savePanel_data_success(self.window!, imageData: image.jpgData(), allowedTypes: ["jpg"]) { url in
  373. NSWorkspace.shared.selectFile(url.path, inFileViewerRootedAtPath: "")
  374. }
  375. }
  376. @objc func menuItemClick_Copy(_ sender: AnyObject?) {
  377. guard let image = self.thumbnailWithSize(0) else {
  378. return
  379. }
  380. if let tiffData = image.tiffRepresentation {
  381. let pasteboardItem = NSPasteboardItem()
  382. pasteboardItem.setData(tiffData, forType: .tiff)
  383. let pboard = NSPasteboard.general
  384. pboard.clearContents()
  385. pboard.writeObjects([pasteboardItem])
  386. }
  387. }
  388. @objc func menuItemClick_ExportPNG(_ sender: NSMenuItem) {
  389. guard let image = self.thumbnailWithSize(0) else {
  390. return
  391. }
  392. NSPanel.savePanel_data_success(self.window!, imageData: image.pngData(), allowedTypes: ["png"]) { url in
  393. NSWorkspace.shared.selectFile(url.path, inFileViewerRootedAtPath: "")
  394. }
  395. }
  396. }
  397. // MARK: - Private Methods
  398. extension KMSnapshotPDFView {
  399. private func _commonInitialization() {
  400. self._scalePopUpButton = nil
  401. self.autoFitPage = nil
  402. self.autoFitRect = .zero
  403. NotificationCenter.default.addObserver(self, selector: #selector(handlePDFViewFrameChangedNotification), name: NSView.frameDidChangeNotification, object: self)
  404. NotificationCenter.default.addObserver(self, selector: #selector(handlePDFViewFrameChangedNotification), name: NSView.boundsDidChangeNotification, object: self)
  405. NotificationCenter.default.addObserver(self, selector: #selector(handlePDFContentViewFrameChangedNotification), name: NSView.boundsDidChangeNotification, object: self.documentView()?.contentView)
  406. NotificationCenter.default.addObserver(self, selector: #selector(handlePDFContentViewFrameChangedDelayedNotification), name: NSNotification.Name(SKPDFContentViewChangedNotification), object: self)
  407. // if ([PDFView instancesRespondToSelector:@selector(magnifyWithEvent:)] == NO || [PDFView instanceMethodForSelector:@selector(magnifyWithEvent:)] == [NSView instanceMethodForSelector:@selector(magnifyWithEvent:)])
  408. // [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handlePDFViewScaleChangedNotification:)
  409. // name:PDFViewScaleChangedNotification object:self];
  410. }
  411. private func _setScaleFactor(_ newScaleFactor: CGFloat) {
  412. self._setScaleFactor(newScaleFactor, adjustPopup: true)
  413. }
  414. private func _setScaleFactor(_ newScaleFactor: CGFloat, adjustPopup flag: Bool) {
  415. var newValue = newScaleFactor
  416. if flag {
  417. let i = self._index(for: newScaleFactor)
  418. self.scalePopUpButton?.selectItem(at: Int(i))
  419. newValue = self._SKDefaultScaleMenuFactors[Int(i)]
  420. }
  421. if self.autoFits {
  422. self._setAutoFits(false, adjustPopup: false)
  423. }
  424. super.scaleFactor = newValue
  425. }
  426. private func _lowerIndex(for scaleFactor: CGFloat) -> UInt {
  427. var count = self._SKDefaultScaleMenuFactorsCount
  428. for i in 0 ..< count {
  429. let index = count-i-1
  430. if (scaleFactor * 1.01 > self._SKDefaultScaleMenuFactors[index]) {
  431. return UInt(index)
  432. }
  433. }
  434. return 1
  435. }
  436. private func _upperIndex(for scaleFactor: CGFloat) -> UInt {
  437. var count = self._SKDefaultScaleMenuFactorsCount
  438. for i in 1 ..< count {
  439. if (scaleFactor * 0.99 < self._SKDefaultScaleMenuFactors[i]) {
  440. return UInt(i)
  441. }
  442. }
  443. return UInt(count - 1)
  444. }
  445. private func _index(for scaleFactor: CGFloat) -> UInt {
  446. let lower = self._lowerIndex(for: scaleFactor)
  447. let upper = self._upperIndex(for: scaleFactor)
  448. if (upper > lower && scaleFactor < 0.5 * (self._SKDefaultScaleMenuFactors[Int(lower)] + self._SKDefaultScaleMenuFactors[Int(upper)])) {
  449. return lower
  450. }
  451. return upper
  452. }
  453. private func _setAutoFits(_ newAuto: Bool) {
  454. self._setAutoFits(newAuto, adjustPopup: true)
  455. }
  456. private func _setAutoFits(_ newAuto: Bool, adjustPopup flag: Bool) {
  457. if (self.autoFits != newAuto) {
  458. self.autoFits = newAuto;
  459. if (self.autoFits) {
  460. super.autoScales = false
  461. self._resetAutoFitRectIfNeeded()
  462. if (flag) {
  463. self.scalePopUpButton?.selectItem(at: 0)
  464. }
  465. } else {
  466. self.autoFitPage = nil
  467. self.autoFitRect = NSZeroRect
  468. if (flag) {
  469. self._setScaleFactor(self.scaleFactor, adjustPopup: flag)
  470. }
  471. }
  472. }
  473. }
  474. private func _resetAutoFitRectIfNeeded() {
  475. if self.autoFits {
  476. if let clipView = self.documentView()?.contentView {
  477. self.autoFitPage = self.currentPage()
  478. let rect = self.convert(clipView.visibleRect, from: clipView)
  479. self.autoFitRect = self.convert(rect, to: self.autoFitPage)
  480. }
  481. }
  482. }
  483. @objc private func _scalePopUpAction(_ sender: AnyObject?) {
  484. // NSNumber *selectedFactorObject = [[sender selectedItem] representedObject];
  485. let selectedFactorObject = self.scalePopUpButton?.selectedItem?.representedObject
  486. if let data = selectedFactorObject as? NSNumber {
  487. self._setScaleFactor(data.doubleValue, adjustPopup: false)
  488. } else {
  489. self._setAutoFits(true, adjustPopup: false)
  490. }
  491. }
  492. }
  493. extension KMSnapshotPDFView {
  494. override func validate(_ menuItem: NSMenuItem) -> Bool {
  495. if (menuItem.action == #selector(doAutoFit)) {
  496. menuItem.state = self.autoFits ? .on : .off
  497. return true
  498. } else if (menuItem.action == #selector(doActualSize)) {
  499. menuItem.state = fabs(self.scaleFactor - 1.0) < 0.1 ? .on : .off
  500. return true
  501. }
  502. // else if (menuItem.action == #selector(doPhysicalSize)) {
  503. // [menuItem setState:([self autoScales] || fabs([self physicalScaleFactor] - 1.0 ) > 0.01) ? NSOffState : NSOnState];
  504. // return true
  505. // }
  506. // } else if ([[SKSnapshotPDFView superclass] instancesRespondToSelector:_cmd]) {
  507. // return [super validateMenuItem:menuItem];
  508. // }
  509. return true
  510. }
  511. }