From 27c398ec40c5e717d3e26b7b0f2628e1f8adb96e Mon Sep 17 00:00:00 2001 From: Matt Baer Date: Thu, 3 Aug 2017 18:16:14 -0400 Subject: [PATCH] Make Night Mode global for all windows - Now it changes all windows when enabled - Newly launched windows respect the setting - Multiple windows restored on launch respect the setting --- writeas/AppDelegate.swift | 22 ++++++++++++++++------ writeas/WindowController.swift | 4 ++++ 2 files changed, 20 insertions(+), 6 deletions(-) diff --git a/writeas/AppDelegate.swift b/writeas/AppDelegate.swift index bc9c6b6..9b97019 100644 --- a/writeas/AppDelegate.swift +++ b/writeas/AppDelegate.swift @@ -20,12 +20,18 @@ class AppDelegate: NSObject, NSApplicationDelegate { @IBOutlet weak var formatFontSansItem: NSMenuItem! @IBOutlet weak var formatFontMonoItem: NSMenuItem! + struct GlobalSettings { + var isNight = false + } + var globalSettings = GlobalSettings() + func applicationDidFinishLaunching(_ aNotification: Notification) { // Set night mode state - nightModeItem.state = Int(UserDefaults.standard.string(forKey: "night_mode_state") ?? String(NSOffState))! - if nightModeItem.state == NSOnState { - let wc = NSApplication.shared().mainWindow!.windowController as? WindowController - wc?.toggle(isNight: true) + let nightModeState = Int(UserDefaults.standard.string(forKey: "night_mode_state") ?? String(NSOffState))! + globalSettings.isNight = nightModeState == NSOnState + if globalSettings.isNight { + // Toggle Night Mode menu item on + toggleNightMode(nightModeItem) } // Set font @@ -64,10 +70,14 @@ class AppDelegate: NSObject, NSApplicationDelegate { } @IBAction func toggleNightMode(_ sender: NSMenuItem) { - let wc = NSApplication.shared().mainWindow!.windowController as? WindowController let isOff = sender.state == NSOffState - wc?.toggle(isNight: isOff) + + for w in NSApplication.shared().windows { + let wc = w.windowController as? WindowController + wc?.toggle(isNight: isOff) + } sender.state = isOff ? NSOnState : NSOffState + globalSettings.isNight = isOff UserDefaults.standard.set(String(sender.state), forKey: "night_mode_state") } diff --git a/writeas/WindowController.swift b/writeas/WindowController.swift index 18ec929..ee79ee5 100644 --- a/writeas/WindowController.swift +++ b/writeas/WindowController.swift @@ -18,6 +18,10 @@ class WindowController: NSWindowController { super.windowDidLoad() vc = (self.window?.contentViewController)! as! ViewController + let delegate = NSApplication.shared().delegate as! AppDelegate + + // Set night mode state + vc?.toggle(isNight: delegate.globalSettings.isNight) } func toggle(isNight: Bool) {