-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPerseusDarkModeSingle.swift
451 lines (360 loc) · 13.2 KB
/
PerseusDarkModeSingle.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
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
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
//
// PerseusDarkModeSingle.swift
// Version: 1.1.5
//
// Created by Mikhail Zhigulin in 7530.
//
// Copyright © 7530 - 7531 Mikhail Zhigulin of Novosibirsk.
// All rights reserved.
//
//
// MIT License
//
// Copyright © 7530 - 7531 Mikhail Zhigulin of Novosibirsk
//
// The year starts from the creation of the world according to a Slavic calendar.
// September, the 1st of Slavic year.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
// swiftlint:disable file_length block_based_kvo
//
#if canImport(UIKit)
import UIKit
#elseif canImport(Cocoa)
import Cocoa
#endif
#if os(iOS)
public typealias Responder = UIResponder
#elseif os(macOS)
public typealias Responder = NSResponder
#endif
// MARK: - Notifications
public extension Notification.Name {
static let MakeAppearanceUpNotification =
Notification.Name("MakeAppearanceUpNotification")
#if os(macOS)
static let AppleInterfaceThemeChangedNotification =
Notification.Name("AppleInterfaceThemeChangedNotification")
#endif
}
// MARK: - Constants
public let DARK_MODE_USER_CHOICE_KEY = "DarkModeUserChoiceOptionKey"
public let DARK_MODE_USER_CHOICE_DEFAULT = DarkModeOption.auto
public let DARK_MODE_STYLE_DEFAULT = AppearanceStyle.light
public let OBSERVERED_VARIABLE_NAME = "styleObservable"
// MARK: - Appearance service
// swiftlint:disable identifier_name
public extension Responder {
var DarkMode: DarkMode { return AppearanceService.shared }
}
// swiftlint:enable identifier_name
public class AppearanceService {
public static var shared: DarkMode = { _ = it; return DarkMode() }()
private(set) static var it = { AppearanceService() }()
private init() {
#if os(macOS)
AppearanceService.distributedNCenter.addObserver(
self,
selector: #selector(interfaceModeChanged),
name: .AppleInterfaceThemeChangedNotification,
object: nil
)
#endif
}
#if os(macOS)
@objc internal func interfaceModeChanged() {
if #available(macOS 10.14, *) {
AppearanceService.processAppearanceOSDidChange()
}
}
@available(macOS 10.14, *)
public static var defaultDarkAppearanceOS: NSAppearance.Name = .darkAqua
public static var defaultLightAppearanceOS: NSAppearance.Name = .aqua
#endif
public static var isEnabled: Bool { return hidden_isEnabled }
#if os(macOS)
/// Default Distributed NotificationCenter.
public static var distributedNCenter = DistributedNotificationCenter.default
#endif
/// Default NotificationCenter.
public static var nCenter = NotificationCenter.default
/// Default UserDefaults.
public static var ud = UserDefaults.standard
public static var DarkModeUserChoice: DarkModeOption {
get {
// Load enum Int value
let rawValue = ud.valueExists(forKey: DARK_MODE_USER_CHOICE_KEY) ?
ud.integer(forKey: DARK_MODE_USER_CHOICE_KEY) :
DARK_MODE_USER_CHOICE_DEFAULT.rawValue
// Try to cast Int value to enum
if let result = DarkModeOption.init(rawValue: rawValue) { return result }
return DARK_MODE_USER_CHOICE_DEFAULT
}
set {
ud.setValue(newValue.rawValue, forKey: DARK_MODE_USER_CHOICE_KEY)
// Used for KVO to immediately notify a change has happened
recalculateStyleIfNeeded()
}
}
// MARK: - Public API: register stakeholder
public static func register(stakeholder: Any, selector: Selector) {
nCenter.addObserver(stakeholder,
selector: selector,
name: .MakeAppearanceUpNotification,
object: nil)
}
// MARK: - Public API: make the app's appearance up
public static func makeUp() {
hidden_isEnabled = true
hidden_changeManually = true
if #available(iOS 13.0, macOS 10.14, *) { overrideUserInterfaceStyleIfNeeded() }
recalculateStyleIfNeeded()
nCenter.post(name: .MakeAppearanceUpNotification, object: nil)
hidden_changeManually = false
}
#if os(iOS)
@available(iOS 13.0, *)
public static func processTraitCollectionDidChange(
_ previousTraitCollection: UITraitCollection?) {
if hidden_changeManually { return }
guard let previousSystemStyle = previousTraitCollection?.userInterfaceStyle,
previousSystemStyle.rawValue != shared.systemStyle.rawValue
else { return }
hidden_systemCalledMakeUp()
}
#elseif os(macOS)
@available(macOS 10.14, *)
internal static func processAppearanceOSDidChange() {
if hidden_changeManually { return }
hidden_systemCalledMakeUp()
}
#endif
// MARK: - Implementation helpers, privates and internals
private(set) static var hidden_isEnabled: Bool = false {
willSet { if newValue == false { return }}
}
internal static var hidden_changeManually: Bool = false
internal static func hidden_systemCalledMakeUp() {
if hidden_changeManually { return }
hidden_isEnabled = true
recalculateStyleIfNeeded()
nCenter.post(name: .MakeAppearanceUpNotification, object: nil)
}
public static func recalculateStyleIfNeeded() {
let actualStyle = DarkModeDecision.calculate(DarkModeUserChoice, shared.systemStyle)
if shared.hidden_style != actualStyle { shared.hidden_style = actualStyle }
}
@available(iOS 13.0, macOS 10.14, *)
internal static func overrideUserInterfaceStyleIfNeeded() {
if hidden_changeManually == false { return }
#if os(iOS) && compiler(>=5)
guard let keyWindow = UIWindow.key else { return }
var overrideStyle: UIUserInterfaceStyle = .unspecified
switch DarkModeUserChoice {
case .auto:
overrideStyle = .unspecified
case .on:
overrideStyle = .dark
case .off:
overrideStyle = .light
}
keyWindow.overrideUserInterfaceStyle = overrideStyle
#elseif os(macOS)
switch DarkModeUserChoice {
case .auto:
NSApplication.shared.appearance = nil
case .on:
NSApplication.shared.appearance =
NSAppearance(named: AppearanceService.defaultDarkAppearanceOS)
case .off:
NSApplication.shared.appearance =
NSAppearance(named: AppearanceService.defaultLightAppearanceOS)
}
#endif
}
}
// MARK: - Dark Mode
public class DarkMode: NSObject {
// MARK: - The App's current Appearance Style
public var style: AppearanceStyle { return hidden_style }
// MARK: - Observable Appearance Style Value (Using Key-Value Observing)
@objc public dynamic var styleObservable: Int = DARK_MODE_STYLE_DEFAULT.rawValue
// MARK: - System's Appearance Style
public var systemStyle: SystemStyle {
if #available(iOS 13.0, macOS 10.14, *) {
#if os(iOS)
guard let keyWindow = UIWindow.key else { return .unspecified }
switch keyWindow.traitCollection.userInterfaceStyle {
case .unspecified:
return .unspecified
case .light:
return .light
case .dark:
return .dark
@unknown default:
return .unspecified
}
#elseif os(macOS)
if let isDark = UserDefaults.standard.string(forKey: "AppleInterfaceStyle"),
isDark == "Dark" {
return .dark
} else {
return .light
}
#endif
} else {
return .unspecified
}
}
internal var hidden_style: AppearanceStyle = DARK_MODE_STYLE_DEFAULT {
didSet { styleObservable = style.rawValue }
}
}
// MARK: - Dark Mode decision-making table
public class DarkModeDecision {
private init() { }
// MARK: - Calculating Dark Mode decision
/// Calculates the current appearance style of the app.
///
/// Dark Mode decision-making:
///
/// | DarkModeOption
/// -------------+-----------------------
/// SystemStyle | auto | on | off
/// -------------+---------+------+------
/// .unspecified | default | dark | light
/// .light | light | dark | light
/// .dark | dark | dark | light
///
public class func calculate(_ userChoice: DarkModeOption,
_ systemStyle: SystemStyle) -> AppearanceStyle {
// Calculate outputs
if (systemStyle == .unspecified) && (userChoice == .auto) {
return DARK_MODE_STYLE_DEFAULT
}
if (systemStyle == .unspecified) && (userChoice == .on) { return .dark }
if (systemStyle == .unspecified) && (userChoice == .off) { return .light }
if (systemStyle == .light) && (userChoice == .auto) { return .light }
if (systemStyle == .light) && (userChoice == .on) { return .dark }
if (systemStyle == .light) && (userChoice == .off) { return .light }
if (systemStyle == .dark) && (userChoice == .auto) { return .dark }
if (systemStyle == .dark) && (userChoice == .on) { return .dark }
if (systemStyle == .dark) && (userChoice == .off) { return .light }
// Output default value if somethings goes out of the decision table
return DARK_MODE_STYLE_DEFAULT
}
}
// MARK: - Appearance Style Observering
public class DarkModeObserver: NSObject {
public var action: ((_ newStyle: AppearanceStyle) -> Void)?
private(set) var objectToObserve = AppearanceService.shared
public override init() {
super.init()
objectToObserve.addObserver(self,
forKeyPath: OBSERVERED_VARIABLE_NAME,
options: .new,
context: nil)
}
public init(_ action: @escaping ((_ newStyle: AppearanceStyle) -> Void)) {
super.init()
self.action = action
objectToObserve.addObserver(self,
forKeyPath: OBSERVERED_VARIABLE_NAME,
options: .new,
context: nil)
}
public override func observeValue(forKeyPath keyPath: String?,
of object: Any?,
change: [NSKeyValueChangeKey: Any]?,
context: UnsafeMutableRawPointer?) {
guard
keyPath == OBSERVERED_VARIABLE_NAME,
let style = change?[.newKey],
let styleRawValue = style as? Int,
let newStyle = AppearanceStyle.init(rawValue: styleRawValue)
else { return }
action?(newStyle)
}
deinit {
objectToObserve.removeObserver(self, forKeyPath: OBSERVERED_VARIABLE_NAME)
}
}
// MARK: - Dark Mode Option
public enum DarkModeOption: Int, CustomStringConvertible {
case auto = 0
case on = 1
case off = 2
public var description: String {
switch self {
case .auto:
return ".auto"
case .on:
return ".on"
case .off:
return ".off"
}
}
}
// MARK: - Appearance Style
public enum AppearanceStyle: Int, CustomStringConvertible {
case light = 0
case dark = 1
public var description: String {
switch self {
case .light:
return ".light"
case .dark:
return ".dark"
}
}
}
// MARK: - System Style
public enum SystemStyle: Int, CustomStringConvertible {
case unspecified = 0
case light = 1
case dark = 2
public var description: String {
switch self {
case .unspecified:
return ".unspecified"
case .light:
return ".light"
case .dark:
return ".dark"
}
}
}
// MARK: - Helpers
extension UserDefaults {
public func valueExists(forKey key: String) -> Bool {
return object(forKey: key) != nil
}
}
#if os(iOS)
extension UIWindow {
static var key: UIWindow? {
if #available(iOS 13, *) {
return UIApplication.shared.windows.first { $0.isKeyWindow }
} else {
return UIApplication.shared.keyWindow
}
}
}
#endif