NSWindow+PopOver.swift 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. //
  2. // NSWindow+PopOver.swift
  3. // PDF Master
  4. //
  5. // Created by kdanmobile on 2023/10/26.
  6. //
  7. import Foundation
  8. let KMWindowPopOverKey = "KMWindowPopOverKey"
  9. let KMWindowPopOverSourcesRectKey = "KMWindowPopOverSourcesRectKey"
  10. extension NSWindow {
  11. var popover: NSPopover? {
  12. get {
  13. return objc_getAssociatedObject(self,KMWindowPopOverKey) as? NSPopover
  14. }
  15. set {
  16. objc_setAssociatedObject(self, KMWindowPopOverKey, newValue, .OBJC_ASSOCIATION_RETAIN)
  17. }
  18. }
  19. var sourcesRect: CGRect? {
  20. get {
  21. guard let value = objc_getAssociatedObject(self, KMWindowPopOverSourcesRectKey) as? NSValue else {
  22. return nil
  23. }
  24. return value.rectValue
  25. }
  26. set {
  27. if let newValue = newValue {
  28. let value = NSValue(rect: newValue)
  29. objc_setAssociatedObject(self, KMWindowPopOverSourcesRectKey, value, .OBJC_ASSOCIATION_RETAIN)
  30. } else {
  31. objc_setAssociatedObject(self, KMWindowPopOverSourcesRectKey, nil, .OBJC_ASSOCIATION_RETAIN)
  32. }
  33. }
  34. }
  35. open override func mouseMoved(with event: NSEvent) {
  36. super.mouseMoved(with: event)
  37. let point = event.locationInWindow
  38. if NSStringFromClass(event.window!.classForCoder).elementsEqual("_NSPopoverWindow") == false {
  39. if !sourcesRect!.contains(point) {
  40. if (self.popover != nil) {
  41. NotificationCenter.default.post(name: NSNotification.Name("KMPopOverClosedByWindowNotification"), object: self.popover)
  42. popover!.close()
  43. self.popover = nil
  44. self.sourcesRect = CGRect.null
  45. }
  46. }
  47. }
  48. }
  49. }