From d4f6173345e3a8407e2ccb2f3cd5b31e4da8bf69 Mon Sep 17 00:00:00 2001 From: DragonNameLeo <15801369+DragonNameLeo@users.noreply.github.com> Date: Thu, 26 Nov 2026 12:08:36 +0900 Subject: [PATCH 1/2] fix(native): do not lose every app when the menu bar is auto-hidden MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit With System Settings › Menu Bar › "Automatically hide and show the menu bar" on, macOS 27.2.1 parks every app's status items while the bar is hidden, and they leave Accessibility, Hidden Bar's own arrow included. A read taken then (the auto-collapse timer, a launch, or a relaunch before the icons are back) listed no app. It was cached, every app fell out of the allow list, and with the always-hidden section held on expand no later read replaced it: a click on the arrow showed nothing until Hidden Bar was relaunched. Measured on a live bar: every read that listed no app happened while MenuBarAgent logged "menu bar hidden", and every read taken while the bar was revealed listed the apps. - The inventory also asks whether Hidden Bar's own status items are in Accessibility. When they are not and no app item was read, the read is from a hidden menu bar (MenuBarHiddenRead). An unanswered own read never counts as hidden. - The engine keeps the last read instead of such a read and learns nothing from it: no pinned-table or section-memory edit, no catalog record, and it does not become lastCompleteLayout. - A running app the read did not list, but whose section Hidden Bar knows (pinned table, or section memory with pinned sections off), keeps that section. Apps not running, and apps never seen, are not filled in. Verified on 27.2.1 with the menu bar set to auto-hide: a read with the bar hidden logs "own items listed false, menu bar hidden true" and keeps 8 hidden and 3 always-hidden apps from the table; a read with the bar revealed logs "own items listed true, menu bar hidden false". The arrow shows the hidden icons afterwards. Tests: ReadListsNoAppTests (6). The direct scheme passes 822, fails 34; the same 34 fail without this change (UI copy tests on a Japanese-language Mac). Co-Authored-By: Claude Opus 5.5 --- HiddenBarTests/MenuBarEngineTests.swift | 122 ++++++++++++++++++ .../Engine/NativeVisibilityEngine.swift | 54 +++++++- .../AccessibilityMenuBarInventory.swift | 27 +++- .../StatusBar/Layout/MenuBarLayout.swift | 24 ++++ 4 files changed, 222 insertions(+), 5 deletions(-) diff --git a/HiddenBarTests/MenuBarEngineTests.swift b/HiddenBarTests/MenuBarEngineTests.swift index c3e836b8..bfe00667 100644 --- a/HiddenBarTests/MenuBarEngineTests.swift +++ b/HiddenBarTests/MenuBarEngineTests.swift @@ -34,6 +34,8 @@ private final class FakeInventory: MenuBarInventoryProviding { var snapshots = 0 // False: a read never comes back, as when an app never answers. var answers = true + // True: the read was taken while the menu bar was auto-hidden. + var menuBarWasHiddenAtLastSnapshot = false func requestAuthorization() { authorizationRequests += 1 @@ -4457,3 +4459,123 @@ final class CaptureActivityMonitorTests: XCTestCase { return count } } + +// MARK: - Reads that list no app (menu bar auto-hidden, icons not back yet) + +// With "Automatically hide and show the menu bar" on, macOS 27.2.1 parks every +// app's status items while the bar is hidden, and a read then lists none of +// them. Cached, that read left every app out of the allow list, and with the +// always-hidden section held on expand no later read replaced it: a click on +// the arrow showed nothing. +final class ReadListsNoAppTests: XCTestCase { + private let own = "com.dwarvesv.minimalbar" + private var items: FakeItems! + private var inventory: FakeInventory! + private var visibility: FakeVisibility! + private var observed: InMemorySectionMemory! + private var table: InMemorySectionMemory! + private var pins = true + private var running: Set = [] + private let fullBar = [item("com.hidden", x: 1100), item("com.visible", x: 1400)] + private let parkedBar = [systemExtra("com.apple.menuextra.clock", x: 1500)] + + override func setUp() { + super.setUp() + items = FakeItems() + inventory = FakeInventory() + inventory.items = fullBar + visibility = FakeVisibility() + observed = InMemorySectionMemory() + table = InMemorySectionMemory() + pins = true + running = ["com.always", "com.hidden", "com.visible"] + } + + private func makeEngine() -> NativeVisibilityEngine { + let items = self.items! + let engine = NativeVisibilityEngine(items: items, inventory: inventory, visibility: visibility, clock: FakeClock(), + ownBundleIdentifier: own, + itemFrame: { $0 === items.toggleItem ? separator : alwaysHiddenSeparator }, + displays: { [mainDisplay] }, + runningBundleIdentifiers: { [unowned self] in running }, + isLTR: { true }, + sectionMemory: observed, + pinnedSections: table, + pinsSections: { [unowned self] in pins }) + return engine + } + + @discardableResult + private func collapse(_ engine: NativeVisibilityEngine) -> [String] { + engine.collapse { _ in } + visibility.succeed(visibility.requests.count - 1) + return visibility.requests.last?.bundles ?? [] + } + + func testTheHiddenReadRule() { + let app = item("com.app", x: 1100) + var unreadable = item("com.slow", x: 0) + unreadable.isUnreadable = true + XCTAssertTrue(MenuBarHiddenRead.isHidden(items: parkedBar, ownItemsListed: false)) + XCTAssertTrue(MenuBarHiddenRead.isHidden(items: parkedBar + [unreadable], ownItemsListed: false), + "an app that did not answer says nothing about the bar") + XCTAssertFalse(MenuBarHiddenRead.isHidden(items: parkedBar, ownItemsListed: true), "Hidden Bar's own arrow is in the bar") + XCTAssertFalse(MenuBarHiddenRead.isHidden(items: parkedBar, ownItemsListed: nil), "unknown never counts as hidden") + XCTAssertFalse(MenuBarHiddenRead.isHidden(items: parkedBar + [app], ownItemsListed: false), + "an app's item was read, so the bar was there") + } + + func testAReadFromAHiddenMenuBarKeepsTheLastRead() { + let engine = makeEngine() + XCTAssertEqual(collapse(engine), [own, "com.visible"]) + engine.expand() + let tableBefore = table.sections + let observedBefore = observed.sections + + inventory.items = parkedBar + inventory.menuBarWasHiddenAtLastSnapshot = true + XCTAssertEqual(collapse(engine), [own, "com.visible"], "the visible app is still allowed") + XCTAssertEqual(engine.hiddenSectionBundles, ["com.hidden"], "an expand still brings the hidden app back") + XCTAssertEqual(table.sections, tableBefore, "nothing is learned from a read of a hidden bar") + XCTAssertEqual(observed.sections, observedBefore) + } + + func testRunningPinnedAppsTheReadMissedKeepTheirSection() { + table.sections = ["com.always": .alwaysHidden, "com.hidden": .hidden, "com.visible": .visible] + // A first read with no app listed: Hidden Bar started while the bar was + // hidden, or before the apps' icons were back. No earlier read stands in. + inventory.items = parkedBar + inventory.menuBarWasHiddenAtLastSnapshot = true + let engine = makeEngine() + XCTAssertEqual(collapse(engine), [own, "com.visible"]) + XCTAssertEqual(engine.hiddenSectionBundles, ["com.hidden"]) + XCTAssertEqual(table.sections, ["com.always": .alwaysHidden, "com.hidden": .hidden, "com.visible": .visible]) + } + + func testAnAppThatIsNotRunningIsNotFilledIn() { + table.sections = ["com.always": .alwaysHidden, "com.hidden": .hidden, "com.visible": .visible] + running = ["com.visible"] + inventory.items = parkedBar + let engine = makeEngine() + XCTAssertEqual(collapse(engine), [own, "com.visible"]) + XCTAssertEqual(engine.hiddenSectionBundles, [], "a quit app has nothing to show") + } + + func testAnAppHiddenBarNeverSawIsNotFilledIn() { + table.sections = ["com.visible": .visible] + running = ["com.visible", "com.never.seen"] + inventory.items = parkedBar + let engine = makeEngine() + XCTAssertEqual(collapse(engine), [own, "com.visible"]) + } + + func testWithoutPinnedSectionsTheLastReadSectionIsUsed() { + pins = false + let engine = makeEngine() + XCTAssertEqual(collapse(engine), [own, "com.visible"]) + engine.expand() + inventory.items = parkedBar + XCTAssertEqual(collapse(engine), [own, "com.visible"]) + XCTAssertEqual(engine.hiddenSectionBundles, ["com.hidden"]) + } +} diff --git a/hidden/Features/StatusBar/Engine/NativeVisibilityEngine.swift b/hidden/Features/StatusBar/Engine/NativeVisibilityEngine.swift index ae418849..06cf3d67 100644 --- a/hidden/Features/StatusBar/Engine/NativeVisibilityEngine.swift +++ b/hidden/Features/StatusBar/Engine/NativeVisibilityEngine.swift @@ -502,6 +502,25 @@ final class NativeVisibilityEngine: MenuBarEngine { NSLog("NativeVisibility: the arrow at \(NSStringFromRect(boundary)) is on no display \(displays.map { NSStringFromRect($0.appKitFrame) })") return body(nil) } + // Taken while the menu bar was auto-hidden, the read lists no app at + // all. Cached, it would leave every app out of the allow list until + // the next unrestricted read, which an always-hidden section held + // on expand never allows: a click on the arrow showed nothing. The + // last read stands in, and nothing is remembered from this one. + let menuBarHidden = self.inventory.menuBarWasHiddenAtLastSnapshot + if menuBarHidden, let previous = self.layout ?? self.lastCompleteLayout { + var kept = previous + if self.pinsSections() { + let table = self.pinnedSections.sections + for bundle in kept.sections.keys { + if let pinned = table[bundle] { kept.sections[bundle] = pinned } + } + } + let filled = self.fillRunningAppsTheReadMissed(&kept) + NSLog("NativeVisibility: the menu bar is hidden, so the read lists no app; keeping the last read (hidden \(kept.bundles(in: [.hidden])), always hidden \(kept.bundles(in: [.alwaysHidden])), filled in \(filled))") + self.layout = kept + return body(kept) + } var layout = MenuBarLayoutResolver.resolve(inventory: inventory, separatorFrame: boundary, alwaysHiddenSeparatorFrame: alwaysHiddenFrame, @@ -517,7 +536,7 @@ final class NativeVisibilityEngine: MenuBarEngine { layout = layout.fillingIn(from: complete) } NSLog("NativeVisibility: the active menu bar overflows; apps it does not list keep their last known section") - } else { + } else if !menuBarHidden { self.lastCompleteLayout = layout } if self.pinsSections() { @@ -534,8 +553,15 @@ final class NativeVisibilityEngine: MenuBarEngine { } self.launchedSinceRead.subtract(layout.sections.keys) // What the read listed, before apps that only started are filled in: - // those may have no menu-bar icon at all. - self.onUnrestrictedRead?(layout, inventory) + // those may have no menu-bar icon at all. A read from a hidden menu + // bar lists nothing worth recording. + if !menuBarHidden { + self.onUnrestrictedRead?(layout, inventory) + } + let filledIn = self.fillRunningAppsTheReadMissed(&layout) + if !filledIn.isEmpty { + NSLog("NativeVisibility: running apps the read did not list keep their saved section: \(filledIn)\(menuBarHidden ? " (the menu bar is hidden)" : "")") + } var missing = self.launchedSinceRead if layout.isIncomplete { missing.formUnion(self.runningBundleIdentifiers()) @@ -945,6 +971,28 @@ final class NativeVisibilityEngine: MenuBarEngine { return sectionMemory.sections[bundle] ?? .visible } + // A running app the read did not list, although Hidden Bar knows its section + // (pinned, or where it was last read), keeps that section. An app is left + // out of a read when its items are not in Accessibility at that moment: the + // menu bar auto-hidden, or the app's icon not back yet after a launch or a + // relaunch of Hidden Bar. Without this it was out of the allow list until + // the next read, which an always-hidden section held on expand never + // allows: the arrow showed nothing. Apps Hidden Bar never saw are left + // out, as before. Returns the bundles filled in. + @discardableResult + private func fillRunningAppsTheReadMissed(_ layout: inout MenuBarLayout) -> [String] { + let known = pinsSections() ? pinnedSections.sections : sectionMemory.sections + var filled: [String] = [] + for bundle in runningBundleIdentifiers() where layout.sections[bundle] == nil + && bundle != ownBundleIdentifier + && !MenuBarLayoutResolver.systemItemOwners.contains(bundle) { + guard let section = known[bundle] else { continue } + layout.sections[bundle] = section + filled.append(bundle) + } + return filled.sorted() + } + // Preferences changed the pinned sections: apply them to the held // restriction at once. A collapse or expand in flight applies them when it // lands. Apps no read listed yet keep the section they were given. diff --git a/hidden/Features/StatusBar/Layout/AccessibilityMenuBarInventory.swift b/hidden/Features/StatusBar/Layout/AccessibilityMenuBarInventory.swift index 0e0da572..f8f041ab 100644 --- a/hidden/Features/StatusBar/Layout/AccessibilityMenuBarInventory.swift +++ b/hidden/Features/StatusBar/Layout/AccessibilityMenuBarInventory.swift @@ -47,11 +47,34 @@ final class AccessibilityMenuBarInventory: MenuBarInventoryProviding { DispatchQueue.global(qos: .userInitiated).async { let start = Date() let items = Self.statusItems(of: apps) - NSLog("NativeVisibility: inventory of \(apps.count) apps took \(Int(Date().timeIntervalSince(start) * 1000)) ms") - DispatchQueue.main.async { completion(items) } + let ownItemsListed = Self.listsStatusItems(pid: ownPID) + let menuBarHidden = MenuBarHiddenRead.isHidden(items: items, ownItemsListed: ownItemsListed) + NSLog("NativeVisibility: inventory of \(apps.count) apps took \(Int(Date().timeIntervalSince(start) * 1000)) ms; own items listed \(ownItemsListed.map(String.init) ?? "unknown"), menu bar hidden \(menuBarHidden)") + DispatchQueue.main.async { [weak self] in + self?.menuBarWasHiddenAtLastSnapshot = menuBarHidden + completion(items) + } } } + private(set) var menuBarWasHiddenAtLastSnapshot = false + + // Whether a process's status items are in Accessibility right now. Read off + // the main thread, so asking about Hidden Bar itself cannot wait on itself. + // nil when the process did not answer. + private static func listsStatusItems(pid: pid_t) -> Bool? { + let element = AXUIElementCreateApplication(pid) + AXUIElementSetMessagingTimeout(element, retryTimeout) + var barValue: CFTypeRef? + let barError = AXUIElementCopyAttributeValue(element, "AXExtrasMenuBar" as CFString, &barValue) + if barError == .cannotComplete || barError == .apiDisabled { return nil } + guard barError == .success, let bar = barValue else { return false } + var childrenValue: CFTypeRef? + let childrenError = AXUIElementCopyAttributeValue(bar as! AXUIElement, kAXChildrenAttribute as CFString, &childrenValue) + if childrenError == .cannotComplete { return nil } + return !((childrenValue as? [AXUIElement])?.isEmpty ?? true) + } + // macOS 27 hides an app run from outside an Applications folder although its // bundle id is allowed (#521), as it does Hidden Bar's own arrow. Measured // with iStat Menus 7, whose LaunchAgent runs it from ~/Library/Application diff --git a/hidden/Features/StatusBar/Layout/MenuBarLayout.swift b/hidden/Features/StatusBar/Layout/MenuBarLayout.swift index 276e1e70..4995e1a7 100644 --- a/hidden/Features/StatusBar/Layout/MenuBarLayout.swift +++ b/hidden/Features/StatusBar/Layout/MenuBarLayout.swift @@ -84,6 +84,30 @@ protocol MenuBarInventoryProviding: AnyObject { // while nothing is hidden: once a native visibility assertion is active, // hidden items report stale frames. func snapshot(completion: @escaping ([MenuBarInventoryItem]) -> Void) + // True when the last snapshot was taken while the menu bar itself was hidden + // (System Settings › Menu Bar › "Automatically hide and show the menu bar"). + // macOS then parks every app's status items, Hidden Bar's own included, and + // they leave Accessibility, so that read lists none of them (#584 follow-up, + // measured on 27.2.1). + var menuBarWasHiddenAtLastSnapshot: Bool { get } +} + +extension MenuBarInventoryProviding { + var menuBarWasHiddenAtLastSnapshot: Bool { return false } +} + +// A read lists no app's item although macOS's own extras are there: what a read +// taken while the menu bar is auto-hidden returns (27.2.1). `ownItemsListed` is +// whether Hidden Bar's own status items were in Accessibility at the same time; +// nil when that could not be read, which never counts as hidden. +enum MenuBarHiddenRead { + static func isHidden(items: [MenuBarInventoryItem], ownItemsListed: Bool?) -> Bool { + guard ownItemsListed == false else { return false } + return !items.contains { item in + guard !item.isUnreadable, let bundle = item.bundleIdentifier else { return false } + return !MenuBarLayoutResolver.systemItemOwners.contains(bundle) + } + } } // The section each app was last read in, per bundle. From e0d6453cb0ed0cc4908894d96de82ff75a241746 Mon Sep 17 00:00:00 2001 From: DragonNameLeo <15801369+DragonNameLeo@users.noreply.github.com> Date: Thu, 26 Nov 2026 13:05:30 +0900 Subject: [PATCH 2/2] =?UTF-8?q?fix(native):=20read=20a=20=E2=8C=98-drag=20?= =?UTF-8?q?in=20the=20menu=20bar=20as=20soon=20as=20it=20ends?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit With pinned sections on and an app in the always-hidden section, an expand keeps a restriction that hides that section, so the next collapse uses the cached read and never sees where the user dragged an icon. Only a bar with nothing held (Option-click, or the camera or microphone lift) was read again, and with the menu bar set to auto-hide even that read came when the auto-collapse found the bar already gone, so it was discarded. A ⌘-drag across the arrow therefore never changed an app's section. - CommandDragWatcher (MenuBarClock.swift) watches left mouse-down with ⌘ in a menu bar, global and local, and reports the next mouse-up after 0.5 s, once macOS has moved the icon and reflowed the bar. The bar is on screen then, auto-hide or not. - NativeVisibilityEngine.menuBarRearranged, pinned sections only: - nothing held and expanded: a full read, cached, so a collapse that finds the menu bar hidden keeps it; - a restriction held (collapsed, or expanded with the always-hidden section hidden): only the apps it shows are read, against the arrow, since hidden apps report stale frames. An app the palette lifted for now is left out. The table is edited through PinnedSectionResolver as on a collapse, so "Ignore drags" and relaunches are respected, and the hold follows at once. - Skipped while presenting, while an activation is in flight, and when the read finds the menu bar hidden. - The engine posts .pinnedSectionsChanged so Settings › Icons and the catalog follow; the controller skips the engine's own post. Verified on 27.2.1 with the menu bar set to auto-hide and the always-hidden section held on expand: three ⌘-drags of WeChat across the arrow logged "a ⌘-drag moved com.tencent.xinWeChat to hidden / visible / hidden", each from a read with "menu bar hidden false", and the pinned table followed. Tests: PinnedSectionsTests (4 new). The direct scheme passes 826, fails 34; the same 34 UI copy tests fail on this Japanese-language Mac without it. Co-Authored-By: Claude Opus 5.5 --- HiddenBarTests/MenuBarEngineTests.swift | 81 ++++++++++++++++- .../Engine/MenuBarEngineFactory.swift | 3 +- .../Engine/Native/MenuBarClock.swift | 86 ++++++++++++++++++- .../Engine/NativeVisibilityEngine.swift | 70 ++++++++++++++- .../StatusBar/StatusBarController.swift | 6 +- 5 files changed, 238 insertions(+), 8 deletions(-) diff --git a/HiddenBarTests/MenuBarEngineTests.swift b/HiddenBarTests/MenuBarEngineTests.swift index bfe00667..a1270adb 100644 --- a/HiddenBarTests/MenuBarEngineTests.swift +++ b/HiddenBarTests/MenuBarEngineTests.swift @@ -126,6 +126,15 @@ private final class FakeCaptureActivity: CaptureActivityMonitoring { } } +// Stands in for the ⌘-drag watcher: the test ends a drag. +private final class FakeRearrange: MenuBarRearrangeWatching { + var onRearrange: (() -> Void)? + + func endDrag() { + onRearrange?() + } +} + private func item(_ bundle: String?, x: CGFloat, width: CGFloat = 24) -> MenuBarInventoryItem { return MenuBarInventoryItem(bundleIdentifier: bundle, frame: CGRect(x: x, y: 0, width: width, height: 24)) } @@ -2372,9 +2381,11 @@ final class PinnedSectionsTests: XCTestCase { private var table: InMemorySectionMemory! private var pins = true private var dragLocked: Set = [] + private var rearrange: FakeRearrange! override func setUp() { super.setUp() + rearrange = FakeRearrange() items = FakeItems() inventory = FakeInventory() inventory.items = [item("com.always", x: 900), item("com.hidden", x: 1100), item("com.visible", x: 1400)] @@ -2395,7 +2406,75 @@ final class PinnedSectionsTests: XCTestCase { sectionMemory: observed, pinnedSections: table, pinsSections: { [unowned self] in pins }, - ignoredDrags: { [unowned self] in dragLocked }) + ignoredDrags: { [unowned self] in dragLocked }, + rearrange: rearrange) + } + + // Collapsed once, then expanded with the always-hidden section held. + private func expandedHoldingAlwaysHidden() -> NativeVisibilityEngine { + table.sections = ["com.always": .alwaysHidden] + let engine = makeEngine() + engine.updateAlwaysHiddenSection(enabled: true, separatorHidden: true) + collapse(engine) + engine.expand() + XCTAssertEqual(visibility.requests.last?.bundles, [own, "com.hidden", "com.visible"]) + visibility.succeed(visibility.requests.count - 1) + return engine + } + + // Given the always-hidden section held while expanded, so a collapse reads nothing + // When the user ⌘-drags a hidden app right of the arrow + // Then the drag is read when it ends, and the next collapse keeps the app visible + func testADragWhileTheAlwaysHiddenSectionIsHeldEditsTheTable() { + let engine = expandedHoldingAlwaysHidden() + move("com.hidden", to: 1450) + // A hidden app's frame is stale: it must not count as a drag. + move("com.always", to: 1500) + let reads = inventory.snapshots + rearrange.endDrag() + XCTAssertGreaterThan(inventory.snapshots, reads, "the drag is read") + XCTAssertEqual(table.sections["com.hidden"], .visible) + XCTAssertEqual(table.sections["com.always"], .alwaysHidden, "an app the restriction hides is not read") + XCTAssertEqual(collapse(engine), [own, "com.hidden", "com.visible"]) + } + + // Given a collapsed bar + // When the user ⌘-drags a visible app left of the arrow + // Then it hides at once + func testADragWhileCollapsedHidesTheApp() { + let engine = makeEngine() + XCTAssertEqual(collapse(engine), [own, "com.visible"]) + move("com.visible", to: 1120) + rearrange.endDrag() + XCTAssertEqual(table.sections["com.visible"], .hidden) + XCTAssertEqual(visibility.requests.last?.bundles, [own]) + } + + // A read from an auto-hidden menu bar lists nothing; a drag-locked app keeps its section. + func testADragReadFromAHiddenMenuBarOrOfALockedAppChangesNothing() { + _ = expandedHoldingAlwaysHidden() + move("com.hidden", to: 1450) + inventory.menuBarWasHiddenAtLastSnapshot = true + rearrange.endDrag() + XCTAssertEqual(table.sections["com.hidden"], .hidden) + + inventory.menuBarWasHiddenAtLastSnapshot = false + dragLocked = ["com.hidden"] + rearrange.endDrag() + XCTAssertEqual(table.sections["com.hidden"], .hidden) + } + + // With nothing held, a drag refreshes the cached read, which a collapse + // from an auto-hidden menu bar then keeps. + func testADragOnAnUnrestrictedBarIsKeptWhenTheCollapseFindsTheMenuBarHidden() { + let engine = makeEngine() + collapse(engine) + engine.expand() + move("com.hidden", to: 1450) + rearrange.endDrag() + XCTAssertEqual(table.sections["com.hidden"], .visible) + inventory.menuBarWasHiddenAtLastSnapshot = true + XCTAssertEqual(collapse(engine), [own, "com.hidden", "com.visible"]) } @discardableResult diff --git a/hidden/Features/StatusBar/Engine/MenuBarEngineFactory.swift b/hidden/Features/StatusBar/Engine/MenuBarEngineFactory.swift index d069086a..30785f92 100644 --- a/hidden/Features/StatusBar/Engine/MenuBarEngineFactory.swift +++ b/hidden/Features/StatusBar/Engine/MenuBarEngineFactory.swift @@ -43,7 +43,8 @@ enum MenuBarEngineFactory { pinnedSections: UserDefaultsPinnedSections(), pinsSections: { Preferences.pinnedSectionsEnabled }, ignoredDrags: { UserDefaultsDragLocks().bundles }, - agentLaunches: agentLaunches) + agentLaunches: agentLaunches, + rearrange: CommandDragWatcher()) let catalog = MenuBarItemCatalog.shared engine.onUnrestrictedRead = { layout, inventory in ArrivalsController.shared.noteInventory(inventory) diff --git a/hidden/Features/StatusBar/Engine/Native/MenuBarClock.swift b/hidden/Features/StatusBar/Engine/Native/MenuBarClock.swift index cb37ee9c..4e64bb48 100644 --- a/hidden/Features/StatusBar/Engine/Native/MenuBarClock.swift +++ b/hidden/Features/StatusBar/Engine/Native/MenuBarClock.swift @@ -454,8 +454,9 @@ final class SystemMenuBarClock: MenuBarClockProviding { } } - // Keeps the Accessibility lookups to clicks in a menu bar. - private static func isInMenuBar(_ location: CGPoint) -> Bool { + // Keeps the Accessibility lookups to clicks in a menu bar. CoreGraphics + // coordinates (origin at the primary display's top left). + static func isInMenuBar(_ location: CGPoint) -> Bool { guard let primaryHeight = NSScreen.screens.first?.frame.maxY else { return false } return NSScreen.screens.contains { screen in let top = primaryHeight - screen.frame.maxY @@ -550,6 +551,87 @@ final class SystemMenuBarClock: MenuBarClockProviding { } } +// A ⌘-drag that rearranged the menu bar. Sections are otherwise read only on a +// collapse from an unrestricted bar, which never comes while the always-hidden +// section is held on expand, and which the auto-collapse takes once the pointer +// has left the bar, when an auto-hidden menu bar is already gone. Right after a +// drag the bar is on screen, so that is when the engine reads it. +protocol MenuBarRearrangeWatching: AnyObject { + // Runs on the main queue once a ⌘-drag begun in a menu bar has ended and + // the bar has had a moment to settle. Nothing is watched while nil. + var onRearrange: (() -> Void)? { get set } +} + +// The engine's default, so tests never watch the real mouse. +final class NoRearrangeWatching: MenuBarRearrangeWatching { + var onRearrange: (() -> Void)? +} + +final class CommandDragWatcher: MenuBarRearrangeWatching { + var onRearrange: (() -> Void)? { + didSet { updateMonitors() } + } + + // macOS moves the icon on mouse-up and reflows the bar after it. + private let settleDelay: TimeInterval + private var monitors: [Any] = [] + private var dragging = false + private var pending: DispatchWorkItem? + + init(settleDelay: TimeInterval = 0.5) { + self.settleDelay = settleDelay + } + + deinit { + monitors.forEach(NSEvent.removeMonitor) + pending?.cancel() + } + + private func updateMonitors() { + if onRearrange != nil, monitors.isEmpty { + let mask: NSEvent.EventTypeMask = [.leftMouseDown, .leftMouseUp] + // Other apps' icons are global events; Hidden Bar's own arrow and + // separator are local ones. + if let global = NSEvent.addGlobalMonitorForEvents(matching: mask, handler: { [weak self] in self?.handle($0) }) { + monitors.append(global) + } + if let local = NSEvent.addLocalMonitorForEvents(matching: mask, handler: { [weak self] event in + self?.handle(event) + return event + }) { + monitors.append(local) + } + } else if onRearrange == nil, !monitors.isEmpty { + monitors.forEach(NSEvent.removeMonitor) + monitors = [] + dragging = false + pending?.cancel() + pending = nil + } + } + + private func handle(_ event: NSEvent) { + switch event.type { + case .leftMouseDown: + // ⌘ counts at the press only: the user may let go of it mid-drag. + guard let location = event.cgEvent?.location else { return } + dragging = event.modifierFlags.contains(.command) && SystemMenuBarClock.isInMenuBar(location) + case .leftMouseUp: + guard dragging else { return } + dragging = false + pending?.cancel() + let work = DispatchWorkItem { [weak self] in + self?.pending = nil + self?.onRearrange?() + } + pending = work + DispatchQueue.main.asyncAfter(deadline: .now() + settleDelay, execute: work) + default: + break + } + } +} + #if DEBUG // When each step of the last clock replay happened (systemUptime, seconds), for // measuring how long hidden icons show. Debug builds only. diff --git a/hidden/Features/StatusBar/Engine/NativeVisibilityEngine.swift b/hidden/Features/StatusBar/Engine/NativeVisibilityEngine.swift index 06cf3d67..17e7bb60 100644 --- a/hidden/Features/StatusBar/Engine/NativeVisibilityEngine.swift +++ b/hidden/Features/StatusBar/Engine/NativeVisibilityEngine.swift @@ -39,7 +39,8 @@ import AppKit // bar. An app that starts while something is hidden is not in the read, so it // gets the section it was last read in (remembered across launches), or the // visible one if it was never read, until that next read places it by where -// macOS put its icon. +// macOS put its icon. With pinned sections a ⌘-drag is also read as soon as +// it ends, from the apps the held restriction shows (`menuBarRearranged`). // - The restriction is assessment mode, which makes macOS ignore the clock, so // Notification Center cannot open from it (#410). A click on the clock while // collapsed expands the bar, presses the clock, and collapses again once the @@ -163,6 +164,8 @@ final class NativeVisibilityEngine: MenuBarEngine { private let pinnedSections: MenuBarSectionMemory private let ignoredDrags: () -> Set private let pinsSections: () -> Bool + // Reports a ⌘-drag in the menu bar, read at once (`menuBarRearranged`). + private let rearrange: MenuBarRearrangeWatching // Items right of the arrow that the allow-list cannot keep visible: an item // whose owner has no bundle id, or a system extra no system item id covers @@ -201,9 +204,11 @@ final class NativeVisibilityEngine: MenuBarEngine { pinnedSections: MenuBarSectionMemory = InMemorySectionMemory(), pinsSections: @escaping () -> Bool = { false }, ignoredDrags: @escaping () -> Set = { [] }, - agentLaunches: NotificationCenter? = nil) { + agentLaunches: NotificationCenter? = nil, + rearrange: MenuBarRearrangeWatching = NoRearrangeWatching()) { self.items = items self.ignoredDrags = ignoredDrags + self.rearrange = rearrange self.agentLaunches = agentLaunches self.pinnedSections = pinnedSections self.pinsSections = pinsSections @@ -229,6 +234,9 @@ final class NativeVisibilityEngine: MenuBarEngine { captureActivity.onChange = { [weak self] in self?.captureActivityDidChange() } + rearrange.onRearrange = { [weak self] in + self?.menuBarRearranged() + } // Quit lifts the restriction explicitly as well as by process exit. terminationObserver = (terminationNotifications, terminationNotifications.addObserver( forName: NSApplication.willTerminateNotification, object: nil, queue: nil) { [weak self] _ in @@ -996,6 +1004,64 @@ final class NativeVisibilityEngine: MenuBarEngine { // Preferences changed the pinned sections: apply them to the held // restriction at once. A collapse or expand in flight applies them when it // lands. Apps no read listed yet keep the section they were given. + // A ⌘-drag in the menu bar just ended, so the bar is on screen even when + // macOS auto-hides it. Pinned sections only: without them every collapse + // reads the positions anyway. + // - Nothing held: a full read, cached for the next collapse, which keeps it + // when that collapse finds the menu bar hidden. + // - A restriction held (collapsed, or expanded with the always-hidden + // section hidden): the apps it hides report stale frames, so only the + // apps it shows are read. Those sit where the user just put them, left or + // right of the arrow; the always-hidden separator is out of the bar then, + // so that section is changed by Option-click and a drag, or in Settings. + func menuBarRearranged() { + guard pinsSections(), inventory.isAuthorized, state != .calibrating, + inFlightHold == nil, !holdsPresentationList else { return } + guard assertion != nil else { + guard state == .expanded else { return } + return withLayout { _ in } + } + guard generation == assertionGeneration, + let arrow = items?.toggleItem, let boundary = itemFrame(arrow), + Self.isPlaced(arrow: boundary, displays: displays()) else { return } + // An app the palette lifted shows only for now, wherever macOS put it. + let shown = Set(assertionBundles).subtracting(temporaryAllow.map { [$0.bundle] } ?? []) + let generation = self.generation + inventory.snapshot { [weak self] inventory in + guard let self = self, generation == self.generation, self.assertion != nil, + Set(self.assertionBundles).isSuperset(of: shown) else { return } + guard !self.inventory.menuBarWasHiddenAtLastSnapshot else { + NSLog("NativeVisibility: the menu bar was hidden when the drag was read; sections unchanged") + return + } + let read = MenuBarLayoutResolver.resolve(inventory: inventory, + separatorFrame: boundary, + alwaysHiddenSeparatorFrame: nil, + displays: self.displays(), + isLTR: self.isLTR(), + excludingBundle: self.ownBundleIdentifier) + let positions = read.sections.filter { shown.contains($0.key) } + guard !positions.isEmpty else { return } + var observed = self.sectionMemory.sections + var table = self.pinnedSections.sections + let before = table + _ = PinnedSectionResolver.resolve(read: positions, + launchedSinceRead: self.launchedSinceRead, + ignoringDrags: self.ignoredDrags(), + observed: &observed, table: &table) + self.sectionMemory.sections = observed + self.launchedSinceRead.subtract(positions.keys) + let changed = table.filter { before[$0.key] != $0.value } + guard !changed.isEmpty else { return } + NSLog("NativeVisibility: a ⌘-drag moved \(changed.keys.sorted().map { "\($0) to \(table[$0]!)" })") + self.pinnedSections.sections = table + self.pinnedSectionsDidChange() + // Settings › Icons and the catalog follow the table; the controller, + // which passes this notification on to the engine, skips its own. + NotificationCenter.default.post(name: .pinnedSectionsChanged, object: self) + } + } + func pinnedSectionsDidChange() { guard pinsSections() else { return } let table = pinnedSections.sections diff --git a/hidden/Features/StatusBar/StatusBarController.swift b/hidden/Features/StatusBar/StatusBarController.swift index 4c10b4f6..5d65ce4f 100644 --- a/hidden/Features/StatusBar/StatusBarController.swift +++ b/hidden/Features/StatusBar/StatusBarController.swift @@ -261,8 +261,10 @@ class StatusBarController: MenuBarItemProvider { native.expandBar = { [weak self] in self?.expandMenubar() } native.collapseBar = { [weak self] in self?.collapseMenuBar() } native.expandBarForCapture = { [weak self] in self?.expandMenubar(activatingApp: false) } - pinnedSectionsObserver = NotificationCenter.default.addObserver(forName: .pinnedSectionsChanged, object: nil, queue: .main) { [weak native] _ in - native?.pinnedSectionsDidChange() + pinnedSectionsObserver = NotificationCenter.default.addObserver(forName: .pinnedSectionsChanged, object: nil, queue: .main) { [weak native] note in + // The engine posts after a ⌘-drag, having applied it already. + guard let native = native, note.object as AnyObject? !== native else { return } + native.pinnedSectionsDidChange() } native.onUserChangedBar = { [weak self] in #if HIDDENBAR_NATIVE_VISIBILITY