KMSnapshotWindowController.swift 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696
  1. //
  2. // KMSnapshotWindowController.swift
  3. // PDF Reader Pro
  4. //
  5. // Created by tangchao on 2023/12/12.
  6. //
  7. import Cocoa
  8. @objc protocol KMSnapshotWindowControllerDelegate: NSObjectProtocol {
  9. @objc optional func snapshotControllerDidFinishSetup(_ controller: KMSnapshotWindowController)
  10. @objc optional func snapshotControllerWillClose(_ controller: KMSnapshotWindowController)
  11. @objc optional func snapshotControllerDidChange(_ controller: KMSnapshotWindowController)
  12. @objc optional func snapshotController(_ controller: KMSnapshotWindowController, miniaturizedRect isMiniaturize: Bool) -> NSRect
  13. }
  14. class KMSnapshotWindowController: NSWindowController {
  15. @IBOutlet var pdfView: KMSnapshotPDFView!
  16. var hasWindow = false
  17. var forceOnTop = false
  18. weak var delegate: KMSnapshotWindowControllerDelegate?
  19. var string: String = ""
  20. var pageLabel: String = "" {
  21. didSet {
  22. self.synchronizeWindowTitleWithDocumentName()
  23. }
  24. }
  25. var animating = false
  26. var thumbnail: NSImage?
  27. var windowImage: NSImage?
  28. /*
  29. #define EM_DASH_CHARACTER (unichar)0x2014
  30. NSString *SKSnapshotCurrentSetupKey = @"currentSetup";
  31. static char SKSnaphotWindowDefaultsObservationContext;
  32. */
  33. private let SMALL_DELAY = 0.1
  34. private let RESIZE_TIME_FACTOR = 0.6
  35. private let PAGE_KEY = "page"
  36. private let RECT_KEY = "rect"
  37. private let SCALEFACTOR_KEY = "scaleFactor"
  38. private let AUTOFITS_KEY = "autoFits"
  39. private let WINDOWFRAME_KEY = "windowFrame"
  40. private let HASWINDOW_KEY = "hasWindow"
  41. private let PAGELABEL_KEY = "pageLabel"
  42. private let PAGEANDWINDOW_KEY = "pageAndWindow"
  43. private let SKSnapshotWindowFrameAutosaveName = "SKSnapshotWindow"
  44. private let SKSnapshotViewChangedNotification = "SKSnapshotViewChangedNotification"
  45. private let SKSnapshotPageCellLabelKey = "label"
  46. private let SKSnapshotPageCellHasWindowKey = "hasWindow"
  47. deinit {
  48. KMPrint("KMSnapshotWindowController deinit.")
  49. NotificationCenter.default.removeObserver(self)
  50. }
  51. override var windowNibName: NSNib.Name? {
  52. return "SnapshotWindow"
  53. }
  54. override func windowDidLoad() {
  55. super.windowDidLoad()
  56. // if ([NSWindow instancesRespondToSelector:@selector(setTabbingMode:)])
  57. // [[self window] setTabbingMode:NSWindowTabbingModeDisallowed];
  58. // if ([NSWindow instancesRespondToSelector:@selector(toggleFullScreen:)])
  59. // [[self window] setCollectionBehavior:[[self window] collectionBehavior] | NSWindowCollectionBehaviorFullScreenAuxiliary];
  60. // if ([[self window] respondsToSelector:@selector(contentLayoutRect)]) {
  61. // [[self window] setStyleMask:[[self window] styleMask] | NSFullSizeContentViewWindowMask];
  62. // [pdfView setFrame:[[self window] contentLayoutRect]];
  63. // }
  64. if let data = self.window?.responds(to: NSSelectorFromString("contentLayoutRect")), data {
  65. self.window?.styleMask.insert(.fullSizeContentView)
  66. self.pdfView.frame = self.window?.contentLayoutRect ?? NSMakeRect(0, 0, 400, 400)
  67. }
  68. self._updateWindowLevel()
  69. // [[NSUserDefaultsController sharedUserDefaultsController] addObserver:self forKeys:[NSArray arrayWithObjects:SKSnapshotsOnTopKey, SKShouldAntiAliasKey, SKGreekingThresholdKey, SKBackgroundColorKey, SKPageBackgroundColorKey, nil] context:&SKSnaphotWindowDefaultsObservationContext];
  70. // the window is initialially exposed. The windowDidExpose notification is useless, it has nothing to do with showing the window
  71. self.hasWindow = true
  72. }
  73. /*
  74. + (NSSet *)keyPathsForValuesAffectingPageAndWindow {
  75. return [NSSet setWithObjects:PAGELABEL_KEY, HASWINDOW_KEY, nil];
  76. }
  77. - (NSString *)windowTitleForDocumentDisplayName:(NSString *)displayName {
  78. return [NSString stringWithFormat:@"%@ %C %@", displayName, EM_DASH_CHARACTER, [NSString stringWithFormat:NSLocalizedString(@"Page %@", @""), [self pageLabel]]];
  79. }
  80. - (void)setNeedsDisplayInRect:(NSRect)rect ofPage:(PDFPage *)page {
  81. NSRect aRect = [pdfView convertRect:rect fromPage:page];
  82. CGFloat scale = [pdfView scaleFactor];
  83. CGFloat maxX = ceil(NSMaxX(aRect) + scale);
  84. CGFloat maxY = ceil(NSMaxY(aRect) + scale);
  85. CGFloat minX = floor(NSMinX(aRect) - scale);
  86. CGFloat minY = floor(NSMinY(aRect) - scale);
  87. aRect = NSIntersectionRect([pdfView bounds], NSMakeRect(minX, minY, maxX - minX, maxY - minY));
  88. if (NSIsEmptyRect(aRect) == NO)
  89. [pdfView setNeedsDisplayInRect:aRect];
  90. }
  91. - (void)setNeedsDisplayForAnnotation:(PDFAnnotation *)annotation onPage:(PDFPage *)page {
  92. [self setNeedsDisplayInRect:[annotation displayRect] ofPage:page];
  93. }
  94. - (void)redisplay {
  95. [pdfView requiresDisplay];
  96. }
  97. */
  98. func redisplay() {
  99. self.pdfView.needsDisplay = true
  100. }
  101. @objc func handlePageChangedNotification(_ notification: NSNotification?) {
  102. // [self setPageLabel:[[pdfView currentPage] displayLabel]];
  103. let label = "\(self.pdfView.currentPage().pageIndex()+1)"
  104. self.pageLabel = label
  105. self.handlePDFViewFrameChangedNotification(nil)
  106. }
  107. @objc func handleDocumentDidUnlockNotification(_ notification: NSNotification) {
  108. let label = "\(self.pdfView.currentPage().pageIndex()+1)"
  109. self.pageLabel = label
  110. self.handlePDFViewFrameChangedNotification(nil)
  111. }
  112. @objc func handlePDFViewFrameChangedNotification(_ notification: NSNotification?) {
  113. if let _ = self.delegate?.snapshotControllerDidChange?(self) {
  114. let note = NSNotification(name: NSNotification.Name(rawValue: SKSnapshotViewChangedNotification), object: self)
  115. NotificationQueue.default.enqueue(note as Notification, postingStyle: .whenIdle, coalesceMask: .onName, forModes: nil)
  116. }
  117. }
  118. @objc func handleViewChangedNotification(_ notification: NSNotification) {
  119. self.updateString()
  120. self.delegate?.snapshotControllerDidChange?(self)
  121. }
  122. @objc func handleDidAddRemoveAnnotationNotification(_ notification: NSNotification) {
  123. // PDFAnnotation *annotation = [[notification userInfo] objectForKey:SKPDFViewAnnotationKey];
  124. // PDFPage *page = [[notification userInfo] objectForKey:SKPDFViewPageKey];
  125. guard let annotation = notification.userInfo?["annotation"] as? CPDFAnnotation else {
  126. return
  127. }
  128. guard let page = notification.userInfo?["page"] as? CPDFPage else {
  129. return
  130. }
  131. // if ([[page document] isEqual:[pdfView document]] && [self isPageVisible:page])
  132. // [self setNeedsDisplayForAnnotation:annotation onPage:page];
  133. }
  134. @objc func notifiyDidFinishSetup() {
  135. self.delegate?.snapshotControllerDidFinishSetup?(self)
  136. }
  137. /*
  138. - (void)handleDidMoveAnnotationNotification:(NSNotification *)notification {
  139. PDFAnnotation *annotation = [[notification userInfo] objectForKey:SKPDFViewAnnotationKey];
  140. PDFPage *oldPage = [[notification userInfo] objectForKey:SKPDFViewOldPageKey];
  141. PDFPage *newPage = [[notification userInfo] objectForKey:SKPDFViewNewPageKey];
  142. if ([[newPage document] isEqual:[pdfView document]]) {
  143. if ([self isPageVisible:oldPage])
  144. [self setNeedsDisplayForAnnotation:annotation onPage:oldPage];
  145. if ([self isPageVisible:newPage])
  146. [self setNeedsDisplayForAnnotation:annotation onPage:newPage];
  147. }
  148. }
  149. - (void)setPdfDocument:(PDFDocument *)pdfDocument setup:(NSDictionary *)setup {
  150. [self setPdfDocument:pdfDocument
  151. goToPageNumber:[[setup objectForKey:PAGE_KEY] unsignedIntegerValue]
  152. rect:NSRectFromString([setup objectForKey:RECT_KEY])
  153. scaleFactor:[[setup objectForKey:SCALEFACTOR_KEY] doubleValue]
  154. autoFits:[[setup objectForKey:AUTOFITS_KEY] boolValue]];
  155. [self setHasWindow:[[setup objectForKey:HASWINDOW_KEY] boolValue]];
  156. if ([setup objectForKey:WINDOWFRAME_KEY])
  157. [[self window] setFrame:NSRectFromString([setup objectForKey:WINDOWFRAME_KEY]) display:NO];
  158. }
  159. - (BOOL)isPageVisible:(PDFPage *)page {
  160. return [[page document] isEqual:[pdfView document]] && NSLocationInRange([page pageIndex], [pdfView displayedPageIndexRange]);
  161. }
  162. #pragma mark Acessors
  163. - (NSRect)bounds {
  164. NSView *clipView = [[[pdfView documentView] enclosingScrollView] contentView];
  165. return [pdfView convertRect:[pdfView convertRect:[clipView bounds] fromView:clipView] toPage:[pdfView currentPage]];
  166. }
  167. */
  168. func isPageVisible(_ page: CPDFPage?) -> Bool {
  169. guard let doc = page?.document else {
  170. return false
  171. }
  172. let result = doc.isEqual(to: self.pdfView.document)
  173. if result == false {
  174. return result
  175. }
  176. return NSLocationInRange(Int(page!.pageIndex()), self.pdfView.displayedPageIndexRange())
  177. }
  178. func pageIndex() -> UInt {
  179. return self.pdfView.currentPage().pageIndex()
  180. }
  181. func pageAndWindow() -> NSDictionary {
  182. return [SKSnapshotPageCellLabelKey : self.pageLabel, SKSnapshotPageCellHasWindowKey : NSNumber(booleanLiteral: self.hasWindow)]
  183. }
  184. func setForceOnTop(_ flag: Bool) {
  185. self.forceOnTop = flag
  186. if let data = self.window?.isVisible, data {
  187. self._updateWindowLevel()
  188. }
  189. }
  190. /*
  191. - (NSDictionary *)currentSetup {
  192. NSView *clipView = [[[pdfView documentView] enclosingScrollView] contentView];
  193. NSRect rect = [pdfView convertRect:[pdfView convertRect:[clipView bounds] fromView:clipView] toPage:[pdfView currentPage]];
  194. BOOL autoFits = [pdfView autoFits];
  195. return [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithUnsignedInteger:[self pageIndex]], PAGE_KEY, NSStringFromRect(rect), RECT_KEY, [NSNumber numberWithDouble:[pdfView scaleFactor]], SCALEFACTOR_KEY, [NSNumber numberWithBool:autoFits], AUTOFITS_KEY, [NSNumber numberWithBool:[[self window] isVisible]], HASWINDOW_KEY, NSStringFromRect([[self window] frame]), WINDOWFRAME_KEY, nil];
  196. }
  197. */
  198. // MARK: - Actions
  199. @IBAction func doGoToNextPage(_ sender: AnyObject?) {
  200. self.pdfView.goToNextPage(sender)
  201. }
  202. @IBAction func doGoToPreviousPage(_ sender: AnyObject?) {
  203. self.pdfView.goToPreviousPage(sender)
  204. }
  205. @IBAction func doGoToFirstPage(_ sender: AnyObject?) {
  206. self.pdfView.goToFirstPage(sender)
  207. }
  208. @IBAction func doGoToLastPage(_ sender: AnyObject?) {
  209. self.pdfView.goToLastPage(sender)
  210. }
  211. @IBAction func doGoBack(_ sender: AnyObject?) {
  212. self.pdfView.km_goBack(sender)
  213. }
  214. @IBAction func doGoForward(_ sender: AnyObject?) {
  215. self.pdfView.km_goForward(sender)
  216. }
  217. @IBAction func doZoomIn(_ sender: AnyObject?) {
  218. self.pdfView.zoomIn(sender)
  219. }
  220. @IBAction func doZoomOut(_ sender: AnyObject?) {
  221. self.pdfView.zoomOut(sender)
  222. }
  223. // @IBAction func doZoomToPhysicalSize(_ sender: AnyObject?) {
  224. // self.pdfv
  225. // }
  226. // - (IBAction):(id)sender {
  227. // [pdfView setPhysicalScaleFactor:1.0];
  228. // }
  229. @IBAction func doZoomToActualSize(_ sender: AnyObject?) {
  230. self.pdfView.scaleFactor = 1.0
  231. }
  232. @IBAction func toggleAutoScale(_ sender: AnyObject?) {
  233. self.pdfView.autoFits = !self.pdfView.autoFits
  234. }
  235. // MARK: - Thumbnails
  236. func thumbnailWithSize(_ size: CGFloat) -> NSImage? {
  237. let clipView = self.pdfView.documentView().contentView
  238. var bounds = self.pdfView.convert(clipView.bounds, from: clipView)
  239. if (CGRectEqualToRect(CGRectZero, bounds) || CGRectIsNull(bounds)) {
  240. return nil
  241. }
  242. let imageRep = self.pdfView.bitmapImageRepForCachingDisplay(in: bounds)
  243. var transform: NSAffineTransform?
  244. var thumbnailSize = bounds.size
  245. var shadowBlurRadius: CGFloat = 0.0
  246. var shadowOffset: CGFloat = 0.0
  247. var image: NSImage?
  248. if let data = imageRep {
  249. self.pdfView.cacheDisplay(in: bounds, to: data)
  250. }
  251. bounds.origin = NSZeroPoint
  252. if (size > 0.0) {
  253. shadowBlurRadius = round(size / 32.0)
  254. shadowOffset = -ceil(shadowBlurRadius * 0.75)
  255. if (NSHeight(bounds) > NSWidth(bounds)) {
  256. thumbnailSize = NSMakeSize(round((size - 2.0 * shadowBlurRadius) * NSWidth(bounds) / NSHeight(bounds) + 2.0 * shadowBlurRadius), size);
  257. } else {
  258. thumbnailSize = NSMakeSize(size, round((size - 2.0 * shadowBlurRadius) * NSHeight(bounds) / NSWidth(bounds) + 2.0 * shadowBlurRadius));
  259. }
  260. transform = NSAffineTransform()
  261. transform?.translateX(by: shadowBlurRadius, yBy: shadowBlurRadius - shadowOffset)
  262. transform?.scaleX(by: (thumbnailSize.width - 2.0 * shadowBlurRadius) / NSWidth(bounds), yBy: (thumbnailSize.height - 2.0 * shadowBlurRadius) / NSHeight(bounds))
  263. }
  264. if (CGSizeEqualToSize(CGSizeZero, thumbnailSize)) {
  265. return nil
  266. }
  267. image = NSImage(size: thumbnailSize)
  268. if (CGSizeEqualToSize(CGSizeZero, image!.size)) {
  269. return nil
  270. }
  271. image?.lockFocus()
  272. NSGraphicsContext.current?.imageInterpolation = .high
  273. transform?.concat()
  274. NSGraphicsContext.saveGraphicsState()
  275. // [[PDFView defaultPageBackgroundColor] set];
  276. if (shadowBlurRadius > 0.0) {
  277. // [NSShadow setShadowWithColor:[NSColor colorWithCalibratedWhite:0.0 alpha:0.5] blurRadius:shadowBlurRadius yOffset:shadowOffset];
  278. }
  279. __NSRectFill(bounds)
  280. NSGraphicsContext.current?.imageInterpolation = .default
  281. NSGraphicsContext.restoreGraphicsState()
  282. imageRep?.draw(in: bounds)
  283. image?.unlockFocus()
  284. return image
  285. }
  286. func thumbnailAttachment() -> NSAttributedString? {
  287. return self._thumbnailAttachment(size: 0)
  288. }
  289. func thumbnail512Attachment() -> NSAttributedString? {
  290. return self._thumbnailAttachment(size: 512)
  291. }
  292. func thumbnail256Attachment() -> NSAttributedString? {
  293. return self._thumbnailAttachment(size: 256)
  294. }
  295. func thumbnail128Attachment() -> NSAttributedString? {
  296. return self._thumbnailAttachment(size: 128)
  297. }
  298. func thumbnail64Attachment() -> NSAttributedString? {
  299. return self._thumbnailAttachment(size: 64)
  300. }
  301. func thumbnail32Attachment() -> NSAttributedString? {
  302. return self._thumbnailAttachment(size: 32)
  303. }
  304. // MARK: - Miniaturize / Deminiaturize
  305. func miniaturizedRectForDockingRect(_ dockRect: NSRect) -> NSRect {
  306. let clipView = self.pdfView.documentView().contentView
  307. let sourceRect = clipView.convert(clipView.bounds, to: nil)
  308. var targetRect: NSRect = .zero
  309. let windowSize = self.window?.frame.size ?? .zero
  310. let thumbSize = self.thumbnail?.size ?? .zero
  311. var thumbRatio: CGFloat = 0
  312. if thumbSize.width > 0 {
  313. thumbRatio = thumbSize.height / thumbSize.width
  314. }
  315. var dockRatio: CGFloat = 0
  316. if NSWidth(dockRect) > 0 {
  317. dockRatio = NSHeight(dockRect) / NSWidth(dockRect)
  318. }
  319. var scaleFactor: CGFloat = 0
  320. var shadowRadius = round(fmax(thumbSize.width, thumbSize.height) / 32.0)
  321. var shadowOffset = ceil(0.75 * shadowRadius)
  322. if (thumbRatio > dockRatio) {
  323. targetRect = NSInsetRect(dockRect, 0.5 * NSWidth(dockRect) * (1.0 - dockRatio / thumbRatio), 0.0)
  324. scaleFactor = NSHeight(targetRect) / thumbSize.height
  325. } else {
  326. targetRect = NSInsetRect(dockRect, 0.0, 0.5 * NSHeight(dockRect) * (1.0 - thumbRatio / dockRatio))
  327. scaleFactor = NSWidth(targetRect) / thumbSize.width
  328. }
  329. shadowRadius *= scaleFactor
  330. shadowOffset *= scaleFactor
  331. targetRect = NSOffsetRect(NSInsetRect(targetRect, shadowRadius, shadowRadius), 0.0, shadowOffset)
  332. if thumbRatio > dockRatio {
  333. if NSHeight(sourceRect) != 0 {
  334. scaleFactor = NSHeight(targetRect) / NSHeight(sourceRect)
  335. }
  336. } else {
  337. if NSWidth(sourceRect) != 0 {
  338. scaleFactor = NSWidth(targetRect) / NSWidth(sourceRect)
  339. }
  340. }
  341. return NSMakeRect(NSMinX(targetRect) - scaleFactor * NSMinX(sourceRect), NSMinY(targetRect) - scaleFactor * NSMinY(sourceRect), scaleFactor * windowSize.width, scaleFactor * windowSize.height);
  342. }
  343. func miniaturizeWindowFromRect(_ startRect: NSRect, toRect endRect: NSRect) {
  344. if (self.windowImage == nil) {
  345. self.windowImage = (self.window as? KMSnapshotWindow)?.windowImage
  346. }
  347. let miniaturizeWindow = KMAnimatedBorderlessWindow(contentRect: startRect)
  348. miniaturizeWindow.level = .floating
  349. miniaturizeWindow.backgroundImage = self.windowImage
  350. miniaturizeWindow.orderFront(nil)
  351. self.animating = true
  352. NSAnimationContext.runAnimationGroup { context in
  353. context.duration = RESIZE_TIME_FACTOR * miniaturizeWindow.animationResizeTime(endRect)
  354. miniaturizeWindow.animator().setFrame(endRect, display: true)
  355. } completionHandler: {
  356. if self.hasWindow {
  357. if let data = self.window?.responds(to: NSSelectorFromString("setAnimationBehavior:")), data {
  358. self.window?.animationBehavior = .none
  359. }
  360. self.window?.orderFront(nil)
  361. self._updateWindowLevel()
  362. if let data = self.window?.responds(to: NSSelectorFromString("setAnimationBehavior:")), data {
  363. self.window?.animationBehavior = .default
  364. }
  365. }
  366. miniaturizeWindow.orderOut(nil)
  367. self.animating = false
  368. }
  369. }
  370. func miniaturize() {
  371. if (self.animating) {
  372. return
  373. }
  374. if let dockRect = self.delegate?.snapshotController?(self, miniaturizedRect: true) {
  375. let startRect = self.window?.frame ?? .zero
  376. let endRect = self.miniaturizedRectForDockingRect(dockRect)
  377. self.miniaturizeWindowFromRect(startRect, toRect: endRect)
  378. if let data = self.window?.responds(to: NSSelectorFromString("setAnimationBehavior:")), data {
  379. self.window?.animationBehavior = .none
  380. }
  381. }
  382. self.window?.orderOut(nil)
  383. if let data = self.window?.responds(to: NSSelectorFromString("setAnimationBehavior:")), data {
  384. self.window?.animationBehavior = .default
  385. }
  386. self.hasWindow = false
  387. }
  388. func deminiaturize() {
  389. if (self.animating) {
  390. return
  391. }
  392. if let dockRect = self.delegate?.snapshotController?(self, miniaturizedRect: false) {
  393. let endRect = self.window?.frame ?? .zero
  394. let startRect = self.miniaturizedRectForDockingRect(dockRect)
  395. self.miniaturizeWindowFromRect(startRect, toRect: endRect)
  396. // SKDESTROY(windowImage);
  397. } else {
  398. self.showWindow(self)
  399. }
  400. self.hasWindow = true
  401. }
  402. /*
  403. #pragma mark KVO
  404. - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
  405. if (context == &SKSnaphotWindowDefaultsObservationContext) {
  406. NSString *key = [keyPath substringFromIndex:7];
  407. if ([key isEqualToString:SKSnapshotsOnTopKey]) {
  408. if ([[self window] isVisible])
  409. [self updateWindowLevel];
  410. } else if ([key isEqualToString:SKShouldAntiAliasKey]) {
  411. [pdfView setShouldAntiAlias:[[NSUserDefaults standardUserDefaults] boolForKey:SKShouldAntiAliasKey]];
  412. [pdfView applyDefaultInterpolationQuality];
  413. } else if ([key isEqualToString:SKGreekingThresholdKey]) {
  414. [pdfView setGreekingThreshold:[[NSUserDefaults standardUserDefaults] floatForKey:SKGreekingThresholdKey]];
  415. } else if ([key isEqualToString:SKBackgroundColorKey]) {
  416. [pdfView setBackgroundColor:[[NSUserDefaults standardUserDefaults] colorForKey:SKBackgroundColorKey]];
  417. } else if ([key isEqualToString:SKPageBackgroundColorKey]) {
  418. [pdfView applyDefaultPageBackgroundColor];
  419. }
  420. } else {
  421. [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
  422. }
  423. }
  424. */
  425. func updateString() {
  426. var mutableString = ""
  427. let clipView = self.pdfView.documentView().contentView
  428. let rect = clipView.convert(clipView.visibleRect, to: self.pdfView)
  429. for page in self.pdfView.displayedPages() {
  430. guard let _page = page as? CPDFPage else {
  431. continue
  432. }
  433. let frame = self.pdfView.convert(rect, to: _page)
  434. let sel = _page.selection(for: frame)
  435. if let data = sel?.hasCharacters(), data {
  436. if mutableString.isEmpty == false {
  437. mutableString.append("\n")
  438. }
  439. mutableString.append(sel?.string() ?? "")
  440. }
  441. }
  442. self.string = mutableString
  443. }
  444. @objc func goToRect(_ rectValue: NSValue) {
  445. self.pdfView.go(to: rectValue.rectValue, on: self.pdfView.currentPage())
  446. self.pdfView.resetHistory()
  447. self.updateString()
  448. self.window?.makeFirstResponder(self.pdfView)
  449. self.handlePageChangedNotification(nil)
  450. NotificationCenter.default.addObserver(self, selector: #selector(handlePageChangedNotification), name: NSNotification.Name.CPDFViewPageChanged, object: self.pdfView)
  451. NotificationCenter.default.addObserver(self, selector: #selector(handleDocumentDidUnlockNotification), name: NSNotification.Name.CPDFDocumentDidUnlock, object: self.pdfView.document)
  452. let clipView = self.pdfView.documentView().contentView
  453. NotificationCenter.default.addObserver(self, selector: #selector(handlePDFViewFrameChangedNotification), name: NSView.frameDidChangeNotification, object: clipView)
  454. NotificationCenter.default.addObserver(self, selector: #selector(handlePDFViewFrameChangedNotification), name: NSView.boundsDidChangeNotification, object: clipView)
  455. NotificationCenter.default.addObserver(self, selector: #selector(handleViewChangedNotification), name: NSNotification.Name(SKSnapshotViewChangedNotification), object: self)
  456. // NotificationCenter.default.addObserver(self, selector: #selector(handleDidAddRemoveAnnotationNotification), name: SKPDFViewDidAddAnnotationNotification, object: nil)
  457. // NotificationCenter.default.addObserver(self, selector: #selector(handleDidAddRemoveAnnotationNotification), name: SKPDFViewDidRemoveAnnotationNotification, object: nil)
  458. // NotificationCenter.default.addObserver(self, selector: #selector(handleDidMoveAnnotationNotification), name: SKPDFViewDidMoveAnnotationNotification, object: nil)
  459. self.perform(#selector(notifiyDidFinishSetup), with: nil, afterDelay: SMALL_DELAY)
  460. if self.hasWindow {
  461. self.showWindow(nil)
  462. }
  463. }
  464. func setPdfDocument(_ pdfDocument: CPDFDocument, goToPageNumber pageNum: Int, rect: NSRect, scaleFactor factor: CGFloat, autoFits: Bool) {
  465. let window = self.window
  466. self.pdfView.scaleFactor = factor
  467. self.pdfView.autoScales = false
  468. self.pdfView.displaysPageBreaks = false
  469. self.pdfView.displayBox = .cropBox
  470. // [pdfView setShouldAntiAlias:[[NSUserDefaults standardUserDefaults] floatForKey:]];
  471. self.pdfView.setShouldAntiAlias(UserDefaults.standard.bool(forKey: SKShouldAntiAliasKey))
  472. self.pdfView.setGreekingThreshold(UserDefaults.standard.float(forKey: SKGreekingThresholdKey).cgFloat)
  473. self.pdfView.backgroundColor = UserDefaults.standard.color(forKey: SKBackgroundColorKey)
  474. // [pdfView applyDefaultPageBackgroundColor];
  475. // [pdfView applyDefaultInterpolationQuality];
  476. self.pdfView.document = pdfDocument
  477. // [self setWindowFrameAutosaveNameOrCascade:SKSnapshotWindowFrameAutosaveName];
  478. if let controlView = self.pdfView.scalePopUpButton {
  479. var controlFrame: NSRect = .zero
  480. var frame: NSRect = .zero
  481. NSDivideRect(self.pdfView.frame, &controlFrame, &frame, NSHeight(controlView.frame), .minY)
  482. // NSDivideRect([pdfView frame], &controlFrame, &frame, NSHeight([controlView frame]), NSMinYEdge);
  483. controlFrame.size.width = NSWidth(controlView.frame)
  484. controlView.frame = controlFrame
  485. controlView.autoresizingMask = [.maxXMargin, .maxYMargin]
  486. window?.contentView?.addSubview(controlView)
  487. self.pdfView.frame = frame
  488. window?.backgroundColor = NSColor(calibratedWhite: 0.97, alpha: 1)
  489. let page = pdfDocument.page(at: UInt(pageNum))
  490. frame = self.pdfView.convert(rect, from: page)
  491. var view: NSView?
  492. frame = self.pdfView.convert(frame, to: view)
  493. frame.size.height += NSHeight(controlFrame)
  494. // frame = [NSWindow frameRectForContentRect:frame styleMask:[window styleMask] & ~NSWindowStyleMaskFullSizeContentView];
  495. var styleMask = window?.styleMask
  496. styleMask?.remove(.fullSizeContentView)
  497. frame = NSWindow.frameRect(forContentRect: frame, styleMask: styleMask!)
  498. frame.origin.x = NSMinX(window!.frame)
  499. frame.origin.y = NSMaxY(window!.frame) - NSHeight(frame)
  500. self.window?.setFrame(frame, display: false, animate: false)
  501. }
  502. self.pdfView.go(toPageIndex: pageNum, animated: false)
  503. // if (autoFits) {
  504. // self.pdfView.autoFits = autoFits
  505. // }
  506. self.pdfView.autoFits = true
  507. self.pdfView.autoScales = true
  508. // Delayed to allow PDFView to finish its bookkeeping
  509. // fixes bug of apparently ignoring the point but getting the page right.
  510. self.perform(#selector(goToRect), with: NSValue(rect: rect), afterDelay: SMALL_DELAY)
  511. }
  512. }
  513. // MARK: - Private Methods
  514. extension KMSnapshotWindowController {
  515. private func _updateWindowLevel() {
  516. let onTop = self.forceOnTop || UserDefaults.standard.bool(forKey: SKSnapshotsOnTopKey)
  517. self.window?.level = onTop ? .floating : .normal
  518. self.window?.hidesOnDeactivate = onTop
  519. }
  520. private func _thumbnailAttachment(size: CGFloat) -> NSAttributedString? {
  521. guard let imageData = self.thumbnailWithSize(size)?.tiffRepresentation else {
  522. return nil
  523. }
  524. let wrapper = FileWrapper(regularFileWithContents: imageData)
  525. let filename = String(format: "snapshot_page_%lu.tiff", self.pageIndex() + 1)
  526. wrapper.filename = filename
  527. wrapper.preferredFilename = filename
  528. let attachment = NSTextAttachment(fileWrapper: wrapper)
  529. return NSAttributedString(attachment: attachment)
  530. }
  531. }
  532. extension KMSnapshotWindowController: NSWindowDelegate {
  533. func windowWillClose(_ notification: Notification) {
  534. // @try { [[NSUserDefaultsController sharedUserDefaultsController] removeObserver:self forKeys:[NSArray arrayWithObjects:SKSnapshotsOnTopKey, SKShouldAntiAliasKey, SKGreekingThresholdKey, SKBackgroundColorKey, SKPageBackgroundColorKey, nil]]; }
  535. // @catch (id e) {}
  536. self.delegate?.snapshotControllerWillClose?(self)
  537. self.delegate = nil
  538. // Yosemite and El Capitan have a retain cycle when we leave the PDFView with a document
  539. // if (RUNNING_AFTER(10_9) && RUNNING_BEFORE(10_12))
  540. self.pdfView.document = nil
  541. }
  542. func windowDidMiniaturize(_ notification: Notification) {
  543. self.window?.orderOut(nil)
  544. self.hasWindow = false
  545. }
  546. func windowDidDeminiaturize(_ notification: Notification) {
  547. self._updateWindowLevel()
  548. self.hasWindow = true
  549. }
  550. }
  551. extension KMSnapshotWindowController: NSMenuItemValidation {
  552. func validateMenuItem(_ menuItem: NSMenuItem) -> Bool {
  553. let action = menuItem.action
  554. if (action == #selector(doGoToNextPage)) {
  555. return self.pdfView.canGoToNextPage()
  556. } else if (action == #selector(doGoToPreviousPage)) {
  557. return self.pdfView.canGoToPreviousPage()
  558. } else if (action == #selector(doGoToFirstPage)) {
  559. return self.pdfView.canGoToFirstPage()
  560. } else if (action == #selector(doGoToLastPage)) {
  561. return self.pdfView.canGoToLastPage()
  562. } else if (action == #selector(doGoBack)) {
  563. return self.pdfView.km_canGoBack()
  564. } else if (action == #selector(doGoForward)) {
  565. return self.pdfView.km_canGoForward()
  566. } else if (action == #selector(doZoomIn)) {
  567. return self.pdfView.canZoomIn
  568. } else if (action == #selector(doZoomOut)) {
  569. return self.pdfView.canZoomOut
  570. } else if (action == #selector(doZoomToActualSize)) {
  571. return abs(pdfView.scaleFactor - 1.0 ) > 0.01
  572. }
  573. // else if (action == #selector(doZoomToPhysicalSize)) {
  574. // return fabs(pdfView.physicalScaleFactor - 1.0 ) > 0.01
  575. // }
  576. else if (action == #selector(toggleAutoScale)) {
  577. menuItem.state = self.pdfView.autoFits ? .on : .off
  578. return true
  579. }
  580. return true
  581. }
  582. }