forked from chenxtdo/UPImageMacApp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPasteboardObserver.swift
More file actions
106 lines (84 loc) · 2.3 KB
/
PasteboardObserver.swift
File metadata and controls
106 lines (84 loc) · 2.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
//
// PasteboardObserver.swift
// U图床
//
// Created by Pro.chen on 7/20/16.
// Copyright © 2016 chenxt. All rights reserved.
//
import Cocoa
@objc protocol PasteboardObserverSubscriber: NSObjectProtocol {
func pasteboardChanged(_ pasteboard: NSPasteboard)
}
enum PasteboardObserverState {
case disabled
case enabled
case paused
}
class PasteboardObserver: NSObject {
var pasteboard: NSPasteboard = NSPasteboard.general()
var subscribers: NSMutableSet = NSMutableSet()
var serialQueue: DispatchQueue = DispatchQueue(label: "org.okolodev.PrettyPasteboard", attributes: [])
var changeCount: Int = -1
var state: PasteboardObserverState = PasteboardObserverState.disabled
override init() {
super.init()
}
deinit {
self.stopObserving()
self.removeSubscribers()
}
// Observing
func startObserving() {
DispatchQueue.global(priority: DispatchQueue.GlobalQueuePriority.default).async(execute: { () -> Void in
self.changeState(PasteboardObserverState.enabled)
self.observerLoop()
});
}
func stopObserving() {
self.changeState(PasteboardObserverState.disabled)
}
func pauseObserving() {
self.changeState(PasteboardObserverState.paused)
}
func continueObserving() {
if (self.state == PasteboardObserverState.paused) {
self.changeCount = self.pasteboard.changeCount;
self.state = PasteboardObserverState.enabled
}
}
func observerLoop() {
while self.isEnabled() {
usleep(250000)
let countEquals = self.changeCount == self.pasteboard.changeCount
if countEquals {
continue
}
self.changeCount = self.pasteboard.changeCount
self.pasteboardContentChanged()
}
}
func pasteboardContentChanged() {
self.pauseObserving()
for anySubscriber in self.subscribers {
if let subscriber = anySubscriber as? PasteboardObserverSubscriber {
subscriber.pasteboardChanged(self.pasteboard)
}
}
self.continueObserving()
}
func changeState(_ newState: PasteboardObserverState) {
self.serialQueue.sync(execute: { () -> Void in
self.state = newState;
});
}
func isEnabled() -> Bool {
return self.state == PasteboardObserverState.enabled;
}
// Subscribers
func addSubscriber(_ subscriber: PasteboardObserverSubscriber) {
self.subscribers.add(subscriber)
}
func removeSubscribers() {
self.subscribers.removeAllObjects()
}
}