tokenary/Tokenary macOS/Window.swift

84 lines
2.8 KiB
Swift
Raw Normal View History

2021-11-30 15:56:00 +03:00
// Copyright © 2021 Tokenary. All rights reserved.
2021-06-12 19:33:24 +03:00
import Cocoa
struct Window {
2021-06-13 05:45:54 +03:00
static func showNew() -> NSWindowController {
closeAll()
let windowController = new
activate(windowController)
return windowController
}
static func activate(_ windowController: NSWindowController) {
windowController.showWindow(nil)
2021-06-19 00:31:19 +03:00
activateWindow(windowController.window)
2021-06-13 05:45:54 +03:00
}
2021-06-19 00:31:19 +03:00
static func activateWindow(_ window: NSWindow?) {
NSApp.activate(ignoringOtherApps: true)
2021-06-19 00:31:19 +03:00
window?.makeKeyAndOrderFront(nil)
}
static func closeAllAndActivateBrowser(force browser: Browser?) {
closeAll()
activateBrowser(force: browser)
}
static func closeAll(updateStatusBarItem: Bool = true) {
2021-06-12 19:33:24 +03:00
NSApplication.shared.windows.forEach { $0.close() }
if updateStatusBarItem {
Agent.shared.setupStatusBarItem()
}
2021-06-12 19:33:24 +03:00
}
static func activateBrowser(force browser: Browser?) {
if let browser = browser {
activateBrowser(browser)
return
}
let browsers = NSWorkspace.shared.runningApplications.filter { app in
if let bundleId = app.bundleIdentifier {
return Browser.allBundleIds.contains(bundleId)
} else {
return false
}
}
guard !browsers.isEmpty else { return }
let browsersPids = Set(browsers.map { $0.processIdentifier })
let options = CGWindowListOption(arrayLiteral: [.excludeDesktopElements, .optionOnScreenOnly])
guard let windows = CGWindowListCopyWindowInfo(options, CGWindowID(0)) as? [[String: AnyObject]] else { return }
for window in windows {
if let pid = window[kCGWindowOwnerPID as String] as? pid_t, browsersPids.contains(pid) {
browsers.first(where: { $0.processIdentifier == pid })?.activate(options: .activateIgnoringOtherApps)
2021-06-16 20:09:30 +03:00
return
}
2021-06-12 19:33:24 +03:00
}
}
private static func activateBrowser(_ browser: Browser) {
NSWorkspace.shared.runningApplications.first(where: { $0.bundleIdentifier == browser.rawValue })?.activate(options: .activateIgnoringOtherApps)
}
2021-06-13 05:45:54 +03:00
static var current: NSWindowController? {
return NSApplication.shared.windows.first?.windowController
}
static var new: NSWindowController {
return NSStoryboard.main.instantiateController(withIdentifier: "initial") as! NSWindowController
2021-06-13 05:45:54 +03:00
}
}
extension NSStoryboard {
static let main = NSStoryboard(name: "Main", bundle: nil)
}
func instantiate<ViewController: NSViewController>(_ type: ViewController.Type) -> ViewController {
return NSStoryboard.main.instantiateController(withIdentifier: String(describing: type)) as! ViewController
2021-06-12 19:33:24 +03:00
}