|
| 1 | +// |
| 2 | +// AppDelegate.swift |
| 3 | +// Song Rating Helper |
| 4 | +// |
| 5 | +// Created by Cirno MainasuK on 2019-10-26. |
| 6 | +// Copyright © 2019 Cirno MainasuK. All rights reserved. |
| 7 | +// |
| 8 | + |
| 9 | +import Cocoa |
| 10 | +import os |
| 11 | + |
| 12 | +// Ref: https://developer.apple.com/library/archive/documentation/Security/Conceptual/AppSandboxDesignGuide/DesigningYourSandbox/DesigningYourSandbox.html#//apple_ref/doc/uid/TP40011183-CH4-SW3 |
| 13 | +// https://developer.apple.com/library/archive/documentation/MacOSX/Conceptual/BPSystemStartup/Chapters/CreatingLoginItems.html#//apple_ref/doc/uid/10000172i-SW5-SW1 |
| 14 | +// https://products.delitestudio.com/start-dockless-apps-at-login-with-app-sandbox-enabled/ |
| 15 | + |
| 16 | +@NSApplicationMain |
| 17 | +class AppDelegate: NSObject, NSApplicationDelegate { |
| 18 | + |
| 19 | + func applicationDidFinishLaunching(_ aNotification: Notification) { |
| 20 | + |
| 21 | + let mainAppIdentifier = "com.mainasuk.Song-Rating" |
| 22 | + let runningApps = NSWorkspace.shared.runningApplications |
| 23 | + let isRunning = runningApps.contains(where: { $0.bundleIdentifier == mainAppIdentifier }) |
| 24 | + |
| 25 | + guard !isRunning else { |
| 26 | + os_log("%{public}s[%{public}ld], %{public}s: Main app isRunning. Helper exit", ((#file as NSString).lastPathComponent), #line, #function) |
| 27 | + terminate() |
| 28 | + return |
| 29 | + } |
| 30 | + |
| 31 | + DistributedNotificationCenter.default().addObserver(self, selector: #selector(AppDelegate.terminate), name: .killLauncher, object: mainAppIdentifier) |
| 32 | + |
| 33 | + let path = Bundle.main.bundlePath as NSString |
| 34 | + var components = path.pathComponents |
| 35 | + components.removeLast() |
| 36 | + components.removeLast() |
| 37 | + components.removeLast() |
| 38 | + components.append("MacOS") |
| 39 | + components.append("Song Rating") |
| 40 | + |
| 41 | + let newPath = NSString.path(withComponents: components) |
| 42 | + |
| 43 | + os_log("%{public}s[%{public}ld], %{public}s: launch %{public}s", ((#file as NSString).lastPathComponent), #line, #function, newPath) |
| 44 | + NSWorkspace.shared.launchApplication(newPath) |
| 45 | + } |
| 46 | + |
| 47 | +} |
| 48 | + |
| 49 | +extension AppDelegate { |
| 50 | + |
| 51 | + @objc private func terminate() { |
| 52 | +// os_log("%{public}s[%{public}ld], %{public}s: exit", ((#file as NSString).lastPathComponent), #line, #function) |
| 53 | + NSApp.terminate(nil) |
| 54 | + } |
| 55 | + |
| 56 | +} |
| 57 | + |
0 commit comments