KMSnapshotWindowController.swift 29 KB

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