aboutsummaryrefslogtreecommitdiff
path: root/Sources/phbar/Models/Notifier.swift
blob: a428c4919e32825eeb6de2553841fe735846a4d3 (plain) (blame)
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
import Foundation

/// Retains the handler for the lifetime of the registration.
///
/// The raw pointer returned by ``Notifier/register(_:handler:)``
/// is a retained reference to this box; it is released when
/// the registration is cancelled.
private final class NotifyBox {
	let handler: @Sendable () -> Void
	init(_ handler: @escaping @Sendable () -> Void) { self.handler = handler }
}

/// Delivers refresh triggers via Darwin notifications.
///
/// Wraps CoreFoundation notifications — the macOS-native,
/// signal-like way to trigger behaviour from the shell with
/// no client binary, using `notifyutil`:
///
/// ```
/// notifyutil -p <prefix><name>
/// ```
///
/// Each category of events uses a different ``prefix``
/// to avoid collisions. For example, block refresh
/// notifications use ``touchPrefix``:
///
/// ```
/// notifyutil -p house.panini.phbar.touch.<name>
/// ```
///
/// > Note: `notify.h` isn't part of Swift's Darwin module,
/// > so we go through `CFNotificationCenter`, which talks
/// > to the same subsystem.
/// >
/// > The callback fires on an arbitrary thread; handlers
/// > must hop to the main actor themselves (see ``AppDelegate``).
enum Notifier {
	/// Prefix for block refresh notifications.
	///
	/// Use `notifyutil -p house.panini.phbar.touch.<name>` to trigger
	/// a block update from the shell.
	static let touchPrefix = "house.panini.phbar.touch."

	/// Register `handler` to fire whenever the notification is posted.
	///
	/// - Parameters:
	///   - name: The notification name suffix.
	///   - prefix: The full notification name will be `prefix + name`.
	///             Defaults to ``touchPrefix``.
	///   - handler: Closure to invoke when the notification fires.
	///
	/// The returned token is a retained pointer used to keep the handler
	/// alive and to cancel the registration later. The handler runs on an
	/// arbitrary thread, so hop to the main actor inside it if you touch
	/// UI or published state.
	@discardableResult
	static func register(
		_ name: String,
		prefix: String = Notifier.touchPrefix,
		handler: @escaping @Sendable () -> Void
	) -> UnsafeMutableRawPointer {
		let fullName = prefix + name
		let ctx = Unmanaged.passRetained(NotifyBox(handler)).toOpaque()

		CFNotificationCenterAddObserver(
			CFNotificationCenterGetDarwinNotifyCenter(),
			ctx,
			{ _, observer, _, _, _ in
				guard let observer else { return }
				let box = Unmanaged<NotifyBox>.fromOpaque(observer).takeUnretainedValue()
				box.handler()
			},
			fullName as CFString,
			nil,
			.deliverImmediately
		)

		return ctx
	}

	/// Remove and release a registration.
	///
	/// Pass the token returned by ``Notifier/register(_:handler:)``.
	/// Optional: process exit clears all pending registrations anyway.
	static func cancel(_ token: UnsafeMutableRawPointer) {
		let center = CFNotificationCenterGetDarwinNotifyCenter()
		CFNotificationCenterRemoveEveryObserver(center, token)
		Unmanaged<NotifyBox>.fromOpaque(token).release()
	}
}