You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

303 lines
11 KiB

// Copyright © 2015 Abhishek Banthia
import Cocoa
import CoreLoggerKit
import CoreModelKit
5 years ago
open class AppDelegate: NSObject, NSApplicationDelegate {
5 years ago
private lazy var floatingWindow: FloatingWindowController = FloatingWindowController.shared()
private lazy var panelController: PanelController = PanelController.shared()
private var statusBarHandler: StatusItemHandler!
private var panelObserver: NSKeyValueObservation?
5 years ago
deinit {
panelObserver?.invalidate()
}
5 years ago
5 years ago
open override func observeValue(forKeyPath keyPath: String?, of object: Any?, change _: [NSKeyValueChangeKey: Any]?, context _: UnsafeMutableRawPointer?) {
if let path = keyPath, path == PreferencesConstants.hotKeyPathIdentifier {
let hotKeyCenter = PTHotKeyCenter.shared()
5 years ago
// Unregister old hot key
let oldHotKey = hotKeyCenter?.hotKey(withIdentifier: path)
hotKeyCenter?.unregisterHotKey(oldHotKey)
5 years ago
// We don't register unless there's a valid key combination
guard let newObject = object as? NSObject, let newShortcut = newObject.value(forKeyPath: path) as? [AnyHashable: Any] else {
return
}
5 years ago
// Register new key
let newHotKey: PTHotKey = PTHotKey(identifier: keyPath,
keyCombo: newShortcut,
target: self,
action: #selector(ping(_:)))
5 years ago
hotKeyCenter?.register(newHotKey)
}
}
5 years ago
5 years ago
public func applicationWillFinishLaunching(_: Notification) {
iVersion.sharedInstance().useAllAvailableLanguages = true
iVersion.sharedInstance().verboseLogging = false
}
5 years ago
5 years ago
public func applicationDidFinishLaunching(_: Notification) {
// Initializing the event store takes really long
EventCenter.sharedCenter()
5 years ago
// Required for migrating our model type to CoreModelKit
NSKeyedUnarchiver.setClass(CoreModelKit.TimezoneData.classForKeyedUnarchiver(), forClassName: "Clocker.TimezoneData")
4 years ago
AppDefaults.initialize()
4 years ago
// For users, still on the old timezones, only migrate timezonezes once setClass has been called
migrateOverridenTimezones()
// Check if we can show the onboarding flow!
showOnboardingFlowIfEligible()
5 years ago
// Ratings Controller initialization
ReviewController.applicationDidLaunch(UserDefaults.standard)
#if RELEASE
Fabric.with([Crashlytics.self])
checkIfRunFromApplicationsFolder()
#endif
}
5 years ago
private func migrateOverridenTimezones() {
let defaults = UserDefaults.standard
if let shortCircuit = defaults.object(forKey: "MigrateIndividualTimezoneFormat") as? Bool, shortCircuit == true {
return
}
let timezones = DataStore.shared().timezones()
var migratedTimezones: [Data] = []
for encodedTimezone in timezones {
if let timezoneObject = TimezoneData.customObject(from: encodedTimezone) {
timezoneObject.setShouldOverrideGlobalTimeFormat(0)
migratedTimezones.append(NSKeyedArchiver.archivedData(withRootObject: timezoneObject))
}
}
if migratedTimezones.count > 0 {
defaults.set(migratedTimezones, forKey: CLDefaultPreferenceKey)
defaults.set(true, forKey: "MigrateIndividualTimezoneFormat")
}
}
5 years ago
public func applicationDockMenu(_: NSApplication) -> NSMenu? {
let menu = NSMenu(title: "Quick Access")
5 years ago
let toggleMenuItem = NSMenuItem(title: "Toggle Panel", action: #selector(AppDelegate.togglePanel(_:)), keyEquivalent: "")
let openPreferences = NSMenuItem(title: "Preferences", action: #selector(AppDelegate.openPreferencesWindow), keyEquivalent: ",")
let hideFromDockMenuItem = NSMenuItem(title: "Hide from Dock", action: #selector(AppDelegate.hideFromDock), keyEquivalent: "")
5 years ago
[toggleMenuItem, openPreferences, hideFromDockMenuItem].forEach {
$0.isEnabled = true
menu.addItem($0)
}
5 years ago
return menu
}
5 years ago
@objc private func openPreferencesWindow() {
let displayMode = UserDefaults.standard.integer(forKey: CLShowAppInForeground)
5 years ago
if displayMode == 1 {
let floatingWindow = FloatingWindowController.shared()
floatingWindow.openPreferences(NSButton())
} else {
let panelController = PanelController.shared()
panelController.openPreferences(NSButton())
}
}
5 years ago
@objc func hideFromDock() {
4 years ago
UserDefaults.standard.set(0, forKey: CLAppDisplayOptions)
NSApp.setActivationPolicy(.accessory)
}
private lazy var controller: OnboardingController? = {
5 years ago
let onboardingStoryboard = NSStoryboard(name: NSStoryboard.Name("Onboarding"), bundle: nil)
return onboardingStoryboard.instantiateController(withIdentifier: NSStoryboard.SceneIdentifier("onboardingFlow")) as? OnboardingController
}()
private func showOnboardingFlowIfEligible() {
5 years ago
let shouldLaunchOnboarding = (DataStore.shared().retrieve(key: CLShowOnboardingFlow) == nil && DataStore.shared().timezones().isEmpty)
5 years ago
|| ProcessInfo.processInfo.arguments.contains(CLOnboaringTestsLaunchArgument)
5 years ago
4 years ago
shouldLaunchOnboarding ? controller?.launch() : continueUsually()
}
5 years ago
func continueUsually() {
// Check if another instance of the app is already running. If so, then stop this one.
checkIfAppIsAlreadyOpen()
5 years ago
// Install the menubar item!
statusBarHandler = StatusItemHandler()
5 years ago
if ProcessInfo.processInfo.arguments.contains(CLUITestingLaunchArgument) {
ReviewController.setPreviewMode(true)
}
5 years ago
UserDefaults.standard.register(defaults: ["NSApplicationCrashOnExceptions": true])
5 years ago
assignShortcut()
5 years ago
5 years ago
panelObserver = panelController.observe(\.hasActivePanel, options: [.new]) { obj, _ in
self.statusBarHandler.setHasActiveIcon(obj.hasActivePanelGetter())
}
5 years ago
let defaults = UserDefaults.standard
5 years ago
setActivationPolicy()
5 years ago
// Set the display mode default as panel!
if let displayMode = defaults.object(forKey: CLShowAppInForeground) as? NSNumber, displayMode.intValue == 1 {
showFloatingWindow()
} else if let displayMode = defaults.object(forKey: CLShowAppInForeground) as? Int, displayMode == 1 {
showFloatingWindow()
}
}
5 years ago
// Should we have a dock icon or just stay in the menubar?
private func setActivationPolicy() {
let defaults = UserDefaults.standard
5 years ago
let currentActivationPolicy = NSRunningApplication.current.activationPolicy
4 years ago
let activationPolicy: NSApplication.ActivationPolicy = defaults.integer(forKey: CLAppDisplayOptions) == 0 ? .accessory : .regular
if currentActivationPolicy != activationPolicy {
NSApp.setActivationPolicy(activationPolicy)
}
}
5 years ago
private func checkIfAppIsAlreadyOpen() {
guard let bundleID = Bundle.main.bundleIdentifier else {
5 years ago
return
}
5 years ago
let apps = NSRunningApplication.runningApplications(withBundleIdentifier: bundleID)
5 years ago
if apps.count > 1 {
let currentApplication = NSRunningApplication.current
for app in apps where app != currentApplication {
app.terminate()
}
}
}
5 years ago
private func showAppAlreadyOpenMessage() {
showAlert(message: "An instance of Clocker is already open 😅",
informativeText: "This instance of Clocker will terminate now.",
buttonTitle: "Close")
}
5 years ago
private func showAlert(message: String, informativeText: String, buttonTitle: String) {
NSApplication.shared.activate(ignoringOtherApps: true)
let alert = NSAlert()
alert.messageText = message
alert.informativeText = informativeText
alert.addButton(withTitle: buttonTitle)
alert.runModal()
}
5 years ago
@IBAction func ping(_ sender: Any) {
togglePanel(sender)
}
private func retrieveLatestLocation() {
let locationController = LocationController.sharedController()
locationController.determineAndRequestLocationAuthorization()
}
5 years ago
private func showFloatingWindow() {
// Display the Floating Window!
floatingWindow.showWindow(nil)
floatingWindow.updateTableContent()
floatingWindow.startWindowTimer()
5 years ago
NSApp.activate(ignoringOtherApps: true)
}
5 years ago
private func assignShortcut() {
NSUserDefaultsController.shared.addObserver(self,
forKeyPath: PreferencesConstants.hotKeyPathIdentifier,
5 years ago
options: [.initial, .new],
context: nil)
}
5 years ago
private func checkIfRunFromApplicationsFolder() {
if let shortCircuit = UserDefaults.standard.object(forKey: "AllowOutsideApplicationsFolder") as? Bool, shortCircuit == true {
return
}
5 years ago
let bundlePath = Bundle.main.bundlePath
let applicationDirectory = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.applicationDirectory,
FileManager.SearchPathDomainMask.localDomainMask,
true)
for appDir in applicationDirectory {
if bundlePath.hasPrefix(appDir) {
return
}
}
5 years ago
5 years ago
let informativeText = """
5 years ago
Clocker must be run from the Applications folder in order to work properly.
Please quit Clocker, move it to the Applications folder, and relaunch.
Current folder: \(applicationDirectory)"
"""
5 years ago
// Clocker is installed out of Applications directory
// This breaks start at login! Time to show an alert and terminate
showAlert(message: "Move Clocker to the Applications folder",
5 years ago
informativeText: informativeText,
buttonTitle: "Quit")
5 years ago
// Terminate
NSApp.terminate(nil)
}
5 years ago
5 years ago
@IBAction open func togglePanel(_: Any) {
let displayMode = UserDefaults.standard.integer(forKey: CLShowAppInForeground)
5 years ago
if displayMode == 1 {
floatingWindow.showWindow(nil)
floatingWindow.updateTableContent()
floatingWindow.startWindowTimer()
} else {
panelController.showWindow(nil)
panelController.setActivePanel(newValue: !panelController.hasActivePanelGetter())
}
NSApp.activate(ignoringOtherApps: true)
}
open func setupFloatingWindow() {
showFloatingWindow()
}
5 years ago
open func closeFloatingWindow() {
floatingWindow.window?.close()
}
5 years ago
func statusItemForPanel() -> StatusItemHandler {
return statusBarHandler
}
5 years ago
open func setPanelDefaults() {
panelController.updateDefaultPreferences()
}
5 years ago
open func setupMenubarTimer() {
statusBarHandler.setupStatusItem()
}
5 years ago
open func invalidateMenubarTimer(_ showIcon: Bool) {
statusBarHandler.invalidateTimer(showIcon: showIcon, isSyncing: true)
}
}