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