Skip to content

armgit / peel

Public Imported from GitHub
0

Uninstall Mac apps with every file they leave behind, and see why each belongs. Free up space, fine-tune macOS, and set up Terminal.

Let Peel leave the Dock while it runs in the menu bar with no window open

Țugui Dragoș1241bf056c7b
diff --git a/Localization/Peel/Localizable.xcstrings b/Localization/Peel/Localizable.xcstrings
index 09de1a4e..a3f06bb4 100644
--- a/Localization/Peel/Localizable.xcstrings
+++ b/Localization/Peel/Localizable.xcstrings
@@ -53072,6 +53072,112 @@
}
}
},
+ "Hide from the Dock while no window is open" : {
+ "localizations" : {
+ "cs" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Skrývat v Docku, když není otevřené žádné okno"
+ }
+ },
+ "de" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Aus dem Dock ausblenden, solange kein Fenster geöffnet ist"
+ }
+ },
+ "es" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Ocultar del Dock mientras no haya ninguna ventana abierta"
+ }
+ },
+ "fr" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Masquer du Dock tant qu’aucune fenêtre n’est ouverte"
+ }
+ },
+ "it" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Nascondi dal Dock quando non ci sono finestre aperte"
+ }
+ },
+ "ja" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "ウインドウが開いていないときはDockに表示しない"
+ }
+ },
+ "ko" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "열려 있는 윈도우가 없을 때 Dock에서 가리기"
+ }
+ },
+ "nl" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Toon niet in Dock zolang er geen venster open is"
+ }
+ },
+ "pl" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Ukrywaj w Docku, gdy nie ma otwartych okien"
+ }
+ },
+ "pt" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Ocultar do Dock enquanto nenhuma janela estiver aberta"
+ }
+ },
+ "ro" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Ascundeți din Dock cât timp nu este deschisă nicio fereastră"
+ }
+ },
+ "ru" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Убирать из Dock, когда нет открытых окон"
+ }
+ },
+ "sv" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Göm från Dock när inget fönster är öppet"
+ }
+ },
+ "tr" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Hiçbir pencere açık değilken Dock’ta gizle"
+ }
+ },
+ "uk" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Прибирати з Dock, коли немає відкритих вікон"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "无打开的窗口时从程序坞中隐藏"
+ }
+ },
+ "zh-Hant" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "沒有打開的視窗時從Dock中隱藏"
+ }
+ }
+ }
+ },
"High" : {
"localizations" : {
"cs" : {
@@ -215004,6 +215110,112 @@
}
}
},
+ "While Peel shows in the menu bar, its icon leaves the Dock when you close its last window, and comes back when you open Peel again from the menu bar, Finder, or Spotlight." : {
+ "localizations" : {
+ "cs" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Když se Peel zobrazuje v řádku nabídek, jeho ikona po zavření posledního okna zmizí z Docku a vrátí se, až Peel znovu otevřete z řádku nabídek, z Finderu nebo ze Spotlightu."
+ }
+ },
+ "de" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Solange Peel in der Menüleiste angezeigt wird, verschwindet sein Symbol aus dem Dock, wenn du sein letztes Fenster schließt, und kehrt zurück, sobald du Peel erneut über die Menüleiste, den Finder oder Spotlight öffnest."
+ }
+ },
+ "es" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Mientras Peel se muestra en la barra de menús, su icono desaparece del Dock cuando cierras su última ventana y reaparece cuando vuelves a abrir Peel desde la barra de menús, el Finder o Spotlight."
+ }
+ },
+ "fr" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Tant que Peel s’affiche dans la barre des menus, son icône disparaît du Dock lorsque vous fermez sa dernière fenêtre, et y revient lorsque vous rouvrez Peel depuis la barre des menus, le Finder ou Spotlight."
+ }
+ },
+ "it" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Mentre Peel è nella barra dei menu, la sua icona scompare dal Dock quando ne chiudi l’ultima finestra e ricompare quando riapri Peel dalla barra dei menu, dal Finder o da Spotlight."
+ }
+ },
+ "ja" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Peelがメニューバーに表示されている間は、最後のウインドウを閉じるとPeelのアイコンがDockに表示されなくなり、メニューバー、Finder、またはSpotlightからPeelをもう一度開くとDockに戻ります。"
+ }
+ },
+ "ko" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Peel이 메뉴 막대에 표시되는 동안에는 마지막 윈도우를 닫으면 아이콘이 Dock에서 사라지고, 메뉴 막대, Finder 또는 Spotlight에서 Peel을 다시 열면 아이콘이 다시 나타납니다."
+ }
+ },
+ "nl" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Zolang Peel in de menubalk staat, verdwijnt het symbool van Peel uit het Dock wanneer je het laatste venster sluit, en komt het terug wanneer je Peel opnieuw opent vanuit de menubalk, Finder of Spotlight."
+ }
+ },
+ "pl" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Gdy Peel jest widoczny na pasku menu, jego ikona znika z Docka po zamknięciu jego ostatniego okna i wraca, gdy ponownie otworzysz Peel z paska menu, z Findera lub ze Spotlight."
+ }
+ },
+ "pt" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Enquanto o Peel aparece na barra de menus, o ícone dele sai do Dock quando você fecha a última janela dele, e volta quando você abre o Peel novamente pela barra de menus, pelo Finder ou pelo Spotlight."
+ }
+ },
+ "ro" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Cât timp Peel este afișat în bara de meniu, pictograma sa dispare din Dock când îi închideți ultima fereastră și revine când deschideți din nou Peel din bara de meniu, din Finder sau din Spotlight."
+ }
+ },
+ "ru" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Пока Peel отображается в строке меню, его значок убирается из Dock, когда Вы закрываете его последнее окно, и возвращается, когда Вы снова открываете Peel из строки меню, Finder или Spotlight."
+ }
+ },
+ "sv" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Så länge Peel visas i menyraden försvinner dess symbol från Dock när du stänger Peels sista fönster, och den kommer tillbaka när du öppnar Peel igen från menyraden, Finder eller Spotlight."
+ }
+ },
+ "tr" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Peel menü çubuğunda gösterilirken, son penceresini kapattığınızda simgesi Dock’tan kaybolur ve Peel’i menü çubuğundan, Finder’dan veya Spotlight’tan yeniden açtığınızda geri gelir."
+ }
+ },
+ "uk" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Поки Peel показується на смузі меню, її іконка зникає з Dock, коли ви закриваєте її останнє вікно, і повертається, коли ви знову відкриваєте Peel зі смуги меню, з Finder або зі Spotlight."
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Peel在菜单栏显示时,它的图标会在你关闭其最后一个窗口后从程序坞中消失,并在你从菜单栏、“访达”或“聚焦”再次打开Peel时重新出现。"
+ }
+ },
+ "zh-Hant" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Peel在選單列中顯示時,其圖像會在你關閉其最後一個視窗時離開Dock,並在你從選單列、Finder或Spotlight再次打開Peel時回來。"
+ }
+ }
+ }
+ },
"While Terminal is open, it doesn’t see a change to its settings, and can undo it the next time it saves them." : {
"localizations" : {
"cs" : {
diff --git a/Peel/Model/DockPresence.swift b/Peel/Model/DockPresence.swift
new file mode 100644
index 00000000..a8362186
--- /dev/null
+++ b/Peel/Model/DockPresence.swift
@@ -0,0 +1,66 @@
+import AppKit
+
+/// Keeps Peel out of the Dock while it shows in the menu bar with no window open, when the person chose so in
+/// Settings, and brings it back as soon as one of its windows opens.
+final class DockPresence {
+ static let shared = DockPresence()
+
+ private var observers: [any NSObjectProtocol] = []
+
+ private init() {}
+
+ static func belongsInTheDock(hidesFromDock: Bool, showsInMenuBar: Bool, hasAWindowOpen: Bool) -> Bool {
+ !hidesFromDock || !showsInMenuBar || hasAWindowOpen
+ }
+
+ func start() {
+ guard observers.isEmpty else { return }
+ let center = NotificationCenter.default
+ observers.append(center.addObserver(forName: NSWindow.willCloseNotification, object: nil, queue: nil) { note in
+ let window = note.object as? NSWindow
+ MainActor.assumeIsolated {
+ guard let window, window.canBecomeMain else { return }
+ DockPresence.shared.update(closing: window)
+ }
+ })
+ for name in [NSWindow.didBecomeKeyNotification, NSWindow.didChangeOcclusionStateNotification] {
+ observers.append(center.addObserver(forName: name, object: nil, queue: nil) { note in
+ let window = note.object as? NSWindow
+ MainActor.assumeIsolated {
+ guard let window else { return }
+ DockPresence.shared.comeBack(for: window)
+ }
+ })
+ }
+ update()
+ }
+
+ /// Puts Peel in the Dock or takes it out, as the rule says for the windows open now but `closing`.
+ func update(closing: NSWindow? = nil) {
+ guard !observers.isEmpty else { return }
+ let defaults = UserDefaults.standard
+ let inTheDock = Self.belongsInTheDock(
+ hidesFromDock: defaults.bool(forKey: SettingsKey.hidesFromDock),
+ showsInMenuBar: defaults.bool(forKey: SettingsKey.showsInMenuBar),
+ hasAWindowOpen: NSApp.windows.containsAnOpenWindow(besides: closing)
+ )
+ let policy: NSApplication.ActivationPolicy = inTheDock ? .regular : .accessory
+ if NSApp.activationPolicy() != policy {
+ NSApp.setActivationPolicy(policy)
+ }
+ }
+
+ private func comeBack(for window: NSWindow) {
+ guard window.canBecomeMain, window.isVisible, NSApp.activationPolicy() != .regular else { return }
+ NSApp.setActivationPolicy(.regular)
+ NSApp.activate()
+ }
+}
+
+extension [NSWindow] {
+ /// Whether a window that can be main is on screen or minimized, leaving out `closing`. The menu bar panel and
+ /// the menu bar item's own window can't be main.
+ func containsAnOpenWindow(besides closing: NSWindow? = nil) -> Bool {
+ contains { $0 !== closing && $0.canBecomeMain && ($0.isVisible || $0.isMiniaturized) }
+ }
+}
diff --git a/Peel/PeelApp.swift b/Peel/PeelApp.swift
index 5ae0809a..231e5b16 100644
--- a/Peel/PeelApp.swift
+++ b/Peel/PeelApp.swift
@@ -12,6 +12,11 @@ final class PeelAppDelegate: NSObject, NSApplicationDelegate {
}
}
+ func applicationDidFinishLaunching(_ notification: Notification) {
+ guard !PeelApp.isHostingTests else { return }
+ DockPresence.shared.start()
+ }
+
func applicationShouldTerminateAfterLastWindowClosed(_ application: NSApplication) -> Bool {
!UserDefaults.standard.bool(forKey: SettingsKey.showsInMenuBar)
}
@@ -38,6 +43,7 @@ struct PeelApp: App {
@AppStorage(SettingsKey.checksForAppUpdates) private var checksForAppUpdates = true
@AppStorage(SettingsKey.watchesTrash) private var watchesTrash = false
@AppStorage(SettingsKey.showsInMenuBar) private var showsInMenuBar = false
+ @AppStorage(SettingsKey.hidesFromDock) private var hidesFromDock = false
@AppStorage(SettingsKey.warnsWhenDiskIsNearlyFull) private var warnsWhenDiskIsNearlyFull = false
@State private var trashMonitor = TrashMonitor()
@State private var notifications: PeelNotifications
@@ -457,10 +463,15 @@ struct PeelApp: App {
}
}
.onChange(of: showsInMenuBar) { _, shows in
- if !shows, !NSApp.windows.contains(where: { $0.isVisible && $0.canBecomeMain }) {
+ if !shows, !NSApp.windows.containsAnOpenWindow() {
QuitGuard.quit()
+ } else {
+ DockPresence.shared.update()
}
}
+ .onChange(of: hidesFromDock) {
+ DockPresence.shared.update()
+ }
.onChange(of: checksForAppUpdates) { _, isChecking in
guard isChecking else { return }
Task { await library.checkForUpdates(library.apps) }
diff --git a/Peel/Views/Settings/SettingsView.swift b/Peel/Views/Settings/SettingsView.swift
index eb7234d4..54bea825 100644
--- a/Peel/Views/Settings/SettingsView.swift
+++ b/Peel/Views/Settings/SettingsView.swift
@@ -134,6 +134,7 @@ enum SettingsKey {
static let checksForAppUpdates = "checksForAppUpdates"
static let watchesTrash = "watchesTrash"
static let showsInMenuBar = "showsInMenuBar"
+ static let hidesFromDock = "hidesFromDock"
static let warnsWhenDiskIsNearlyFull = "lowDiskSpace.warns"
static let toldDiskIsNearlyFull = "lowDiskSpace.told"
/// How many older removals History's page last said it no longer lists.
@@ -209,6 +210,7 @@ private struct GeneralSettingsView: View {
@AppStorage(SettingsKey.updateSource) private var updateSource = UpdateSource.automatic.rawValue
@AppStorage(SettingsKey.watchesTrash) private var watchesTrash = false
@AppStorage(SettingsKey.showsInMenuBar) private var showsInMenuBar = false
+ @AppStorage(SettingsKey.hidesFromDock) private var hidesFromDock = false
@AppStorage(SettingsKey.warnsWhenDiskIsNearlyFull) private var warnsWhenDiskIsNearlyFull = false
@AppStorage(SettingsKey.sidebarTools) private var sidebarTools = ""
@Environment(TrashMonitor.self) private var trashMonitor
@@ -276,6 +278,9 @@ private struct GeneralSettingsView: View {
Section("While Peel Runs") {
toggle("Show in Menu Bar", isOn: $showsInMenuBar,
"Peel stays in the menu bar after you close its window, with what each tool found and the updates waiting. Without it, Peel quits when you close its window.")
+ toggle("Hide from the Dock while no window is open", isOn: $hidesFromDock,
+ "While Peel shows in the menu bar, its icon leaves the Dock when you close its last window, and comes back when you open Peel again from the menu bar, Finder, or Spotlight.")
+ .disabled(!showsInMenuBar)
toggle("Watch the Trash", isOn: $watchesTrash,
"When you move an app to the Trash yourself, Peel offers to remove the files it left behind. Peel watches the Trash while it is open, or while it is in the menu bar.")
if watchesTrash, trashMonitor.status == .needsFullDiskAccess {
diff --git a/PeelTests/DockPresenceTests.swift b/PeelTests/DockPresenceTests.swift
new file mode 100644
index 00000000..9613eacd
--- /dev/null
+++ b/PeelTests/DockPresenceTests.swift
@@ -0,0 +1,38 @@
+import AppKit
+@testable import Peel
+import Testing
+
+struct DockPresenceTests {
+ @Test func leavesTheDockOnlyWhenAskedWhileInTheMenuBarWithNoWindowOpen() {
+ #expect(!DockPresence.belongsInTheDock(hidesFromDock: true, showsInMenuBar: true, hasAWindowOpen: false))
+ #expect(DockPresence.belongsInTheDock(hidesFromDock: true, showsInMenuBar: true, hasAWindowOpen: true))
+ #expect(DockPresence.belongsInTheDock(hidesFromDock: true, showsInMenuBar: false, hasAWindowOpen: false))
+ #expect(DockPresence.belongsInTheDock(hidesFromDock: false, showsInMenuBar: true, hasAWindowOpen: false))
+ }
+
+ @Test func countsAMinimizedWindowButNeitherOneClosingNorOneThatCantBeMain() {
+ let open = window(visible: true)
+ #expect([open].containsAnOpenWindow())
+ #expect([window(minimized: true)].containsAnOpenWindow())
+ #expect(![open, window(visible: true, mayBeMain: false), window()].containsAnOpenWindow(besides: open))
+ }
+
+ private func window(visible: Bool = false, minimized: Bool = false, mayBeMain: Bool = true) -> NSWindow {
+ let window = StandInWindow(contentRect: .zero, styleMask: .titled, backing: .buffered, defer: true)
+ window.onScreen = visible
+ window.minimized = minimized
+ window.mayBeMain = mayBeMain
+ return window
+ }
+}
+
+/// Never ordered in, so the window server makes no window for it.
+private final class StandInWindow: NSWindow {
+ var onScreen = false
+ var minimized = false
+ var mayBeMain = true
+
+ override var isVisible: Bool { onScreen }
+ override var isMiniaturized: Bool { minimized }
+ override var canBecomeMain: Bool { mayBeMain }
+}