forked from divvun/macdivvun-service
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBundlesWatcher.swift
74 lines (55 loc) · 2.47 KB
/
BundlesWatcher.swift
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
//
// BundlesWatcher.swift
// MacDivvun
//
// Created by Charlotte Tortorella on 13/2/17.
// Copyright © 2017 Divvun. All rights reserved.
//
import Foundation
public class BundlesWatcher {
// MARK: - Initialization / Deinitialization
public init(callback: @escaping (String) -> Void) {
self.userCallback = callback
self.pathsToWatch = ["\(NSHomeDirectory())/Library/Speller/\(Global.vendor)"]
}
deinit {
stop()
}
// MARK: - Private Properties
private let eventCallback: FSEventStreamCallback = { (stream: ConstFSEventStreamRef, contextInfo: UnsafeMutableRawPointer?, numEvents: Int, eventPaths: UnsafeMutableRawPointer, eventFlags: UnsafePointer<FSEventStreamEventFlags>?, eventIds: UnsafePointer<FSEventStreamEventId>?) in
let bundlesWatcher: BundlesWatcher = unsafeBitCast(contextInfo, to: BundlesWatcher.self)
let paths = unsafeBitCast(eventPaths, to: NSArray.self) as! [String]
for index in 0..<numEvents {
bundlesWatcher.processEvent(eventPath: paths[index])
}
}
private let pathsToWatch: [String]
private var started = false
private var streamRef: FSEventStreamRef!
private let userCallback: (String) -> Void
// MARK: - Private Methods
private func processEvent(eventPath: String) {
if eventPath.hasSuffix(".bundle") {
userCallback(eventPath)
}
}
// MARK: - Pubic Methods
public func start() {
guard started == false else { return }
var context = FSEventStreamContext(version: 0, info: nil, retain: nil, release: nil, copyDescription: nil)
context.info = UnsafeMutableRawPointer(Unmanaged.passUnretained(self).toOpaque())
let flags = UInt32(kFSEventStreamCreateFlagUseCFTypes | kFSEventStreamCreateFlagFileEvents)
streamRef = FSEventStreamCreate(kCFAllocatorDefault, eventCallback, &context, pathsToWatch as CFArray, FSEventStreamEventId(kFSEventStreamEventIdSinceNow), 0, flags)
FSEventStreamScheduleWithRunLoop(streamRef, CFRunLoopGetMain(), CFRunLoopMode.defaultMode.rawValue)
FSEventStreamStart(streamRef)
started = true
}
public func stop() {
guard started == true else { return }
FSEventStreamStop(streamRef)
FSEventStreamInvalidate(streamRef)
FSEventStreamRelease(streamRef)
streamRef = nil
started = false
}
}