-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathselfwatcher.swift
More file actions
361 lines (310 loc) · 11.1 KB
/
selfwatcher.swift
File metadata and controls
361 lines (310 loc) · 11.1 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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
import Carbon
import Cocoa
import CoreGraphics
import Foundation
let homeDirURL = FileManager.default.homeDirectoryForCurrentUser
let logBaseDirURL =
homeDirURL
.appendingPathComponent(".local")
.appendingPathComponent("selfwatcher")
assert(
FileManager.default.fileExists(atPath: logBaseDirURL.path),
"Log dir missing: \(logBaseDirURL.path)")
let IDLE_TIMEOUT_SEC: TimeInterval = 5 * 60
let POLL_INTERVAL_SEC: TimeInterval = 2
let PRINT_INTERVAL_SEC: TimeInterval = 59
let LINE_SEP = ";"
let UNKNOWN = "_unknown"
let IDLE = "_idle"
let KEYS_ARR: [(String, String)] = [
("ALPHABETS", "k-az"),
("NUMBERS", "k-09"),
("SPECHARS", "k-spl"),
("ALT", "k-alt"),
("SHIFT", "k-sft"),
("CTRL", "k-ctl"),
("DELETE", "k-del"),
("CMD", "k-cmd"),
("ARROWS", "k-arr"),
("ENTER", "k-etr"),
("SPACE", "k-spc"),
("TAB", "k-tab"),
("ESC", "k-esc"),
("NAV", "k-nav"),
("FUNC", "k-fun"),
("OTHERS", "k-oth"),
("LCLICK", "m-lc"),
("RCLICK", "m-rc"),
("MCLICK", "m-mc"),
("SCROLL", "m-srl"),
]
let KEYS_INDICES = Dictionary(
uniqueKeysWithValues: KEYS_ARR.enumerated().map { ($0.element.0, $0.offset) })
let INIT_COUNTS = Array(repeating: 0, count: KEYS_ARR.count)
var G_key_counts_now = INIT_COUNTS
var G_key_counts_next = INIT_COUNTS
var G_data_now = [((Date, Date), String, [Int])]()
var G_data_next = [((Date, Date), String, [Int])]()
var G_last_input_time = Date()
var G_last_mouse_position = NSEvent.mouseLocation
let lock = NSLock()
let lock2 = NSLock()
func getActiveWindowTitle() -> String {
guard let frontmostApp = NSWorkspace.shared.frontmostApplication else {
return UNKNOWN + LINE_SEP + UNKNOWN
}
let appName = frontmostApp.localizedName ?? UNKNOWN
var windowTitle = UNKNOWN
let pid = frontmostApp.processIdentifier
let focusedApp = AXUIElementCreateApplication(pid)
var focusedWindow: AnyObject?
AXUIElementCopyAttributeValue(focusedApp, kAXFocusedWindowAttribute as CFString, &focusedWindow)
if focusedWindow != nil {
let window = focusedWindow as! AXUIElement
var title: AnyObject?
AXUIElementCopyAttributeValue(window, kAXTitleAttribute as CFString, &title)
windowTitle = title as? String ?? UNKNOWN
}
let cleanApp = appName.replacingOccurrences(of: LINE_SEP, with: "_")
let cleanTitle = windowTitle.replacingOccurrences(of: LINE_SEP, with: "_")
return cleanApp + LINE_SEP + cleanTitle
}
func classifyKey(event: CGEvent) -> [Int] {
let keyCode = CGKeyCode(event.getIntegerValueField(.keyboardEventKeycode))
let flags = event.flags
var out: [Int] = []
// Modifier keys (like CMD, ALT, SHIFT)
if flags.contains(.maskAlternate) {
out.append(KEYS_INDICES["ALT"]!)
}
if flags.contains(.maskShift) {
out.append(KEYS_INDICES["SHIFT"]!)
}
if flags.contains(.maskControl) {
out.append(KEYS_INDICES["CTRL"]!)
}
if flags.contains(.maskCommand) {
out.append(KEYS_INDICES["CMD"]!)
}
// print(keyCode)
switch keyCode {
case 0, 11, 8, 2, 14, 3, 5, 4, 34, 38, 40, 37, 46, 45, 31, 35, 12, 15, 1, 17, 32, 9, 13, 7, 16,
6: // a-z
out.append(KEYS_INDICES["ALPHABETS"]!)
case 29, 18, 19, 20, 21, 23, 22, 26, 28, 25: // 0-9
out.append(KEYS_INDICES["NUMBERS"]!)
case 50, 27, 24, 33, 30, 41, 39, 43, 47, 44, 42, 75, 67, 78, 69, 65: // specialchars
out.append(KEYS_INDICES["SPECHARS"]!)
case 51, 117: // delete, forward delete
out.append(KEYS_INDICES["DELETE"]!)
case 123, 124, 125, 126: // arrows: left, right, down, up
out.append(KEYS_INDICES["ARROWS"]!)
case 36: // return
out.append(KEYS_INDICES["ENTER"]!)
case 49: // space
out.append(KEYS_INDICES["SPACE"]!)
case 48: // tab
out.append(KEYS_INDICES["TAB"]!)
case 53: // esc
out.append(KEYS_INDICES["ESC"]!)
case 115, 119, 121, 116, 114, 57: // home, end, page down, page up, insert, caps lock
out.append(KEYS_INDICES["NAV"]!)
case 122, 120, 99, 118, 96, 97, 98, 100, 101, 109, 103, 111: // F1–F12
out.append(KEYS_INDICES["FUNC"]!)
default:
out.append(KEYS_INDICES["OTHERS"]!)
}
return out
}
func updateLastInput() {
lock.lock()
G_last_input_time = Date()
lock.unlock()
}
let timeZone = TimeZone.current
let utcFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.timeZone = timeZone
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX"
return formatter
}()
func getTimestamp(now: Date) -> String {
return utcFormatter.string(from: now)
}
func startReporter() {
DispatchQueue.global(qos: .background).async {
while true {
Thread.sleep(forTimeInterval: POLL_INTERVAL_SEC)
let currentMousePosition = NSEvent.mouseLocation
if currentMousePosition != G_last_mouse_position {
updateLastInput()
G_last_mouse_position = currentMousePosition
}
lock.lock()
let is_idle = Date().timeIntervalSince(G_last_input_time) > IDLE_TIMEOUT_SEC
lock.unlock()
var idle_str = ""
if is_idle {
idle_str = IDLE
}
let title = getActiveWindowTitle()
let windowTitle = "\(idle_str)\(LINE_SEP)\(title)"
lock.lock()
swap(&G_key_counts_now, &G_key_counts_next)
lock.unlock()
lock2.lock()
var last = G_data_now.count - 1
let now = Date()
if G_data_now.count == 0 || G_data_now[last].1 != windowTitle
|| G_data_now[last].0.0.timeIntervalSince(G_data_now[last].0.1) > PRINT_INTERVAL_SEC
{
G_data_now.append(((now, now), windowTitle, INIT_COUNTS))
last += 1
}
G_data_now[last].0.0 = now
for (_, index) in KEYS_INDICES {
G_data_now[last].2[index] += G_key_counts_next[index]
G_key_counts_next[index] = 0
}
lock2.unlock()
}
}
}
func startPrinter() {
writeToFile(lines: [
"_started: TIMESTAMP: \(getTimestamp(now: Date())) | POLL_INTERVAL_SEC: \(Int(POLL_INTERVAL_SEC)) | IDLE_TIMEOUT_SEC: \(Int(IDLE_TIMEOUT_SEC)) | PRINT_INTERVAL_SEC: \(Int(PRINT_INTERVAL_SEC))"
])
DispatchQueue.global(qos: .background).async {
while true {
Thread.sleep(forTimeInterval: PRINT_INTERVAL_SEC)
lock2.lock()
swap(&G_data_now, &G_data_next)
lock2.unlock()
var lines: [String] = []
for (metadata, window, counts) in G_data_next {
let timeEnd = getTimestamp(now: metadata.0)
let timeDiff = String(
format: "%.3f", metadata.0.timeIntervalSince(metadata.1) + POLL_INTERVAL_SEC)
let stats = KEYS_ARR.map { "\($0.1):\(counts[KEYS_INDICES[$0.0]!])" }.joined(
separator: LINE_SEP)
lines.append([timeEnd, timeDiff, window, stats].joined(separator: LINE_SEP))
}
writeToFile(lines: lines)
G_data_next.removeAll()
}
}
}
func writeToFile(lines: [String]) {
let now = Date()
let dateFormatter = DateFormatter()
dateFormatter.timeZone = timeZone
dateFormatter.dateFormat = "yyyy"
let year = dateFormatter.string(from: now)
dateFormatter.dateFormat = "MM"
let month = dateFormatter.string(from: now)
dateFormatter.dateFormat = "dd"
let day = dateFormatter.string(from: now)
let logDir = logBaseDirURL.appendingPathComponent(year)
.appendingPathComponent(
month)
do {
try FileManager.default.createDirectory(
at: logDir, withIntermediateDirectories: true, attributes: nil)
} catch {
print("Error creating log directory: \(error)")
exit(1)
}
let logFile = logDir.appendingPathComponent(
"window-\(year).\(month).\(day).txt"
)
do {
if !FileManager.default.fileExists(atPath: logFile.path) {
FileManager.default.createFile(
atPath: logFile.path, contents: nil, attributes: nil)
}
let fileHandle = try FileHandle(forUpdating: logFile)
defer {
fileHandle.closeFile()
}
for line in lines {
if let data = (line + "\n").data(using: .utf8) {
fileHandle.seekToEndOfFile()
fileHandle.write(data)
}
}
} catch {
print("Error writing to log file: \(error)")
exit(1)
}
}
func setupCGEventTap() {
let eventMask: CGEventMask =
((1 << CGEventType.keyDown.rawValue) | (1 << CGEventType.leftMouseDown.rawValue)
| (1 << CGEventType.rightMouseDown.rawValue)
| (1 << CGEventType.otherMouseDown.rawValue) | (1 << CGEventType.scrollWheel.rawValue))
let eventTap = CGEvent.tapCreate(
tap: .cgSessionEventTap,
place: .headInsertEventTap,
options: .listenOnly,
eventsOfInterest: eventMask,
callback: { _, type, event, _ -> Unmanaged<CGEvent>? in
switch type {
case .keyDown:
updateLastInput()
let indices = classifyKey(event: event)
// print(keys)
lock.lock()
for index in indices {
G_key_counts_now[index] += 1
}
lock.unlock()
case .leftMouseDown:
updateLastInput()
// print("click: left")
lock.lock()
G_key_counts_now[KEYS_INDICES["LCLICK"]!] += 1
lock.unlock()
case .rightMouseDown:
updateLastInput()
// print("click: right")
lock.lock()
G_key_counts_now[KEYS_INDICES["RCLICK"]!] += 1
lock.unlock()
case .otherMouseDown:
updateLastInput()
// print("click: middle")
lock.lock()
G_key_counts_now[KEYS_INDICES["MCLICK"]!] += 1
lock.unlock()
case .scrollWheel:
updateLastInput()
// print("scroll")
lock.lock()
G_key_counts_now[KEYS_INDICES["SCROLL"]!] += 1
lock.unlock()
default:
break
}
return Unmanaged.passRetained(event)
},
userInfo: nil
)
guard let tap = eventTap else {
print("Failed to create event tap. Run with accessibility permissions enabled.")
exit(1)
}
let runLoopSource = CFMachPortCreateRunLoopSource(kCFAllocatorDefault, tap, 0)
CFRunLoopAddSource(CFRunLoopGetCurrent(), runLoopSource, .commonModes)
CGEvent.tapEnable(tap: tap, enable: true)
}
func checkAccess() -> Bool {
let checkOptPrompt = kAXTrustedCheckOptionPrompt.takeUnretainedValue() as NSString
let options = [checkOptPrompt: true]
let accessEnabled = AXIsProcessTrustedWithOptions(options as CFDictionary?)
return accessEnabled
}
assert(checkAccess())
startReporter()
startPrinter()
setupCGEventTap()
CFRunLoopRun()