refactor: use static vars/funcs as much as possible
This commit is contained in:
1 parent
5ce48c18e6
commit
db34a7eb8f
40 files changed
+500
-468
No files matched your search
@@ -48,21 +48,21 @@ class ATShortcut {
|
||||
return modifiersCleaned == (modifiersCleaned | shortcutModifiersCleaned)
|
||||
}
|
||||
// other shortcuts: contains exactly or exactly + holdShortcut modifiers
|
||||
let holdModifiersCleaned = ControlsTab.shortcuts[Preferences.indexToName("holdShortcut", App.app.shortcutIndex)]?.shortcut.carbonModifierFlags.cleaned() ?? 0
|
||||
let holdModifiersCleaned = ControlsTab.shortcuts[Preferences.indexToName("holdShortcut", App.shortcutIndex)]?.shortcut.carbonModifierFlags.cleaned() ?? 0
|
||||
return modifiersCleaned == shortcutModifiersCleaned || modifiersCleaned == (shortcutModifiersCleaned | holdModifiersCleaned)
|
||||
}
|
||||
|
||||
func shouldTrigger() -> Bool {
|
||||
if scope == .global {
|
||||
if triggerPhase == .down && (!App.app.appIsBeingUsed || index == nil || index == App.app.shortcutIndex) {
|
||||
if triggerPhase == .down && (!App.appIsBeingUsed || index == nil || index == App.shortcutIndex) {
|
||||
return true
|
||||
}
|
||||
if triggerPhase == .up && App.app.appIsBeingUsed && (index == nil || index == App.app.shortcutIndex) && !App.app.forceDoNothingOnRelease && Preferences.shortcutStyle == .focusOnRelease {
|
||||
if triggerPhase == .up && App.appIsBeingUsed && (index == nil || index == App.shortcutIndex) && !App.forceDoNothingOnRelease && Preferences.shortcutStyle == .focusOnRelease {
|
||||
return true
|
||||
}
|
||||
}
|
||||
if scope == .local {
|
||||
if App.app.appIsBeingUsed && (index == nil || index == App.app.shortcutIndex) {
|
||||
if App.appIsBeingUsed && (index == nil || index == App.shortcutIndex) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
@@ -83,8 +83,8 @@ class ATShortcut {
|
||||
// Another issue is events being dropped by macOS, which we never receive
|
||||
// Knowing this, we handle these edge-cases by double checking if holdShortcut is UP, when any shortcut state is UP
|
||||
// If it is, then we trigger the holdShortcut action
|
||||
if App.app.appIsBeingUsed && !App.app.forceDoNothingOnRelease && Preferences.shortcutStyle == .focusOnRelease {
|
||||
if let currentHoldShortcut = ControlsTab.shortcuts[Preferences.indexToName("holdShortcut", App.app.shortcutIndex)],
|
||||
if App.appIsBeingUsed && !App.forceDoNothingOnRelease && Preferences.shortcutStyle == .focusOnRelease {
|
||||
if let currentHoldShortcut = ControlsTab.shortcuts[Preferences.indexToName("holdShortcut", App.shortcutIndex)],
|
||||
id == currentHoldShortcut.id {
|
||||
let currentModifiers = cocoaToCarbonFlags(ModifierFlags.current)
|
||||
if currentModifiers != (currentModifiers | (currentHoldShortcut.shortcut.carbonModifierFlags)) {
|
||||
|
||||
@@ -39,7 +39,7 @@ class AppCenterCrash: NSObject {
|
||||
|
||||
func checkIfShouldSend() -> Bool {
|
||||
if Preferences.crashPolicy == .ask {
|
||||
App.app.activate(ignoringOtherApps: true)
|
||||
App.shared.activate(ignoringOtherApps: true)
|
||||
let alert = NSAlert()
|
||||
alert.alertStyle = .warning
|
||||
alert.messageText = NSLocalizedString("Send a crash report?", comment: "")
|
||||
|
||||
@@ -158,7 +158,7 @@ class Application: NSObject {
|
||||
DispatchQueue.main.async { [weak self] in
|
||||
guard let self else { return }
|
||||
if self.addWindowlessWindowIfNeeded() != nil {
|
||||
App.app.refreshOpenUiAfterExternalEvent([])
|
||||
App.refreshOpenUiAfterExternalEvent([])
|
||||
}
|
||||
}
|
||||
// workaround: some apps launch but take a while to create their window(s)
|
||||
@@ -181,7 +181,7 @@ class Application: NSObject {
|
||||
}
|
||||
|
||||
func manuallyUpdateWindow(_ axWindow: AXUIElement, _ wid: CGWindowID) throws {
|
||||
guard wid != 0 && wid != App.app.tilesPanel.windowNumber else { return } // some bogus "windows" have wid 0
|
||||
guard wid != 0 && wid != TilesPanel.shared.windowNumber else { return } // some bogus "windows" have wid 0
|
||||
let level = wid.level()
|
||||
let a = try axWindow.attributes([kAXTitleAttribute, kAXSubroleAttribute, kAXRoleAttribute, kAXSizeAttribute, kAXPositionAttribute, kAXFullscreenAttribute, kAXMinimizedAttribute])
|
||||
DispatchQueue.main.async { [weak self] in
|
||||
@@ -190,7 +190,7 @@ class Application: NSObject {
|
||||
guard let window = findOrCreate.0 else { return }
|
||||
if findOrCreate.1 {
|
||||
Logger.info { "manuallyUpdateWindows found a new window:\(window.debugId)" }
|
||||
App.app.refreshOpenUiAfterExternalEvent([window])
|
||||
App.refreshOpenUiAfterExternalEvent([window])
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -202,14 +202,14 @@ class Application: NSObject {
|
||||
let window = Window(self)
|
||||
Windows.appendWindow(window)
|
||||
focusedWindow = nil
|
||||
App.app.refreshOpenUiAfterExternalEvent([])
|
||||
App.refreshOpenUiAfterExternalEvent([])
|
||||
return window
|
||||
}
|
||||
|
||||
func removeWindowlessAppWindow() {
|
||||
guard let windowlessAppWindow = (Windows.list.first { $0.isWindowlessApp == true && $0.application.pid == pid }) else { return }
|
||||
Windows.removeWindows([windowlessAppWindow], false)
|
||||
App.app.refreshOpenUiAfterExternalEvent([])
|
||||
App.refreshOpenUiAfterExternalEvent([])
|
||||
}
|
||||
|
||||
func hideOrShow() {
|
||||
|
||||
@@ -77,11 +77,11 @@ class Applications {
|
||||
// comparing pid here can fail here, as it can be already nil; we use isEqual here to avoid the issue
|
||||
list.removeAll { $0.runningApplication.isEqual(tApp) }
|
||||
}
|
||||
App.app.refreshOpenUiAfterExternalEvent([])
|
||||
App.refreshOpenUiAfterExternalEvent([])
|
||||
}
|
||||
|
||||
static func refreshBadgesAsync() {
|
||||
guard App.app.appIsBeingUsed && !Preferences.hideAppBadges else { return }
|
||||
guard App.appIsBeingUsed && !Preferences.hideAppBadges else { return }
|
||||
AXUIElement.retryAxCallUntilTimeout(callType: .updateDockBadges) {
|
||||
guard let dockPid = (list.first { $0.bundleIdentifier == "com.apple.dock" }?.pid),
|
||||
let axDockChildren = try AXUIElementCreateApplication(dockPid).attributes([kAXChildrenAttribute]).children,
|
||||
@@ -94,7 +94,7 @@ class Applications {
|
||||
}
|
||||
guard !axAppDockItemUrlAndLabel.isEmpty else { return }
|
||||
DispatchQueue.main.async {
|
||||
guard App.app.appIsBeingUsed && !Preferences.hideAppBadges else { return }
|
||||
guard App.appIsBeingUsed && !Preferences.hideAppBadges else { return }
|
||||
refreshBadges_(axAppDockItemUrlAndLabel)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -27,14 +27,14 @@ final class BenchmarkRunner {
|
||||
private static func scheduleShow(after delay: Int) {
|
||||
guard remainingCycles > 0 else { scheduleTerminate(after: hideDuration); return }
|
||||
DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(delay)) {
|
||||
App.app.showUi(shortcutIndex)
|
||||
App.showUi(shortcutIndex)
|
||||
scheduleHide(after: showDuration)
|
||||
}
|
||||
}
|
||||
|
||||
private static func scheduleHide(after delay: Int) {
|
||||
DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(delay)) {
|
||||
App.app.hideUi()
|
||||
App.hideUi()
|
||||
remainingCycles -= 1
|
||||
scheduleShow(after: hideDuration)
|
||||
}
|
||||
|
||||
@@ -11,15 +11,15 @@ class KeyRepeatTimer {
|
||||
// events already repeat when using a shortcut with a keycode; no need for artificial repeat
|
||||
shortcut.shortcut.keyCode == .none {
|
||||
startTimerForRepeatingKey(shortcut) {
|
||||
App.app.previousWindowShortcutWithRepeatingKey()
|
||||
App.previousWindowShortcutWithRepeatingKey()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static func startRepeatingKeyNextWindow() {
|
||||
if let shortcut = ControlsTab.shortcuts[Preferences.indexToName("nextWindowShortcut", App.app.shortcutIndex)] {
|
||||
if let shortcut = ControlsTab.shortcuts[Preferences.indexToName("nextWindowShortcut", App.shortcutIndex)] {
|
||||
startTimerForRepeatingKey(shortcut) {
|
||||
ControlsTab.executeAction(Preferences.indexToName("nextWindowShortcut", App.app.shortcutIndex))
|
||||
ControlsTab.executeAction(Preferences.indexToName("nextWindowShortcut", App.shortcutIndex))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -34,7 +34,7 @@ class KeyRepeatTimer {
|
||||
}
|
||||
|
||||
private static func isSearchEditing() -> Bool {
|
||||
App.app.appIsBeingUsed && App.app.tilesPanel.isKeyWindow && App.app.tilesPanel.tilesView.isSearchEditing
|
||||
App.appIsBeingUsed && TilesPanel.shared.isKeyWindow && TilesView.isSearchEditing
|
||||
}
|
||||
|
||||
private static func startTimerForRepeatingKey(_ atShortcut: ATShortcut, _ block: @escaping () -> Void) {
|
||||
|
||||
@@ -16,7 +16,7 @@ class SystemPermissions {
|
||||
|
||||
private static func checkPermissionsOnTimer() {
|
||||
AccessibilityPermission.update()
|
||||
let isPermissionsWindowVisible = App.app.permissionsWindow?.isVisible ?? false
|
||||
let isPermissionsWindowVisible = PermissionsWindow.shared?.isVisible ?? false
|
||||
if !preStartupPermissionsPassed || isPermissionsWindowVisible {
|
||||
ScreenRecordingPermission.update()
|
||||
}
|
||||
@@ -33,7 +33,9 @@ class SystemPermissions {
|
||||
}
|
||||
DispatchQueue.main.async {
|
||||
Menubar.togglePermissionCallout(ScreenRecordingPermission.status != .granted)
|
||||
App.app.permissionsWindow?.updatePermissionViews()
|
||||
if PermissionsWindow.shared != nil {
|
||||
PermissionsWindow.updatePermissionViews()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -41,13 +43,13 @@ class SystemPermissions {
|
||||
if AccessibilityPermission.status != .notGranted && ScreenRecordingPermission.status != .notGranted {
|
||||
DispatchQueue.main.async {
|
||||
preStartupPermissionsPassed = true
|
||||
App.app.permissionsWindow?.close()
|
||||
PermissionsWindow.shared?.close()
|
||||
setInfrequentTimer()
|
||||
App.app.continueAppLaunchAfterPermissionsAreGranted()
|
||||
App.continueAppLaunchAfterPermissionsAreGranted()
|
||||
}
|
||||
} else {
|
||||
DispatchQueue.main.async {
|
||||
App.app.showPermissionsWindow()
|
||||
App.showPermissionsWindow()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -55,7 +57,7 @@ class SystemPermissions {
|
||||
private static func checkPermissionsPostStartup() {
|
||||
if AccessibilityPermission.status == .notGranted {
|
||||
Logger.error { "Accessibility permission revoked while AltTab was running; restarting" }
|
||||
DispatchQueue.main.async { App.app.restart() }
|
||||
DispatchQueue.main.async { App.restart() }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -108,7 +108,7 @@ class Window {
|
||||
|
||||
func refreshThumbnail(_ screenshot: CALayerContents) {
|
||||
thumbnail = screenshot
|
||||
if !App.app.appIsBeingUsed || !shouldShowTheUser { return }
|
||||
if !App.appIsBeingUsed || !shouldShowTheUser { return }
|
||||
if let position, let size,
|
||||
let view = (TilesView.recycledViews.first { $0.window_?.cgWindowId == cgWindowId }) {
|
||||
if !view.thumbnail.isHidden {
|
||||
@@ -117,10 +117,10 @@ class Window {
|
||||
view.thumbnail.updateContents(screenshot, thumbnailSize)
|
||||
// if the thumbnail size has changed, we need to refresh the open UI
|
||||
if newSize {
|
||||
App.app.refreshOpenUiAfterExternalEvent([])
|
||||
App.refreshOpenUiAfterExternalEvent([])
|
||||
}
|
||||
}
|
||||
App.app.previewPanel.updateIfShowing(cgWindowId, screenshot, position, size)
|
||||
PreviewPanel.updateIfShowing(cgWindowId, screenshot, position, size)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -312,7 +312,7 @@ class Window {
|
||||
|
||||
private func altTabWindow() -> NSWindow? {
|
||||
if application.bundleURL == App.bundleURL, let cgWindowId {
|
||||
return App.app.window(withWindowNumber: Int(cgWindowId))
|
||||
return App.shared.window(withWindowNumber: Int(cgWindowId))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
+28
-28
@@ -20,7 +20,7 @@ class Windows {
|
||||
let previousTrimmedQuery = Search.normalizedQuery(searchQuery)
|
||||
let newTrimmedQuery = Search.normalizedQuery(query)
|
||||
searchQuery = query
|
||||
guard App.app.appIsBeingUsed else {
|
||||
guard App.appIsBeingUsed else {
|
||||
shouldSelectBestMatchOnSearchChange = false
|
||||
shouldRestoreDefaultSelectionOnSearchClear = false
|
||||
sort()
|
||||
@@ -60,31 +60,31 @@ class Windows {
|
||||
}
|
||||
|
||||
static func voiceOverWindow(_ windowIndex: Int = selectedWindowIndex) {
|
||||
guard App.app.appIsBeingUsed && App.app.tilesPanel.isKeyWindow else { return }
|
||||
if App.app.tilesPanel.tilesView.isSearchEditing { return }
|
||||
guard App.appIsBeingUsed && TilesPanel.shared.isKeyWindow else { return }
|
||||
if TilesView.isSearchEditing { return }
|
||||
// it seems that sometimes makeFirstResponder is called before the view is visible
|
||||
// and it creates a delay in showing the main window; calling it with some delay seems to work around this
|
||||
DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(10)) {
|
||||
if App.app.tilesPanel.tilesView.isSearchEditing { return }
|
||||
if TilesView.isSearchEditing { return }
|
||||
let window = TilesView.recycledViews[windowIndex]
|
||||
if window.window_ != nil && window.window != nil {
|
||||
App.app.tilesPanel.makeFirstResponder(window)
|
||||
TilesPanel.shared.makeFirstResponder(window)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static func previewSelectedWindowIfNeeded() {
|
||||
if App.app.appIsBeingUsed && ScreenRecordingPermission.status == .granted
|
||||
if App.appIsBeingUsed && ScreenRecordingPermission.status == .granted
|
||||
&& Preferences.previewSelectedWindow && !Preferences.onlyShowApplications()
|
||||
&& App.app.tilesPanel.isKeyWindow,
|
||||
&& TilesPanel.shared.isKeyWindow,
|
||||
let window = selectedWindow(),
|
||||
let id = window.cgWindowId,
|
||||
let thumbnail = window.thumbnail,
|
||||
let position = window.position,
|
||||
let size = window.size {
|
||||
App.app.previewPanel.show(id, thumbnail, position, size)
|
||||
PreviewPanel.show(id, thumbnail, position, size)
|
||||
} else {
|
||||
App.app.previewPanel.orderOut(nil)
|
||||
PreviewPanel.shared.orderOut(nil)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -186,16 +186,16 @@ class Windows {
|
||||
id.hasPrefix($0.bundleIdentifier) && shouldHideWindow(window, $0)
|
||||
}
|
||||
} ?? false) &&
|
||||
!(Preferences.appsToShow[App.app.shortcutIndex] == .active && window.application.pid != Applications.frontmostPid) &&
|
||||
!(Preferences.appsToShow[App.app.shortcutIndex] == .nonActive && window.application.pid == Applications.frontmostPid) &&
|
||||
!(!(Preferences.showHiddenWindows[App.app.shortcutIndex] != .hide) && window.isHidden) &&
|
||||
((Preferences.showWindowlessApps[App.app.shortcutIndex] != .hide && window.isWindowlessApp) ||
|
||||
!(Preferences.appsToShow[App.shortcutIndex] == .active && window.application.pid != Applications.frontmostPid) &&
|
||||
!(Preferences.appsToShow[App.shortcutIndex] == .nonActive && window.application.pid == Applications.frontmostPid) &&
|
||||
!(!(Preferences.showHiddenWindows[App.shortcutIndex] != .hide) && window.isHidden) &&
|
||||
((Preferences.showWindowlessApps[App.shortcutIndex] != .hide && window.isWindowlessApp) ||
|
||||
!window.isWindowlessApp &&
|
||||
!(!(Preferences.showFullscreenWindows[App.app.shortcutIndex] != .hide) && window.isFullscreen) &&
|
||||
!(!(Preferences.showMinimizedWindows[App.app.shortcutIndex] != .hide) && window.isMinimized) &&
|
||||
!(Preferences.spacesToShow[App.app.shortcutIndex] == .visible && !Spaces.visibleSpaces.contains { visibleSpace in window.spaceIds.contains { $0 == visibleSpace } }) &&
|
||||
!(Preferences.spacesToShow[App.app.shortcutIndex] == .nonVisible && Spaces.visibleSpaces.contains { visibleSpace in window.spaceIds.contains { $0 == visibleSpace } }) &&
|
||||
!(Preferences.screensToShow[App.app.shortcutIndex] == .showingAltTab && !window.isOnScreen(NSScreen.preferred)) &&
|
||||
!(!(Preferences.showFullscreenWindows[App.shortcutIndex] != .hide) && window.isFullscreen) &&
|
||||
!(!(Preferences.showMinimizedWindows[App.shortcutIndex] != .hide) && window.isMinimized) &&
|
||||
!(Preferences.spacesToShow[App.shortcutIndex] == .visible && !Spaces.visibleSpaces.contains { visibleSpace in window.spaceIds.contains { $0 == visibleSpace } }) &&
|
||||
!(Preferences.spacesToShow[App.shortcutIndex] == .nonVisible && Spaces.visibleSpaces.contains { visibleSpace in window.spaceIds.contains { $0 == visibleSpace } }) &&
|
||||
!(Preferences.screensToShow[App.shortcutIndex] == .showingAltTab && !window.isOnScreen(NSScreen.preferred)) &&
|
||||
(Preferences.showTabsAsWindows || !window.isTabbed))
|
||||
}
|
||||
|
||||
@@ -246,7 +246,7 @@ class Windows {
|
||||
}
|
||||
if let frontmostPid = Applications.frontmostPid,
|
||||
let frontmostApp = Applications.findOrCreate(frontmostPid, false),
|
||||
(frontmostApp.focusedWindow == nil || Preferences.windowOrder[App.app.shortcutIndex] != .recentlyFocused),
|
||||
(frontmostApp.focusedWindow == nil || Preferences.windowOrder[App.shortcutIndex] != .recentlyFocused),
|
||||
let lastFocusedOrderWindowIndex = getLastFocusedOrderWindowIndex() {
|
||||
updateSelectedAndHoveredWindowIndex(lastFocusedOrderWindowIndex)
|
||||
} else {
|
||||
@@ -302,7 +302,7 @@ class Windows {
|
||||
}
|
||||
|
||||
private static func focusedWindowChangedWhileShowing(_ focusedWindowTarget: String?) -> Bool {
|
||||
guard App.app.appIsBeingUsed, Search.normalizedQuery(searchQuery).isEmpty else { return false }
|
||||
guard App.appIsBeingUsed, Search.normalizedQuery(searchQuery).isEmpty else { return false }
|
||||
guard let lastFocusedWindowTarget, let focusedWindowTarget else { return false }
|
||||
return focusedWindowTarget != lastFocusedWindowTarget
|
||||
}
|
||||
@@ -347,7 +347,7 @@ class Windows {
|
||||
lastWindowActivityType = .hover
|
||||
}
|
||||
if !fromMouse {
|
||||
App.app.tilesPanel.tilesView.thumbnailOverView.resetHoveredWindow()
|
||||
TilesView.thumbnailOverView.resetHoveredWindow()
|
||||
}
|
||||
if (!fromMouse || Preferences.mouseHoverEnabled)
|
||||
&& (newIndex != selectedWindowIndex || lastWindowActivityType == .hover) {
|
||||
@@ -362,12 +362,12 @@ class Windows {
|
||||
guard let index else { return }
|
||||
TilesView.highlight(index)
|
||||
let focusedView = TilesView.recycledViews[index]
|
||||
App.app.tilesPanel.tilesView.scrollView.contentView.scrollToVisible(focusedView.frame)
|
||||
TilesView.scrollView.contentView.scrollToVisible(focusedView.frame)
|
||||
voiceOverWindow(index)
|
||||
}
|
||||
|
||||
static func cycleSelectedWindowIndex(_ step: Int, allowWrap: Bool = true) {
|
||||
guard App.app.appIsBeingUsed else { return }
|
||||
guard App.appIsBeingUsed else { return }
|
||||
guard list.contains(where: { shouldDisplay($0) }) else { return }
|
||||
let nextIndex = selectedWindowIndexAfterCycling(step)
|
||||
// don't wrap-around at the end, if key-repeat
|
||||
@@ -428,17 +428,17 @@ class Windows {
|
||||
return $0.lastFocusOrder < $1.lastFocusOrder
|
||||
}
|
||||
// separate buckets for these types of windows
|
||||
if Preferences.showWindowlessApps[App.app.shortcutIndex] == .showAtTheEnd && $0.isWindowlessApp != $1.isWindowlessApp {
|
||||
if Preferences.showWindowlessApps[App.shortcutIndex] == .showAtTheEnd && $0.isWindowlessApp != $1.isWindowlessApp {
|
||||
return $1.isWindowlessApp
|
||||
}
|
||||
if Preferences.showHiddenWindows[App.app.shortcutIndex] == .showAtTheEnd && $0.isHidden != $1.isHidden {
|
||||
if Preferences.showHiddenWindows[App.shortcutIndex] == .showAtTheEnd && $0.isHidden != $1.isHidden {
|
||||
return $1.isHidden
|
||||
}
|
||||
if Preferences.showMinimizedWindows[App.app.shortcutIndex] == .showAtTheEnd && $0.isMinimized != $1.isMinimized {
|
||||
if Preferences.showMinimizedWindows[App.shortcutIndex] == .showAtTheEnd && $0.isMinimized != $1.isMinimized {
|
||||
return $1.isMinimized
|
||||
}
|
||||
// sort within each buckets
|
||||
let sortType = Preferences.windowOrder[App.app.shortcutIndex]
|
||||
let sortType = Preferences.windowOrder[App.shortcutIndex]
|
||||
if sortType == .recentlyFocused {
|
||||
return $0.lastFocusOrder < $1.lastFocusOrder
|
||||
}
|
||||
@@ -533,7 +533,7 @@ class Windows {
|
||||
if addWindowlessWindowIfNeeded {
|
||||
windows.forEach { $0.application.addWindowlessWindowIfNeeded() }
|
||||
}
|
||||
App.app.refreshOpenUiAfterExternalEvent([], windowRemoved: true)
|
||||
App.refreshOpenUiAfterExternalEvent([], windowRemoved: true)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -51,10 +51,10 @@ class AccessibilityEvents {
|
||||
try handleEventWindow(kAXFocusedWindowChangedNotification, wid, pid, appFocusedWindow)
|
||||
}
|
||||
} else {
|
||||
App.app.checkIfShortcutsShouldBeDisabled(nil, app)
|
||||
App.checkIfShortcutsShouldBeDisabled(nil, app)
|
||||
if let windowless = (Windows.list.first { $0.isWindowlessApp && $0.application.pid == pid }) {
|
||||
if let windows = Windows.updateLastFocusOrder(windowless) {
|
||||
App.app.refreshOpenUiAfterExternalEvent(windows)
|
||||
App.refreshOpenUiAfterExternalEvent(windows)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -69,13 +69,13 @@ class AccessibilityEvents {
|
||||
// if we process the "shown" event too fast, the window won't be listed by CGSCopyWindowsWithOptionsAndTags
|
||||
// it will thus be detected as isTabbed. We add a delay to work around this scenario
|
||||
DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(200)) {
|
||||
App.app.refreshOpenUiAfterExternalEvent(windows)
|
||||
App.refreshOpenUiAfterExternalEvent(windows)
|
||||
}
|
||||
}
|
||||
|
||||
static func handleEventWindow(_ type: String, _ wid: CGWindowID, _ pid: pid_t, _ element: AXUIElement) throws {
|
||||
guard wid != 0 || type == kAXUIElementDestroyedNotification,
|
||||
wid != App.app.tilesPanel.windowNumber else { return } // don't process events for the thumbnails panel
|
||||
wid != TilesPanel.shared.windowNumber else { return } // don't process events for the thumbnails panel
|
||||
let level = wid.level()
|
||||
let a = try element.attributes([kAXTitleAttribute, kAXSubroleAttribute, kAXRoleAttribute, kAXSizeAttribute, kAXPositionAttribute, kAXFullscreenAttribute, kAXMinimizedAttribute])
|
||||
DispatchQueue.main.async {
|
||||
@@ -95,14 +95,14 @@ class AccessibilityEvents {
|
||||
}
|
||||
Logger.debug { "\(type) win:\(window.debugId)" }
|
||||
if findOrCreate.1 {
|
||||
App.app.refreshOpenUiAfterExternalEvent([window])
|
||||
App.refreshOpenUiAfterExternalEvent([window])
|
||||
}
|
||||
if type == kAXMainWindowChangedNotification || type == kAXFocusedWindowChangedNotification {
|
||||
focusedWindowChanged(window)
|
||||
} else if type == kAXWindowResizedNotification || type == kAXWindowMovedNotification {
|
||||
windowResizedOrMoved(window)
|
||||
} else if !findOrCreate.1 {
|
||||
App.app.refreshOpenUiAfterExternalEvent([window])
|
||||
App.refreshOpenUiAfterExternalEvent([window])
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -120,14 +120,14 @@ class AccessibilityEvents {
|
||||
// if the window is shown by alt-tab, we mark it as focused for this app
|
||||
// this avoids issues with dialogs, quicklook, etc (see scenarios from #1044 and #2003)
|
||||
window.application.focusedWindow = window
|
||||
App.app.checkIfShortcutsShouldBeDisabled(window, nil)
|
||||
App.checkIfShortcutsShouldBeDisabled(window, nil)
|
||||
if let windows = Windows.updateLastFocusOrder(window) {
|
||||
App.app.refreshOpenUiAfterExternalEvent(windows)
|
||||
App.refreshOpenUiAfterExternalEvent(windows)
|
||||
}
|
||||
}
|
||||
|
||||
private static func windowResizedOrMoved(_ window: Window) {
|
||||
window.updateSpacesAndScreen()
|
||||
App.app.refreshOpenUiAfterExternalEvent([window])
|
||||
App.refreshOpenUiAfterExternalEvent([window])
|
||||
}
|
||||
}
|
||||
@@ -85,7 +85,7 @@ class CliServer {
|
||||
}
|
||||
if rawValue.hasPrefix("--show="),
|
||||
let shortcutIndex = Int(rawValue.dropFirst("--show=".count)), (0..<Preferences.shortcutCount).contains(shortcutIndex) {
|
||||
App.app.showUi(shortcutIndex)
|
||||
App.showUi(shortcutIndex)
|
||||
return noOutput
|
||||
}
|
||||
return error
|
||||
|
||||
@@ -41,7 +41,7 @@ class CursorEvents {
|
||||
// we run on main-thread directly since all we do is check NSEvent and UI coordinates, which we must do on main-thread
|
||||
CFRunLoopAddSource(CFRunLoopGetMain(), runLoopSource, .commonModes)
|
||||
} else {
|
||||
App.app.restart()
|
||||
App.restart()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -81,7 +81,7 @@ class CursorEvents {
|
||||
return Unmanaged.passUnretained(cgEvent)
|
||||
}
|
||||
guard isPointerInsideUi() else {
|
||||
App.app.hideUi()
|
||||
App.hideUi()
|
||||
return nil
|
||||
}
|
||||
if let button = mouseDownButton {
|
||||
@@ -117,21 +117,21 @@ class CursorEvents {
|
||||
private static func handleMouseMoved(_ cgEvent: CGEvent) -> Unmanaged<CGEvent>? {
|
||||
updateDeadzoneSituation(cgEvent)
|
||||
if isAllowedToMouseHover {
|
||||
App.app.tilesPanel.tilesView.thumbnailOverView.updateHover()
|
||||
TilesView.thumbnailOverView.updateHover()
|
||||
}
|
||||
return Unmanaged.passUnretained(cgEvent)
|
||||
}
|
||||
|
||||
private static func pointerLocationInWindow() -> NSPoint {
|
||||
App.app.tilesPanel.mouseLocationOutsideOfEventStream
|
||||
TilesPanel.shared.mouseLocationOutsideOfEventStream
|
||||
}
|
||||
|
||||
private static func isPointerInsideUi() -> Bool {
|
||||
App.app.tilesPanel.contentLayoutRect.contains(pointerLocationInWindow())
|
||||
TilesPanel.shared.contentLayoutRect.contains(pointerLocationInWindow())
|
||||
}
|
||||
|
||||
private static func isPointerInsideSearchField() -> Bool {
|
||||
let searchField = App.app.tilesPanel.tilesView.searchField
|
||||
let searchField = TilesView.searchField
|
||||
if searchField.isHidden { return false }
|
||||
let point = searchField.convert(pointerLocationInWindow(), from: nil)
|
||||
return searchField.bounds.contains(point)
|
||||
@@ -142,7 +142,7 @@ class CursorEvents {
|
||||
}
|
||||
|
||||
private static func pointerInOverlay() -> (TileOverView, NSPoint) {
|
||||
let overlay = App.app.tilesPanel.tilesView.thumbnailOverView
|
||||
let overlay = TilesView.thumbnailOverView
|
||||
return (overlay, overlay.convert(pointerLocationInWindow(), from: nil))
|
||||
}
|
||||
|
||||
|
||||
@@ -14,7 +14,7 @@ class KeyboardEvents {
|
||||
private static let cgEventFlagsChangedHandler: CGEventTapCallBack = { _, type, cgEvent, _ in
|
||||
if type == .flagsChanged {
|
||||
// TODO: it would be great to shortcut matching and trigger on the background thread
|
||||
// it would enable us to set App.app.isBeingUsed here, and could stop tasks on main when they check the flag
|
||||
// it would enable us to set App.shared.isBeingUsed here, and could stop tasks on main when they check the flag
|
||||
DispatchQueue.main.async {
|
||||
let modifiers = NSEvent.ModifierFlags(rawValue: UInt(cgEvent.flags.rawValue))
|
||||
// TODO: ideally, we want to absorb all modifier keys except holdShortcut
|
||||
@@ -103,7 +103,7 @@ class KeyboardEvents {
|
||||
let runLoopSource = CFMachPortCreateRunLoopSource(nil, eventTap, 0)
|
||||
CFRunLoopAddSource(BackgroundWork.keyboardAndMouseAndTrackpadEventsThread.runLoop, runLoopSource, .commonModes)
|
||||
} else {
|
||||
App.app.restart()
|
||||
App.restart()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -12,7 +12,7 @@ class KeyboardEventsTestable {
|
||||
@discardableResult
|
||||
func handleKeyboardEvent(_ globalId: Int?, _ shortcutState: ShortcutState?, _ keyCode: UInt32?, _ modifiers: NSEvent.ModifierFlags?, _ isARepeat: Bool, _ event: NSEvent? = nil) -> Bool {
|
||||
let shouldAbsorbEvent = shouldAbsorbSearchEditingKeyDown(event)
|
||||
if let event, shouldAbsorbEvent, App.app.tilesPanel.tilesView.handleSearchEditingKeyDown(event) {
|
||||
if let event, shouldAbsorbEvent, TilesView.handleSearchEditingKeyDown(event) {
|
||||
return true
|
||||
}
|
||||
logKeyboardEvent(globalId, shortcutState, keyCode, modifiers, isARepeat)
|
||||
@@ -37,7 +37,7 @@ private func logKeyboardEvent(_ globalId: Int?, _ shortcutState: ShortcutState?,
|
||||
}
|
||||
|
||||
private func shouldAbsorbSearchEditingKeyDown(_ event: NSEvent?) -> Bool {
|
||||
guard let event, event.type == .keyDown, App.app.appIsBeingUsed, App.app.tilesPanel.isKeyWindow, App.app.tilesPanel.tilesView.isSearchEditing else {
|
||||
guard let event, event.type == .keyDown, App.appIsBeingUsed, TilesPanel.shared.isKeyWindow, TilesView.isSearchEditing else {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
@@ -58,6 +58,6 @@ private func triggerMatchingShortcuts(_ globalId: Int?, _ shortcutState: Shortcu
|
||||
// TODO if we manage to move all keyboard listening to the background thread, we'll have issues returning this boolean
|
||||
// this function uses many objects that are also used on the main-thread. It also executes the actions
|
||||
// we'll have to rework this whole approach. Today we rely on somewhat in-order events/actions
|
||||
// special attention should be given to App.app.appIsBeingUsed which is being set to true when executing the nextWindowShortcut action
|
||||
// special attention should be given to App.appIsBeingUsed which is being set to true when executing the nextWindowShortcut action
|
||||
return someShortcutTriggered
|
||||
}
|
||||
@@ -56,7 +56,7 @@ class PreferencesEvents {
|
||||
case "nextWindowGesture": TrackpadEvents.toggle(Preferences.nextWindowGesture != .disabled)
|
||||
case "startAtLogin": applyStartAtLoginPreference()
|
||||
case "updatePolicy": applyUpdatePolicyPreference()
|
||||
case let k where preferencesRequiringUiReset.contains(k) && App.app.tilesPanel != nil: App.app.resetPreferencesDependentComponents()
|
||||
case let k where preferencesRequiringUiReset.contains(k) && TilesPanel.shared != nil: App.resetPreferencesDependentComponents()
|
||||
default: break
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,7 +15,7 @@ class ScreensEvents {
|
||||
Spaces.refresh()
|
||||
Screens.refresh()
|
||||
// a screen added or removed, or screen resolution change can mess up layout; we reset components
|
||||
App.app.resetPreferencesDependentComponents()
|
||||
App.resetPreferencesDependentComponents()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -38,7 +38,7 @@ final class Debouncer {
|
||||
}
|
||||
// ScreensEvents: a screen added or removed can shuffle windows around Spaces; we refresh them
|
||||
// SpacesEvents: if UI was kept open during Space transition, the Spaces may be obsolete; we refresh them
|
||||
App.app.refreshOpenUiAfterExternalEvent(Windows.list)
|
||||
App.refreshOpenUiAfterExternalEvent(Windows.list)
|
||||
Logger.info { "screens:\(NSScreen.screens.map { ($0.cachedUuid() ?? "nil" as CFString, $0.frame) })" }
|
||||
Logger.info { "currentSpace:\(Spaces.currentSpaceIndex) (id:\(Spaces.currentSpaceId)) spaces:\(Spaces.screenSpacesMap)" }
|
||||
})
|
||||
|
||||
@@ -30,7 +30,7 @@ class ScrollwheelEvents {
|
||||
let runLoopSource = CFMachPortCreateRunLoopSource(nil, eventTap, 0)
|
||||
CFRunLoopAddSource(BackgroundWork.keyboardAndMouseAndTrackpadEventsThread.runLoop, runLoopSource, .commonModes)
|
||||
} else {
|
||||
App.app.restart()
|
||||
App.restart()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -16,7 +16,7 @@ class SpacesEvents {
|
||||
if let frontmostPid = Applications.frontmostPid,
|
||||
let frontmostApp = Applications.findOrCreate(frontmostPid, false),
|
||||
let focusedWindow = frontmostApp.focusedWindow {
|
||||
App.app.checkIfShortcutsShouldBeDisabled(focusedWindow, nil)
|
||||
App.checkIfShortcutsShouldBeDisabled(focusedWindow, nil)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,6 +11,6 @@ class SystemAppearanceEvents {
|
||||
Logger.debug { notification.name.rawValue }
|
||||
Logger.info { UserDefaults.standard.string(forKey: "AppleInterfaceStyle") ?? "Light" }
|
||||
// fix layout issues by resetting components
|
||||
App.app.resetPreferencesDependentComponents()
|
||||
App.resetPreferencesDependentComponents()
|
||||
}
|
||||
}
|
||||
@@ -7,8 +7,8 @@ class SystemScrollerStyleEvents {
|
||||
|
||||
@objc private static func handleEvent(_ notification: Notification) {
|
||||
Logger.debug { notification.name.rawValue }
|
||||
Logger.info { App.app.tilesPanel.tilesView.scrollView.scrollerStyle == .overlay ? "overlay" : "legacy" }
|
||||
Logger.info { TilesView.scrollView.scrollerStyle == .overlay ? "overlay" : "legacy" }
|
||||
// force overlay style after a change in System Preference > General > Show scroll bars
|
||||
App.app.tilesPanel?.tilesView.scrollView.scrollerStyle = .overlay
|
||||
TilesView.scrollView.scrollerStyle = .overlay
|
||||
}
|
||||
}
|
||||
@@ -41,7 +41,7 @@ class TrackpadEvents {
|
||||
let runLoopSource = CFMachPortCreateRunLoopSource(nil, eventTap, 0)
|
||||
CFRunLoopAddSource(BackgroundWork.keyboardAndMouseAndTrackpadEventsThread.runLoop, runLoopSource, .commonModes)
|
||||
} else {
|
||||
App.app.restart()
|
||||
App.restart()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -68,7 +68,7 @@ class TrackpadEvents {
|
||||
let activeTouches = touches.filter { !$0.isResting && ($0.phase == .began || $0.phase == .moved) }
|
||||
let fingersDown = touches.count { $0.phase == .began || $0.phase == .moved || $0.phase == .stationary }
|
||||
let requiredFingers = Preferences.nextWindowGesture.isThreeFinger() ? 3 : 4
|
||||
if App.app.appIsBeingUsed {
|
||||
if App.appIsBeingUsed {
|
||||
handleEventIfAppIsBeingUsed(fingersDown, activeTouches, requiredFingers)
|
||||
return true // absorb the touch event
|
||||
}
|
||||
@@ -77,9 +77,9 @@ class TrackpadEvents {
|
||||
|
||||
private static func handleEventIfAppIsBeingUsed(_ fingersDown: Int, _ activeTouches: Set<NSTouch>, _ requiredFingers: Int) {
|
||||
if fingersDown <= TriggerSwipeDetector.maxFingersDownDuringTrigger - requiredFingers {
|
||||
if App.app.shortcutIndex == Preferences.gestureIndex && !App.app.forceDoNothingOnRelease && Preferences.shortcutStyle == .focusOnRelease {
|
||||
if App.shortcutIndex == Preferences.gestureIndex && !App.forceDoNothingOnRelease && Preferences.shortcutStyle == .focusOnRelease {
|
||||
DispatchQueue.main.async {
|
||||
App.app.focusTarget()
|
||||
App.focusTarget()
|
||||
}
|
||||
}
|
||||
return
|
||||
@@ -158,7 +158,7 @@ class TriggerSwipeDetector {
|
||||
DispatchQueue.main.async {
|
||||
ScrollwheelEvents.toggle(true)
|
||||
performHapticFeedback()
|
||||
App.app.showUiOrCycleSelection(Preferences.gestureIndex, false)
|
||||
App.showUiOrCycleSelection(Preferences.gestureIndex, false)
|
||||
}
|
||||
return true
|
||||
}
|
||||
@@ -184,7 +184,7 @@ class NavigationSwipeDetector {
|
||||
let direction: Direction = maxIsX ? (averageDistance.x < 0 ? .left : .right) : (averageDistance.y < 0 ? .down : .up)
|
||||
DispatchQueue.main.async {
|
||||
performHapticFeedback()
|
||||
App.app.cycleSelection(direction, allowWrap: false)
|
||||
App.cycleSelection(direction, allowWrap: false)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -10,7 +10,7 @@ class WindowCaptureScreenshots {
|
||||
let windows = windowsToScreenshot.compactMap { $0.cgWindowId }
|
||||
guard !windows.isEmpty else { return }
|
||||
BackgroundWork.screenshotsQueue.addOperation {
|
||||
guard source != .refreshOnlyThumbnailsAfterShowUi || App.app.appIsBeingUsed else { return }
|
||||
guard source != .refreshOnlyThumbnailsAfterShowUi || App.appIsBeingUsed else { return }
|
||||
let (cachedWindows, notCachedWindows) = sortCachedAndNotCached(windows)
|
||||
Logger.debug { "cached:\(cachedWindows.map { $0.windowID }) notCached:\(notCachedWindows)" }
|
||||
handleCachedWindows(cachedWindows, source)
|
||||
@@ -29,11 +29,11 @@ class WindowCaptureScreenshots {
|
||||
guard !notCachedWindows.isEmpty else { return }
|
||||
SCShareableContent.getExcludingDesktopWindows(true, onScreenWindowsOnly: false) { shareableContent, error in
|
||||
guard let shareableContent, error == nil else { Logger.error { "\(shareableContent == nil) \(error)" }; return }
|
||||
guard source != .refreshOnlyThumbnailsAfterShowUi || App.app.appIsBeingUsed else { return }
|
||||
guard source != .refreshOnlyThumbnailsAfterShowUi || App.appIsBeingUsed else { return }
|
||||
// this callback is executed on an undetermined queue; we move execution to main-thread
|
||||
BackgroundWork.screenshotsQueue.addOperation {
|
||||
cachedSCWindows = shareableContent.windows
|
||||
guard source != .refreshOnlyThumbnailsAfterShowUi || App.app.appIsBeingUsed else { return }
|
||||
guard source != .refreshOnlyThumbnailsAfterShowUi || App.appIsBeingUsed else { return }
|
||||
for notCachedWindow in notCachedWindows {
|
||||
if let cachedWindow = (cachedSCWindows.first { $0.windowID == notCachedWindow }) {
|
||||
oneTimeCapture(cachedWindow, source)
|
||||
@@ -59,18 +59,18 @@ class WindowCaptureScreenshots {
|
||||
}
|
||||
|
||||
private static func oneTimeCapture(_ scWindow: SCWindow, _ source: RefreshCausedBy) {
|
||||
guard !App.app.isTerminating, let window = (Windows.list.first { $0.cgWindowId == scWindow.windowID }), window.size != nil else { return }
|
||||
guard !App.isTerminating, let window = (Windows.list.first { $0.cgWindowId == scWindow.windowID }), window.size != nil else { return }
|
||||
let config = SCStreamConfiguration.forWindow(scWindow, window, false)
|
||||
let filter = SCContentFilter(desktopIndependentWindow: scWindow)
|
||||
ActiveWindowCaptures.increment()
|
||||
SCScreenshotManager.captureSampleBuffer(contentFilter: filter, configuration: config) { sampleBuffer, error in
|
||||
ActiveWindowCaptures.decrement()
|
||||
guard let sampleBuffer, error == nil else { Logger.error { "\(window.debugId) \(sampleBuffer == nil) \(error)" }; return }
|
||||
guard source != .refreshOnlyThumbnailsAfterShowUi || App.app.appIsBeingUsed else { return }
|
||||
guard source != .refreshOnlyThumbnailsAfterShowUi || App.appIsBeingUsed else { return }
|
||||
let pixelBuffer: CVPixelBuffer? = sampleBuffer.pixelBuffer() ?? sampleBuffer.imageBuffer
|
||||
guard let pixelBuffer else { Logger.error { "\(window.debugId) no pixelBuffer" }; return }
|
||||
DispatchQueue.main.async {
|
||||
guard source != .refreshOnlyThumbnailsAfterShowUi || App.app.appIsBeingUsed else { return }
|
||||
guard source != .refreshOnlyThumbnailsAfterShowUi || App.appIsBeingUsed else { return }
|
||||
if let window = (Windows.list.first { $0.cgWindowId == scWindow.windowID }) {
|
||||
window.refreshThumbnail(.pixelBuffer(pixelBuffer))
|
||||
}
|
||||
@@ -83,11 +83,11 @@ class WindowCaptureScreenshotsPrivateApi {
|
||||
static func oneTimeScreenshots(_ eligibleWindows: [Window], _ source: RefreshCausedBy) {
|
||||
for window in eligibleWindows {
|
||||
BackgroundWork.screenshotsQueue.addOperation { [weak window] in
|
||||
guard source != .refreshOnlyThumbnailsAfterShowUi || App.app.appIsBeingUsed else { return }
|
||||
guard source != .refreshOnlyThumbnailsAfterShowUi || App.appIsBeingUsed else { return }
|
||||
guard let wid = window?.cgWindowId, let cgImage = oneTimeCapture(wid) else { return }
|
||||
guard source != .refreshOnlyThumbnailsAfterShowUi || App.app.appIsBeingUsed else { return }
|
||||
guard source != .refreshOnlyThumbnailsAfterShowUi || App.appIsBeingUsed else { return }
|
||||
DispatchQueue.main.async { [weak window] in
|
||||
guard source != .refreshOnlyThumbnailsAfterShowUi || App.app.appIsBeingUsed else { return }
|
||||
guard source != .refreshOnlyThumbnailsAfterShowUi || App.appIsBeingUsed else { return }
|
||||
window?.refreshThumbnail(.cgImage(cgImage))
|
||||
}
|
||||
}
|
||||
@@ -95,7 +95,7 @@ class WindowCaptureScreenshotsPrivateApi {
|
||||
}
|
||||
|
||||
private static func oneTimeCapture(_ wid: CGWindowID) -> CGImage? {
|
||||
guard !App.app.isTerminating else { return nil }
|
||||
guard !App.isTerminating else { return nil }
|
||||
// we use CGSHWCaptureWindowList because it can screenshot minimized windows, which CGWindowListCreateImage can't
|
||||
var windowId_ = wid
|
||||
ActiveWindowCaptures.increment()
|
||||
@@ -129,7 +129,7 @@ class WindowCaptureScreenshotsPrivateApi {
|
||||
// // this callback is executed on an undetermined queue
|
||||
// // we move execution to main-thread to avoid races with starting/stopping streams and the app being shown/hidden
|
||||
// DispatchQueue.main.async {
|
||||
// guard App.app.appIsBeingUsed else { return }
|
||||
// guard App.appIsBeingUsed else { return }
|
||||
// startCaptures(windowsToStart, shareableContent)
|
||||
// updateCaptures(windowsWhichMayHaveChanged_, shareableContent)
|
||||
// Logger.debug { streams.keys }
|
||||
|
||||
+1
-1
@@ -39,7 +39,7 @@ fileprivate func emergencyExit(_ logs: Any?...) {
|
||||
}
|
||||
|
||||
func makeSureAllCapturesAreFinished() {
|
||||
App.app.isTerminating = true
|
||||
App.isTerminating = true
|
||||
let timeout = 5.0
|
||||
let startTime = DispatchTime.now()
|
||||
var elapsedTime = 0.0
|
||||
|
||||
+154
-172
@@ -16,32 +16,24 @@ class App: AppCenterApplication {
|
||||
static let repository = "https://github.com/lwouis/alt-tab-macos"
|
||||
static let website = "https://alt-tab-macos.netlify.app"
|
||||
static let appIcon = CGImage.named("app.icns")
|
||||
static var supportProjectAction: Selector { #selector(App.app.supportProject) }
|
||||
static var app: App!
|
||||
var isTerminating = false
|
||||
var tilesPanel: TilesPanel!
|
||||
var previewPanel: PreviewPanel!
|
||||
var appIsBeingUsed = false
|
||||
var shortcutIndex = 0
|
||||
var forceDoNothingOnRelease = false
|
||||
var settingsWindow: SettingsWindow!
|
||||
var aboutWindow: AboutWindow!
|
||||
var permissionsWindow: PermissionsWindow?
|
||||
private var feedbackWindow: FeedbackWindow!
|
||||
private var debugWindow: DebugWindow!
|
||||
private var isFirstSummon = true
|
||||
private var isVeryFirstSummon = true
|
||||
override class var shared: App { super.shared as! App }
|
||||
static var supportProjectAction: Selector { #selector(App.supportProject) }
|
||||
static var isTerminating = false
|
||||
static var appIsBeingUsed = false
|
||||
static var shortcutIndex = 0
|
||||
static var forceDoNothingOnRelease = false
|
||||
private static var isFirstSummon = true
|
||||
private static var isVeryFirstSummon = true
|
||||
// periphery:ignore
|
||||
private var appCenterDelegate: AppCenterCrash?
|
||||
private static var appCenterDelegate: AppCenterCrash?
|
||||
// don't queue multiple delayed rebuildUi() calls
|
||||
private var delayedDisplayScheduled = 0
|
||||
private var lastRefreshTimeInNanoseconds = DispatchTime.now().uptimeNanoseconds
|
||||
private var nextRefreshScheduled = false
|
||||
private static var delayedDisplayScheduled = 0
|
||||
private static var lastRefreshTimeInNanoseconds = DispatchTime.now().uptimeNanoseconds
|
||||
private static var nextRefreshScheduled = false
|
||||
|
||||
override init() {
|
||||
super.init()
|
||||
delegate = self
|
||||
App.app = self
|
||||
}
|
||||
|
||||
required init?(coder: NSCoder) {
|
||||
@@ -49,37 +41,37 @@ class App: AppCenterApplication {
|
||||
}
|
||||
|
||||
/// we put application code here which should be executed on init() and Preferences change
|
||||
func resetPreferencesDependentComponents() {
|
||||
tilesPanel.tilesView.reset()
|
||||
static func resetPreferencesDependentComponents() {
|
||||
TilesView.reset()
|
||||
}
|
||||
|
||||
func restart() {
|
||||
static func restart() {
|
||||
// we use -n to open a new instance, to avoid calling applicationShouldHandleReopen
|
||||
// we use Bundle.main.bundlePath in case of multiple AltTab versions on the machine
|
||||
printStackTrace()
|
||||
Process.launchedProcess(launchPath: "/usr/bin/open", arguments: ["-n", Bundle.main.bundlePath])
|
||||
App.shared.terminate(self)
|
||||
App.shared.terminate(nil)
|
||||
}
|
||||
|
||||
func hideUi(_ keepPreview: Bool = false) {
|
||||
Logger.info { "appIsBeingUsed:\(self.appIsBeingUsed)" }
|
||||
static func hideUi(_ keepPreview: Bool = false) {
|
||||
Logger.info { "appIsBeingUsed:\(appIsBeingUsed)" }
|
||||
guard appIsBeingUsed else { return } // already hidden
|
||||
appIsBeingUsed = false
|
||||
isFirstSummon = true
|
||||
forceDoNothingOnRelease = false
|
||||
tilesPanel.tilesView.endSearchSession()
|
||||
TilesView.endSearchSession()
|
||||
CursorEvents.toggle(false)
|
||||
TrackpadEvents.reset()
|
||||
hideTilesPanelWithoutChangingKeyWindow()
|
||||
if !keepPreview {
|
||||
previewPanel.orderOut(nil)
|
||||
PreviewPanel.shared.orderOut(nil)
|
||||
}
|
||||
hideAllTooltips()
|
||||
MainMenu.toggle(enabled: true)
|
||||
}
|
||||
|
||||
/// some tooltips may not be hidden when the main window is hidden; we force it through a private API
|
||||
private func hideAllTooltips() {
|
||||
private static func hideAllTooltips() {
|
||||
let selector = NSSelectorFromString("abortAllToolTips")
|
||||
if NSApp.responds(to: selector) {
|
||||
NSApp.perform(selector)
|
||||
@@ -87,183 +79,171 @@ class App: AppCenterApplication {
|
||||
}
|
||||
|
||||
/// we don't want another window to become key when the TilesPanel is hidden
|
||||
func hideTilesPanelWithoutChangingKeyWindow() {
|
||||
static func hideTilesPanelWithoutChangingKeyWindow() {
|
||||
allSecondaryWindowsCanBecomeKey(false)
|
||||
tilesPanel.orderOut(nil)
|
||||
TilesPanel.shared.orderOut(nil)
|
||||
allSecondaryWindowsCanBecomeKey(true)
|
||||
}
|
||||
|
||||
private func allSecondaryWindowsCanBecomeKey(_ canBecomeKey_: Bool) {
|
||||
settingsWindow?.canBecomeKey_ = canBecomeKey_
|
||||
aboutWindow?.canBecomeKey_ = canBecomeKey_
|
||||
permissionsWindow?.canBecomeKey_ = canBecomeKey_
|
||||
feedbackWindow?.canBecomeKey_ = canBecomeKey_
|
||||
debugWindow?.canBecomeKey_ = canBecomeKey_
|
||||
private static func allSecondaryWindowsCanBecomeKey(_ canBecomeKey_: Bool) {
|
||||
SettingsWindow.canBecomeKey_ = canBecomeKey_
|
||||
AboutWindow.canBecomeKey_ = canBecomeKey_
|
||||
PermissionsWindow.canBecomeKey_ = canBecomeKey_
|
||||
FeedbackWindow.canBecomeKey_ = canBecomeKey_
|
||||
DebugWindow.canBecomeKey_ = canBecomeKey_
|
||||
}
|
||||
|
||||
func closeSelectedWindow() {
|
||||
static func closeSelectedWindow() {
|
||||
Windows.selectedWindow()?.close()
|
||||
}
|
||||
|
||||
func minDeminSelectedWindow() {
|
||||
static func minDeminSelectedWindow() {
|
||||
Windows.selectedWindow()?.minDemin()
|
||||
}
|
||||
|
||||
func toggleFullscreenSelectedWindow() {
|
||||
static func toggleFullscreenSelectedWindow() {
|
||||
Windows.selectedWindow()?.toggleFullscreen()
|
||||
}
|
||||
|
||||
func quitSelectedApp() {
|
||||
static func quitSelectedApp() {
|
||||
Windows.selectedWindow()?.application.quit()
|
||||
}
|
||||
|
||||
func hideShowSelectedApp() {
|
||||
static func hideShowSelectedApp() {
|
||||
Windows.selectedWindow()?.application.hideOrShow()
|
||||
}
|
||||
|
||||
func toggleSearchMode() {
|
||||
static func toggleSearchMode() {
|
||||
guard appIsBeingUsed else { return }
|
||||
tilesPanel.tilesView.toggleSearchModeFromShortcut()
|
||||
TilesView.toggleSearchModeFromShortcut()
|
||||
}
|
||||
|
||||
func lockSearchMode() {
|
||||
guard appIsBeingUsed, tilesPanel.tilesView.isSearchModeOn else { return }
|
||||
tilesPanel.tilesView.lockSearchMode()
|
||||
static func lockSearchMode() {
|
||||
guard appIsBeingUsed, TilesView.isSearchModeOn else { return }
|
||||
TilesView.lockSearchMode()
|
||||
}
|
||||
|
||||
func cancelSearchModeOrHideUi() {
|
||||
static func cancelSearchModeOrHideUi() {
|
||||
guard appIsBeingUsed else { return }
|
||||
if tilesPanel.tilesView.isSearchModeOn {
|
||||
tilesPanel.tilesView.disableSearchMode()
|
||||
if TilesView.isSearchModeOn {
|
||||
TilesView.disableSearchMode()
|
||||
} else {
|
||||
hideUi()
|
||||
}
|
||||
}
|
||||
|
||||
func focusTarget() {
|
||||
static func focusTarget() {
|
||||
guard appIsBeingUsed else { return } // already hidden
|
||||
let selectedWindow = Windows.selectedWindow()
|
||||
Logger.info { selectedWindow?.debugId }
|
||||
focusSelectedWindow(selectedWindow)
|
||||
}
|
||||
|
||||
@objc func checkForUpdatesNow(_ sender: NSMenuItem) {
|
||||
@objc static func checkForUpdatesNow(_ sender: NSMenuItem) {
|
||||
GeneralTab.checkForUpdatesNow(sender)
|
||||
}
|
||||
|
||||
@objc func checkPermissions(_ sender: NSMenuItem) {
|
||||
@objc static func checkPermissions(_ sender: NSMenuItem) {
|
||||
showPermissionsWindow()
|
||||
}
|
||||
|
||||
@objc func supportProject() {
|
||||
@objc static func supportProject() {
|
||||
NSWorkspace.shared.open(URL(string: App.website + "/support")!)
|
||||
}
|
||||
|
||||
@objc func showFeedbackPanel() {
|
||||
showSecondaryWindow(getOrCreateFeedbackWindow())
|
||||
@objc static func showFeedbackPanel() {
|
||||
initializeFeedbackWindowIfNeeded()
|
||||
showSecondaryWindow(FeedbackWindow.shared!)
|
||||
}
|
||||
|
||||
@objc func showDebugWindow() {
|
||||
showSecondaryWindow(getOrCreateDebugWindow())
|
||||
@objc static func showDebugWindow() {
|
||||
initializeDebugWindowIfNeeded()
|
||||
showSecondaryWindow(DebugWindow.shared!)
|
||||
}
|
||||
|
||||
@objc func showSettingsWindow() {
|
||||
showSecondaryWindow(getOrCreateSettingsWindow())
|
||||
if settingsWindow?.isVisible != true {
|
||||
settingsWindow = SettingsWindow()
|
||||
showSecondaryWindow(settingsWindow)
|
||||
settingsWindow?.orderFrontRegardless()
|
||||
@objc static func showSettingsWindow() {
|
||||
initializeSettingsWindowIfNeeded()
|
||||
showSecondaryWindow(SettingsWindow.shared!)
|
||||
if SettingsWindow.shared!.isVisible != true {
|
||||
let window = SettingsWindow()
|
||||
showSecondaryWindow(window)
|
||||
window.orderFrontRegardless()
|
||||
}
|
||||
}
|
||||
|
||||
@objc func showAboutWindow() {
|
||||
showSecondaryWindow(getOrCreateAboutWindow())
|
||||
@objc static func showAboutWindow() {
|
||||
initializeAboutWindowIfNeeded()
|
||||
showSecondaryWindow(AboutWindow.shared!)
|
||||
}
|
||||
|
||||
func showSecondaryWindow(_ window: NSWindow?) {
|
||||
if let window {
|
||||
NSScreen.updatePreferred()
|
||||
App.shared.activate(ignoringOtherApps: true)
|
||||
window.makeKeyAndOrderFront(nil)
|
||||
// if the window was resized/repositioned by the user, restore the window the way it was
|
||||
let restored = window.setFrameUsingName(window.frameAutosaveName)
|
||||
if !restored {
|
||||
NSScreen.preferred.repositionPanel(window)
|
||||
// Use the center function to continue to center, the `repositionPanel` function cannot center, it may be a system bug
|
||||
window.center()
|
||||
}
|
||||
static func showSecondaryWindow(_ window: NSWindow) {
|
||||
NSScreen.updatePreferred()
|
||||
App.shared.activate(ignoringOtherApps: true)
|
||||
window.makeKeyAndOrderFront(nil)
|
||||
// if the window was resized/repositioned by the user, restore the window the way it was
|
||||
let restored = window.setFrameUsingName(window.frameAutosaveName)
|
||||
if !restored {
|
||||
NSScreen.preferred.repositionPanel(window)
|
||||
// Use the center function to continue to center, the `repositionPanel` function cannot center, it may be a system bug
|
||||
window.center()
|
||||
}
|
||||
}
|
||||
|
||||
private func getOrCreateSettingsWindow() -> SettingsWindow {
|
||||
if settingsWindow == nil {
|
||||
settingsWindow = SettingsWindow()
|
||||
}
|
||||
return settingsWindow
|
||||
private static func initializeSettingsWindowIfNeeded() {
|
||||
if SettingsWindow.shared == nil { _ = SettingsWindow() }
|
||||
}
|
||||
|
||||
private func getOrCreateAboutWindow() -> AboutWindow {
|
||||
if aboutWindow == nil {
|
||||
aboutWindow = AboutWindow()
|
||||
}
|
||||
return aboutWindow
|
||||
private static func initializeAboutWindowIfNeeded() {
|
||||
if AboutWindow.shared == nil { _ = AboutWindow() }
|
||||
}
|
||||
|
||||
private func getOrCreateFeedbackWindow() -> FeedbackWindow {
|
||||
if feedbackWindow == nil {
|
||||
feedbackWindow = FeedbackWindow()
|
||||
}
|
||||
return feedbackWindow
|
||||
private static func initializeFeedbackWindowIfNeeded() {
|
||||
if FeedbackWindow.shared == nil { _ = FeedbackWindow() }
|
||||
}
|
||||
|
||||
private func getOrCreateDebugWindow() -> DebugWindow {
|
||||
if debugWindow == nil {
|
||||
debugWindow = DebugWindow()
|
||||
}
|
||||
return debugWindow
|
||||
private static func initializeDebugWindowIfNeeded() {
|
||||
if DebugWindow.shared == nil { _ = DebugWindow() }
|
||||
}
|
||||
|
||||
private func getOrCreatePermissionsWindow() -> PermissionsWindow {
|
||||
if permissionsWindow == nil {
|
||||
permissionsWindow = PermissionsWindow()
|
||||
}
|
||||
return permissionsWindow!
|
||||
private static func initializePermissionsWindowIfNeeded() {
|
||||
if PermissionsWindow.shared == nil { _ = PermissionsWindow() }
|
||||
}
|
||||
|
||||
@discardableResult
|
||||
private func showSettingsWindowOnFirstLaunchIfNeeded() -> Bool {
|
||||
private static func showSettingsWindowOnFirstLaunchIfNeeded() -> Bool {
|
||||
guard !Preferences.settingsWindowShownOnFirstLaunch else { return false }
|
||||
showSettingsWindow()
|
||||
Preferences.markSettingsWindowShownOnFirstLaunch()
|
||||
return true
|
||||
}
|
||||
|
||||
func showPermissionsWindow() {
|
||||
getOrCreatePermissionsWindow().show()
|
||||
static func showPermissionsWindow() {
|
||||
initializePermissionsWindowIfNeeded()
|
||||
PermissionsWindow.show()
|
||||
}
|
||||
|
||||
func showUi(_ shortcutIndex: Int) {
|
||||
static func showUi(_ shortcutIndex: Int) {
|
||||
showUiOrCycleSelection(shortcutIndex, true)
|
||||
}
|
||||
|
||||
@objc func showUiFromShortcut0() {
|
||||
@objc static func showUiFromShortcut0() {
|
||||
showUi(0)
|
||||
}
|
||||
|
||||
func cycleSelection(_ direction: Direction, allowWrap: Bool = true) {
|
||||
static func cycleSelection(_ direction: Direction, allowWrap: Bool = true) {
|
||||
if direction == .up || direction == .down {
|
||||
tilesPanel.tilesView.navigateUpOrDown(direction, allowWrap: allowWrap)
|
||||
TilesView.navigateUpOrDown(direction, allowWrap: allowWrap)
|
||||
} else {
|
||||
Windows.cycleSelectedWindowIndex(direction.step(), allowWrap: allowWrap)
|
||||
}
|
||||
}
|
||||
|
||||
func previousWindowShortcutWithRepeatingKey() {
|
||||
static func previousWindowShortcutWithRepeatingKey() {
|
||||
cycleSelection(.trailing)
|
||||
KeyRepeatTimer.startRepeatingKeyPreviousWindow()
|
||||
}
|
||||
|
||||
func focusSelectedWindow(_ selectedWindow: Window?) {
|
||||
static func focusSelectedWindow(_ selectedWindow: Window?) {
|
||||
guard appIsBeingUsed else { return } // already hidden
|
||||
hideUi(true)
|
||||
if let window = selectedWindow, MissionControl.state() == .inactive || MissionControl.state() == .showDesktop {
|
||||
@@ -273,70 +253,72 @@ class App: AppCenterApplication {
|
||||
moveCursorToSelectedWindow(window)
|
||||
}
|
||||
} else {
|
||||
previewPanel.orderOut(nil)
|
||||
PreviewPanel.shared.orderOut(nil)
|
||||
}
|
||||
}
|
||||
|
||||
func moveCursorToSelectedWindow(_ window: Window) {
|
||||
static func moveCursorToSelectedWindow(_ window: Window) {
|
||||
let referenceWindow = window.referenceWindowForTabbedWindow()
|
||||
guard let position = referenceWindow?.position, let size = referenceWindow?.size else { return }
|
||||
let point = CGPoint(x: position.x + size.width / 2, y: position.y + size.height / 2)
|
||||
CGWarpMouseCursorPosition(point)
|
||||
}
|
||||
|
||||
func refreshOpenUiAfterExternalEvent(_ windowsToScreenshot: [Window], windowRemoved: Bool = false) {
|
||||
static func refreshOpenUiAfterExternalEvent(_ windowsToScreenshot: [Window], windowRemoved: Bool = false) {
|
||||
Windows.refreshThumbnailsAsync(windowsToScreenshot, .refreshUiAfterExternalEvent, windowRemoved: windowRemoved)
|
||||
refreshOpenUiWithThrottling {
|
||||
guard self.appIsBeingUsed else { return }
|
||||
if !Windows.updatesBeforeShowing() { self.hideUi(); return }
|
||||
self.refreshUi(true)
|
||||
guard appIsBeingUsed else { return }
|
||||
if !Windows.updatesBeforeShowing() { hideUi(); return }
|
||||
refreshUi(true)
|
||||
}
|
||||
}
|
||||
|
||||
func refreshUi(_ preserveScrollPosition: Bool = false) {
|
||||
guard self.appIsBeingUsed else { return }
|
||||
let preservedScrollOrigin = preserveScrollPosition ? tilesPanel.tilesView.currentScrollOrigin() : nil
|
||||
static func refreshUi(_ preserveScrollPosition: Bool = false) {
|
||||
guard appIsBeingUsed else { return }
|
||||
let preservedScrollOrigin = preserveScrollPosition ? TilesView.currentScrollOrigin() : nil
|
||||
Windows.updateSelectedWindow()
|
||||
guard self.appIsBeingUsed else { return }
|
||||
self.tilesPanel.updateContents(preservedScrollOrigin)
|
||||
guard self.appIsBeingUsed else { return }
|
||||
guard appIsBeingUsed else { return }
|
||||
TilesPanel.shared.updateContents(preservedScrollOrigin)
|
||||
guard appIsBeingUsed else { return }
|
||||
Windows.voiceOverWindow() // at this point TileViews are assigned to the window, and ready
|
||||
guard self.appIsBeingUsed else { return }
|
||||
guard appIsBeingUsed else { return }
|
||||
Windows.previewSelectedWindowIfNeeded()
|
||||
guard self.appIsBeingUsed else { return }
|
||||
guard appIsBeingUsed else { return }
|
||||
Applications.refreshBadgesAsync()
|
||||
}
|
||||
|
||||
func refreshOpenUiWithThrottling( _ block: @escaping () -> Void) {
|
||||
static func refreshOpenUiWithThrottling(_ block: @escaping () -> Void) {
|
||||
let throttleDelayInMs = 200
|
||||
let timeSinceLastRefreshInSeconds = Float(DispatchTime.now().uptimeNanoseconds - lastRefreshTimeInNanoseconds) / 1_000_000
|
||||
if timeSinceLastRefreshInSeconds >= Float(throttleDelayInMs) {
|
||||
lastRefreshTimeInNanoseconds = DispatchTime.now().uptimeNanoseconds
|
||||
let now = DispatchTime.now().uptimeNanoseconds
|
||||
let (elapsedInNanoseconds, overflow) = now.subtractingReportingOverflow(lastRefreshTimeInNanoseconds)
|
||||
let timeSinceLastRefreshInMs = overflow ? 0 : Float(elapsedInNanoseconds) / 1_000_000
|
||||
if timeSinceLastRefreshInMs >= Float(throttleDelayInMs) {
|
||||
lastRefreshTimeInNanoseconds = now
|
||||
block()
|
||||
return
|
||||
}
|
||||
guard !nextRefreshScheduled else { return }
|
||||
nextRefreshScheduled = true
|
||||
DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(throttleDelayInMs + 10)) {
|
||||
self.nextRefreshScheduled = false
|
||||
self.refreshOpenUiWithThrottling(block)
|
||||
nextRefreshScheduled = false
|
||||
refreshOpenUiWithThrottling(block)
|
||||
}
|
||||
}
|
||||
|
||||
func showUiOrCycleSelection(_ shortcutIndex: Int, _ forceDoNothingOnRelease_: Bool) {
|
||||
static func showUiOrCycleSelection(_ shortcutIndex: Int, _ forceDoNothingOnRelease_: Bool) {
|
||||
forceDoNothingOnRelease = forceDoNothingOnRelease_
|
||||
Logger.debug { "isFirstSummon:\(self.isFirstSummon) shortcutIndex:\(shortcutIndex)" }
|
||||
App.app.appIsBeingUsed = true
|
||||
if isFirstSummon || shortcutIndex != self.shortcutIndex {
|
||||
Logger.debug { "isFirstSummon:\(isFirstSummon) shortcutIndex:\(shortcutIndex)" }
|
||||
appIsBeingUsed = true
|
||||
if isFirstSummon || shortcutIndex != App.shortcutIndex {
|
||||
NSScreen.updatePreferred()
|
||||
if isVeryFirstSummon {
|
||||
Windows.sortByLevel()
|
||||
isVeryFirstSummon = false
|
||||
}
|
||||
isFirstSummon = false
|
||||
self.shortcutIndex = shortcutIndex
|
||||
App.shortcutIndex = shortcutIndex
|
||||
let shouldStartInSearchMode = Preferences.shortcutStyle == .searchOnRelease
|
||||
tilesPanel.tilesView.startSearchSession(shouldStartInSearchMode)
|
||||
TilesView.startSearchSession(shouldStartInSearchMode)
|
||||
if shouldStartInSearchMode {
|
||||
forceDoNothingOnRelease = true
|
||||
}
|
||||
@@ -347,10 +329,10 @@ class App: AppCenterApplication {
|
||||
} else {
|
||||
delayedDisplayScheduled += 1
|
||||
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Preferences.windowDisplayDelay) { () -> () in
|
||||
if self.delayedDisplayScheduled == 1 {
|
||||
self.buildUiAndShowPanel()
|
||||
if delayedDisplayScheduled == 1 {
|
||||
buildUiAndShowPanel()
|
||||
}
|
||||
self.delayedDisplayScheduled -= 1
|
||||
delayedDisplayScheduled -= 1
|
||||
}
|
||||
}
|
||||
} else {
|
||||
@@ -359,21 +341,21 @@ class App: AppCenterApplication {
|
||||
}
|
||||
}
|
||||
|
||||
func buildUiAndShowPanel() {
|
||||
static func buildUiAndShowPanel() {
|
||||
guard appIsBeingUsed else { return }
|
||||
Appearance.update()
|
||||
guard appIsBeingUsed else { return }
|
||||
refreshUi()
|
||||
guard appIsBeingUsed else { return }
|
||||
tilesPanel.show()
|
||||
if tilesPanel.tilesView.isSearchEditing {
|
||||
tilesPanel.tilesView.enableSearchEditing()
|
||||
TilesPanel.shared.show()
|
||||
if TilesView.isSearchEditing {
|
||||
TilesView.enableSearchEditing()
|
||||
}
|
||||
KeyRepeatTimer.startRepeatingKeyNextWindow()
|
||||
Windows.refreshThumbnailsAsync(Windows.list, .refreshOnlyThumbnailsAfterShowUi)
|
||||
}
|
||||
|
||||
func checkIfShortcutsShouldBeDisabled(_ activeWindow: Window?, _ activeApp: Application?) {
|
||||
static func checkIfShortcutsShouldBeDisabled(_ activeWindow: Window?, _ activeApp: Application?) {
|
||||
let app = activeWindow?.application ?? activeApp!
|
||||
let shortcutsShouldBeDisabled = Preferences.exceptions.contains { exception in
|
||||
if let id = app.bundleIdentifier {
|
||||
@@ -383,31 +365,12 @@ class App: AppCenterApplication {
|
||||
return false
|
||||
}
|
||||
KeyboardEvents.toggleGlobalShortcuts(shortcutsShouldBeDisabled)
|
||||
if shortcutsShouldBeDisabled && App.app.appIsBeingUsed {
|
||||
App.app.hideUi()
|
||||
if shortcutsShouldBeDisabled && appIsBeingUsed {
|
||||
hideUi()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension App: NSApplicationDelegate {
|
||||
func applicationDidFinishLaunching(_ aNotification: Notification) {
|
||||
appCenterDelegate = AppCenterCrash()
|
||||
App.shared.disableRelaunchOnLogin()
|
||||
Logger.initialize()
|
||||
Logger.info { "Launching AltTab \(App.version)" }
|
||||
#if DEBUG
|
||||
UserDefaults.standard.set(true, forKey: "NSConstraintBasedLayoutVisualizeMutuallyExclusiveConstraints")
|
||||
#endif
|
||||
#if !DEBUG
|
||||
PFMoveToApplicationsFolderIfNecessary()
|
||||
#endif
|
||||
AXUIElement.setGlobalTimeout()
|
||||
Preferences.initialize()
|
||||
BackgroundWork.preStart()
|
||||
SystemPermissions.ensurePermissionsAreGranted()
|
||||
}
|
||||
|
||||
func continueAppLaunchAfterPermissionsAreGranted() {
|
||||
static func continueAppLaunchAfterPermissionsAreGranted() {
|
||||
Logger.info { "System permissions are granted; continuing launch" }
|
||||
BackgroundWork.start()
|
||||
NSScreen.updatePreferred()
|
||||
@@ -416,8 +379,8 @@ extension App: NSApplicationDelegate {
|
||||
TilesPanel.updateMaxPossibleAppIconSize()
|
||||
Menubar.initialize()
|
||||
MainMenu.loadFromXib()
|
||||
self.tilesPanel = TilesPanel()
|
||||
self.previewPanel = PreviewPanel()
|
||||
_ = TilesPanel()
|
||||
_ = PreviewPanel()
|
||||
Spaces.refresh()
|
||||
Screens.refresh()
|
||||
SpacesEvents.observe()
|
||||
@@ -433,13 +396,32 @@ extension App: NSApplicationDelegate {
|
||||
BenchmarkRunner.startIfNeeded()
|
||||
showSettingsWindowOnFirstLaunchIfNeeded()
|
||||
#if DEBUG
|
||||
// self.showSettingsWindow()
|
||||
// App.showSettingsWindow()
|
||||
#endif
|
||||
Logger.info { "Finished launching AltTab" }
|
||||
}
|
||||
}
|
||||
|
||||
extension App: NSApplicationDelegate {
|
||||
func applicationDidFinishLaunching(_ aNotification: Notification) {
|
||||
App.appCenterDelegate = AppCenterCrash()
|
||||
App.shared.disableRelaunchOnLogin()
|
||||
Logger.initialize()
|
||||
Logger.info { "Launching AltTab \(App.version)" }
|
||||
#if DEBUG
|
||||
UserDefaults.standard.set(true, forKey: "NSConstraintBasedLayoutVisualizeMutuallyExclusiveConstraints")
|
||||
#endif
|
||||
#if !DEBUG
|
||||
PFMoveToApplicationsFolderIfNecessary()
|
||||
#endif
|
||||
AXUIElement.setGlobalTimeout()
|
||||
Preferences.initialize()
|
||||
BackgroundWork.preStart()
|
||||
SystemPermissions.ensurePermissionsAreGranted()
|
||||
}
|
||||
|
||||
func applicationShouldHandleReopen(_ sender: NSApplication, hasVisibleWindows flag: Bool) -> Bool {
|
||||
showSettingsWindow()
|
||||
App.showSettingsWindow()
|
||||
return true
|
||||
}
|
||||
|
||||
|
||||
@@ -2,8 +2,9 @@ import Cocoa
|
||||
import SwiftyBeaver
|
||||
|
||||
class DebugWindow: NSPanel {
|
||||
var canBecomeKey_ = true
|
||||
override var canBecomeKey: Bool { canBecomeKey_ }
|
||||
static var shared: DebugWindow?
|
||||
static var canBecomeKey_ = true
|
||||
override var canBecomeKey: Bool { Self.canBecomeKey_ }
|
||||
private var scrollView: NSScrollView!
|
||||
private var textView: NSTextView!
|
||||
private var filterControl: NSSegmentedControl!
|
||||
@@ -32,6 +33,7 @@ class DebugWindow: NSPanel {
|
||||
setupWindow()
|
||||
setupView()
|
||||
setFrameAutosaveName("DebugWindow")
|
||||
Self.shared = self
|
||||
}
|
||||
|
||||
private func setupWindow() {
|
||||
|
||||
@@ -7,19 +7,21 @@ class FeedbackWindow: NSWindow {
|
||||
let base64Token = Bundle.main.object(forInfoDictionaryKey: "FeedbackToken") as! String
|
||||
return String(data: Data(base64Encoded: base64Token)!, encoding: .utf8)!
|
||||
}()
|
||||
static var shared: FeedbackWindow?
|
||||
var issueTitle: TextArea!
|
||||
var body: TextArea!
|
||||
var email: TextArea!
|
||||
var sendButton: NSButton!
|
||||
var debugProfile: NSButton!
|
||||
var canBecomeKey_ = true
|
||||
override var canBecomeKey: Bool { canBecomeKey_ }
|
||||
static var canBecomeKey_ = true
|
||||
override var canBecomeKey: Bool { Self.canBecomeKey_ }
|
||||
|
||||
convenience init() {
|
||||
self.init(contentRect: .zero, styleMask: [.titled, .miniaturizable, .closable], backing: .buffered, defer: false)
|
||||
setupWindow()
|
||||
setupView()
|
||||
setFrameAutosaveName("FeedbackWindow")
|
||||
Self.shared = self
|
||||
}
|
||||
|
||||
private func setupWindow() {
|
||||
@@ -70,7 +72,7 @@ class FeedbackWindow: NSWindow {
|
||||
checkEmptyFields()
|
||||
}
|
||||
|
||||
func checkEmptyFields() {
|
||||
private func checkEmptyFields() {
|
||||
sendButton.isEnabled = !body.stringValue.isEmpty && !issueTitle.stringValue.isEmpty
|
||||
sendButton.toolTip = sendButton.isEnabled ? "" : NSLocalizedString("Please fill in the form", comment: "")
|
||||
}
|
||||
@@ -87,7 +89,7 @@ class FeedbackWindow: NSWindow {
|
||||
openTicket()
|
||||
}
|
||||
|
||||
func openTicket() {
|
||||
private func openTicket() {
|
||||
URLSession.shared.dataTask(with: prepareRequest(), completionHandler: { data, response, error in
|
||||
if error != nil || response == nil || (response as! HTTPURLResponse).statusCode != 201 {
|
||||
Logger.error { "HTTP call failed. response:\(response) error:\(error) data:\(data.flatMap { String(data: $0, encoding: .utf8) })" }
|
||||
@@ -98,7 +100,7 @@ class FeedbackWindow: NSWindow {
|
||||
close()
|
||||
}
|
||||
|
||||
func warnAboutNoEmail() -> Bool {
|
||||
private func warnAboutNoEmail() -> Bool {
|
||||
let alert = NSAlert()
|
||||
alert.alertStyle = .warning
|
||||
alert.messageText = NSLocalizedString("Are you sure you don’t want a response?", comment: "")
|
||||
|
||||
+12
-11
@@ -5,8 +5,9 @@ class Menubar {
|
||||
static var menu: NSMenu!
|
||||
static var permissionCalloutMenuItems: [NSMenuItem]?
|
||||
|
||||
static func addMenuItem(_ title: String, _ action: Selector, _ keyEquivalent: String, _ symbolName: String?, _ color: NSColor? = nil) {
|
||||
static func addMenuItem(_ title: String, _ action: Selector, _ keyEquivalent: String, _ symbolName: String?, _ color: NSColor? = nil, _ target: AnyObject? = nil) {
|
||||
let item = menu.addItem(withTitle: title, action: action, keyEquivalent: keyEquivalent)
|
||||
item.target = target
|
||||
if #available(macOS 26.0, *), let symbolName {
|
||||
item.image = NSImage(systemSymbolName: symbolName, accessibilityDescription: nil)
|
||||
if let color {
|
||||
@@ -22,16 +23,16 @@ class Menubar {
|
||||
permissionCalloutMenuItem.view = PermissionCallout()
|
||||
let calloutSeparator = NSMenuItem.separator()
|
||||
permissionCalloutMenuItems = [permissionCalloutMenuItem, calloutSeparator]
|
||||
addMenuItem(NSLocalizedString("Show", comment: "Menubar option"), #selector(App.app.showUiFromShortcut0), "", "eye")
|
||||
addMenuItem(NSLocalizedString("Show", comment: "Menubar option"), #selector(App.showUiFromShortcut0), "", "eye", nil, App.self)
|
||||
menu.addItem(NSMenuItem.separator())
|
||||
addMenuItem(NSLocalizedString("Settings…", comment: "Menubar option"), #selector(App.app.showSettingsWindow), ",", "gear")
|
||||
addMenuItem(NSLocalizedString("Check for updates…", comment: "Menubar option"), #selector(App.app.checkForUpdatesNow), "", "checkmark.arrow.trianglehead.clockwise")
|
||||
addMenuItem(NSLocalizedString("Check permissions…", comment: "Menubar option"), #selector(App.app.checkPermissions), "", "hand.raised")
|
||||
addMenuItem(NSLocalizedString("Settings…", comment: "Menubar option"), #selector(App.showSettingsWindow), ",", "gear", nil, App.self)
|
||||
addMenuItem(NSLocalizedString("Check for updates…", comment: "Menubar option"), #selector(App.checkForUpdatesNow), "", "checkmark.arrow.trianglehead.clockwise", nil, App.self)
|
||||
addMenuItem(NSLocalizedString("Check permissions…", comment: "Menubar option"), #selector(App.checkPermissions), "", "hand.raised", nil, App.self)
|
||||
menu.addItem(NSMenuItem.separator())
|
||||
addMenuItem(String(format: NSLocalizedString("About %@", comment: "Menubar option. %@ is AltTab"), App.name), #selector(App.app.showAboutWindow), "", "info.circle")
|
||||
addMenuItem(NSLocalizedString("Debug tools", comment: "Menubar option"), #selector(App.app.showDebugWindow), "", "scope")
|
||||
addMenuItem(NSLocalizedString("Send feedback…", comment: "Menubar option"), #selector(App.app.showFeedbackPanel), "", "text.bubble")
|
||||
addMenuItem(NSLocalizedString("Support this project", comment: "Menubar option"), App.supportProjectAction, "", "heart.fill", .red)
|
||||
addMenuItem(String(format: NSLocalizedString("About %@", comment: "Menubar option. %@ is AltTab"), App.name), #selector(App.showAboutWindow), "", "info.circle", nil, App.self)
|
||||
addMenuItem(NSLocalizedString("Debug tools", comment: "Menubar option"), #selector(App.showDebugWindow), "", "scope", nil, App.self)
|
||||
addMenuItem(NSLocalizedString("Send feedback…", comment: "Menubar option"), #selector(App.showFeedbackPanel), "", "text.bubble", nil, App.self)
|
||||
addMenuItem(NSLocalizedString("Support this project", comment: "Menubar option"), App.supportProjectAction, "", "heart.fill", .red, App.self)
|
||||
menu.addItem(NSMenuItem.separator())
|
||||
addMenuItem(String(format: NSLocalizedString("Quit %@", comment: "Menubar option. %@ is AltTab"), App.name), #selector(NSApplication.terminate(_:)), "q", nil) // "xmark.rectangle" is not necessary; macos automatically recognizes Quit
|
||||
statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.squareLength)
|
||||
@@ -55,7 +56,7 @@ class Menubar {
|
||||
@objc static func statusItemOnClick() {
|
||||
// NSApp.currentEvent == nil if the icon is "clicked" through VoiceOver
|
||||
if let type = NSApp.currentEvent?.type, type != .leftMouseDown {
|
||||
App.app.showUiFromShortcut0()
|
||||
App.showUiFromShortcut0()
|
||||
} else {
|
||||
statusItem.popUpMenu(Menubar.menu)
|
||||
}
|
||||
@@ -95,7 +96,7 @@ class PermissionCallout: StackView {
|
||||
button.attributedTitle = NSAttributedString(string: NSLocalizedString("Grant permission", comment: "Menubar callout button"), attributes: [NSAttributedString.Key.foregroundColor: NSColor.white])
|
||||
button.onAction = { _ in
|
||||
Preferences.remove("screenRecordingPermissionSkipped")
|
||||
App.app.restart()
|
||||
App.restart()
|
||||
}
|
||||
self.init([label, button], .vertical, true, top: 8, right: 15, bottom: 10, left: 15)
|
||||
wantsLayer = true
|
||||
|
||||
+18
-16
@@ -1,9 +1,10 @@
|
||||
import Cocoa
|
||||
|
||||
class PreviewPanel: NSPanel {
|
||||
private let previewView = LightImageView(withTransparencyChecks: true)
|
||||
private let borderView = BorderView()
|
||||
private var currentId: CGWindowID?
|
||||
private static let previewView = LightImageView(withTransparencyChecks: true)
|
||||
private static let borderView = BorderView()
|
||||
private static var currentId: CGWindowID?
|
||||
static var shared: PreviewPanel!
|
||||
|
||||
/// this allows the window to be above the menubar when its origin.y is set to 0
|
||||
override func constrainFrameRect(_ frameRect: NSRect, to screen: NSScreen?) -> NSRect {
|
||||
@@ -18,52 +19,53 @@ class PreviewPanel: NSPanel {
|
||||
titleVisibility = .hidden
|
||||
titlebarAppearsTransparent = true
|
||||
backgroundColor = .clear
|
||||
contentView = previewView
|
||||
borderView.autoresizingMask = [.width, .height]
|
||||
previewView.addSubview(borderView)
|
||||
contentView = Self.previewView
|
||||
Self.borderView.autoresizingMask = [.width, .height]
|
||||
Self.previewView.addSubview(Self.borderView)
|
||||
// triggering AltTab before or during Space transition animation brings the window on the Space post-transition
|
||||
collectionBehavior = .canJoinAllSpaces
|
||||
// helps filter out this window from the thumbnails
|
||||
setAccessibilitySubrole(.unknown)
|
||||
Self.shared = self
|
||||
}
|
||||
|
||||
func show(_ id: CGWindowID, _ preview: CALayerContents, _ position: CGPoint, _ size: CGSize) {
|
||||
static func show(_ id: CGWindowID, _ preview: CALayerContents, _ position: CGPoint, _ size: CGSize) {
|
||||
if id != currentId {
|
||||
repositionAndResize(position, size)
|
||||
previewView.updateContents(preview, size)
|
||||
}
|
||||
if id != currentId || !isVisible {
|
||||
if id != currentId || !Self.shared.isVisible {
|
||||
if Preferences.previewFadeInAnimation {
|
||||
alphaValue = 0
|
||||
Self.shared.alphaValue = 0
|
||||
NSAnimationContext.runAnimationGroup { context in
|
||||
context.duration = 0.3
|
||||
animator().alphaValue = 1
|
||||
Self.shared.animator().alphaValue = 1
|
||||
}
|
||||
}
|
||||
currentId = id
|
||||
order(.below, relativeTo: App.app.tilesPanel.windowNumber)
|
||||
Self.shared.order(.below, relativeTo: TilesPanel.shared.windowNumber)
|
||||
// Despite using `previewPanel.order(.below)`, a z-ordering issue can occur in the following scenario:
|
||||
// 1. Show a preview of a window that is on a different monitor than the thumbnails panel
|
||||
// 2. Select a window in the switcher that is on the same monitor as the thumbnails panel, and whose position overlaps with the thumbnails panel
|
||||
// 3. For a single frame, the preview of the newly selected window can appear above the thumbnails panel before going back underneath it
|
||||
// Simply using order(.below) is not sufficient to prevent this brief flicker. We explicitly set the preview panel's window level to be one below the thumbnails panel
|
||||
level = NSWindow.Level(rawValue: App.app.tilesPanel.level.rawValue - 1)
|
||||
Self.shared.level = NSWindow.Level(rawValue: TilesPanel.shared.level.rawValue - 1)
|
||||
}
|
||||
}
|
||||
|
||||
func updateIfShowing(_ id: CGWindowID?, _ preview: CALayerContents, _ position: CGPoint, _ size: CGSize) {
|
||||
if isVisible && id == currentId {
|
||||
static func updateIfShowing(_ id: CGWindowID?, _ preview: CALayerContents, _ position: CGPoint, _ size: CGSize) {
|
||||
if Self.shared.isVisible && id == currentId {
|
||||
repositionAndResize(position, size)
|
||||
previewView.updateContents(preview, size)
|
||||
}
|
||||
}
|
||||
|
||||
private func repositionAndResize( _ position: CGPoint, _ size: CGSize) {
|
||||
private static func repositionAndResize( _ position: CGPoint, _ size: CGSize) {
|
||||
var frame = NSRect(origin: position, size: size)
|
||||
// Flip Y coordinate from Quartz (0,0 at bottom-left) to Cocoa coordinates (0,0 at top-left)
|
||||
// Always use the primary screen as reference since all coordinates are relative to it
|
||||
frame.origin.y = NSScreen.screens.first!.frame.maxY - frame.maxY
|
||||
setFrame(frame, display: false)
|
||||
Self.shared.setFrame(frame, display: false)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -37,7 +37,7 @@ class TileOverView: FlippedView {
|
||||
|
||||
func updateHover() {
|
||||
guard let scrollView, !scrollView.isCurrentlyScrolling else { return }
|
||||
let location = convert(App.app.tilesPanel.mouseLocationOutsideOfEventStream, from: nil)
|
||||
let location = convert(TilesPanel.shared.mouseLocationOutsideOfEventStream, from: nil)
|
||||
updateButtonHover(location)
|
||||
let newTarget = findTarget(location)
|
||||
if let target = newTarget ?? previousTarget {
|
||||
|
||||
@@ -70,7 +70,7 @@ class TileView: FlippedView {
|
||||
lastDragLocation = nil
|
||||
dragAndDropTimer?.invalidate()
|
||||
dragAndDropTimer = nil
|
||||
App.app.tilesPanel.tilesView.thumbnailOverView.resetHoveredWindow()
|
||||
TilesView.thumbnailOverView.resetHoveredWindow()
|
||||
}
|
||||
|
||||
override func performDragOperation(_ sender: NSDraggingInfo) -> Bool {
|
||||
@@ -79,7 +79,7 @@ class TileView: FlippedView {
|
||||
let urls = sender.draggingPasteboard.readObjects(forClasses: [NSURL.self]) as! [URL]
|
||||
let appUrl = window_!.application.bundleURL!
|
||||
let open = try? NSWorkspace.shared.open(urls, withApplicationAt: appUrl, options: [], configuration: [:])
|
||||
App.app.hideUi()
|
||||
App.hideUi()
|
||||
return open != nil
|
||||
}
|
||||
|
||||
@@ -253,8 +253,8 @@ class TileView: FlippedView {
|
||||
isFullscreen: element.isFullscreen && !Preferences.hideStatusIcons,
|
||||
isMinimized: element.isMinimized && !Preferences.hideStatusIcons,
|
||||
showSpace: !(element.isWindowlessApp || Spaces.isSingleSpace() || Preferences.hideSpaceNumberLabels || (
|
||||
Preferences.spacesToShow[App.app.shortcutIndex] == .visible && (
|
||||
NSScreen.screens.count < 2 || Preferences.screensToShow[App.app.shortcutIndex] == .showingAltTab
|
||||
Preferences.spacesToShow[App.shortcutIndex] == .visible && (
|
||||
NSScreen.screens.count < 2 || Preferences.screensToShow[App.shortcutIndex] == .showingAltTab
|
||||
)
|
||||
))
|
||||
)
|
||||
@@ -288,7 +288,7 @@ class TileView: FlippedView {
|
||||
updateAppIcon(element, title)
|
||||
updateDockLabelIcon(element.dockLabel)
|
||||
setAccessibilityHelp(getAccessibilityHelp(element.application.localizedName, element.dockLabel))
|
||||
mouseUpCallback = { () -> Void in App.app.focusSelectedWindow(element) }
|
||||
mouseUpCallback = { () -> Void in App.focusSelectedWindow(element) }
|
||||
mouseMovedCallback = { () -> Void in Windows.updateSelectedAndHoveredWindowIndex(index, true) }
|
||||
}
|
||||
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
import Cocoa
|
||||
|
||||
class TilesPanel: NSPanel {
|
||||
var tilesView = TilesView()
|
||||
override var canBecomeKey: Bool { true }
|
||||
static var maxPossibleThumbnailSize = NSSize.zero
|
||||
static var maxPossibleAppIconSize = NSSize.zero
|
||||
static var shared: TilesPanel!
|
||||
|
||||
convenience init() {
|
||||
self.init(contentRect: .zero, styleMask: .nonactivatingPanel, backing: .buffered, defer: false)
|
||||
@@ -14,7 +14,8 @@ class TilesPanel: NSPanel {
|
||||
hidesOnDeactivate = false
|
||||
titleVisibility = .hidden
|
||||
backgroundColor = .clear
|
||||
contentView! = tilesView.contentView
|
||||
TilesView.initialize()
|
||||
contentView! = TilesView.contentView
|
||||
// triggering AltTab before or during Space transition animation brings the window on the Space post-transition
|
||||
collectionBehavior = .canJoinAllSpaces
|
||||
// 2nd highest level possible; this allows the app to go on top of context menus
|
||||
@@ -25,6 +26,7 @@ class TilesPanel: NSPanel {
|
||||
// for VoiceOver
|
||||
setAccessibilityLabel(App.name)
|
||||
updateAppearance()
|
||||
Self.shared = self
|
||||
}
|
||||
|
||||
func updateAppearance() {
|
||||
@@ -34,18 +36,18 @@ class TilesPanel: NSPanel {
|
||||
|
||||
func updateContents(_ preservedScrollOrigin: CGPoint?) {
|
||||
caTransaction {
|
||||
tilesView.updateItemsAndLayout(preservedScrollOrigin)
|
||||
guard App.app.appIsBeingUsed else { return }
|
||||
setContentSize(tilesView.contentView.frame.size)
|
||||
guard App.app.appIsBeingUsed else { return }
|
||||
TilesView.updateItemsAndLayout(preservedScrollOrigin)
|
||||
guard App.appIsBeingUsed else { return }
|
||||
setContentSize(TilesView.contentView.frame.size)
|
||||
guard App.appIsBeingUsed else { return }
|
||||
NSScreen.preferred.repositionPanel(self)
|
||||
}
|
||||
// prevent further AppKit work
|
||||
tilesView.clearNeedsLayout()
|
||||
TilesView.clearNeedsLayout()
|
||||
}
|
||||
|
||||
override func orderOut(_ sender: Any?) {
|
||||
tilesView.clearNeedsLayout()
|
||||
TilesView.clearNeedsLayout()
|
||||
if Preferences.fadeOutAnimation {
|
||||
NSAnimationContext.runAnimationGroup(
|
||||
{ _ in animator().alphaValue = 0 },
|
||||
@@ -63,7 +65,7 @@ class TilesPanel: NSPanel {
|
||||
alphaValue = 1
|
||||
makeKeyAndOrderFront(nil)
|
||||
CursorEvents.toggle(true)
|
||||
DispatchQueue.main.async { self.tilesView.scrollView.flashScrollers() }
|
||||
DispatchQueue.main.async { TilesView.scrollView.flashScrollers() }
|
||||
}
|
||||
|
||||
static func maxThumbnailsWidth(_ screen: NSScreen = NSScreen.preferred) -> CGFloat {
|
||||
@@ -113,8 +115,8 @@ extension TilesPanel: NSWindowDelegate {
|
||||
// other windows can steal key focus from alt-tab; we make sure that if it's active, if keeps key focus
|
||||
// dispatching to the main queue is necessary to introduce a delay in scheduling the makeKey; otherwise it is ignored
|
||||
DispatchQueue.main.async {
|
||||
if App.app.appIsBeingUsed {
|
||||
App.app.tilesPanel.makeKeyAndOrderFront(nil)
|
||||
if App.appIsBeingUsed {
|
||||
TilesPanel.shared.makeKeyAndOrderFront(nil)
|
||||
}
|
||||
MainMenu.toggle(enabled: true)
|
||||
}
|
||||
|
||||
@@ -8,48 +8,50 @@ enum SearchMode {
|
||||
case locked
|
||||
}
|
||||
|
||||
class TilesView: NSObject {
|
||||
var scrollView: ScrollView!
|
||||
var contentView: EffectView!
|
||||
var searchField = NSSearchField(frame: .zero)
|
||||
private(set) var searchMode: SearchMode = .off
|
||||
var rows = [[TileView]]()
|
||||
private var lastRowSignature = [Int]()
|
||||
class TilesView {
|
||||
static var scrollView: ScrollView!
|
||||
static var contentView: EffectView!
|
||||
static var searchField = NSSearchField(frame: .zero)
|
||||
private(set) static var searchMode: SearchMode = .off
|
||||
static var rows = [[TileView]]()
|
||||
private static var lastRowSignature = [Int]()
|
||||
static var recycledViews = [TileView]()
|
||||
static var thumbnailsWidth = CGFloat(0.0)
|
||||
static var thumbnailsHeight = CGFloat(0.0)
|
||||
static var layoutCache = LayoutCache()
|
||||
var thumbnailUnderLayer = TileUnderLayer()
|
||||
var thumbnailOverView = TileOverView()
|
||||
static var thumbnailUnderLayer = TileUnderLayer()
|
||||
static var thumbnailOverView = TileOverView()
|
||||
private static var initialized = false
|
||||
|
||||
override init() {
|
||||
super.init()
|
||||
static func initialize() {
|
||||
guard !initialized else { return }
|
||||
configureSearchField()
|
||||
updateBackgroundView()
|
||||
// TODO: think about this optimization more
|
||||
(1...20).forEach { _ in TilesView.recycledViews.append(TileView()) }
|
||||
Self.updateCachedSizes()
|
||||
initialized = true
|
||||
}
|
||||
|
||||
var isSearchModeOn: Bool { searchMode != .off }
|
||||
var isSearchEditing: Bool { searchMode == .editing }
|
||||
var isSearchLocked: Bool { searchMode == .locked }
|
||||
static var isSearchModeOn: Bool { searchMode != .off }
|
||||
static var isSearchEditing: Bool { searchMode == .editing }
|
||||
static var isSearchLocked: Bool { searchMode == .locked }
|
||||
|
||||
func startSearchSession(_ startInSearchMode: Bool) {
|
||||
static func startSearchSession(_ startInSearchMode: Bool) {
|
||||
searchField.stringValue = ""
|
||||
Windows.updateSearchQuery("")
|
||||
searchMode = startInSearchMode ? .editing : .off
|
||||
updateSearchFieldEditability()
|
||||
}
|
||||
|
||||
func endSearchSession() {
|
||||
static func endSearchSession() {
|
||||
searchField.stringValue = ""
|
||||
Windows.updateSearchQuery("")
|
||||
searchMode = .off
|
||||
updateSearchFieldEditability()
|
||||
}
|
||||
|
||||
func toggleSearchModeFromShortcut() {
|
||||
static func toggleSearchModeFromShortcut() {
|
||||
if searchMode == .off {
|
||||
enableSearchEditing()
|
||||
} else if searchMode == .editing {
|
||||
@@ -59,18 +61,18 @@ class TilesView: NSObject {
|
||||
}
|
||||
}
|
||||
|
||||
func disableSearchMode() {
|
||||
static func disableSearchMode() {
|
||||
guard searchMode != .off else { return }
|
||||
searchMode = .off
|
||||
updateSearchFieldEditability()
|
||||
searchField.stringValue = ""
|
||||
clearHover()
|
||||
Windows.updateSearchQuery("")
|
||||
App.app.refreshUi(true)
|
||||
App.refreshUi(true)
|
||||
focusSelectedTileIfPossible()
|
||||
}
|
||||
|
||||
func lockSearchMode() {
|
||||
static func lockSearchMode() {
|
||||
if searchMode == .editing {
|
||||
searchMode = .locked
|
||||
updateSearchFieldEditability()
|
||||
@@ -80,7 +82,7 @@ class TilesView: NSObject {
|
||||
}
|
||||
}
|
||||
|
||||
func enableSearchEditing() {
|
||||
static func enableSearchEditing() {
|
||||
guard searchMode != .editing else {
|
||||
placeSearchCaretAtEnd()
|
||||
return
|
||||
@@ -88,22 +90,22 @@ class TilesView: NSObject {
|
||||
let wasOff = searchMode == .off
|
||||
searchMode = .editing
|
||||
updateSearchFieldEditability()
|
||||
App.app.forceDoNothingOnRelease = true
|
||||
App.forceDoNothingOnRelease = true
|
||||
clearHover()
|
||||
stopKeyRepeatTimers()
|
||||
if wasOff {
|
||||
App.app.refreshUi(true)
|
||||
App.refreshUi(true)
|
||||
}
|
||||
App.app.tilesPanel.makeFirstResponder(searchField)
|
||||
TilesPanel.shared.makeFirstResponder(searchField)
|
||||
placeSearchCaretAtEnd()
|
||||
}
|
||||
|
||||
func handleSearchEditingKeyDown(_ event: NSEvent) -> Bool {
|
||||
static func handleSearchEditingKeyDown(_ event: NSEvent) -> Bool {
|
||||
let keyCode = event.keyCode
|
||||
if keyCode == UInt16(kVK_LeftArrow) { App.app.cycleSelection(.left); return true }
|
||||
if keyCode == UInt16(kVK_RightArrow) { App.app.cycleSelection(.right); return true }
|
||||
if keyCode == UInt16(kVK_UpArrow) { App.app.cycleSelection(.up); return true }
|
||||
if keyCode == UInt16(kVK_DownArrow) { App.app.cycleSelection(.down); return true }
|
||||
if keyCode == UInt16(kVK_LeftArrow) { App.cycleSelection(.left); return true }
|
||||
if keyCode == UInt16(kVK_RightArrow) { App.cycleSelection(.right); return true }
|
||||
if keyCode == UInt16(kVK_UpArrow) { App.cycleSelection(.up); return true }
|
||||
if keyCode == UInt16(kVK_DownArrow) { App.cycleSelection(.down); return true }
|
||||
if keyCode == UInt16(kVK_Space) { return false }
|
||||
if keyCode == UInt16(kVK_Delete) || keyCode == UInt16(kVK_ForwardDelete) {
|
||||
deleteSearchCharacter(keyCode)
|
||||
@@ -114,7 +116,7 @@ class TilesView: NSObject {
|
||||
return true
|
||||
}
|
||||
if matchesShortcut(event, "cancelShortcut") {
|
||||
App.app.cancelSearchModeOrHideUi()
|
||||
App.cancelSearchModeOrHideUi()
|
||||
return true
|
||||
}
|
||||
if matchesSearchShortcut(event) {
|
||||
@@ -124,7 +126,7 @@ class TilesView: NSObject {
|
||||
return false
|
||||
}
|
||||
|
||||
private func configureSearchField() {
|
||||
private static func configureSearchField() {
|
||||
searchField.placeholderString = NSLocalizedString("Search", comment: "")
|
||||
searchField.sendsSearchStringImmediately = true
|
||||
searchField.sendsWholeSearchString = true
|
||||
@@ -137,24 +139,24 @@ class TilesView: NSObject {
|
||||
searchField.controlSize = .regular
|
||||
}
|
||||
searchField.usesSingleLineMode = true
|
||||
searchField.target = self
|
||||
searchField.action = #selector(searchFieldChanged(_:))
|
||||
searchField.target = Self.self
|
||||
searchField.action = #selector(Self.searchFieldChanged(_:))
|
||||
updateSearchFieldEditability()
|
||||
}
|
||||
|
||||
@objc private func searchFieldChanged(_ sender: NSSearchField) {
|
||||
@objc private static func searchFieldChanged(_ sender: NSSearchField) {
|
||||
updateSearchQuery(sender.stringValue)
|
||||
}
|
||||
|
||||
private func updateSearchQuery(_ query: String) {
|
||||
private static func updateSearchQuery(_ query: String) {
|
||||
if Windows.searchQuery == query { return }
|
||||
clearHover()
|
||||
Windows.updateSearchQuery(query)
|
||||
stopKeyRepeatTimers()
|
||||
App.app.refreshUi(true)
|
||||
App.refreshUi(true)
|
||||
}
|
||||
|
||||
private func appendSearchText(_ text: String) {
|
||||
private static func appendSearchText(_ text: String) {
|
||||
guard !text.isEmpty else { return }
|
||||
if let editor = searchField.currentEditor() {
|
||||
let current = searchField.stringValue as NSString
|
||||
@@ -167,7 +169,7 @@ class TilesView: NSObject {
|
||||
updateSearchQuery(searchField.stringValue)
|
||||
}
|
||||
|
||||
private func deleteSearchCharacter(_ keyCode: UInt16) {
|
||||
private static func deleteSearchCharacter(_ keyCode: UInt16) {
|
||||
guard !searchField.stringValue.isEmpty else { return }
|
||||
if let editor = searchField.currentEditor() {
|
||||
let current = searchField.stringValue as NSString
|
||||
@@ -189,13 +191,13 @@ class TilesView: NSObject {
|
||||
updateSearchQuery(searchField.stringValue)
|
||||
}
|
||||
|
||||
private func clampedSelectionRange(_ stringLength: Int, _ selectedRange: NSRange) -> NSRange {
|
||||
private static func clampedSelectionRange(_ stringLength: Int, _ selectedRange: NSRange) -> NSRange {
|
||||
let location = max(0, min(selectedRange.location, stringLength))
|
||||
let length = max(0, min(selectedRange.length, stringLength - location))
|
||||
return NSRange(location: location, length: length)
|
||||
}
|
||||
|
||||
private func clearHover() {
|
||||
private static func clearHover() {
|
||||
if let oldHoveredWindowIndex = Windows.hoveredWindowIndex {
|
||||
Windows.hoveredWindowIndex = nil
|
||||
TilesView.highlight(oldHoveredWindowIndex)
|
||||
@@ -203,27 +205,27 @@ class TilesView: NSObject {
|
||||
}
|
||||
}
|
||||
|
||||
private func stopKeyRepeatTimers() {
|
||||
KeyRepeatTimer.stopTimerForRepeatingKey(Preferences.indexToName("nextWindowShortcut", App.app.shortcutIndex))
|
||||
private static func stopKeyRepeatTimers() {
|
||||
KeyRepeatTimer.stopTimerForRepeatingKey(Preferences.indexToName("nextWindowShortcut", App.shortcutIndex))
|
||||
KeyRepeatTimer.stopTimerForRepeatingKey("previousWindowShortcut")
|
||||
}
|
||||
|
||||
private func focusSelectedTileIfPossible() {
|
||||
private static func focusSelectedTileIfPossible() {
|
||||
guard Windows.selectedWindowIndex >= 0, Windows.selectedWindowIndex < TilesView.recycledViews.count else { return }
|
||||
App.app.tilesPanel.makeFirstResponder(TilesView.recycledViews[Windows.selectedWindowIndex])
|
||||
TilesPanel.shared.makeFirstResponder(TilesView.recycledViews[Windows.selectedWindowIndex])
|
||||
}
|
||||
|
||||
private func placeSearchCaretAtEnd() {
|
||||
private static func placeSearchCaretAtEnd() {
|
||||
guard searchMode == .editing else { return }
|
||||
if App.app.tilesPanel.firstResponder !== searchField.currentEditor() {
|
||||
App.app.tilesPanel.makeFirstResponder(searchField)
|
||||
if TilesPanel.shared.firstResponder !== searchField.currentEditor() {
|
||||
TilesPanel.shared.makeFirstResponder(searchField)
|
||||
}
|
||||
guard let editor = searchField.currentEditor() else { return }
|
||||
let end = searchField.stringValue.utf16.count
|
||||
editor.selectedRange = NSRange(location: end, length: 0)
|
||||
}
|
||||
|
||||
private func insertedSearchText(from event: NSEvent) -> String? {
|
||||
private static func insertedSearchText(from event: NSEvent) -> String? {
|
||||
if event.modifierFlags.contains(.command) || event.modifierFlags.contains(.control) || event.modifierFlags.contains(.function) {
|
||||
return nil
|
||||
}
|
||||
@@ -239,20 +241,20 @@ class TilesView: NSObject {
|
||||
return String(value)
|
||||
}
|
||||
|
||||
private func matchesSearchShortcut(_ event: NSEvent) -> Bool {
|
||||
private static func matchesSearchShortcut(_ event: NSEvent) -> Bool {
|
||||
matchesShortcut(event, "searchShortcut")
|
||||
}
|
||||
|
||||
private func updateSearchFieldEditability() {
|
||||
private static func updateSearchFieldEditability() {
|
||||
let editable = searchMode == .editing
|
||||
searchField.isEditable = editable
|
||||
searchField.isSelectable = editable
|
||||
}
|
||||
|
||||
private func matchesShortcut(_ event: NSEvent, _ shortcutId: String) -> Bool {
|
||||
private static func matchesShortcut(_ event: NSEvent, _ shortcutId: String) -> Bool {
|
||||
guard let shortcut = ControlsTab.shortcuts[shortcutId]?.shortcut else { return false }
|
||||
if shortcut.keyCode == .none || shortcut.carbonKeyCode != UInt32(event.keyCode) { return false }
|
||||
let holdModifiers = ControlsTab.shortcuts[Preferences.indexToName("holdShortcut", App.app.shortcutIndex)]?.shortcut.carbonModifierFlags.cleaned() ?? 0
|
||||
let holdModifiers = ControlsTab.shortcuts[Preferences.indexToName("holdShortcut", App.shortcutIndex)]?.shortcut.carbonModifierFlags.cleaned() ?? 0
|
||||
let eventModifiers = cocoaToCarbonFlags(event.modifierFlags).cleaned()
|
||||
let shortcutModifiers = shortcut.carbonModifierFlags.cleaned()
|
||||
return eventModifiers == shortcutModifiers || eventModifiers == (shortcutModifiers | holdModifiers)
|
||||
@@ -268,7 +270,7 @@ class TilesView: NSObject {
|
||||
TileFontIconView.warmCaches(symbols: [.circledPlusSign, .circledMinusSign, .circledSlashSign, .circledNumber0, .circledNumber10, .circledStar], size: Appearance.fontHeight, color: Appearance.fontColor)
|
||||
}
|
||||
|
||||
func updateBackgroundView() {
|
||||
static func updateBackgroundView() {
|
||||
contentView = makeAppropriateEffectView()
|
||||
scrollView = ScrollView()
|
||||
searchField.isHidden = searchMode == .off
|
||||
@@ -276,7 +278,7 @@ class TilesView: NSObject {
|
||||
contentView.addSubview(scrollView)
|
||||
}
|
||||
|
||||
func reset() {
|
||||
static func reset() {
|
||||
// it would be nicer to remove this whole "reset" logic, and instead update each component to check Appearance properties before showing
|
||||
// Maybe in some Appkit willDraw() function that triggers before drawing it
|
||||
NSScreen.updatePreferred()
|
||||
@@ -290,7 +292,7 @@ class TilesView: NSObject {
|
||||
Applications.updateAppIcons()
|
||||
}
|
||||
updateBackgroundView()
|
||||
App.app.tilesPanel.contentView = contentView
|
||||
TilesPanel.shared.contentView = contentView
|
||||
for i in 0..<TilesView.recycledViews.count {
|
||||
TilesView.recycledViews[i] = TileView()
|
||||
}
|
||||
@@ -307,7 +309,7 @@ class TilesView: NSObject {
|
||||
view.indexInRecycledViews = indexInRecycledViews
|
||||
guard view.frame != .zero else { return }
|
||||
view.drawHighlight()
|
||||
let underLayer = App.app.tilesPanel.tilesView.thumbnailUnderLayer
|
||||
let underLayer = TilesView.thumbnailUnderLayer
|
||||
guard Windows.selectedWindowIndex >= 0, Windows.selectedWindowIndex < recycledViews.count else { return }
|
||||
let focusedView = recycledViews[Windows.selectedWindowIndex]
|
||||
let hoveredView = Windows.hoveredWindowIndex.flatMap { $0 >= 0 && $0 < recycledViews.count ? recycledViews[$0] : nil }
|
||||
@@ -317,7 +319,7 @@ class TilesView: NSObject {
|
||||
)
|
||||
}
|
||||
|
||||
func nextRow(_ direction: Direction, allowWrap: Bool = true) -> [TileView]? {
|
||||
static func nextRow(_ direction: Direction, allowWrap: Bool = true) -> [TileView]? {
|
||||
let step = direction == .down ? 1 : -1
|
||||
if let currentRow = Windows.selectedWindow()?.rowIndex {
|
||||
var nextRow = currentRow + step
|
||||
@@ -343,7 +345,7 @@ class TilesView: NSObject {
|
||||
return nil
|
||||
}
|
||||
|
||||
func navigateUpOrDown(_ direction: Direction, allowWrap: Bool = true) {
|
||||
static func navigateUpOrDown(_ direction: Direction, allowWrap: Bool = true) {
|
||||
guard Windows.selectedWindowIndex < TilesView.recycledViews.count else { return }
|
||||
let focusedViewFrame = TilesView.recycledViews[Windows.selectedWindowIndex].frame
|
||||
let originCenter = NSMidX(focusedViewFrame)
|
||||
@@ -361,7 +363,7 @@ class TilesView: NSObject {
|
||||
Windows.updateSelectedAndHoveredWindowIndex(targetIndex)
|
||||
}
|
||||
|
||||
func updateItemsAndLayout(_ preservedScrollOrigin: CGPoint?) {
|
||||
static func updateItemsAndLayout(_ preservedScrollOrigin: CGPoint?) {
|
||||
let widthMax = TilesPanel.maxThumbnailsWidth().rounded()
|
||||
if Preferences.appearanceSize == .auto {
|
||||
resolveAutoSize(widthMax)
|
||||
@@ -390,11 +392,11 @@ class TilesView: NSObject {
|
||||
}
|
||||
}
|
||||
|
||||
func currentScrollOrigin() -> CGPoint {
|
||||
scrollView.contentView.bounds.origin
|
||||
static func currentScrollOrigin() -> CGPoint {
|
||||
return scrollView.contentView.bounds.origin
|
||||
}
|
||||
|
||||
private func restoreScrollOrigin(_ scrollOrigin: CGPoint) {
|
||||
private static func restoreScrollOrigin(_ scrollOrigin: CGPoint) {
|
||||
guard let documentView = scrollView.documentView else { return }
|
||||
let visibleSize = scrollView.contentView.bounds.size
|
||||
let documentSize = documentView.frame.size
|
||||
@@ -405,7 +407,7 @@ class TilesView: NSObject {
|
||||
scrollView.reflectScrolledClipView(scrollView.contentView)
|
||||
}
|
||||
|
||||
private func resolveAutoSize(_ widthMax: CGFloat) {
|
||||
private static func resolveAutoSize(_ widthMax: CGFloat) {
|
||||
let searchReservedHeight: CGFloat = searchMode == .off ? 0 : searchBarHeight() + 10
|
||||
let heightMax = max(0, TilesPanel.maxThumbnailsHeight() - searchReservedHeight)
|
||||
for size in [AppearanceSizePreference.large, .medium, .small] {
|
||||
@@ -416,7 +418,7 @@ class TilesView: NSObject {
|
||||
}
|
||||
}
|
||||
|
||||
private func dryRunLayoutTileViews(_ widthMax: CGFloat) -> CGFloat {
|
||||
private static func dryRunLayoutTileViews(_ widthMax: CGFloat) -> CGFloat {
|
||||
let labelHeight = Self.layoutCache.labelHeight
|
||||
let height = TileView.height(labelHeight)
|
||||
let isLeftToRight = App.shared.userInterfaceLayoutDirection == .leftToRight
|
||||
@@ -426,7 +428,7 @@ class TilesView: NSObject {
|
||||
var maxY = currentY + height + Appearance.interCellPadding
|
||||
var index = 0
|
||||
while index < TilesView.recycledViews.count {
|
||||
guard App.app.appIsBeingUsed else { return maxY }
|
||||
guard App.appIsBeingUsed else { return maxY }
|
||||
defer { index += 1 }
|
||||
let view = TilesView.recycledViews[index]
|
||||
guard index < Windows.list.count else { break }
|
||||
@@ -447,7 +449,7 @@ class TilesView: NSObject {
|
||||
return maxY
|
||||
}
|
||||
|
||||
private func layoutTileViews(_ widthMax: CGFloat) -> (CGFloat, CGFloat, CGFloat, [Int])? {
|
||||
private static func layoutTileViews(_ widthMax: CGFloat) -> (CGFloat, CGFloat, CGFloat, [Int])? {
|
||||
let labelHeight = Self.layoutCache.labelHeight
|
||||
let height = TileView.height(labelHeight)
|
||||
let isLeftToRight = App.shared.userInterfaceLayoutDirection == .leftToRight
|
||||
@@ -462,7 +464,7 @@ class TilesView: NSObject {
|
||||
rows.append([TileView]())
|
||||
var index = 0
|
||||
while index < TilesView.recycledViews.count {
|
||||
guard App.app.appIsBeingUsed else { return nil }
|
||||
guard App.appIsBeingUsed else { return nil }
|
||||
defer { index = index + 1 }
|
||||
let view = TilesView.recycledViews[index]
|
||||
if index < Windows.list.count {
|
||||
@@ -506,25 +508,25 @@ class TilesView: NSObject {
|
||||
return (maxX, maxY, labelHeight, rowSignature)
|
||||
}
|
||||
|
||||
private func needNewLine(_ projectedX: CGFloat, _ widthMax: CGFloat) -> Bool {
|
||||
private static func needNewLine(_ projectedX: CGFloat, _ widthMax: CGFloat) -> Bool {
|
||||
if App.shared.userInterfaceLayoutDirection == .leftToRight {
|
||||
return projectedX > widthMax
|
||||
}
|
||||
return projectedX < 0
|
||||
}
|
||||
|
||||
private func projectedWidth(_ currentX: CGFloat, _ width: CGFloat) -> CGFloat {
|
||||
private static func projectedWidth(_ currentX: CGFloat, _ width: CGFloat) -> CGFloat {
|
||||
if App.shared.userInterfaceLayoutDirection == .leftToRight {
|
||||
return currentX + width + Appearance.interCellPadding
|
||||
}
|
||||
return currentX - width - Appearance.interCellPadding
|
||||
}
|
||||
|
||||
private func localizedCurrentX(_ currentX: CGFloat, _ width: CGFloat) -> CGFloat {
|
||||
private static func localizedCurrentX(_ currentX: CGFloat, _ width: CGFloat) -> CGFloat {
|
||||
App.shared.userInterfaceLayoutDirection == .leftToRight ? currentX : currentX - width
|
||||
}
|
||||
|
||||
private func layoutParentViews(_ maxX: CGFloat, _ widthMax: CGFloat, _ maxY: CGFloat, _ labelHeight: CGFloat) {
|
||||
private static func layoutParentViews(_ maxX: CGFloat, _ widthMax: CGFloat, _ maxY: CGFloat, _ labelHeight: CGFloat) {
|
||||
let searchBarHeight = searchBarHeight()
|
||||
let searchBottomPadding = CGFloat(10)
|
||||
let searchReservedHeight = searchMode == .off ? 0 : searchBarHeight + searchBottomPadding
|
||||
@@ -562,7 +564,7 @@ class TilesView: NSObject {
|
||||
thumbnailUnderLayer.frame = CGRect(origin: .zero, size: docSize)
|
||||
}
|
||||
|
||||
private func searchBarHeight() -> CGFloat {
|
||||
private static func searchBarHeight() -> CGFloat {
|
||||
let fitting = searchField.fittingSize.height
|
||||
if fitting > 0 {
|
||||
return ceil(fitting)
|
||||
@@ -570,14 +572,14 @@ class TilesView: NSObject {
|
||||
return ceil(searchField.cell?.cellSize.height ?? 30)
|
||||
}
|
||||
|
||||
private func appIconsBottomViewportPadding(_ maxY: CGFloat, _ heightMax: CGFloat, _ labelHeight: CGFloat) -> CGFloat {
|
||||
private static func appIconsBottomViewportPadding(_ maxY: CGFloat, _ heightMax: CGFloat, _ labelHeight: CGFloat) -> CGFloat {
|
||||
guard Preferences.appearanceStyle == .appIcons, maxY > heightMax else { return 0 }
|
||||
return max(0, Appearance.windowPadding - labelHeight)
|
||||
}
|
||||
|
||||
func centerRows(_ maxX: CGFloat) {
|
||||
static func centerRows(_ maxX: CGFloat) {
|
||||
for row in rows where !row.isEmpty {
|
||||
guard App.app.appIsBeingUsed else { return }
|
||||
guard App.appIsBeingUsed else { return }
|
||||
let rowWidth = Appearance.interCellPadding + row.reduce(CGFloat(0)) { $0 + $1.frame.size.width + Appearance.interCellPadding }
|
||||
let offset = ((maxX - rowWidth) / 2).rounded()
|
||||
if offset > 0 {
|
||||
@@ -588,7 +590,7 @@ class TilesView: NSObject {
|
||||
}
|
||||
}
|
||||
|
||||
private func highlightStartView() {
|
||||
private static func highlightStartView() {
|
||||
if Windows.selectedWindow() != nil {
|
||||
TilesView.highlight(Windows.selectedWindowIndex)
|
||||
} else {
|
||||
@@ -608,7 +610,7 @@ class TilesView: NSObject {
|
||||
}
|
||||
}
|
||||
|
||||
func clearNeedsLayout() {
|
||||
static func clearNeedsLayout() {
|
||||
var views = [NSView]()
|
||||
if let contentView { views.append(contentView as NSView) }
|
||||
views.append(searchField)
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
import Cocoa
|
||||
|
||||
class PermissionsWindow: NSWindow {
|
||||
var accessibilityView: PermissionView!
|
||||
var screenRecordingView: PermissionView!
|
||||
var canBecomeKey_ = true
|
||||
override var canBecomeKey: Bool { canBecomeKey_ }
|
||||
static var accessibilityView: PermissionView!
|
||||
static var screenRecordingView: PermissionView!
|
||||
static var canBecomeKey_ = true
|
||||
override var canBecomeKey: Bool { Self.canBecomeKey_ }
|
||||
static var shared: PermissionsWindow!
|
||||
|
||||
convenience init() {
|
||||
self.init(contentRect: .zero, styleMask: [.titled, .closable], backing: .buffered, defer: false)
|
||||
@@ -12,24 +13,25 @@ class PermissionsWindow: NSWindow {
|
||||
setupWindow()
|
||||
setupView()
|
||||
setFrameAutosaveName("PermissionsWindow")
|
||||
Self.shared = self
|
||||
}
|
||||
|
||||
func show() {
|
||||
guard !isVisible else { return }
|
||||
Logger.debug { "" }
|
||||
center()
|
||||
App.shared.activate(ignoringOtherApps: true)
|
||||
makeKeyAndOrderFront(nil)
|
||||
SystemPermissions.setFrequentTimer()
|
||||
}
|
||||
|
||||
func updatePermissionViews() {
|
||||
static func updatePermissionViews() {
|
||||
accessibilityView.updatePermissionStatus(AccessibilityPermission.status)
|
||||
if #available(macOS 10.15, *) {
|
||||
screenRecordingView.updatePermissionStatus(ScreenRecordingPermission.status)
|
||||
}
|
||||
}
|
||||
|
||||
static func show() {
|
||||
guard !Self.shared.isVisible else { return }
|
||||
Logger.debug { "" }
|
||||
Self.shared.center()
|
||||
App.shared.activate(ignoringOtherApps: true)
|
||||
Self.shared.makeKeyAndOrderFront(nil)
|
||||
SystemPermissions.setFrequentTimer()
|
||||
}
|
||||
|
||||
private func setupWindow() {
|
||||
title = NSLocalizedString("AltTab needs some permissions", comment: "")
|
||||
hidesOnDeactivate = false
|
||||
@@ -48,7 +50,7 @@ class PermissionsWindow: NSWindow {
|
||||
let header = NSStackView(views: [appIcon, appText])
|
||||
header.translatesAutoresizingMaskIntoConstraints = false
|
||||
header.spacing = GridView.interPadding
|
||||
accessibilityView = PermissionView(
|
||||
Self.accessibilityView = PermissionView(
|
||||
"accessibility",
|
||||
NSLocalizedString("Accessibility", comment: ""),
|
||||
NSLocalizedString("This permission is needed to focus windows after you release the shortcut", comment: ""),
|
||||
@@ -57,10 +59,10 @@ class PermissionsWindow: NSWindow {
|
||||
)
|
||||
var rows = [
|
||||
[header],
|
||||
[accessibilityView],
|
||||
[Self.accessibilityView],
|
||||
]
|
||||
if #available(macOS 10.15, *) {
|
||||
screenRecordingView = PermissionView(
|
||||
Self.screenRecordingView = PermissionView(
|
||||
"screen-recording",
|
||||
NSLocalizedString("Screen Recording", comment: ""),
|
||||
NSLocalizedString("This permission is needed to show thumbnails and preview of open windows", comment: ""),
|
||||
@@ -68,7 +70,7 @@ class PermissionsWindow: NSWindow {
|
||||
"x-apple.systempreferences:com.apple.preference.security?Privacy_ScreenCapture",
|
||||
StackView(LabelAndControl.makeLabelWithCheckbox(NSLocalizedString("Use the app without this permission. Thumbnails won’t show.", comment: ""), "screenRecordingPermissionSkipped", labelPosition: .right))
|
||||
)
|
||||
rows.append([screenRecordingView])
|
||||
rows.append([Self.screenRecordingView])
|
||||
}
|
||||
let widestRowWidth = rows.reduce(0) { max($0, $1[0]!.fittingSize.width) }
|
||||
rows.forEach { $0[0]!.fit(widestRowWidth, $0[0]!.fittingSize.height) }
|
||||
@@ -102,4 +104,4 @@ extension PermissionsWindow: NSWindowDelegate {
|
||||
}
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -490,9 +490,10 @@ class SettingsWindow: NSWindow {
|
||||
private static let controlHighlightInset = CGFloat(1)
|
||||
private static let controlHighlightMinCornerRadius = CGFloat(4)
|
||||
private static let controlHighlightMaxCornerRadius = CGFloat(9)
|
||||
static var shared: SettingsWindow!
|
||||
|
||||
var canBecomeKey_ = true
|
||||
override var canBecomeKey: Bool { canBecomeKey_ }
|
||||
static var canBecomeKey_ = true
|
||||
override var canBecomeKey: Bool { Self.canBecomeKey_ }
|
||||
|
||||
private let splitViewController = NSSplitViewController()
|
||||
private let sidebarContainer = NSView()
|
||||
@@ -522,6 +523,7 @@ class SettingsWindow: NSWindow {
|
||||
setupWindow()
|
||||
setupView()
|
||||
setFrameAutosaveName("SettingsWindow")
|
||||
Self.shared = self
|
||||
}
|
||||
|
||||
private func setupWindow() {
|
||||
|
||||
@@ -39,7 +39,7 @@ class AboutTab {
|
||||
}
|
||||
|
||||
static func makeSupportProjectButton() -> NSButton {
|
||||
let button = makeButtonWithIcon(NSLocalizedString("Support this project", comment: ""), App.supportProjectAction, "heart.fill", .red)
|
||||
let button = makeButtonWithIcon(NSLocalizedString("Support this project", comment: ""), App.supportProjectAction, "heart.fill", .red, App.self)
|
||||
styleSupportProjectButton(button)
|
||||
return button
|
||||
}
|
||||
@@ -50,8 +50,8 @@ class AboutTab {
|
||||
button.heightAnchor.constraint(equalToConstant: SettingsWindow.sidebarActionButtonHeight).isActive = true
|
||||
}
|
||||
|
||||
private static func makeButtonWithIcon(_ title: String, _ selector: Selector, _ symbolName: String?, _ color: NSColor? = nil) -> NSButton {
|
||||
let button = NSButton(title: title, target: nil, action: selector)
|
||||
private static func makeButtonWithIcon(_ title: String, _ selector: Selector, _ symbolName: String?, _ color: NSColor? = nil, _ target: AnyObject? = nil) -> NSButton {
|
||||
let button = NSButton(title: title, target: target, action: selector)
|
||||
if #available(macOS 26.0, *), let symbolName {
|
||||
button.image = NSImage(systemSymbolName: symbolName, accessibilityDescription: nil)
|
||||
button.imagePosition = .imageLeading
|
||||
@@ -65,15 +65,17 @@ class AboutTab {
|
||||
|
||||
class AboutWindow: NSPanel {
|
||||
private static let contentPadding = CGFloat(24)
|
||||
static var shared: AboutWindow?
|
||||
|
||||
var canBecomeKey_ = true
|
||||
override var canBecomeKey: Bool { canBecomeKey_ }
|
||||
static var canBecomeKey_ = true
|
||||
override var canBecomeKey: Bool { Self.canBecomeKey_ }
|
||||
|
||||
convenience init() {
|
||||
self.init(contentRect: NSRect(x: 0, y: 0, width: 600, height: 450), styleMask: [.utilityWindow, .titled, .closable], backing: .buffered, defer: false)
|
||||
setupWindow()
|
||||
setupView()
|
||||
setFrameAutosaveName("AboutWindow")
|
||||
Self.shared = self
|
||||
}
|
||||
|
||||
private func setupWindow() {
|
||||
|
||||
@@ -70,7 +70,7 @@ class ExceptionsTab {
|
||||
dialog.allowsMultipleSelection = false
|
||||
dialog.allowedFileTypes = ["app"]
|
||||
dialog.canChooseDirectories = false
|
||||
dialog.beginSheetModal(for: App.app.settingsWindow) {
|
||||
dialog.beginSheetModal(for: SettingsWindow.shared) {
|
||||
if $0 == .OK, let url = dialog.url, let bundleId = Bundle(url: url)?.bundleIdentifier {
|
||||
tableView.insertRow(bundleId)
|
||||
}
|
||||
|
||||
@@ -82,7 +82,7 @@ class GeneralTab {
|
||||
if #available(macOS 11.0, *) { resetButton.hasDestructiveAction = true }
|
||||
if alert.runModal() == .alertSecondButtonReturn {
|
||||
Preferences.resetAll()
|
||||
App.app.restart()
|
||||
App.restart()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -119,7 +119,7 @@ class GeneralTab {
|
||||
alert.addButton(withTitle: NSLocalizedString("Restart Now", comment: ""))
|
||||
alert.addButton(withTitle: NSLocalizedString("Later", comment: ""))
|
||||
if alert.runModal() == .alertFirstButtonReturn {
|
||||
App.app.restart()
|
||||
App.restart()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -137,7 +137,7 @@ class GeneralTab {
|
||||
alert.addButton(withTitle: NSLocalizedString("Restart Now", comment: ""))
|
||||
alert.addButton(withTitle: NSLocalizedString("Later", comment: ""))
|
||||
if alert.runModal() == .alertFirstButtonReturn {
|
||||
App.app.restart()
|
||||
App.restart()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -485,10 +485,10 @@ class AppearanceTab: NSObject {
|
||||
}
|
||||
|
||||
@objc static func showCustomizeStyleSheet() {
|
||||
App.app.settingsWindow.beginSheetWithSearchHighlight(customizeStyleSheet)
|
||||
SettingsWindow.shared.beginSheetWithSearchHighlight(customizeStyleSheet)
|
||||
}
|
||||
|
||||
@objc static func showAnimationsSheet() {
|
||||
App.app.settingsWindow.beginSheetWithSearchHighlight(animationsSheet)
|
||||
SettingsWindow.shared.beginSheetWithSearchHighlight(animationsSheet)
|
||||
}
|
||||
}
|
||||
@@ -126,30 +126,30 @@ class ControlsTab {
|
||||
static var shortcuts = [String: ATShortcut]()
|
||||
static var shortcutControls = [String: (CustomRecorderControl, String)]()
|
||||
static var shortcutsActions = [
|
||||
"holdShortcut": { App.app.focusTarget() },
|
||||
"holdShortcut2": { App.app.focusTarget() },
|
||||
"holdShortcut3": { App.app.focusTarget() },
|
||||
"focusWindowShortcut": { App.app.focusTarget() },
|
||||
"nextWindowShortcut": { App.app.showUiOrCycleSelection(0, false) },
|
||||
"nextWindowShortcut2": { App.app.showUiOrCycleSelection(1, false) },
|
||||
"nextWindowShortcut3": { App.app.showUiOrCycleSelection(2, false) },
|
||||
"previousWindowShortcut": { App.app.previousWindowShortcutWithRepeatingKey() },
|
||||
"→": { App.app.cycleSelection(.right) },
|
||||
"←": { App.app.cycleSelection(.left) },
|
||||
"↑": { App.app.cycleSelection(.up) },
|
||||
"↓": { App.app.cycleSelection(.down) },
|
||||
"vimCycleRight": { App.app.cycleSelection(.right) },
|
||||
"vimCycleLeft": { App.app.cycleSelection(.left) },
|
||||
"vimCycleUp": { App.app.cycleSelection(.up) },
|
||||
"vimCycleDown": { App.app.cycleSelection(.down) },
|
||||
"cancelShortcut": { App.app.cancelSearchModeOrHideUi() },
|
||||
"closeWindowShortcut": { App.app.closeSelectedWindow() },
|
||||
"minDeminWindowShortcut": { App.app.minDeminSelectedWindow() },
|
||||
"toggleFullscreenWindowShortcut": { App.app.toggleFullscreenSelectedWindow() },
|
||||
"quitAppShortcut": { App.app.quitSelectedApp() },
|
||||
"hideShowAppShortcut": { App.app.hideShowSelectedApp() },
|
||||
"searchShortcut": { App.app.toggleSearchMode() },
|
||||
"lockSearchShortcut": { App.app.lockSearchMode() },
|
||||
"holdShortcut": { App.focusTarget() },
|
||||
"holdShortcut2": { App.focusTarget() },
|
||||
"holdShortcut3": { App.focusTarget() },
|
||||
"focusWindowShortcut": { App.focusTarget() },
|
||||
"nextWindowShortcut": { App.showUiOrCycleSelection(0, false) },
|
||||
"nextWindowShortcut2": { App.showUiOrCycleSelection(1, false) },
|
||||
"nextWindowShortcut3": { App.showUiOrCycleSelection(2, false) },
|
||||
"previousWindowShortcut": { App.previousWindowShortcutWithRepeatingKey() },
|
||||
"→": { App.cycleSelection(.right) },
|
||||
"←": { App.cycleSelection(.left) },
|
||||
"↑": { App.cycleSelection(.up) },
|
||||
"↓": { App.cycleSelection(.down) },
|
||||
"vimCycleRight": { App.cycleSelection(.right) },
|
||||
"vimCycleLeft": { App.cycleSelection(.left) },
|
||||
"vimCycleUp": { App.cycleSelection(.up) },
|
||||
"vimCycleDown": { App.cycleSelection(.down) },
|
||||
"cancelShortcut": { App.cancelSearchModeOrHideUi() },
|
||||
"closeWindowShortcut": { App.closeSelectedWindow() },
|
||||
"minDeminWindowShortcut": { App.minDeminSelectedWindow() },
|
||||
"toggleFullscreenWindowShortcut": { App.toggleFullscreenSelectedWindow() },
|
||||
"quitAppShortcut": { App.quitSelectedApp() },
|
||||
"hideShowAppShortcut": { App.hideShowSelectedApp() },
|
||||
"searchShortcut": { App.toggleSearchMode() },
|
||||
"lockSearchShortcut": { App.lockSearchMode() },
|
||||
]
|
||||
static var arrowKeysCheckbox: Switch!
|
||||
static var vimKeysCheckbox: Switch!
|
||||
@@ -642,11 +642,11 @@ class ControlsTab {
|
||||
}
|
||||
|
||||
@objc static func showShortcutsSettings() {
|
||||
App.app.settingsWindow.beginSheetWithSearchHighlight(shortcutsWhenActiveSheet)
|
||||
SettingsWindow.shared.beginSheetWithSearchHighlight(shortcutsWhenActiveSheet)
|
||||
}
|
||||
|
||||
@objc static func showAdditionalControlsSettings() {
|
||||
App.app.settingsWindow.beginSheetWithSearchHighlight(additionalControlsSheet)
|
||||
SettingsWindow.shared.beginSheetWithSearchHighlight(additionalControlsSheet)
|
||||
}
|
||||
|
||||
private static func addShortcut(_ triggerPhase: ShortcutTriggerPhase, _ scope: ShortcutScope, _ shortcut: Shortcut, _ controlId: String, _ index: Int?) {
|
||||
@@ -756,7 +756,7 @@ class ControlsTab {
|
||||
}
|
||||
}
|
||||
if !conflicts.isEmpty {
|
||||
if App.app.settingsWindow == nil || !shouldClearConflictingShortcuts(conflicts.map { $0.value }) {
|
||||
if SettingsWindow.shared == nil || !shouldClearConflictingShortcuts(conflicts.map { $0.value }) {
|
||||
return false
|
||||
}
|
||||
conflicts.forEach {
|
||||
@@ -891,11 +891,11 @@ class ControlsTab {
|
||||
return
|
||||
}
|
||||
if action.hasPrefix("holdShortcut") {
|
||||
App.app.focusTarget()
|
||||
App.focusTarget()
|
||||
return
|
||||
}
|
||||
if action.hasPrefix("nextWindowShortcut") {
|
||||
App.app.showUiOrCycleSelection(Preferences.nameToIndex(action), false)
|
||||
App.showUiOrCycleSelection(Preferences.nameToIndex(action), false)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -18,6 +18,37 @@ class App {
|
||||
var tilesPanel = TilesPanelMock()
|
||||
}
|
||||
static let app = AppMock()
|
||||
static var appIsBeingUsed: Bool {
|
||||
get { app.appIsBeingUsed }
|
||||
set { app.appIsBeingUsed = newValue }
|
||||
}
|
||||
static var shortcutIndex: Int {
|
||||
get { app.shortcutIndex }
|
||||
set { app.shortcutIndex = newValue }
|
||||
}
|
||||
static var forceDoNothingOnRelease: Bool {
|
||||
get { app.forceDoNothingOnRelease }
|
||||
set { app.forceDoNothingOnRelease = newValue }
|
||||
}
|
||||
}
|
||||
|
||||
class TilesPanel {
|
||||
static let shared = TilesPanel()
|
||||
var isKeyWindow: Bool {
|
||||
get { App.app.tilesPanel.isKeyWindow }
|
||||
set { App.app.tilesPanel.isKeyWindow = newValue }
|
||||
}
|
||||
}
|
||||
|
||||
class TilesView {
|
||||
static var isSearchEditing: Bool {
|
||||
get { App.app.tilesPanel.tilesView.isSearchEditing }
|
||||
set { App.app.tilesPanel.tilesView.isSearchEditing = newValue }
|
||||
}
|
||||
|
||||
static func handleSearchEditingKeyDown(_ event: NSEvent) -> Bool {
|
||||
return App.app.tilesPanel.tilesView.handleSearchEditingKeyDown(event)
|
||||
}
|
||||
}
|
||||
|
||||
class ControlsTab {
|
||||
|
||||
Reference in new issue
Block a user