-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStatusBarController.swift
More file actions
399 lines (330 loc) · 13.4 KB
/
StatusBarController.swift
File metadata and controls
399 lines (330 loc) · 13.4 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
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
import AppKit
import Foundation
struct ClockDefinition {
let flag: String
let city: String
let timeZoneIdentifier: String
var timeZone: TimeZone? {
TimeZone(identifier: timeZoneIdentifier)
}
}
final class ClockMenuItemView: NSView {
private static let itemWidth: CGFloat = 320
private static let zoneColumnWidth: CGFloat = 150
private static let offsetColumnWidth: CGFloat = 52
private static let dateColumnWidth: CGFloat = 88
private static let horizontalPadding: CGFloat = 16
private static let verticalPadding: CGFloat = 7
private let titleLabel = NSTextField(labelWithString: "")
private let timeLabel = NSTextField(labelWithString: "")
private let zoneLabel = NSTextField(labelWithString: "")
private let offsetLabel = NSTextField(labelWithString: "")
private let dateLabel = NSTextField(labelWithString: "")
init(title: String, time: String, zone: String, offset: String, date: String) {
super.init(frame: NSRect(x: 0, y: 0, width: Self.itemWidth, height: 48))
translatesAutoresizingMaskIntoConstraints = false
titleLabel.stringValue = title
titleLabel.font = .systemFont(ofSize: 13, weight: .semibold)
titleLabel.textColor = .labelColor
timeLabel.stringValue = time
timeLabel.font = .monospacedDigitSystemFont(ofSize: 13, weight: .semibold)
timeLabel.textColor = .labelColor
timeLabel.alignment = .right
zoneLabel.stringValue = zone
zoneLabel.font = .systemFont(ofSize: 11)
zoneLabel.textColor = .secondaryLabelColor
zoneLabel.lineBreakMode = .byTruncatingMiddle
zoneLabel.alignment = .left
offsetLabel.stringValue = offset
offsetLabel.font = .monospacedDigitSystemFont(ofSize: 11, weight: .regular)
offsetLabel.textColor = .secondaryLabelColor
offsetLabel.alignment = .left
dateLabel.stringValue = date
dateLabel.font = .systemFont(ofSize: 11)
dateLabel.textColor = .secondaryLabelColor
dateLabel.alignment = .left
let topRow = NSStackView(views: [titleLabel, NSView(), timeLabel])
topRow.orientation = .horizontal
topRow.alignment = .centerY
let bottomRow = NSStackView(views: [zoneLabel, offsetLabel, dateLabel])
bottomRow.orientation = .horizontal
bottomRow.alignment = .centerY
bottomRow.spacing = 10
let stack = NSStackView(views: [topRow, bottomRow])
stack.orientation = .vertical
stack.alignment = .leading
stack.spacing = 3
stack.translatesAutoresizingMaskIntoConstraints = false
addSubview(stack)
NSLayoutConstraint.activate([
widthAnchor.constraint(equalToConstant: Self.itemWidth),
heightAnchor.constraint(equalToConstant: 48),
stack.leadingAnchor.constraint(equalTo: leadingAnchor, constant: Self.horizontalPadding),
stack.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -Self.horizontalPadding),
stack.topAnchor.constraint(equalTo: topAnchor, constant: Self.verticalPadding),
stack.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -Self.verticalPadding),
zoneLabel.widthAnchor.constraint(equalToConstant: Self.zoneColumnWidth),
offsetLabel.widthAnchor.constraint(equalToConstant: Self.offsetColumnWidth),
dateLabel.widthAnchor.constraint(equalToConstant: Self.dateColumnWidth),
])
zoneLabel.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
zoneLabel.setContentHuggingPriority(.defaultLow, for: .horizontal)
offsetLabel.setContentCompressionResistancePriority(.required, for: .horizontal)
offsetLabel.setContentHuggingPriority(.required, for: .horizontal)
dateLabel.setContentCompressionResistancePriority(.required, for: .horizontal)
dateLabel.setContentHuggingPriority(.required, for: .horizontal)
}
@available(*, unavailable)
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
var dateText: String {
dateLabel.stringValue
}
}
@MainActor
final class StatusBarController {
private let statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)
private var preferencesDidChangeObserver: NSObjectProtocol?
private var refreshTimer: Timer?
private let preferences: AppPreferences
private let openSettings: () -> Void
private var analogClockView: AnalogClockStatusView?
private let clocks: [ClockDefinition] = [
ClockDefinition(flag: "🇺🇸", city: "San Francisco", timeZoneIdentifier: "America/Los_Angeles"),
ClockDefinition(flag: "🇺🇸", city: "New York", timeZoneIdentifier: "America/New_York"),
ClockDefinition(flag: "🇬🇧", city: "London", timeZoneIdentifier: "Europe/London"),
ClockDefinition(flag: "🇩🇪", city: "Berlin", timeZoneIdentifier: "Europe/Berlin"),
ClockDefinition(flag: "🇨🇳", city: "Shanghai", timeZoneIdentifier: "Asia/Shanghai"),
ClockDefinition(flag: "🇯🇵", city: "Tokyo", timeZoneIdentifier: "Asia/Tokyo"),
ClockDefinition(flag: "🇦🇺", city: "Sydney", timeZoneIdentifier: "Australia/Sydney"),
]
private let timeFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.locale = Locale.autoupdatingCurrent
formatter.dateFormat = "HH:mm:ss"
return formatter
}()
init(preferences: AppPreferences, openSettings: @escaping () -> Void) {
self.preferences = preferences
self.openSettings = openSettings
}
var footerViewForTesting: MenuFooterView? {
statusItem.menu?.items.last?.view as? MenuFooterView
}
var renderedMenuDatesForTesting: [String] {
statusItem.menu?.items.compactMap { ($0.view as? ClockMenuItemView)?.dateText } ?? []
}
var statusButtonTitleForTesting: String? {
statusItem.button?.attributedTitle.string
}
var analogClockViewForTesting: AnalogClockStatusView? {
analogClockView
}
deinit {
refreshTimer?.invalidate()
if let preferencesDidChangeObserver {
NotificationCenter.default.removeObserver(preferencesDidChangeObserver)
}
}
func start() {
configureButton()
observePreferences()
rebuildMenu()
scheduleRefreshTimer()
}
private func configureButton() {
guard let button = statusItem.button else {
return
}
button.image = nil
button.imagePosition = .noImage
button.toolTip = "World clocks"
}
private func observePreferences() {
preferencesDidChangeObserver = NotificationCenter.default.addObserver(
forName: .appPreferencesDidChange,
object: nil,
queue: .main
) { [weak self] _ in
Task { @MainActor [weak self] in
self?.rebuildMenu()
}
}
}
private func scheduleRefreshTimer() {
refreshTimer?.invalidate()
refreshTimer = Timer.scheduledTimer(
withTimeInterval: 1,
repeats: true
) { [weak self] _ in
Task { @MainActor [weak self] in
self?.rebuildMenu()
}
}
if let refreshTimer {
RunLoop.main.add(refreshTimer, forMode: .common)
}
}
private func rebuildMenu() {
let now = Date()
updateStatusItem(for: now)
let menu = NSMenu()
menu.autoenablesItems = false
if let localTimeZone = TimeZone.current as TimeZone? {
menu.addItem(
menuItem(
flag: localFlagEmoji(),
label: "Local",
in: localTimeZone,
date: now
)
)
menu.addItem(.separator())
}
for clock in clocks {
guard let timeZone = clock.timeZone else {
continue
}
menu.addItem(menuItem(flag: clock.flag, label: clock.city, in: timeZone, date: now))
}
menu.addItem(.separator())
let footerItem = NSMenuItem(title: "", action: nil, keyEquivalent: "")
footerItem.view = MenuFooterView(
onQuit: { [weak self] in
self?.quit()
},
onSettings: { [weak self] in
self?.openSettingsFromMenu()
}
)
menu.addItem(footerItem)
statusItem.menu = menu
}
private func updateStatusItem(for date: Date) {
guard let button = statusItem.button else {
return
}
switch preferences.clockStyle {
case .digital:
statusItem.length = NSStatusItem.variableLength
removeAnalogClockView(from: button)
let title = ClockDisplayFormatter(locale: ClockDisplayFormatter.systemLocale()).digitalTitle(
for: date,
timeZone: .current,
showsDate: preferences.showsMenuBarDate,
showsWeekday: preferences.showsMenuBarWeekday,
showsSeconds: preferences.showsSecondsInMenuBar,
blinksSeparator: preferences.blinksTimeSeparator
)
button.attributedTitle = NSAttributedString(
string: title,
attributes: [
.font: NSFont.monospacedDigitSystemFont(ofSize: 12, weight: .medium),
]
)
case .analog:
statusItem.length = 30
button.attributedTitle = NSAttributedString(string: "")
ensureAnalogClockView(in: button).update(date: date, timeZone: .current)
}
}
private func ensureAnalogClockView(in button: NSStatusBarButton) -> AnalogClockStatusView {
if let analogClockView {
return analogClockView
}
let view = AnalogClockStatusView(frame: .zero)
view.translatesAutoresizingMaskIntoConstraints = false
button.addSubview(view)
NSLayoutConstraint.activate([
view.centerXAnchor.constraint(equalTo: button.centerXAnchor),
view.centerYAnchor.constraint(equalTo: button.centerYAnchor),
view.widthAnchor.constraint(equalToConstant: 22),
view.heightAnchor.constraint(equalToConstant: 22),
])
analogClockView = view
return view
}
private func removeAnalogClockView(from button: NSStatusBarButton) {
analogClockView?.removeFromSuperview()
analogClockView = nil
button.subviews
.compactMap { $0 as? AnalogClockStatusView }
.forEach { $0.removeFromSuperview() }
}
private func menuItem(flag: String, label: String, in timeZone: TimeZone, date: Date) -> NSMenuItem {
let time = formattedTime(for: date, in: timeZone)
let zone = displayName(for: timeZone, label: label)
let offset = formattedOffset(for: timeZone, date: date)
let dateText = formattedDate(for: date, in: timeZone)
let title = "\(flag) \(label)"
let item = NSMenuItem(title: title, action: nil, keyEquivalent: "")
item.view = ClockMenuItemView(
title: title,
time: time,
zone: zone,
offset: offset,
date: dateText
)
return item
}
private func localFlagEmoji() -> String {
guard let regionCode = Locale.autoupdatingCurrent.region?.identifier else {
return "🏠"
}
return flagEmoji(for: regionCode) ?? "🏠"
}
private func flagEmoji(for regionCode: String) -> String? {
guard regionCode.count == 2 else {
return nil
}
let scalars = regionCode.uppercased().unicodeScalars.compactMap { scalar -> UnicodeScalar? in
guard let regionalScalar = UnicodeScalar(127397 + scalar.value) else {
return nil
}
return regionalScalar
}
guard scalars.count == 2 else {
return nil
}
return String(String.UnicodeScalarView(scalars))
}
private func displayName(for timeZone: TimeZone, label: String) -> String {
if label == "Local" {
return timeZone.identifier
}
return timeZone.identifier.replacingOccurrences(of: "_", with: " ")
}
private func formattedTime(for date: Date, in timeZone: TimeZone) -> String {
timeFormatter.timeZone = timeZone
return timeFormatter.string(from: date)
}
private func formattedDate(for date: Date, in timeZone: TimeZone) -> String {
preferences.menuDateFormat.string(
from: date,
in: timeZone,
locale: ClockDisplayFormatter.systemLocale()
)
}
private func formattedOffset(for timeZone: TimeZone, date: Date) -> String {
let totalMinutes = timeZone.secondsFromGMT(for: date) / 60
let hours = totalMinutes / 60
let minutes = abs(totalMinutes % 60)
let sign = hours >= 0 ? "+" : "-"
let absoluteHours = abs(hours)
if minutes == 0 {
return "UTC\(sign)\(absoluteHours)"
}
return String(format: "UTC%@%d:%02d", sign, absoluteHours, minutes)
}
@objc
private func quit() {
NSApplication.shared.terminate(nil)
}
private func openSettingsFromMenu() {
statusItem.menu?.cancelTracking()
DispatchQueue.main.async { [openSettings] in
openSettings()
}
}
}