From 6b2855961e33b358dda93468b352b6098217e2b9 Mon Sep 17 00:00:00 2001 From: Niko Eltarenko <61957857+nikoelt@users.noreply.github.com> Date: Sun, 15 Nov 2026 16:16:52 +1000 Subject: [PATCH 01/29] feat(notch-hover-panel): morph the panel from the Dynamic Island --- .../Resources/Localizable.xcstrings | 72 +-- .../Sources/NotchHoverPanelController.swift | 3 + .../Sources/NotchHoverPanelGeometry.swift | 43 +- .../Sources/NotchHoverPanelPlugin.swift | 6 +- .../NotchHoverPanelControllerTests.swift | 39 ++ .../Tests/NotchHoverPanelGeometryTests.swift | 45 +- README.md | 2 +- README.zh-CN.md | 2 +- .../App/ConfiguredMenuBarPanelContent.swift | 14 +- Sources/App/MenuBarContent.swift | 2 + Sources/App/MenuBarPanelPresenter.swift | 383 ++++++------ Sources/App/NotchMenuBarPanel.swift | 555 ++++++++++++++++++ .../unreleased/notch-hover-island-trigger.md | 6 + changes/unreleased/notch-panel-morph.md | 6 + docs/plugins/notch-hover-panel.md | 15 +- 15 files changed, 916 insertions(+), 277 deletions(-) create mode 100644 Sources/App/NotchMenuBarPanel.swift create mode 100644 changes/unreleased/notch-hover-island-trigger.md create mode 100644 changes/unreleased/notch-panel-morph.md diff --git a/Plugins/NotchHoverPanel/Resources/Localizable.xcstrings b/Plugins/NotchHoverPanel/Resources/Localizable.xcstrings index b45077208..d20c8c944 100644 --- a/Plugins/NotchHoverPanel/Resources/Localizable.xcstrings +++ b/Plugins/NotchHoverPanel/Resources/Localizable.xcstrings @@ -84,73 +84,73 @@ "ar": { "stringUnit": { "state": "translated", - "value": "أظهر لوحة MacTools عند تمرير المؤشر بجانب Dynamic Island أو التحرك لأعلى من أسفله." + "value": "ضع المؤشر فوق Dynamic Island لفتح لوحة MacTools." } }, "de": { "stringUnit": { "state": "translated", - "value": "MacTools-Bedienfeld einblenden, wenn der Zeiger neben der Dynamic Island schwebt oder von direkt darunter nach oben bewegt wird." + "value": "Bewege den Zeiger über die Dynamic Island, um das MacTools-Panel zu öffnen." } }, "en": { "stringUnit": { "state": "translated", - "value": "Slide out the MacTools panel when the pointer hovers beside the Dynamic Island or moves up from directly below it." + "value": "Hover over the Dynamic Island to open the MacTools panel." } }, "es": { "stringUnit": { "state": "translated", - "value": "Muestra el panel de MacTools al pasar el puntero junto a Dynamic Island o moverlo hacia arriba desde justo debajo." + "value": "Coloca el puntero sobre Dynamic Island para abrir el panel de MacTools." } }, "fr": { "stringUnit": { "state": "translated", - "value": "Affichez le panneau MacTools lorsque le pointeur survole le bord de Dynamic Island ou remonte depuis juste en dessous." + "value": "Survolez la Dynamic Island pour ouvrir le panneau MacTools." } }, "ja": { "stringUnit": { "state": "translated", - "value": "ポインタを Dynamic Island の横に重ねるか、真下から上へ動かすと MacTools パネルを表示します。" + "value": "Dynamic Island にポインタを合わせると、MacTools パネルが開きます。" } }, "ko": { "stringUnit": { "state": "translated", - "value": "포인터를 Dynamic Island 옆에 올리거나 바로 아래에서 위로 이동하면 MacTools 패널을 표시합니다." + "value": "Dynamic Island에 포인터를 올리면 MacTools 패널이 열립니다." } }, "pt": { "stringUnit": { "state": "translated", - "value": "Mostre o painel do MacTools ao passar o ponteiro ao lado do Dynamic Island ou movê-lo para cima a partir de baixo dele." + "value": "Passe o ponteiro sobre o Dynamic Island para abrir o painel do MacTools." } }, "ru": { "stringUnit": { "state": "translated", - "value": "Показывать панель MacTools при наведении курсора рядом с Dynamic Island или движении вверх из-под него." + "value": "Наведите указатель на Dynamic Island, чтобы открыть панель MacTools." } }, "tr": { "stringUnit": { "state": "translated", - "value": "İmleci Dynamic Island'ın yanına getirdiğinizde veya hemen altından yukarı hareket ettirdiğinizde MacTools panelini gösterin." + "value": "MacTools panelini açmak için imleci Dynamic Island'ın üzerine getirin." } }, "zh-Hans": { "stringUnit": { "state": "translated", - "value": "鼠标悬停灵动岛两侧,或从灵动岛正下方往上移动时滑出 MacTools 面板" + "value": "将鼠标悬停在灵动岛上即可打开 MacTools 面板。" } }, "zh-Hant": { "stringUnit": { "state": "translated", - "value": "滑鼠懸停靈動島兩側,或從靈動島正下方往上移動時滑出 MacTools 面板" + "value": "將滑鼠游標停在靈動島上即可開啟 MacTools 面板。" } } } @@ -546,73 +546,73 @@ "ar": { "stringUnit": { "state": "translated", - "value": "مرّر المؤشر فوق أي جانب من Dynamic Island أو حرّكه لأعلى من أسفله مباشرة لعرض اللوحة؛ ادخل إلى اللوحة لإبقائها ظاهرة." + "value": "ضع المؤشر فوق Dynamic Island لفتح لوحة MacTools. حرّك المؤشر إلى اللوحة لإبقائها مفتوحة." } }, "de": { "stringUnit": { "state": "translated", - "value": "Fahre über eine Seite der Dynamic Island oder von direkt darunter nach oben, um das Bedienfeld anzuzeigen; bewege den Zeiger in das Bedienfeld, um es sichtbar zu halten." + "value": "Bewege den Zeiger über die Dynamic Island, um das MacTools-Panel zu öffnen. Bewege den Zeiger auf das Panel, um es offen zu halten." } }, "en": { "stringUnit": { "state": "translated", - "value": "Hover either side of the Dynamic Island, or move upward from directly below it, to show the panel; move into the panel to keep it visible." + "value": "Hover over the Dynamic Island to open the MacTools panel. Move the pointer into the panel to keep it open." } }, "es": { "stringUnit": { "state": "translated", - "value": "Pasa el puntero por cualquier lado de Dynamic Island o muévelo hacia arriba desde justo debajo para mostrar el panel; entra en el panel para mantenerlo visible." + "value": "Coloca el puntero sobre Dynamic Island para abrir el panel de MacTools. Mueve el puntero al panel para mantenerlo abierto." } }, "fr": { "stringUnit": { "state": "translated", - "value": "Survolez un côté de Dynamic Island ou remontez depuis juste en dessous pour afficher le panneau ; entrez dans le panneau pour le maintenir visible." + "value": "Survolez la Dynamic Island pour ouvrir le panneau MacTools. Déplacez le pointeur dans le panneau pour le garder ouvert." } }, "ja": { "stringUnit": { "state": "translated", - "value": "Dynamic Island の左右にポインタを合わせるか、真下から上へ動かすとパネルが表示されます。パネル内に移動すると表示が維持されます。" + "value": "Dynamic Island にポインタを合わせると、MacTools パネルが開きます。ポインタをパネル内に移動すると、開いたままになります。" } }, "ko": { "stringUnit": { "state": "translated", - "value": "Dynamic Island 양옆에 포인터를 올리거나 바로 아래에서 위로 이동하면 패널이 표시됩니다. 패널 안으로 이동하면 계속 표시됩니다." + "value": "Dynamic Island에 포인터를 올리면 MacTools 패널이 열립니다. 포인터를 패널 안으로 옮기면 열린 상태로 유지됩니다." } }, "pt": { "stringUnit": { "state": "translated", - "value": "Passe o ponteiro em qualquer lado do Dynamic Island ou mova-o para cima a partir de baixo dele para mostrar o painel; entre no painel para mantê-lo visível." + "value": "Passe o ponteiro sobre o Dynamic Island para abrir o painel do MacTools. Mova o ponteiro para dentro do painel para mantê-lo aberto." } }, "ru": { "stringUnit": { "state": "translated", - "value": "Наведите курсор на любую сторону Dynamic Island или переместите его вверх из-под неё, чтобы показать панель; переместите курсор на панель, чтобы оставить её открытой." + "value": "Наведите указатель на Dynamic Island, чтобы открыть панель MacTools. Переместите указатель на панель, чтобы она оставалась открытой." } }, "tr": { "stringUnit": { "state": "translated", - "value": "Paneli göstermek için imleci Dynamic Island'ın her iki yanına getirin veya hemen altından yukarı doğru hareket ettirin; görünür kalması için panele girin." + "value": "MacTools panelini açmak için imleci Dynamic Island'ın üzerine getirin. Paneli açık tutmak için imleci panelin içine getirin." } }, "zh-Hans": { "stringUnit": { "state": "translated", - "value": "悬停灵动岛两侧,或从灵动岛正下方往上移动,即可显示面板;将鼠标移入面板可保持显示。" + "value": "将鼠标悬停在灵动岛上即可打开 MacTools 面板。将鼠标移入面板可使其保持打开。" } }, "zh-Hant": { "stringUnit": { "state": "translated", - "value": "懸停靈動島兩側,或從靈動島正下方往上移動,即可顯示面板;將滑鼠移入面板可保持顯示。" + "value": "將滑鼠游標停在靈動島上即可開啟 MacTools 面板。將滑鼠游標移入面板即可保持開啟。" } } } @@ -700,73 +700,73 @@ "ar": { "stringUnit": { "state": "translated", - "value": "أظهر لوحة MacTools عندما يدخل المؤشر إلى أي جانب من Dynamic Island أو يتحرك لأعلى من أسفله مباشرة." + "value": "ضع المؤشر فوق Dynamic Island لفتح لوحة MacTools." } }, "de": { "stringUnit": { "state": "translated", - "value": "MacTools-Bedienfeld anzeigen, wenn der Zeiger eine Seite der Dynamic Island erreicht oder von direkt darunter nach oben bewegt wird." + "value": "Bewege den Zeiger über die Dynamic Island, um das MacTools-Panel zu öffnen." } }, "en": { "stringUnit": { "state": "translated", - "value": "Show the MacTools panel when the pointer enters either side of the Dynamic Island or moves upward from directly below it." + "value": "Hover over the Dynamic Island to open the MacTools panel." } }, "es": { "stringUnit": { "state": "translated", - "value": "Muestra el panel de MacTools cuando el puntero entra en cualquier lado de Dynamic Island o se mueve hacia arriba desde justo debajo." + "value": "Coloca el puntero sobre Dynamic Island para abrir el panel de MacTools." } }, "fr": { "stringUnit": { "state": "translated", - "value": "Afficher le panneau MacTools lorsque le pointeur entre sur un côté de Dynamic Island ou remonte depuis juste en dessous." + "value": "Survolez la Dynamic Island pour ouvrir le panneau MacTools." } }, "ja": { "stringUnit": { "state": "translated", - "value": "ポインタが Dynamic Island の左右に入るか、真下から上へ移動すると MacTools パネルを表示します。" + "value": "Dynamic Island にポインタを合わせると、MacTools パネルが開きます。" } }, "ko": { "stringUnit": { "state": "translated", - "value": "포인터가 Dynamic Island 양옆으로 들어오거나 바로 아래에서 위로 이동하면 MacTools 패널을 표시합니다." + "value": "Dynamic Island에 포인터를 올리면 MacTools 패널이 열립니다." } }, "pt": { "stringUnit": { "state": "translated", - "value": "Mostra o painel do MacTools quando o ponteiro entra em qualquer lado do Dynamic Island ou se move para cima a partir de baixo dele." + "value": "Passe o ponteiro sobre o Dynamic Island para abrir o painel do MacTools." } }, "ru": { "stringUnit": { "state": "translated", - "value": "Показывать панель MacTools, когда курсор попадает на любую сторону Dynamic Island или движется вверх из-под неё." + "value": "Наведите указатель на Dynamic Island, чтобы открыть панель MacTools." } }, "tr": { "stringUnit": { "state": "translated", - "value": "İmleç Dynamic Island'ın her iki yanına girdiğinde veya hemen altından yukarı doğru hareket ettiğinde MacTools panelini göster." + "value": "MacTools panelini açmak için imleci Dynamic Island'ın üzerine getirin." } }, "zh-Hans": { "stringUnit": { "state": "translated", - "value": "鼠标移入灵动岛两侧,或从灵动岛正下方往上接近灵动岛时显示 MacTools 面板。" + "value": "将鼠标悬停在灵动岛上即可打开 MacTools 面板。" } }, "zh-Hant": { "stringUnit": { "state": "translated", - "value": "滑鼠移入靈動島兩側,或從靈動島正下方往上接近靈動島時顯示 MacTools 面板。" + "value": "將滑鼠游標停在靈動島上即可開啟 MacTools 面板。" } } } diff --git a/Plugins/NotchHoverPanel/Sources/NotchHoverPanelController.swift b/Plugins/NotchHoverPanel/Sources/NotchHoverPanelController.swift index 170a6dca9..15624c56c 100644 --- a/Plugins/NotchHoverPanel/Sources/NotchHoverPanelController.swift +++ b/Plugins/NotchHoverPanel/Sources/NotchHoverPanelController.swift @@ -487,6 +487,9 @@ final class NotchHoverPanelController: NotchHoverPanelControlling { // cannot retry or cancel the close. let accepted = requestMenuBarPanelDismissal?(animated) ?? true guard accepted else { return } + // Keep ownership while the host animates closed so a pointer moving + // back onto the island can reverse the transition. + if animated, isEnabled, isPresentedMenuBarPanelVisible?() == true { return } ownsPanelPresentation = false activeDisplay = nil diff --git a/Plugins/NotchHoverPanel/Sources/NotchHoverPanelGeometry.swift b/Plugins/NotchHoverPanel/Sources/NotchHoverPanelGeometry.swift index c6690d7fb..d669d3dce 100644 --- a/Plugins/NotchHoverPanel/Sources/NotchHoverPanelGeometry.swift +++ b/Plugins/NotchHoverPanel/Sources/NotchHoverPanelGeometry.swift @@ -20,16 +20,17 @@ struct NotchHoverDisplay: Equatable, Sendable { } enum NotchHoverGeometry { - static let defaultTriggerWidth: CGFloat = 52 - static let minimumTriggerWidth: CGFloat = 24 + // By default only the island itself opens the panel; both extensions are opt-in. + static let defaultTriggerWidth: CGFloat = 0 + static let minimumTriggerWidth: CGFloat = 0 static let maximumTriggerWidth: CGFloat = 120 - static let allowedTriggerWidthRange: ClosedRange = 24...120 + static let allowedTriggerWidthRange: ClosedRange = 0...120 static let triggerWidthStep: Double = 4 - static let defaultVerticalTriggerReach: CGFloat = 72 - static let minimumVerticalTriggerReach: CGFloat = 24 + static let defaultVerticalTriggerReach: CGFloat = 0 + static let minimumVerticalTriggerReach: CGFloat = 0 static let maximumVerticalTriggerReach: CGFloat = 160 - static let allowedVerticalTriggerReachRange: ClosedRange = 24...160 + static let allowedVerticalTriggerReachRange: ClosedRange = 0...160 static let verticalTriggerReachStep: Double = 8 static func displays( @@ -69,10 +70,9 @@ enum NotchHoverGeometry { guard notchWidth > 0 else { return nil } let bandWidth = min(max(triggerWidth, minimumTriggerWidth), maximumTriggerWidth) - let verticalReach = min( - max(verticalTriggerReach, minimumVerticalTriggerReach), - maximumVerticalTriggerReach - ) + let verticalReach = enableBelowTrigger + ? min(max(verticalTriggerReach, minimumVerticalTriggerReach), maximumVerticalTriggerReach) + : 0 let notchFrame = CGRect( x: screen.frame.minX + leftArea.width, y: screen.frame.maxY - topBandHeight, @@ -93,21 +93,14 @@ enum NotchHoverGeometry { height: notchFrame.height ).intersection(screen.frame) - // Extend the trigger directly below the notch so moving upward toward - // the notch from the content area also reveals the panel. The lower - // trigger can be disabled independently of the side triggers. - var triggers = [leftTrigger, rightTrigger] - if enableBelowTrigger { - let belowNotchTrigger = CGRect( - x: notchFrame.minX, - y: notchFrame.minY - verticalReach, - width: notchFrame.width, - height: notchFrame.height + verticalReach - ).intersection(screen.frame) - triggers.append(belowNotchTrigger) - } - triggers = triggers.filter { !$0.isEmpty } - guard !triggers.isEmpty else { return nil } + // The lower-hover preference controls only the extension below the island. + let islandTrigger = CGRect( + x: notchFrame.minX, + y: notchFrame.minY - verticalReach, + width: notchFrame.width, + height: notchFrame.height + verticalReach + ).intersection(screen.frame) + let triggers = [leftTrigger, rightTrigger, islandTrigger].filter { !$0.isEmpty } return NotchHoverDisplay( displayID: screen.displayID, diff --git a/Plugins/NotchHoverPanel/Sources/NotchHoverPanelPlugin.swift b/Plugins/NotchHoverPanel/Sources/NotchHoverPanelPlugin.swift index ef8c9321c..88687ec46 100644 --- a/Plugins/NotchHoverPanel/Sources/NotchHoverPanelPlugin.swift +++ b/Plugins/NotchHoverPanel/Sources/NotchHoverPanelPlugin.swift @@ -47,7 +47,7 @@ final class NotchHoverPanelPlugin: MacToolsPlugin, PluginMenuBarPanelPresenting, order: 41, defaultDescription: localization.string( "metadata.description", - defaultValue: "鼠标悬停灵动岛两侧,或从灵动岛正下方往上移动时滑出 MacTools 面板" + defaultValue: "将鼠标悬停在灵动岛上即可打开 MacTools 面板。" ) ) } @@ -80,7 +80,7 @@ final class NotchHoverPanelPlugin: MacToolsPlugin, PluginMenuBarPanelPresenting, ), description: localization.string( "settings.enabled.description", - defaultValue: "鼠标移入灵动岛两侧,或从灵动岛正下方往上接近灵动岛时显示 MacTools 面板。" + defaultValue: "将鼠标悬停在灵动岛上即可打开 MacTools 面板。" ), systemImage: "rectangle.topthird.inset.filled", control: .toggle(isOn: snapshot.isEnabled) @@ -248,7 +248,7 @@ final class NotchHoverPanelPlugin: MacToolsPlugin, PluginMenuBarPanelPresenting, systemImage: "rectangle.topthird.inset.filled", footer: localization.string( "settings.footer", - defaultValue: "悬停灵动岛两侧,或从灵动岛正下方往上移动,即可显示面板;将鼠标移入面板可保持显示。" + defaultValue: "将鼠标悬停在灵动岛上即可打开 MacTools 面板。将鼠标移入面板可使其保持打开。" ), rows: rows ), diff --git a/Plugins/NotchHoverPanel/Tests/NotchHoverPanelControllerTests.swift b/Plugins/NotchHoverPanel/Tests/NotchHoverPanelControllerTests.swift index ca5547971..e52042521 100644 --- a/Plugins/NotchHoverPanel/Tests/NotchHoverPanelControllerTests.swift +++ b/Plugins/NotchHoverPanel/Tests/NotchHoverPanelControllerTests.swift @@ -100,6 +100,7 @@ final class NotchHoverPanelControllerTests: XCTestCase { screensProvider: { [Self.notchScreenSnapshot()] }, mouseLocationProvider: { mouse.value } ) + controller.setVerticalTriggerReach(72) controller.setShowDelay(0) controller.setHideDelay(0.05) @@ -244,6 +245,44 @@ final class NotchHoverPanelControllerTests: XCTestCase { XCTAssertTrue(controller.snapshot.isPanelVisible) } + func testReturningDuringAnimatedDismissalReopensThePanel() { + let mouse = TestState(Self.triggerPoint) + let controller = NotchHoverPanelController( + storage: NotchHoverMemoryStorage(), + screensProvider: { [Self.notchScreenSnapshot()] }, + mouseLocationProvider: { mouse.value } + ) + controller.setShowDelay(0) + controller.setHideDelay(0.05) + + var isPanelVisible = false + var isClosing = false + controller.isPresentedMenuBarPanelVisible = { isPanelVisible } + controller.requestMenuBarPanelPresentation = { _ in + isPanelVisible = true + isClosing = false + return true + } + controller.requestMenuBarPanelDismissal = { animated in + isClosing = animated + return true + } + + controller.handlePointerLocation(mouse.value) + waitForScheduledWork() + XCTAssertTrue(controller.snapshot.isPanelVisible) + + mouse.value = NSPoint(x: 40, y: 40) + controller.handlePointerLocation(mouse.value) + waitForScheduledWork() + XCTAssertTrue(isClosing) + + mouse.value = Self.triggerPoint + controller.handlePointerLocation(mouse.value) + XCTAssertFalse(isClosing) + XCTAssertTrue(controller.snapshot.isPanelVisible) + } + private func makeController(storage: NotchHoverMemoryStorage) -> NotchHoverPanelController { NotchHoverPanelController( storage: storage, diff --git a/Plugins/NotchHoverPanel/Tests/NotchHoverPanelGeometryTests.swift b/Plugins/NotchHoverPanel/Tests/NotchHoverPanelGeometryTests.swift index e4fe8e9e9..3c4e94ae6 100644 --- a/Plugins/NotchHoverPanel/Tests/NotchHoverPanelGeometryTests.swift +++ b/Plugins/NotchHoverPanel/Tests/NotchHoverPanelGeometryTests.swift @@ -7,8 +7,29 @@ final class NotchHoverPanelGeometryTests: XCTestCase { private let leftArea = CGRect(x: 0, y: 950, width: 620, height: 32) private let rightArea = CGRect(x: 892, y: 950, width: 620, height: 32) + func testDefaultTriggerIsOnlyTheIsland() throws { + let display = try XCTUnwrap(makeDisplay( + triggerWidth: NotchHoverGeometry.defaultTriggerWidth, + verticalTriggerReach: NotchHoverGeometry.defaultVerticalTriggerReach + )) + + XCTAssertEqual(display.triggerRects, [display.notchFrame]) + let withBelowTriggerDisabled = try XCTUnwrap( + makeDisplay(triggerWidth: 0, enableBelowTrigger: false) + ) + XCTAssertEqual(withBelowTriggerDisabled.triggerRects, [withBelowTriggerDisabled.notchFrame]) + for point in [CGPoint(x: 610, y: 960), CGPoint(x: 900, y: 960), CGPoint(x: 756, y: 940)] { + XCTAssertFalse(NotchHoverGeometry.isPointerActive( + point, + triggers: display.triggerRects, + notchFrame: display.notchFrame, + panelFrame: nil + ), "Pointer just outside the island at \(point) must not open the panel.") + } + } + func testTriggersStayImmediatelyBesideAndBelowTheNotch() throws { - let display = try XCTUnwrap(makeDisplay(triggerWidth: 52)) + let display = try XCTUnwrap(makeDisplay(triggerWidth: 52, verticalTriggerReach: 72)) XCTAssertEqual(display.notchFrame, CGRect(x: 620, y: 950, width: 272, height: 32)) XCTAssertEqual(display.triggerRects.count, 3) @@ -18,9 +39,9 @@ final class NotchHoverPanelGeometryTests: XCTestCase { display.triggerRects[2], CGRect( x: 620, - y: 950 - NotchHoverGeometry.defaultVerticalTriggerReach, + y: 950 - 72, width: 272, - height: 32 + NotchHoverGeometry.defaultVerticalTriggerReach + height: 32 + 72 ) ) @@ -40,7 +61,7 @@ final class NotchHoverPanelGeometryTests: XCTestCase { } func testMovingUpwardFromBelowTheNotchTriggersThePanel() throws { - let display = try XCTUnwrap(makeDisplay(triggerWidth: 52)) + let display = try XCTUnwrap(makeDisplay(triggerWidth: 52, verticalTriggerReach: 72)) XCTAssertTrue(NotchHoverGeometry.isPointerActive( CGPoint(x: 756, y: 900), @@ -62,12 +83,13 @@ final class NotchHoverPanelGeometryTests: XCTestCase { ), "The trigger below the notch stays within the notch width.") } - func testDisablingBelowTriggerKeepsOnlySideTriggers() throws { + func testDisablingBelowTriggerKeepsTheIslandAndSideTriggers() throws { let display = try XCTUnwrap( - makeDisplay(triggerWidth: 52, enableBelowTrigger: false) + makeDisplay(triggerWidth: 52, verticalTriggerReach: 72, enableBelowTrigger: false) ) - XCTAssertEqual(display.triggerRects.count, 2, "Only the side triggers remain.") + XCTAssertEqual(display.triggerRects.count, 3) + XCTAssertEqual(display.triggerRects.last, display.notchFrame) XCTAssertEqual(display.triggerRects[0], CGRect(x: 568, y: 950, width: 52, height: 32)) XCTAssertEqual(display.triggerRects[1], CGRect(x: 892, y: 950, width: 52, height: 32)) XCTAssertFalse(NotchHoverGeometry.isPointerActive( @@ -85,7 +107,7 @@ final class NotchHoverPanelGeometryTests: XCTestCase { } func testVerticalTriggerReachIsClampedAndRespected() throws { - let minimum = try XCTUnwrap(makeDisplay(triggerWidth: 52, verticalTriggerReach: 1)) + let minimum = try XCTUnwrap(makeDisplay(triggerWidth: 52, verticalTriggerReach: -10)) let maximum = try XCTUnwrap(makeDisplay(triggerWidth: 52, verticalTriggerReach: 500)) XCTAssertEqual( @@ -105,10 +127,9 @@ final class NotchHoverPanelGeometryTests: XCTestCase { } func testTriggerWidthIsClampedToSupportedRange() throws { - XCTAssertEqual( - try XCTUnwrap(makeDisplay(triggerWidth: 2)).triggerRects[0].width, - NotchHoverGeometry.minimumTriggerWidth - ) + // Below the minimum, the side areas disappear and only the island remains. + let minimum = try XCTUnwrap(makeDisplay(triggerWidth: -10)) + XCTAssertEqual(minimum.triggerRects, [minimum.notchFrame]) XCTAssertEqual( try XCTUnwrap(makeDisplay(triggerWidth: 500)).triggerRects[0].width, NotchHoverGeometry.maximumTriggerWidth diff --git a/README.md b/README.md index 1fd88902e..9407828e3 100644 --- a/README.md +++ b/README.md @@ -123,7 +123,7 @@ Clipboard selection and scrolling respond immediately. Rapid navigation skips tr Screenshots work on macOS 14+; region recording and per-app volume require macOS 15+. Hardware controls depend on device support. See the [feature guides](docs/README.md) for details. -[Dynamic Island Hover Panel](docs/plugins/notch-hover-panel.md) slides out the MacTools panel when the pointer rests beside the Dynamic Island or moves up from directly below it; it requires a Mac display with a Dynamic Island. The plugin hides the MacTools menu-bar icon by default and can restore it in its settings. +[Dynamic Island Hover Panel](docs/plugins/notch-hover-panel.md) expands the MacTools panel from the notch when the pointer rests over it. The plugin requires a Mac display with a Dynamic Island and offers settings for the hover area and menu-bar icon visibility. Experimental [Trackpad Scale](docs/plugins/trackpad-scale.md) estimates small-object weight on a built-in Force Touch trackpad. Start with no object and keep one finger lightly resting in place; it automatically tares after about one second. Wait for the ready message, then gently place the object while maintaining that contact. Auto capture stops sampling after a stable reading and keeps the result visible so you can lift your finger; turn it off for continuous measuring. Calibration pauses auto capture and includes manual **Tare**; **⌘T** also resets the baseline while measuring. diff --git a/README.zh-CN.md b/README.zh-CN.md index 54e28c451..0872341b3 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -95,7 +95,7 @@ brew upgrade --cask --greedy mactools 「自动切换输入法」会在应用切到前台时应用该规则的输入法与键盘模式。键盘模式可选择跟随系统、使用 F1–F12 功能键或保留 MacBook 快捷键,切走后顶部按键会恢复原来的行为。 -[灵动岛悬浮面板](docs/plugins/notch-hover-panel.md)会在悬停灵动岛两侧,或从灵动岛正下方往上移动时滑出 MacTools 面板;需要带灵动岛的 Mac 屏幕。安装并启用后默认隐藏 MacTools 菜单栏图标,可在插件设置中重新显示。 +[灵动岛悬停面板](docs/plugins/notch-hover-panel.md)会在鼠标悬停于灵动岛上时,从刘海处展开 MacTools 面板。此插件需要带灵动岛的 Mac 屏幕,并可在设置中调整悬停范围和菜单栏图标的显示。 截图支持 macOS 14+;区域录屏和应用音量需要 macOS 15+。硬件控制取决于设备支持,详见[功能指南](docs/README.zh-CN.md)。 diff --git a/Sources/App/ConfiguredMenuBarPanelContent.swift b/Sources/App/ConfiguredMenuBarPanelContent.swift index 22b067e83..64fe19be4 100644 --- a/Sources/App/ConfiguredMenuBarPanelContent.swift +++ b/Sources/App/ConfiguredMenuBarPanelContent.swift @@ -75,9 +75,12 @@ enum ConfiguredMenuBarPanelLayout { static func contentHeight( components: [PluginPanelWidgetSnapshot], features: [PluginPanelRowSnapshot], screen: NSScreen?, - entries: [MenuBarPanelEntry]? = nil, width: CGFloat = MenuBarPanelLayout.surfaceWidth + entries: [MenuBarPanelEntry]? = nil, width: CGFloat = MenuBarPanelLayout.surfaceWidth, + minimumFeatureContentHeight: CGFloat = MenuBarPanelLayout.minimumContentHeight ) -> CGFloat { - if entries == nil && width == MenuBarPanelLayout.surfaceWidth && !features.contains(where: \.usesCompactPresentation) { + if entries == nil && width == MenuBarPanelLayout.surfaceWidth + && minimumFeatureContentHeight == MenuBarPanelLayout.minimumContentHeight + && !features.contains(where: \.usesCompactPresentation) { if components.isEmpty { return MenuBarPanelLayout.preferredFeatureContentHeight(for: features, screen: screen) } if features.isEmpty { return ComponentPanelLayout.preferredContentHeight(for: components, screen: screen) } } @@ -85,11 +88,12 @@ enum ConfiguredMenuBarPanelLayout { ?? components.map { ($0.id, PluginPanelItemKind.widget) } + features.map { ($0.id, PluginPanelItemKind.row) } let height = placement(order: order, components: components, features: features, width: width).height if components.isEmpty { - return MenuBarPanelLayout.preferredFeatureContentHeight(featureContentHeight: height, - maximumFeatureListHeight: MenuBarPanelLayout.maximumFeatureListHeight(for: screen)) + let maxHeight = MenuBarPanelLayout.maximumFeatureListHeight(for: screen) + let minimum = features.isEmpty ? MenuBarPanelLayout.minimumContentHeight : minimumFeatureContentHeight + return max(min(height, maxHeight) + MenuBarPanelLayout.contentVerticalPadding, minimum) } let raw = height + MenuBarPanelLayout.contentVerticalPadding - let minimum = features.isEmpty ? raw : MenuBarPanelLayout.minimumContentHeight + let minimum = features.isEmpty ? raw : minimumFeatureContentHeight return min(max(raw, minimum), MenuBarPanelLayout.maximumContentHeight(for: screen)) } } diff --git a/Sources/App/MenuBarContent.swift b/Sources/App/MenuBarContent.swift index b1497336a..439bd9fae 100644 --- a/Sources/App/MenuBarContent.swift +++ b/Sources/App/MenuBarContent.swift @@ -21,6 +21,8 @@ enum MenuBarPanelLayout { static let panelSpacing: CGFloat = 10 static let outerPadding: CGFloat = 6 static let panelTopPadding: CGFloat = 4 + /// Keeps the header capsules concentric with the notch surface's top corners. + static let notchHeaderHorizontalPadding: CGFloat = 12 static let contentTopPadding: CGFloat = 4 static let contentBottomPadding: CGFloat = 2 static let panelBottomPadding: CGFloat = outerPadding - contentBottomPadding diff --git a/Sources/App/MenuBarPanelPresenter.swift b/Sources/App/MenuBarPanelPresenter.swift index a7b1d902b..8b17daf36 100644 --- a/Sources/App/MenuBarPanelPresenter.swift +++ b/Sources/App/MenuBarPanelPresenter.swift @@ -158,6 +158,11 @@ final class MenuBarPanelContainerController: NSViewController { view = MenuBarPanelBackgroundView(themeStore: themeStore) } + func setDrawsBackground(_ drawsBackground: Bool) { + (view as? MenuBarPanelBackgroundView)?.drawsBackground = drawsBackground + refreshBackground() + } + func refreshBackground() { guard isViewLoaded else { return } view.needsDisplay = true @@ -207,9 +212,11 @@ private final class MenuBarPanelBackgroundView: NSView { fatalError("init(coder:) has not been implemented") } - override var isOpaque: Bool { true } + var drawsBackground = true + override var isOpaque: Bool { drawsBackground } override func draw(_ dirtyRect: NSRect) { + guard drawsBackground else { return } let isDark = effectiveAppearance.bestMatch(from: [.aqua, .darkAqua]) == .darkAqua let appearance: MenuBarPanelThemeAppearance = isDark ? .dark : .light let style = MenuBarPanelThemeResolver.resolve( @@ -291,10 +298,7 @@ final class MenuBarPanelPresenter: NSObject { ) private var popoverSafeAreaInsets = MenuBarPopoverGeometry.fallbackSafeAreaInsets private var hoverAnchorPanel: NSPanel? - private var isHoverPanelPresentation = false - private var isHidingHoverPanel = false - private var hoverPanelRestingFrame: NSRect? - private var hoverDismissGeneration: UInt = 0 + private var notchPanel: NotchMenuBarPanel? init( pluginHost: PluginHost, @@ -397,7 +401,11 @@ final class MenuBarPanelPresenter: NSObject { } var isAnyPanelShown: Bool { - popover.isShown + notchPanel != nil || popover.isShown + } + + private var presentedWindow: NSWindow? { + notchPanel?.window ?? popover.contentViewController?.view.window } private func refreshLocalization() { @@ -478,10 +486,10 @@ final class MenuBarPanelPresenter: NSObject { guard pluginHost.menuBarPanels.contains(where: { $0.id == id }) else { return } let panel = MenuBarPanelTab(id: id) if shouldToggle, - popover.isShown, + isAnyPanelShown, tab(for: selectedPanel).id == id { if panelModel.preventDismissalWhileEditing() { - focus(popover) + focusPresentedWindow() } else { dismissPanels() } @@ -490,109 +498,119 @@ final class MenuBarPanelPresenter: NSObject { present(panel, relativeTo: hoverAnchorView(for: anchorRect)) } - /// Presents the regular panel below an explicit screen rectangle. Used by - /// plugin-owned hover surfaces such as the notch trigger. + /// Presents the regular panel inside a shape anchored to the camera housing. @discardableResult func presentPanelBelowAnchor(panelID: String?, anchorRect: NSRect) -> Bool { guard !anchorRect.isEmpty, anchorRect.width.isFinite, anchorRect.height.isFinite, - !anchorRect.isNull else { return false } - guard NSScreen.screens.contains(where: { $0.frame.intersects(anchorRect) }) else { - return false - } + !anchorRect.isNull, + let screen = NSScreen.screens.first(where: { $0.frame.intersects(anchorRect) }) + else { return false } - if popover.isShown { - guard isHoverPanelPresentation else { return false } - cancelHoverPanelDismissalIfNeeded() + if let notchPanel { + notchPanel.reopen() return true } - guard let resolvedPanel = resolvedPanelForAnchor(panelID: panelID) else { return false } + let systemPanel = NotchMenuBarPanel.systemPanelDetector(over: anchorRect) + guard !popover.isShown, !systemPanel.isVisible, + let selected = resolvedPanelForAnchor(panelID: panelID) + else { return false } - let anchorView = hoverAnchorView(for: anchorRect) - isHoverPanelPresentation = true - isHidingHoverPanel = false - hoverPanelRestingFrame = nil - present(resolvedPanel, relativeTo: anchorView, animates: true) - return popover.isShown + selectedPanel = selected + popover.contentViewController = nil + let panel = NotchMenuBarPanel(anchor: anchorRect, content: containerController) + notchPanel = panel + panelModel.isNotchPresentation = true + containerController.setDrawsBackground(false) + applyCurrentAppearance() + updateContent(selectedTab: selected, screen: screen, isPanelVisible: true) + updatePanelSurfaceVisibility(for: selected, isPanelVisible: true) + + installKeyboardShortcutMonitorIfNeeded() + PluginPresentationSafety.prepareForWindowOrdering() + panel.present(size: panelContentSize) + panel.watchForSystemPanel(systemPanel) { [weak self, weak panel] in + guard let self, let panel, self.notchPanel === panel else { return } + self.dismissPanelBelowAnchor(animated: false) + } + focusPresentedWindow() + scheduleHeightRefresh(for: selected) + return true } - /// Dismisses the panel presented below a plugin-owned anchor. Returns - /// `false` when the host declines because the panel layout is being edited, - /// so the caller can keep ownership and retry later. @discardableResult func dismissPanelBelowAnchor(animated: Bool) -> Bool { - // Check the editing guard before any hide animation starts. Fading the - // panel out first would leave it open but transparent after the close - // is rejected. guard !panelModel.preventDismissalWhileEditing() else { return false } - guard popover.isShown else { - cleanupHoverAnchor() - return true - } - guard isHoverPanelPresentation, animated, - let window = popover.contentViewController?.view.window else { - popover.performClose(nil) - return true - } - - hoverDismissGeneration &+= 1 - let generation = hoverDismissGeneration - let restingFrame = window.frame - hoverPanelRestingFrame = restingFrame - isHidingHoverPanel = true + guard let notchPanel else { return true } - NSAnimationContext.runAnimationGroup({ context in - context.duration = 0.16 - context.timingFunction = CAMediaTimingFunction(name: .easeIn) - window.animator().setFrame( - restingFrame.offsetBy(dx: 0, dy: Self.hoverPanelSlideDistance), - display: true - ) - window.animator().alphaValue = 0 - }, completionHandler: { [weak self] in - Task { @MainActor [weak self] in - guard let self, self.hoverDismissGeneration == generation else { return } - self.isHidingHoverPanel = false - self.hoverPanelRestingFrame = nil - self.popover.performClose(nil) - } - }) + notchPanel.dismiss(animated: animated) { [weak self, weak notchPanel] in + guard let self, let notchPanel, self.notchPanel === notchPanel else { return } + self.finishNotchPanelDismissal(notchPanel) + } return true } var presentedPanelScreenFrame: NSRect? { - guard popover.isShown else { return nil } - return popover.contentViewController?.view.window?.frame + if let notchPanel { return notchPanel.interactiveScreenFrame } + return popover.isShown ? presentedWindow?.frame : nil } func dismissPanels() { nativeMenuPresenter.cancel() guard !panelModel.preventDismissalWhileEditing() else { return } - hoverDismissGeneration &+= 1 - isHidingHoverPanel = false - hoverPanelRestingFrame = nil - popover.performClose(nil) + if notchPanel != nil { + dismissPanelBelowAnchor(animated: true) + } else { + popover.performClose(nil) + } + } + + private func refreshNotchHeaderPlacement() { + guard let notchPanel else { + panelModel.setNotchHeader(besideIsland: false, topOffset: 0) + return + } + let tabsWidth = MenuBarPanelTabLayout.contentWidth(count: pluginHost.visibleMenuBarPanels.count) + let besideIsland = !panelModel.isEditingLayout && notchPanel.headerFitsBesideIsland( + leadingWidth: MenuBarPanelLayout.notchHeaderHorizontalPadding + tabsWidth, + panelWidth: panelModel.contentWidth + ) + panelModel.setNotchHeader( + besideIsland: besideIsland, + topOffset: besideIsland ? 0 : NotchMenuBarPanel.headerBelowIslandOffset(anchor: notchPanel.anchor) + ) + } + + private func finishNotchPanelDismissal(_ panel: NotchMenuBarPanel) { + panel.detachContent() + notchPanel = nil + panelModel.isNotchPresentation = false + panelModel.setNotchHeader(besideIsland: false, topOffset: 0) + containerController.setDrawsBackground(true) + popover.contentViewController = containerController + applyCurrentAppearance() + finishDismissal() } var isTrackingNativeMenu: Bool { nativeMenuPresenter.isTrackingMenu } func containsPresentedWindow(_ window: NSWindow) -> Bool { - window === popover.contentViewController?.view.window + window === presentedWindow || MenuBarPanelWindowRegistry.containsAuxiliaryPanelWindow(window) } private func toggle(_ panel: PanelKind, relativeTo anchorView: NSView) { let action = MenuBarPanelToggleAction.resolve( - isPanelShown: popover.isShown, + isPanelShown: isAnyPanelShown, selectedTab: tab(for: selectedPanel), requestedTab: tab(for: panel) ) if action == .close { if panelModel.preventDismissalWhileEditing() { - focus(popover) + focusPresentedWindow() } else { dismissPanels() } @@ -602,9 +620,9 @@ final class MenuBarPanelPresenter: NSObject { present(panel, relativeTo: anchorView) } - private func present(_ panel: PanelKind, relativeTo anchorView: NSView, animates: Bool = false) { + private func present(_ panel: PanelKind, relativeTo anchorView: NSView) { let action = MenuBarPanelPresentationAction.resolve( - isPanelShown: popover.isShown, + isPanelShown: isAnyPanelShown, selectedTab: tab(for: selectedPanel), requestedTab: tab(for: panel) ) @@ -617,13 +635,12 @@ final class MenuBarPanelPresenter: NSObject { updatePanelSurfaceVisibility(for: tab(for: panel), isPanelVisible: true) if action != .open { - focus(popover) + focusPresentedWindow() scheduleHeightRefresh(for: tab(for: panel)) return } - isHoverPanelPresentation = animates - show(popover, relativeTo: anchorView, animates: animates) + show(popover, relativeTo: anchorView) scheduleHeightRefresh(for: tab(for: panel)) } @@ -652,51 +669,12 @@ final class MenuBarPanelPresenter: NSObject { containerController.view.setFrameSize(popover.contentSize) } - private func show(_ popover: NSPopover, relativeTo anchorView: NSView, animates: Bool) { + private func show(_ popover: NSPopover, relativeTo anchorView: NSView) { applyCurrentAppearance() PluginPresentationSafety.prepareForWindowOrdering() popover.show(relativeTo: anchorView.bounds, of: anchorView, preferredEdge: .minY) applyCurrentAppearance() - if animates { - animateHoverPanelIn() - } - focus(popover) - } - - private static let hoverPanelSlideDistance: CGFloat = 18 - - private func animateHoverPanelIn() { - guard let window = popover.contentViewController?.view.window else { return } - let targetFrame = window.frame - hoverPanelRestingFrame = targetFrame - window.setFrame( - targetFrame.offsetBy(dx: 0, dy: Self.hoverPanelSlideDistance), - display: false - ) - window.alphaValue = 0 - - NSAnimationContext.runAnimationGroup { context in - context.duration = 0.22 - context.timingFunction = CAMediaTimingFunction(name: .easeOut) - window.animator().setFrame(targetFrame, display: true) - window.animator().alphaValue = 1 - } - } - - private func cancelHoverPanelDismissalIfNeeded() { - guard isHidingHoverPanel else { return } - hoverDismissGeneration &+= 1 - isHidingHoverPanel = false - guard let window = popover.contentViewController?.view.window, - let restingFrame = hoverPanelRestingFrame else { return } - hoverPanelRestingFrame = nil - - NSAnimationContext.runAnimationGroup { context in - context.duration = 0.14 - context.timingFunction = CAMediaTimingFunction(name: .easeOut) - window.animator().setFrame(restingFrame, display: true) - window.animator().alphaValue = 1 - } + focusPresentedWindow() } private func resolvedPanelForAnchor(panelID: String?) -> MenuBarPanelTab? { @@ -746,10 +724,6 @@ final class MenuBarPanelPresenter: NSObject { private func cleanupHoverAnchor() { hoverAnchorPanel?.orderOut(nil) hoverAnchorPanel = nil - isHoverPanelPresentation = false - isHidingHoverPanel = false - hoverPanelRestingFrame = nil - hoverDismissGeneration &+= 1 } private func installKeyboardShortcutMonitorIfNeeded() { @@ -777,7 +751,7 @@ final class MenuBarPanelPresenter: NSObject { private func handleKeyboardShortcut(_ event: NSEvent) -> NSEvent? { guard - popover.isShown, + isAnyPanelShown, !nativeMenuPresenter.isTrackingMenu, let eventWindow = event.window, containsPresentedWindow(eventWindow) @@ -786,7 +760,7 @@ final class MenuBarPanelPresenter: NSObject { } if let index = Self.keyboardShortcutIndex(for: event), - eventWindow === popover.contentViewController?.view.window { + eventWindow === presentedWindow { let panels = pluginHost.visibleMenuBarPanels if panels.indices.contains(index) { select(MenuBarPanelTab(id: panels[index].id)) } return nil @@ -799,7 +773,7 @@ final class MenuBarPanelPresenter: NSObject { } if case .selectTab = action, - eventWindow !== popover.contentViewController?.view.window { + eventWindow !== presentedWindow { return event } @@ -853,22 +827,15 @@ final class MenuBarPanelPresenter: NSObject { } } - private func focus(_ popover: NSPopover) { - guard !nativeMenuPresenter.isPresenting else { return } + private func focusPresentedWindow() { + guard !nativeMenuPresenter.isPresenting, let window = presentedWindow else { return } let menuGeneration = nativeMenuPresenter.generation - popover.contentViewController?.view.window?.makeKey() + window.makeKey() - DispatchQueue.main.async { [weak self, weak popover] in - guard let self, let popover, popover.isShown, + DispatchQueue.main.async { [weak self, weak window] in + guard let self, let window, self.isAnyPanelShown, self.presentedWindow === window, self.nativeMenuPresenter.generation == menuGeneration, - !self.nativeMenuPresenter.isPresenting else { - return - } - - guard let window = popover.contentViewController?.view.window else { - return - } - + !self.nativeMenuPresenter.isPresenting else { return } window.makeKey() Self.clearAutomaticInitialFocus(in: window) } @@ -920,12 +887,20 @@ final class MenuBarPanelPresenter: NSObject { private func applyCurrentAppearance() { let preference = AppAppearancePreference.stored() - preference.apply(to: hostingController.view) - preference.apply(to: popover) + if let notchPanel { + let dark = NSAppearance(named: .darkAqua) + notchPanel.window.appearance = dark + hostingController.view.appearance = dark + } else { + preference.apply(to: hostingController.view) + preference.apply(to: popover) + } containerController.refreshBackground() } - private func setPopoverHeight(_ height: CGFloat) { + private func setPopoverHeight(_ baseHeight: CGFloat) { + refreshNotchHeaderPlacement() + let height = baseHeight + panelModel.notchHeaderTopOffset let width = panelModel.contentWidth let currentSize = panelContentSize guard @@ -936,7 +911,11 @@ final class MenuBarPanelPresenter: NSObject { } panelContentSize = NSSize(width: width, height: height) - applyPopoverSize() + if let notchPanel { + notchPanel.resize(to: panelContentSize) + } else { + applyPopoverSize() + } } private func applyPopoverSize() { @@ -1008,10 +987,10 @@ final class MenuBarPanelPresenter: NSObject { pluginHost.rememberMenuBarPanelSelection(id: tab.id) updateContent( selectedTab: tab, - screen: popover.contentViewController?.view.window?.screen ?? NSScreen.main, - isPanelVisible: popover.isShown + screen: presentedWindow?.screen ?? NSScreen.main, + isPanelVisible: isAnyPanelShown ) - updatePanelSurfaceVisibility(for: tab, isPanelVisible: popover.isShown) + updatePanelSurfaceVisibility(for: tab, isPanelVisible: isAnyPanelShown) scheduleHeightRefresh(for: tab) } @@ -1020,7 +999,7 @@ final class MenuBarPanelPresenter: NSObject { if selectedPanel.id == id { // The tab and its editor are about to disappear. End their focus // before SwiftUI releases the associated responder proxies. - popover.contentViewController?.view.window?.makeFirstResponder(nil) + presentedWindow?.makeFirstResponder(nil) } var error: String? var transaction = Transaction(animation: nil) @@ -1039,16 +1018,16 @@ final class MenuBarPanelPresenter: NSObject { let panels = pluginHost.visibleMenuBarPanels guard let selected = panels.first(where: { $0.id == selectedPanel.id }) ?? panels.first else { return } selectedPanel = MenuBarPanelTab(id: selected.id) - guard popover.isShown else { return } + guard isAnyPanelShown else { return } updateContent(selectedTab: selectedPanel, - screen: popover.contentViewController?.view.window?.screen ?? NSScreen.main, - isPanelVisible: popover.isShown) - updatePanelSurfaceVisibility(for: selectedPanel, isPanelVisible: popover.isShown) + screen: presentedWindow?.screen ?? NSScreen.main, + isPanelVisible: isAnyPanelShown) + updatePanelSurfaceVisibility(for: selectedPanel, isPanelVisible: isAnyPanelShown) } private func scheduleHeightRefresh(for tab: MenuBarPanelTab) { DispatchQueue.main.async { [weak self] in - guard let self, self.popover.isShown else { + guard let self, self.isAnyPanelShown else { return } @@ -1061,7 +1040,7 @@ final class MenuBarPanelPresenter: NSObject { return } - let screen = popover.contentViewController?.view.window?.screen ?? NSScreen.main + let screen = presentedWindow?.screen ?? NSScreen.main let heightResolution = resolveContentHeight( for: tab, screen: screen @@ -1070,7 +1049,7 @@ final class MenuBarPanelPresenter: NSObject { selectedTab: tab, contentHeight: heightResolution.contentHeight, maximumFeatureListHeight: heightResolution.maximumFeatureListHeight, - isPanelVisible: popover.isShown + isPanelVisible: isAnyPanelShown ) setPopoverHeight( MenuBarPanelLayout.panelHeight( @@ -1081,7 +1060,7 @@ final class MenuBarPanelPresenter: NSObject { } private func refreshHeightForVisiblePanel() { - guard popover.isShown else { + guard isAnyPanelShown else { return } @@ -1116,7 +1095,9 @@ final class MenuBarPanelPresenter: NSObject { ) } else { height = ConfiguredMenuBarPanelLayout.contentHeight( - components: components, features: features, screen: screen, entries: entries, width: surfaceWidth + components: components, features: features, screen: screen, entries: entries, width: surfaceWidth, + minimumFeatureContentHeight: notchPanel == nil + ? MenuBarPanelLayout.minimumContentHeight : NotchMenuBarPanel.minimumFeatureContentHeight ) } return MenuBarPanelHeightResolution(contentHeight: height, maximumFeatureListHeight: maximumFeatureListHeight) @@ -1154,21 +1135,17 @@ extension MenuBarPanelPresenter: NSPopoverDelegate { } func popoverDidClose(_ notification: Notification) { - if let closedPopover = notification.object as? NSPopover, closedPopover === popover { - nativeMenuPresenter.cancel() - removeKeyboardShortcutMonitorIfNeeded() - cleanupHoverAnchor() - updateContent( - selectedTab: tab(for: selectedPanel), - screen: NSScreen.main, - isPanelVisible: false - ) - updatePanelSurfaceVisibility( - for: tab(for: selectedPanel), - isPanelVisible: false - ) - onAllPanelsClosed() - } + guard let closedPopover = notification.object as? NSPopover, closedPopover === popover else { return } + cleanupHoverAnchor() + finishDismissal() + } + + private func finishDismissal() { + nativeMenuPresenter.cancel() + removeKeyboardShortcutMonitorIfNeeded() + updateContent(selectedTab: tab(for: selectedPanel), screen: NSScreen.main, isPanelVisible: false) + updatePanelSurfaceVisibility(for: tab(for: selectedPanel), isPanelVisible: false) + onAllPanelsClosed() } } @@ -1205,6 +1182,16 @@ final class MenuBarUnifiedPanelModel: ObservableObject { if maximumWidth != maximum { maximumWidth = maximum } } + @Published var isNotchPresentation = false + /// In the notch the header shares the island's row when it fits beside it; + /// otherwise it drops below the island by `notchHeaderTopOffset`. + @Published private(set) var notchHeaderBesideIsland = false + @Published private(set) var notchHeaderTopOffset: CGFloat = 0 + + func setNotchHeader(besideIsland: Bool, topOffset: CGFloat) { + if notchHeaderBesideIsland != besideIsland { notchHeaderBesideIsland = besideIsland } + if notchHeaderTopOffset != topOffset { notchHeaderTopOffset = topOffset } + } @Published private(set) var isEditingLayout = false let editingFeedback = MenuBarPanelEditingFeedback() var onTabSelection: ((MenuBarPanelTab) -> Void)? @@ -1338,11 +1325,13 @@ struct MenuBarUnifiedPanelContent: View { onItemDrop: dropItemOnPanel, canUndoLayout: layoutEditingSession.canUndo(in: pluginHost, panelID: model.selectedTab.id), editingFeedback: model.editingFeedback, - onUndoLayout: undoLayoutEdit + onUndoLayout: undoLayoutEdit, + splitsAroundIsland: model.notchHeaderBesideIsland ) .frame(maxWidth: .infinity) .frame(height: MenuBarPanelLayout.headerHeight) - .padding(.horizontal, MenuBarPanelLayout.outerPadding) + .padding(.horizontal, model.notchHeaderBesideIsland + ? MenuBarPanelLayout.notchHeaderHorizontalPadding : MenuBarPanelLayout.outerPadding) .popover(item: $iconPickerPanel, arrowEdge: .bottom) { panel in iconPickerContent(panel) } @@ -1376,7 +1365,7 @@ struct MenuBarUnifiedPanelContent: View { } } } - .padding(.top, MenuBarPanelLayout.panelTopPadding) + .padding(.top, MenuBarPanelLayout.panelTopPadding + model.notchHeaderTopOffset) .padding(.bottom, model.isEditingLayout ? MenuBarPanelLayout.editingPanelBottomPadding : MenuBarPanelLayout.panelBottomPadding) .frame( @@ -1384,11 +1373,11 @@ struct MenuBarUnifiedPanelContent: View { height: MenuBarPanelLayout.panelHeight( forContentHeight: model.contentHeight, showsEditingActionBar: model.isEditingLayout - ), + ) + model.notchHeaderTopOffset, alignment: .topLeading ) .background { - theme.surfaces.panel + if !model.isNotchPresentation { theme.surfaces.panel } } .foregroundStyle(theme.text.primary) .tint(theme.accent) @@ -1613,6 +1602,10 @@ struct MenuBarPanelHeader: View { let canUndoLayout: Bool let editingFeedback: MenuBarPanelEditingFeedback let onUndoLayout: () -> Void + /// Tabs lead and the actions trail, leaving the middle clear for the camera island. + var splitsAroundIsland = false + @Environment(\.menuBarPanelTheme) private var theme + @Environment(\.colorSchemeContrast) private var contrast var body: some View { if isEditingLayout { @@ -1620,28 +1613,48 @@ struct MenuBarPanelHeader: View { onUndoLayout: onUndoLayout, onDone: onEditLayout) { navigation } + } else if splitsAroundIsland { + HStack(spacing: 0) { + navigation.fixedSize() + Spacer(minLength: 0) + HStack(spacing: MenuBarPanelTabLayout.spacing) { accessories } + .padding(MenuBarPanelLayout.tabCapsuleInset) + .background { + // Matches the tab strip's capsule so both groups read as a pair. + Capsule() + .fill(theme.surfaces.panel) + .overlay { + Capsule().strokeBorder(theme.surfaces.separator, + lineWidth: contrast == .increased ? 1 : 0.5) + } + } + } } else { ZStack { navigation.fixedSize() HStack(spacing: MenuBarPanelLayout.headerAccessorySpacing) { Spacer(minLength: 8) - MenuBarPanelIconButton( - systemImage: "gearshape", - accessibilityTitle: AppL10n.settings("settings.window.title", defaultValue: "设置"), - action: onOpenSettings - ) - MenuBarPanelOverflowMenu( - canEditLayout: canEditLayout, - availableUpdateVersion: availableUpdateVersion, - onEditLayout: onEditLayout, - onOpenUpdate: onOpenUpdate, - onQuit: onQuit - ) + accessories } } } } + @ViewBuilder private var accessories: some View { + MenuBarPanelIconButton( + systemImage: "gearshape", + accessibilityTitle: AppL10n.settings("settings.window.title", defaultValue: "设置"), + action: onOpenSettings + ) + MenuBarPanelOverflowMenu( + canEditLayout: canEditLayout, + availableUpdateVersion: availableUpdateVersion, + onEditLayout: onEditLayout, + onOpenUpdate: onOpenUpdate, + onQuit: onQuit + ) + } + private var navigation: some View { MenuBarPanelTabs( panels: panels, selectedPanelID: selectedTab.id, diff --git a/Sources/App/NotchMenuBarPanel.swift b/Sources/App/NotchMenuBarPanel.swift new file mode 100644 index 000000000..2a3d5fa08 --- /dev/null +++ b/Sources/App/NotchMenuBarPanel.swift @@ -0,0 +1,555 @@ +import AppKit +import QuartzCore + +/// Hosts the menu-bar panel content inside a black surface that grows out of the +/// camera housing and folds back into it. +/// +/// The surface is driven by interruptible springs on a display link instead of +/// fixed-duration Core Animation keyframes, so hovering back in mid-close reverses +/// the motion from wherever it currently is, with its current velocity. +@MainActor +final class NotchMenuBarPanel { + static let minimumFeatureContentHeight: CGFloat = 76 + + private final class Window: NSPanel { + override var canBecomeKey: Bool { true } + override var canBecomeMain: Bool { false } + } + + let window: NSPanel + private let content: NSViewController + private let morphView: NotchMorphView + let anchor: CGRect + private let contentWasLayerBacked: Bool + private let contentAutoresizingMask: NSView.AutoresizingMask + private var model = NotchMorphModel() + private var metrics: NotchMorphMetrics + private var displayLink: CADisplayLink? + private let displayLinkTarget = NotchDisplayLinkTarget() + private var lastFrameTimestamp: CFTimeInterval? + private var closeCompletion: (@MainActor () -> Void)? + private var systemPanelMonitor: DispatchSourceTimer? + private(set) var isClosing = false + + init(anchor: CGRect, content: NSViewController) { + self.anchor = anchor + self.content = content + metrics = NotchMorphMetrics(anchor: anchor, contentSize: .zero) + contentWasLayerBacked = content.view.wantsLayer + contentAutoresizingMask = content.view.autoresizingMask + + window = Window( + contentRect: .zero, + styleMask: [.borderless, .nonactivatingPanel], + backing: .buffered, + defer: false + ) + window.isFloatingPanel = true + window.level = .statusBar + window.isOpaque = false + window.backgroundColor = .clear + window.hasShadow = false + window.hidesOnDeactivate = false + window.isReleasedWhenClosed = false + window.animationBehavior = .none + window.collectionBehavior = [.canJoinAllSpaces, .fullScreenAuxiliary, .ignoresCycle, .stationary] + + morphView = NotchMorphView(content: content.view) + let controller = NSViewController() + controller.view = morphView + controller.addChild(content) + window.contentViewController = controller + + displayLinkTarget.onFrame = { [weak self] link in self?.step(link) } + } + + isolated deinit { + systemPanelMonitor?.cancel() + displayLink?.invalidate() + } + + // MARK: - Presentation + + func present(size: CGSize) { + applyContentSize(size) + model = NotchMorphModel() + render() + window.orderFrontRegardless() + setExpanded(true) + } + + func resize(to size: CGSize) { + guard !isClosing, size != metrics.contentSize else { return } + applyContentSize(size) + render() + startDisplayLinkIfNeeded() + } + + func reopen() { + guard isClosing else { return } + isClosing = false + closeCompletion = nil + window.ignoresMouseEvents = false + setExpanded(true) + } + + func dismiss(animated: Bool, completion: @escaping @MainActor () -> Void) { + guard animated else { + stopDisplayLink() + isClosing = true + closeCompletion = nil + completion() + return + } + guard !isClosing else { return } + isClosing = true + closeCompletion = completion + window.ignoresMouseEvents = true + setExpanded(false) + } + + func detachContent() { + stopWatchingForSystemPanel() + stopDisplayLink() + window.orderOut(nil) + morphView.releaseContent() + content.view.alphaValue = 1 + content.view.autoresizingMask = contentAutoresizingMask + content.view.wantsLayer = contentWasLayerBacked + content.removeFromParent() + } + + /// The screen area the hover controller should treat as part of the panel. + /// While opening it is the final surface so the pointer can travel ahead of + /// the animation; while closing it is only what is still visible. + var interactiveScreenFrame: CGRect { + let rect = isClosing ? metrics.surfaceRect(for: model) : metrics.surfaceRect(expandedFraction: 1) + return metrics.screenRect(fromSurfaceRect: rect) + } + + /// Whether a leading header group of `leadingWidth` stays clear of the island. + func headerFitsBesideIsland(leadingWidth: CGFloat, panelWidth: CGFloat) -> Bool { + leadingWidth <= panelWidth / 2 - anchor.width / 2 - NotchMorphMetrics.islandClearance + } + + /// Extra top inset that moves the header from the island's row to just below it. + static func headerBelowIslandOffset(anchor: CGRect) -> CGFloat { + let metrics = NotchMorphMetrics(anchor: anchor, contentSize: .zero) + let belowIsland = metrics.housingOffset + metrics.housingSize.height + NotchMorphMetrics.contentGap + return max(belowIsland - metrics.contentTopInset - MenuBarPanelLayout.panelTopPadding, 0) + } + + // MARK: - Animation + + private func applyContentSize(_ size: CGSize) { + metrics = NotchMorphMetrics(anchor: anchor, contentSize: size) + let frame = metrics.windowFrame + if window.frame != frame { + window.setFrame(frame, display: false) + } + } + + private func setExpanded(_ expanded: Bool) { + model.target = expanded ? 1 : 0 + if NSWorkspace.shared.accessibilityDisplayShouldReduceMotion { + model.snapToTarget() + render() + finishIfSettled() + return + } + startDisplayLinkIfNeeded() + } + + private func startDisplayLinkIfNeeded() { + guard displayLink == nil else { return } + let link = morphView.displayLink(target: displayLinkTarget, selector: #selector(NotchDisplayLinkTarget.step(_:))) + link.add(to: .main, forMode: .common) + lastFrameTimestamp = nil + displayLink = link + } + + private func stopDisplayLink() { + displayLink?.invalidate() + displayLink = nil + lastFrameTimestamp = nil + } + + private func step(_ link: CADisplayLink) { + let now = link.targetTimestamp + let elapsed = lastFrameTimestamp.map { now - $0 } ?? (link.targetTimestamp - link.timestamp) + lastFrameTimestamp = now + model.advance(by: min(max(elapsed, 0), 1.0 / 30.0)) + render() + finishIfSettled() + } + + private func finishIfSettled() { + guard model.isSettled else { return } + model.snapToTarget() + render() + stopDisplayLink() + guard model.target == 0, isClosing, let completion = closeCompletion else { return } + closeCompletion = nil + completion() + } + + private func render() { + morphView.apply(model: model, metrics: metrics) + } + + // MARK: - System panel coordination + + static func systemPanelDetector(over anchor: CGRect) -> NotchSystemPanelDetector { + NotchSystemPanelDetector( + anchor: CGRect(x: anchor.minX, y: (NSScreen.screens.first?.frame.maxY ?? 0) - anchor.maxY, + width: anchor.width, height: anchor.height) + ) + } + + func watchForSystemPanel(_ detector: NotchSystemPanelDetector, + onPresentation: @escaping @MainActor () -> Void) { + // Spotlight can take keyboard input without sending this panel a key-window + // notification. Check only while the panel is on screen, off the UI thread. + let timer = DispatchSource.makeTimerSource(queue: .global(qos: .utility)) + timer.schedule(deadline: .now() + .milliseconds(100), repeating: .milliseconds(100), + leeway: .milliseconds(20)) + timer.setEventHandler { @Sendable [weak self] in + guard detector.isVisible else { return } + Task { @MainActor [weak self] in + guard let self, self.systemPanelMonitor != nil else { return } + self.stopWatchingForSystemPanel() + onPresentation() + } + } + systemPanelMonitor = timer + timer.activate() + } + + private func stopWatchingForSystemPanel() { + systemPanelMonitor?.cancel() + systemPanelMonitor = nil + } +} + +// MARK: - Spring model + +/// Two critically tuned springs: width leads on the way out and height leads on +/// the way back, which produces the "widen, then deepen" feel of the system island. +struct NotchMorphModel { + struct Spring { + var value: Double = 0 + var velocity: Double = 0 + + mutating func step(toward target: Double, response: Double, dampingRatio: Double, dt: Double) { + let stiffness = pow(2 * Double.pi / response, 2) + let damping = 4 * Double.pi * dampingRatio / response + velocity += (-stiffness * (value - target) - damping * velocity) * dt + value += velocity * dt + } + + func isSettled(at target: Double) -> Bool { + abs(value - target) < 0.001 && abs(velocity) < 0.01 + } + } + + private static let substep = 1.0 / 480.0 + + var target: Double = 0 + private(set) var width = Spring() + private(set) var height = Spring() + private(set) var contentOpacity: Double = 0 + + var isSettled: Bool { + width.isSettled(at: target) && height.isSettled(at: target) + && abs(contentOpacity - target) < 0.01 + } + + mutating func snapToTarget() { + width = Spring(value: target) + height = Spring(value: target) + contentOpacity = target + } + + mutating func advance(by elapsed: Double) { + var remaining = elapsed + while remaining > 0 { + let dt = min(Self.substep, remaining) + remaining -= dt + if target > 0.5 { + width.step(toward: target, response: 0.36, dampingRatio: 0.76, dt: dt) + height.step(toward: target, response: 0.46, dampingRatio: 0.82, dt: dt) + } else { + width.step(toward: target, response: 0.34, dampingRatio: 1, dt: dt) + height.step(toward: target, response: 0.27, dampingRatio: 1, dt: dt) + } + // Content follows the surface in, but leaves ahead of it so nothing is + // still legible while the shape folds back into the camera housing. + let opacityTarget = target > 0.5 ? Self.smoothstep(0.42, 0.92, height.value) : 0 + let timeConstant = target > 0.5 ? 0.035 : 0.045 + contentOpacity += (opacityTarget - contentOpacity) * (1 - exp(-dt / timeConstant)) + } + } + + static func smoothstep(_ edge0: Double, _ edge1: Double, _ x: Double) -> Double { + let t = min(max((x - edge0) / (edge1 - edge0), 0), 1) + return t * t * (3 - 2 * t) + } +} + +// MARK: - Geometry + +/// Geometry in window coordinates (origin at the bottom left). The window's top +/// edge is aligned with the top of the expanded surface. +struct NotchMorphMetrics { + /// The housing sits a few points below the top of the screen. + static let housingTopInset: CGFloat = 6 + /// The system draws its own island around the housing and grows it upward + /// (to about 4pt) while the pointer is on it, so the expanded surface rises + /// above that to keep the island inside it in every state. + static let expandedTopInset: CGFloat = 3 + static let contentGap: CGFloat = 4 + /// Space kept between the header capsules and the island on each side. + static let islandClearance: CGFloat = 12 + static let bottomInset: CGFloat = 6 + static let expandedCornerRadius: CGFloat = 26 + /// Room for spring overshoot and the soft drop shadow. + static let margin: CGFloat = 28 + + let anchor: CGRect + let contentSize: CGSize + let housingSize: CGSize + let collapsedSize: CGSize + let expandedSize: CGSize + /// Distance from the window top (the expanded surface top) to the housing top. + let housingOffset: CGFloat + /// Distance from the window top to the top of the hosted content. + let contentTopInset: CGFloat + + init(anchor: CGRect, contentSize: CGSize) { + self.anchor = anchor + self.contentSize = contentSize + let housingInset = min(Self.housingTopInset, anchor.height * 0.2) + let expandedInset = min(Self.expandedTopInset, housingInset) + housingOffset = housingInset - expandedInset + housingSize = CGSize(width: anchor.width, height: max(anchor.height - housingInset, 1)) + // Start one point inside the housing so the first frame is hidden by it. + collapsedSize = CGSize(width: max(housingSize.width - 2, 2), height: max(housingSize.height - 2, 2)) + // The content's header row is centered on the island, beside it. + let islandCenter = housingOffset + housingSize.height / 2 + contentTopInset = max( + islandCenter - (MenuBarPanelLayout.panelTopPadding + MenuBarPanelLayout.headerHeight / 2), 0 + ) + expandedSize = CGSize( + width: max(contentSize.width, housingSize.width), + height: contentTopInset + contentSize.height + Self.bottomInset + ) + } + + var windowFrame: CGRect { + let width = expandedSize.width + Self.margin * 2 + let height = expandedSize.height + Self.margin + let top = anchor.maxY - (anchor.height - housingSize.height) + housingOffset + return CGRect(x: (anchor.midX - width / 2).rounded(), y: (top - height).rounded(), + width: width.rounded(), height: height.rounded()) + } + + var windowSize: CGSize { windowFrame.size } + + + func surfaceRect(for model: NotchMorphModel) -> CGRect { + surfaceRect(widthFraction: model.width.value, heightFraction: model.height.value) + } + + func surfaceRect(expandedFraction fraction: Double) -> CGRect { + surfaceRect(widthFraction: fraction, heightFraction: fraction) + } + + func surfaceRect(widthFraction: Double, heightFraction: Double) -> CGRect { + let size = windowSize + let width = max(Self.lerp(collapsedSize.width, expandedSize.width, widthFraction), 2) + let height = max(Self.lerp(collapsedSize.height, expandedSize.height, heightFraction), 2) + // Rises from inside the housing to the expanded top as the surface deepens. + let collapsedTop = housingOffset + (housingSize.height - collapsedSize.height) / 2 + let topInset = Self.lerp(collapsedTop, 0, min(max(heightFraction, 0), 1)) + return CGRect(x: size.width / 2 - width / 2, y: size.height - topInset - height, + width: width, height: height) + } + + /// Stays a pill while the surface is shallow, then relaxes toward the + /// expanded radius as it deepens, so the corners change continuously. + func cornerRadius(for rect: CGRect, heightFraction: Double) -> CGFloat { + let pill = min(rect.height, rect.width) / 2 + let settle = NotchMorphModel.smoothstep(0.12, 1, heightFraction) + return min(Self.lerp(pill, Self.expandedCornerRadius, settle), pill) + } + + func screenRect(fromSurfaceRect rect: CGRect) -> CGRect { + rect.offsetBy(dx: windowFrame.minX, dy: windowFrame.minY) + } + + static func lerp(_ from: CGFloat, _ to: CGFloat, _ fraction: Double) -> CGFloat { + from + (to - from) * CGFloat(fraction) + } +} + +enum NotchSurfacePath { + /// A rounded rectangle whose corners ease into the straight edges + /// (continuous curvature) when there is room, and become exact circular + /// arcs as the shape approaches a pill, so morphing never changes the + /// path structure. + static func make(in rect: CGRect, radius requestedRadius: CGFloat) -> CGPath { + let limit = min(rect.width, rect.height) / 2 + let radius = max(min(requestedRadius, limit), 0) + let path = CGMutablePath() + guard radius > 0 else { + path.addRect(rect) + return path + } + + let smoothing = min(max((limit / radius - 1) / 0.4, 0), 1) + let extent = radius * (1 + 0.4 * smoothing) + let handle = extent * (0.5523 + (0.8 - 0.5523) * smoothing) + let minX = rect.minX, maxX = rect.maxX, minY = rect.minY, maxY = rect.maxY + + path.move(to: CGPoint(x: minX + extent, y: maxY)) + path.addLine(to: CGPoint(x: maxX - extent, y: maxY)) + path.addCurve(to: CGPoint(x: maxX, y: maxY - extent), + control1: CGPoint(x: maxX - extent + handle, y: maxY), + control2: CGPoint(x: maxX, y: maxY - extent + handle)) + path.addLine(to: CGPoint(x: maxX, y: minY + extent)) + path.addCurve(to: CGPoint(x: maxX - extent, y: minY), + control1: CGPoint(x: maxX, y: minY + extent - handle), + control2: CGPoint(x: maxX - extent + handle, y: minY)) + path.addLine(to: CGPoint(x: minX + extent, y: minY)) + path.addCurve(to: CGPoint(x: minX, y: minY + extent), + control1: CGPoint(x: minX + extent - handle, y: minY), + control2: CGPoint(x: minX, y: minY + extent - handle)) + path.addLine(to: CGPoint(x: minX, y: maxY - extent)) + path.addCurve(to: CGPoint(x: minX + extent, y: maxY), + control1: CGPoint(x: minX, y: maxY - extent + handle), + control2: CGPoint(x: minX + extent - handle, y: maxY)) + path.closeSubpath() + return path + } +} + +// MARK: - Views + +/// Root view: a shadow behind a black, shape-masked surface that hosts the content. +@MainActor +final class NotchMorphView: NSView { + private static let contentLift: CGFloat = 10 + + private let shadowView = NSView() + private let surfaceView = NSView() + private let surfaceMask = CAShapeLayer() + private weak var content: NSView? + private var surfacePath: CGPath? + + init(content: NSView) { + self.content = content + super.init(frame: .zero) + wantsLayer = true + layer?.masksToBounds = false + + shadowView.wantsLayer = true + shadowView.layer?.shadowColor = NSColor.black.cgColor + shadowView.layer?.shadowRadius = 16 + shadowView.layer?.shadowOffset = CGSize(width: 0, height: -6) + shadowView.layer?.shadowOpacity = 0 + shadowView.layer?.masksToBounds = false + addSubview(shadowView) + + surfaceView.wantsLayer = true + surfaceView.layer?.backgroundColor = NSColor.black.cgColor + surfaceView.layer?.mask = surfaceMask + addSubview(surfaceView) + + content.wantsLayer = true + content.autoresizingMask = [] + content.alphaValue = 0 + surfaceView.addSubview(content) + } + + @available(*, unavailable) + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + override var isOpaque: Bool { false } + + /// Clicks outside the visible surface must not land on hidden content. + override func hitTest(_ point: NSPoint) -> NSView? { + let local = convert(point, from: superview) + guard let surfacePath, surfacePath.contains(local) else { return nil } + return super.hitTest(point) + } + + func releaseContent() { + content?.removeFromSuperview() + content = nil + } + + func apply(model: NotchMorphModel, metrics: NotchMorphMetrics) { + let rect = metrics.surfaceRect(for: model) + let radius = metrics.cornerRadius(for: rect, heightFraction: model.height.value) + let path = NotchSurfacePath.make(in: rect, radius: radius) + surfacePath = path + + CATransaction.begin() + CATransaction.setDisableActions(true) + shadowView.frame = bounds + surfaceView.frame = bounds + surfaceMask.frame = surfaceView.bounds + surfaceMask.path = path + shadowView.layer?.shadowPath = path + let reveal = NotchMorphModel.smoothstep(0.2, 1, model.height.value) + shadowView.layer?.shadowOpacity = Float(0.38 * reveal) + + if let content { + let size = metrics.contentSize + let lift = Self.contentLift * CGFloat(1 - min(max(model.height.value, 0), 1)) + let top = bounds.height - metrics.contentTopInset + lift + let origin = CGPoint(x: ((bounds.width - size.width) / 2).rounded(), y: (top - size.height).rounded()) + if content.frame.size != size { + content.frame = CGRect(origin: origin, size: size) + } else if content.frame.origin != origin { + content.setFrameOrigin(origin) + } + content.alphaValue = CGFloat(min(max(model.contentOpacity, 0), 1)) + } + CATransaction.commit() + } +} + +@MainActor +private final class NotchDisplayLinkTarget: NSObject { + var onFrame: ((CADisplayLink) -> Void)? + + @objc func step(_ link: CADisplayLink) { + onFrame?(link) + } +} + +struct NotchSystemPanelDetector: Sendable { + let anchor: CGRect + + var isVisible: Bool { + guard let windows = CGWindowListCopyWindowInfo(.optionOnScreenOnly, kCGNullWindowID) + as? [[String: Any]] else { return false } + return windows.contains { info in + guard let owner = info[kCGWindowOwnerName as String] as? String, + owner == "Siri" || owner == "Spotlight" || owner == "Siri AI", + (info[kCGWindowAlpha as String] as? Double ?? 1) > 0, + let pid = info[kCGWindowOwnerPID as String] as? pid_t, + let app = NSRunningApplication(processIdentifier: pid), + let path = app.bundleURL?.path, + path.hasPrefix("/System/Library/") || path.hasPrefix("/System/Applications/"), + let bounds = info[kCGWindowBounds as String] as? [String: Double], + let x = bounds["X"], let y = bounds["Y"], + let width = bounds["Width"], let height = bounds["Height"], + height > max(anchor.height, 64), width >= 260 else { return false } + return CGRect(x: x, y: y, width: width, height: height).intersects(anchor) + } + } +} diff --git a/changes/unreleased/notch-hover-island-trigger.md b/changes/unreleased/notch-hover-island-trigger.md new file mode 100644 index 000000000..5ddfe9fae --- /dev/null +++ b/changes/unreleased/notch-hover-island-trigger.md @@ -0,0 +1,6 @@ +--- +release: plugin +type: changed +--- + +The Dynamic Island Hover Panel now opens only when the pointer is over the island. Trigger Width and Lower Trigger Reach can still widen the area. diff --git a/changes/unreleased/notch-panel-morph.md b/changes/unreleased/notch-panel-morph.md new file mode 100644 index 000000000..7613d1830 --- /dev/null +++ b/changes/unreleased/notch-panel-morph.md @@ -0,0 +1,6 @@ +--- +release: app +type: changed +--- + +The notch panel grows out of the camera island and folds back into it, with its tabs and actions beside the island. It respects Reduce Motion. diff --git a/docs/plugins/notch-hover-panel.md b/docs/plugins/notch-hover-panel.md index 27d509641..6b7e6f35f 100644 --- a/docs/plugins/notch-hover-panel.md +++ b/docs/plugins/notch-hover-panel.md @@ -1,10 +1,10 @@ # Dynamic Island Hover Panel -`Plugins/NotchHoverPanel/` presents the regular MacTools menu-bar panel when the pointer rests in the blank menu-bar space immediately beside the Dynamic Island, or moves upward from directly below it toward the Dynamic Island. The plugin owns only hover detection, delays, and visibility ownership; the host owns panel content, sizing, positioning, and animation. +`Plugins/NotchHoverPanel/` opens the regular MacTools menu-bar panel when the pointer rests over the Dynamic Island. The panel expands from the notch and contracts back into it when it closes. The plugin handles hover detection, delays, and which presentation it owns. The host handles panel content, positioning, and animation. -The side triggers use the screen's auxiliary top-left and top-right areas, so they remain limited to the menu-bar band and do not react to the rest of the menu bar. A third trigger spans the Dynamic Island width and extends below it by the configured vertical reach, which makes an upward approach from the content area reveal the panel. Mirrored secondary displays are ignored to avoid duplicate triggers. The panel is shown below the Dynamic Island and stays open while the pointer is inside the panel or the short corridor between the Dynamic Island and panel. It hides after the configured delay once the pointer leaves both regions. +The default trigger matches the Dynamic Island. The side-reach setting extends the trigger into the adjacent menu-bar areas. When enabled, the lower trigger extends below the island by the configured lower reach. The panel stays open while the pointer is over the island or inside the panel. It hides after the configured delay once the pointer leaves both. Mirrored secondary displays are ignored. -Settings include enablement, menu-bar icon visibility, trigger width, lower trigger enablement, lower trigger reach, show delay, and hide delay. Defaults are enabled, visible MacTools menu-bar icon, `52 pt` trigger width, lower trigger enabled, `72 pt` lower reach, `0.18 s` show delay, and `0.28 s` hide delay. Users can hide the icon explicitly; saved visibility preferences remain unchanged on upgrade. A reset action restores those defaults. Preferences are stored locally under `notch-hover.*` keys. The plugin requests no permissions and makes no network requests. +By default the plugin and menu-bar icon are enabled, side reach and lower reach are both `0 pt`, the lower trigger is enabled, the show delay is `0.18 s`, and the hide delay is `0.28 s`. Existing preferences are preserved on upgrade. A reset restores the defaults. Preferences are stored locally under `notch-hover.*` keys. The plugin requests no permissions and makes no network requests. Hiding the menu-bar icon only takes effect while the plugin is enabled and a display can host the hover trigger. Disabling, isolating, or removing the plugin restores the icon, and display hot-plugging also restores it when the last Dynamic Island-capable screen disconnects. Menu-bar-anchored panels fall back to a top-right screen anchor while the icon is hidden. Users can still reach the panel and settings by hovering the Dynamic Island. @@ -12,13 +12,10 @@ The plugin uses the host's anchored menu-bar panel presentation API, so its pack ## Build and Verification -Run `make generate`, then: +Run the targeted tests. ```sh -make build-plugin PLUGIN=NotchHoverPanel -xcodebuild -project MacTools.xcodeproj -scheme MacTools -configuration Debug \ - -derivedDataPath build/DerivedData test -quiet \ - -only-testing:MacToolsTests/NotchHoverPanelGeometryTests +make test TEST_FILTER="NotchHoverPanelGeometryTests NotchHoverPanelControllerTests MenuBarPanelMenuPresenterTests" ``` -Manual checks require a Mac display with a Dynamic Island: hover each side of it and confirm the panel slides out, move upward from directly below it and confirm it also appears, move into the panel and confirm it stays open, leave the panel and Dynamic Island area and confirm it hides after the delay, then adjust each slider and verify the change persists after relaunch. Also verify that opening a panel from the status item is not dismissed by the plugin. +On a Mac display with a Dynamic Island, hover over the notch to open the panel. Move into the panel and check that it stays open, then move away to close it. Re-enter while it is closing and check that it reopens smoothly. With the default reach, hovering beside the notch or below it should leave the panel closed. Increase side and lower reach to check both optional trigger areas, then disable the lower trigger and check that direct hover still works. Open the panel from the status item and check that leaving the notch area does not close it. From 795f9983e0f66ad16577b7cdd23f94a40ad4a546 Mon Sep 17 00:00:00 2001 From: Niko Eltarenko <61957857+nikoelt@users.noreply.github.com> Date: Sun, 15 Nov 2026 16:34:55 +1000 Subject: [PATCH 02/29] fix(notch-hover-panel): fit both header groups around wide notches --- .../Tests/NotchHoverPanelGeometryTests.swift | 14 ++++++++++++++ Sources/App/MenuBarPanelPresenter.swift | 8 ++++---- Sources/App/NotchMenuBarPanel.swift | 10 +++++++--- Tests/App/NotchMenuBarPanelTests.swift | 10 ++++++++++ changes/unreleased/notch-panel-morph.md | 2 +- 5 files changed, 36 insertions(+), 8 deletions(-) create mode 100644 Tests/App/NotchMenuBarPanelTests.swift diff --git a/Plugins/NotchHoverPanel/Tests/NotchHoverPanelGeometryTests.swift b/Plugins/NotchHoverPanel/Tests/NotchHoverPanelGeometryTests.swift index 3c4e94ae6..283b26fef 100644 --- a/Plugins/NotchHoverPanel/Tests/NotchHoverPanelGeometryTests.swift +++ b/Plugins/NotchHoverPanel/Tests/NotchHoverPanelGeometryTests.swift @@ -7,6 +7,20 @@ final class NotchHoverPanelGeometryTests: XCTestCase { private let leftArea = CGRect(x: 0, y: 950, width: 620, height: 32) private let rightArea = CGRect(x: 892, y: 950, width: 620, height: 32) + func testDisplayWithoutCameraHousingHasNoHoverTrigger() { + let screen = NotchHoverScreenSnapshot( + displayID: 1, + frame: screenFrame, + auxiliaryTopLeftArea: nil, + auxiliaryTopRightArea: nil, + isBuiltin: true, + isMain: true, + isInMirrorSet: false + ) + + XCTAssertNil(NotchHoverGeometry.display(for: screen, triggerWidth: 52, verticalTriggerReach: 72)) + } + func testDefaultTriggerIsOnlyTheIsland() throws { let display = try XCTUnwrap(makeDisplay( triggerWidth: NotchHoverGeometry.defaultTriggerWidth, diff --git a/Sources/App/MenuBarPanelPresenter.swift b/Sources/App/MenuBarPanelPresenter.swift index 8b17daf36..e72e2bbb8 100644 --- a/Sources/App/MenuBarPanelPresenter.swift +++ b/Sources/App/MenuBarPanelPresenter.swift @@ -572,10 +572,10 @@ final class MenuBarPanelPresenter: NSObject { panelModel.setNotchHeader(besideIsland: false, topOffset: 0) return } - let tabsWidth = MenuBarPanelTabLayout.contentWidth(count: pluginHost.visibleMenuBarPanels.count) - let besideIsland = !panelModel.isEditingLayout && notchPanel.headerFitsBesideIsland( - leadingWidth: MenuBarPanelLayout.notchHeaderHorizontalPadding + tabsWidth, - panelWidth: panelModel.contentWidth + let besideIsland = !panelModel.isEditingLayout && NotchMenuBarPanel.headerFitsBesideIsland( + tabCount: pluginHost.visibleMenuBarPanels.count, + panelWidth: panelModel.contentWidth, + notchWidth: notchPanel.anchor.width ) panelModel.setNotchHeader( besideIsland: besideIsland, diff --git a/Sources/App/NotchMenuBarPanel.swift b/Sources/App/NotchMenuBarPanel.swift index 2a3d5fa08..e5d55d9e9 100644 --- a/Sources/App/NotchMenuBarPanel.swift +++ b/Sources/App/NotchMenuBarPanel.swift @@ -127,9 +127,13 @@ final class NotchMenuBarPanel { return metrics.screenRect(fromSurfaceRect: rect) } - /// Whether a leading header group of `leadingWidth` stays clear of the island. - func headerFitsBesideIsland(leadingWidth: CGFloat, panelWidth: CGFloat) -> Bool { - leadingWidth <= panelWidth / 2 - anchor.width / 2 - NotchMorphMetrics.islandClearance + /// Both header groups must fit in the space beside the camera housing. + static func headerFitsBesideIsland(tabCount: Int, panelWidth: CGFloat, notchWidth: CGFloat) -> Bool { + let tabsWidth = MenuBarPanelTabLayout.contentWidth(count: tabCount) + let actionsWidth = MenuBarPanelTabLayout.contentWidth(count: 2, width: MenuBarPanelLayout.headerAccessoryWidth) + let requiredWidth = max(tabsWidth, actionsWidth) + MenuBarPanelLayout.notchHeaderHorizontalPadding + let availableWidth = (panelWidth - notchWidth) / 2 - NotchMorphMetrics.islandClearance + return requiredWidth <= availableWidth } /// Extra top inset that moves the header from the island's row to just below it. diff --git a/Tests/App/NotchMenuBarPanelTests.swift b/Tests/App/NotchMenuBarPanelTests.swift new file mode 100644 index 000000000..39b6c3a71 --- /dev/null +++ b/Tests/App/NotchMenuBarPanelTests.swift @@ -0,0 +1,10 @@ +import XCTest +@testable import MacTools + +@MainActor +final class NotchMenuBarPanelTests: XCTestCase { + func testWideNotchNeedsRoomForActionsEvenWithOneTab() { + XCTAssertFalse(NotchMenuBarPanel.headerFitsBesideIsland(tabCount: 1, panelWidth: 316, notchWidth: 180)) + XCTAssertTrue(NotchMenuBarPanel.headerFitsBesideIsland(tabCount: 1, panelWidth: 350, notchWidth: 180)) + } +} diff --git a/changes/unreleased/notch-panel-morph.md b/changes/unreleased/notch-panel-morph.md index 7613d1830..24f690a25 100644 --- a/changes/unreleased/notch-panel-morph.md +++ b/changes/unreleased/notch-panel-morph.md @@ -3,4 +3,4 @@ release: app type: changed --- -The notch panel grows out of the camera island and folds back into it, with its tabs and actions beside the island. It respects Reduce Motion. +The notch panel morphs in and out, placing controls beside or below the camera housing as space allows. It respects Reduce Motion. From fcce34e77d832ba68dfcebb72ffd4c15d8725b72 Mon Sep 17 00:00:00 2001 From: Niko Eltarenko <61957857+nikoelt@users.noreply.github.com> Date: Sun, 15 Nov 2026 16:45:33 +1000 Subject: [PATCH 03/29] fix(notch-hover-panel): flank wide camera cutouts and meet the display edge --- Sources/App/MenuBarPanelPresenter.swift | 10 +++++++--- Sources/App/NotchMenuBarPanel.swift | 23 +++++++++++++++-------- Tests/App/NotchMenuBarPanelTests.swift | 24 ++++++++++++++++++++++++ 3 files changed, 46 insertions(+), 11 deletions(-) diff --git a/Sources/App/MenuBarPanelPresenter.swift b/Sources/App/MenuBarPanelPresenter.swift index e72e2bbb8..28ad76cd9 100644 --- a/Sources/App/MenuBarPanelPresenter.swift +++ b/Sources/App/MenuBarPanelPresenter.swift @@ -1072,9 +1072,13 @@ final class MenuBarPanelPresenter: NSObject { screen: NSScreen? ) -> MenuBarPanelHeightResolution { let maximumWidth = MenuBarPanelWidth.maximum(visibleFrameWidth: screen?.visibleFrame.width) - panelModel.updateWidth(MenuBarPanelWidth.resolved( - preferred: pluginHost.preferredMenuBarPanelWidth, maximum: maximumWidth), - maximum: maximumWidth) + let preferredWidth = MenuBarPanelWidth.resolved( + preferred: pluginHost.preferredMenuBarPanelWidth, maximum: maximumWidth) + let widthForNotchHeader = notchPanel.map { + NotchMenuBarPanel.minimumWidthForHeaderBesideIsland( + tabCount: pluginHost.visibleMenuBarPanels.count, notchWidth: $0.anchor.width) + } ?? 0 + panelModel.updateWidth(min(maximumWidth, max(preferredWidth, widthForNotchHeader)), maximum: maximumWidth) let surfaceWidth = panelModel.contentWidth - MenuBarPanelLayout.outerPadding * 2 let maximumFeatureListHeight = MenuBarPanelLayout.maximumFeatureListHeight(for: screen) let components = pluginHost.componentItems(in: tab.id) diff --git a/Sources/App/NotchMenuBarPanel.swift b/Sources/App/NotchMenuBarPanel.swift index e5d55d9e9..1fa7bcc9d 100644 --- a/Sources/App/NotchMenuBarPanel.swift +++ b/Sources/App/NotchMenuBarPanel.swift @@ -129,11 +129,15 @@ final class NotchMenuBarPanel { /// Both header groups must fit in the space beside the camera housing. static func headerFitsBesideIsland(tabCount: Int, panelWidth: CGFloat, notchWidth: CGFloat) -> Bool { + panelWidth >= minimumWidthForHeaderBesideIsland(tabCount: tabCount, notchWidth: notchWidth) + } + + static func minimumWidthForHeaderBesideIsland(tabCount: Int, notchWidth: CGFloat) -> CGFloat { let tabsWidth = MenuBarPanelTabLayout.contentWidth(count: tabCount) let actionsWidth = MenuBarPanelTabLayout.contentWidth(count: 2, width: MenuBarPanelLayout.headerAccessoryWidth) - let requiredWidth = max(tabsWidth, actionsWidth) + MenuBarPanelLayout.notchHeaderHorizontalPadding - let availableWidth = (panelWidth - notchWidth) / 2 - NotchMorphMetrics.islandClearance - return requiredWidth <= availableWidth + let sideWidth = max(tabsWidth, actionsWidth) + MenuBarPanelLayout.notchHeaderHorizontalPadding + + NotchMorphMetrics.islandClearance + return (notchWidth + sideWidth * 2).rounded(.up) } /// Extra top inset that moves the header from the island's row to just below it. @@ -305,7 +309,7 @@ struct NotchMorphModel { /// Geometry in window coordinates (origin at the bottom left). The window's top /// edge is aligned with the top of the expanded surface. struct NotchMorphMetrics { - /// The housing sits a few points below the top of the screen. + /// The compact island sits a few points below the top of the screen. static let housingTopInset: CGFloat = 6 /// The system draws its own island around the housing and grows it upward /// (to about 4pt) while the pointer is on it, so the expanded surface rises @@ -332,7 +336,10 @@ struct NotchMorphMetrics { init(anchor: CGRect, contentSize: CGSize) { self.anchor = anchor self.contentSize = contentSize - let housingInset = min(Self.housingTopInset, anchor.height * 0.2) + // AppKit reports the housing rectangle. A wide camera cutout reaches the + // display edge, while the compact island has space above it. + let isWideCameraCutout = anchor.width >= anchor.height * 3 + let housingInset = isWideCameraCutout ? 0 : min(Self.housingTopInset, anchor.height * 0.2) let expandedInset = min(Self.expandedTopInset, housingInset) housingOffset = housingInset - expandedInset housingSize = CGSize(width: anchor.width, height: max(anchor.height - housingInset, 1)) @@ -351,10 +358,10 @@ struct NotchMorphMetrics { var windowFrame: CGRect { let width = expandedSize.width + Self.margin * 2 - let height = expandedSize.height + Self.margin + let height = (expandedSize.height + Self.margin).rounded() let top = anchor.maxY - (anchor.height - housingSize.height) + housingOffset - return CGRect(x: (anchor.midX - width / 2).rounded(), y: (top - height).rounded(), - width: width.rounded(), height: height.rounded()) + return CGRect(x: (anchor.midX - width / 2).rounded(), y: top - height, + width: width.rounded(), height: height) } var windowSize: CGSize { windowFrame.size } diff --git a/Tests/App/NotchMenuBarPanelTests.swift b/Tests/App/NotchMenuBarPanelTests.swift index 39b6c3a71..af31fe710 100644 --- a/Tests/App/NotchMenuBarPanelTests.swift +++ b/Tests/App/NotchMenuBarPanelTests.swift @@ -1,3 +1,4 @@ +import CoreGraphics import XCTest @testable import MacTools @@ -7,4 +8,27 @@ final class NotchMenuBarPanelTests: XCTestCase { XCTAssertFalse(NotchMenuBarPanel.headerFitsBesideIsland(tabCount: 1, panelWidth: 316, notchWidth: 180)) XCTAssertTrue(NotchMenuBarPanel.headerFitsBesideIsland(tabCount: 1, panelWidth: 350, notchWidth: 180)) } + + func testHeaderWidthFitsGroupsBesideOlderMacBookProNotch() { + let width = NotchMenuBarPanel.minimumWidthForHeaderBesideIsland(tabCount: 2, notchWidth: 185) + + XCTAssertGreaterThan(width, MenuBarPanelLayout.baseWidth) + XCTAssertTrue(NotchMenuBarPanel.headerFitsBesideIsland(tabCount: 2, panelWidth: width, notchWidth: 185)) + } + + func testWideCameraCutoutPanelReachesDisplayTop() { + let anchor = CGRect(x: 663.5, y: 950, width: 185, height: 32) + let metrics = NotchMorphMetrics(anchor: anchor, contentSize: CGSize(width: 349, height: 114.5)) + let expandedSurface = metrics.screenRect(fromSurfaceRect: metrics.surfaceRect(expandedFraction: 1)) + + XCTAssertEqual(expandedSurface.maxY, anchor.maxY) + } + + func testCompactIslandKeepsAnInsetFromDisplayTop() { + let anchor = CGRect(x: 838.5, y: 1093, width: 59, height: 40) + let metrics = NotchMorphMetrics(anchor: anchor, contentSize: CGSize(width: 316, height: 114)) + let expandedSurface = metrics.screenRect(fromSurfaceRect: metrics.surfaceRect(expandedFraction: 1)) + + XCTAssertLessThan(expandedSurface.maxY, anchor.maxY) + } } From 246a9cd3851181ddc338f58a0f0787783ac1e441 Mon Sep 17 00:00:00 2001 From: Niko Eltarenko <61957857+nikoelt@users.noreply.github.com> Date: Sun, 15 Nov 2026 16:58:03 +1000 Subject: [PATCH 04/29] feat(notch-hover-panel): offer dynamic island and classic panel styles --- Configs/MacTools-Info.plist | 2 + .../Resources/Localizable.xcstrings | 255 +++++++++++++++++- .../Sources/NotchHoverPanelController.swift | 10 + .../Sources/NotchHoverPanelPlugin.swift | 39 ++- .../NotchHoverPanelControllerTests.swift | 36 +++ Plugins/NotchHoverPanel/project.yml | 3 + Sources/App/MenuBarPanelPresenter.swift | 101 ++++++- Sources/App/MenuBarStatusItemController.swift | 8 +- .../Dynamic/DynamicPluginManager.swift | 4 + .../Plugins/Dynamic/PluginPackageStore.swift | 6 +- Sources/Core/Plugins/PluginHost.swift | 6 +- .../PluginSupport/NotchHoverPanelStyle.swift | 15 ++ .../unreleased/notch-hover-island-trigger.md | 2 +- docs/plugins/notch-hover-panel.md | 2 +- 14 files changed, 459 insertions(+), 30 deletions(-) create mode 100644 Plugins/NotchHoverPanel/project.yml create mode 100644 Sources/PluginSupport/NotchHoverPanelStyle.swift diff --git a/Configs/MacTools-Info.plist b/Configs/MacTools-Info.plist index e5e847a5f..d2afe7f5c 100644 --- a/Configs/MacTools-Info.plist +++ b/Configs/MacTools-Info.plist @@ -58,6 +58,8 @@ $(PLUGIN_CATALOG_URL) MTApplicationSupportDirectoryName $(APPLICATION_SUPPORT_DIRECTORY_NAME) + MTSupportsNotchHoverPanelStyles + MTReleaseChannel $(MACTOOLS_RELEASE_CHANNEL) MTRightClickConfigurationHomeRelativePath diff --git a/Plugins/NotchHoverPanel/Resources/Localizable.xcstrings b/Plugins/NotchHoverPanel/Resources/Localizable.xcstrings index d20c8c944..352306e91 100644 --- a/Plugins/NotchHoverPanel/Resources/Localizable.xcstrings +++ b/Plugins/NotchHoverPanel/Resources/Localizable.xcstrings @@ -1310,79 +1310,310 @@ } } }, + "settings.style.title": { + "extractionState": "manual", + "localizations": { + "ar": { + "stringUnit": { + "state": "translated", + "value": "نمط اللوحة" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Panelstil" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Panel style" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Estilo del panel" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Style du panneau" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "パネルのスタイル" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "패널 스타일" + } + }, + "pt": { + "stringUnit": { + "state": "translated", + "value": "Estilo do painel" + } + }, + "ru": { + "stringUnit": { + "state": "translated", + "value": "Стиль панели" + } + }, + "tr": { + "stringUnit": { + "state": "translated", + "value": "Panel stili" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "面板样式" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "面板樣式" + } + } + } + }, + "settings.style.morph": { + "extractionState": "manual", + "localizations": { + "ar": { + "stringUnit": { + "state": "translated", + "value": "Dynamic Island" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Dynamic Island" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Dynamic Island" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Dynamic Island" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Dynamic Island" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "Dynamic Island" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "Dynamic Island" + } + }, + "pt": { + "stringUnit": { + "state": "translated", + "value": "Dynamic Island" + } + }, + "ru": { + "stringUnit": { + "state": "translated", + "value": "Dynamic Island" + } + }, + "tr": { + "stringUnit": { + "state": "translated", + "value": "Dynamic Island" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "灵动岛" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "靈動島" + } + } + } + }, + "settings.style.classic": { + "extractionState": "manual", + "localizations": { + "ar": { + "stringUnit": { + "state": "translated", + "value": "كلاسيكي" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Klassisch" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Classic" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Clásico" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Classique" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "クラシック" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "클래식" + } + }, + "pt": { + "stringUnit": { + "state": "translated", + "value": "Clássico" + } + }, + "ru": { + "stringUnit": { + "state": "translated", + "value": "Классический" + } + }, + "tr": { + "stringUnit": { + "state": "translated", + "value": "Klasik" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "经典" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "經典" + } + } + } + }, "settings.reset.description": { "extractionState": "manual", "localizations": { "ar": { "stringUnit": { "state": "translated", - "value": "يستعيد نطاقات التشغيل والتشغيل السفلي والتأخيرات وإعداد رمز شريط القوائم إلى قيمها الأولية." + "value": "استعادة الإعدادات الافتراضية للوحة التحويم." } }, "de": { "stringUnit": { "state": "translated", - "value": "Stellt Auslösebereiche, die untere Auslösung, Verzögerungen und die Einstellung für das Menüleistensymbol auf die Anfangswerte zurück." + "value": "Die Standardeinstellungen des Hover-Panels wiederherstellen." } }, "en": { "stringUnit": { "state": "translated", - "value": "Restore trigger ranges, the lower trigger, delays, and the menu-bar icon setting to their initial values." + "value": "Restore the default hover panel settings." } }, "es": { "stringUnit": { "state": "translated", - "value": "Restaura los rangos de activación, la activación inferior, los retrasos y el ajuste del icono de la barra de menús." + "value": "Restaura los ajustes predeterminados del panel." } }, "fr": { "stringUnit": { "state": "translated", - "value": "Rétablit les zones de déclenchement, le déclenchement inférieur, les délais et le réglage de l’icône de la barre des menus." + "value": "Rétablissez les réglages par défaut du panneau de survol." } }, "ja": { "stringUnit": { "state": "translated", - "value": "トリガー範囲、下側トリガー、遅延、メニューバーアイコンの設定を初期状態に戻します。" + "value": "ホバーパネルの設定を初期状態に戻します。" } }, "ko": { "stringUnit": { "state": "translated", - "value": "트리거 범위, 아래쪽 트리거, 지연 시간 및 메뉴 막대 아이콘 설정을 초기 상태로 되돌립니다." + "value": "호버 패널의 기본 설정을 복원합니다." } }, "pt": { "stringUnit": { "state": "translated", - "value": "Restaura os intervalos de ativação, a ativação inferior, os atrasos e o ajuste do ícone da barra de menus." + "value": "Restaure os ajustes padrão do painel ao passar o ponteiro." } }, "ru": { "stringUnit": { "state": "translated", - "value": "Возвращает диапазоны срабатывания, нижнее срабатывание, задержки и настройку значка в строке меню к исходным значениям." + "value": "Восстановите настройки панели наведения по умолчанию." } }, "tr": { "stringUnit": { "state": "translated", - "value": "Tetikleme aralıklarını, alt tetiklemeyi, gecikmeleri ve menü çubuğu simgesi ayarını ilk değerlerine döndürür." + "value": "Üzerine gelme panelinin varsayılan ayarlarını geri yükleyin." } }, "zh-Hans": { "stringUnit": { "state": "translated", - "value": "将触发范围、下方触发、显示延迟和菜单栏图标恢复为初始状态。" + "value": "恢复悬浮面板的默认设置。" } }, "zh-Hant": { "stringUnit": { "state": "translated", - "value": "將觸發範圍、下方觸發、顯示延遲和選單列圖示恢復為初始狀態。" + "value": "恢復懸浮面板的預設設定。" } } } diff --git a/Plugins/NotchHoverPanel/Sources/NotchHoverPanelController.swift b/Plugins/NotchHoverPanel/Sources/NotchHoverPanelController.swift index 15624c56c..83a9a9d9e 100644 --- a/Plugins/NotchHoverPanel/Sources/NotchHoverPanelController.swift +++ b/Plugins/NotchHoverPanel/Sources/NotchHoverPanelController.swift @@ -6,6 +6,7 @@ struct NotchHoverPanelSnapshot: Equatable, Sendable { let isEnabled: Bool let hasSupportedDisplay: Bool let showsMenuBarIcon: Bool + let panelStyle: NotchHoverPanelStyle let isBelowTriggerEnabled: Bool let triggerWidth: Double let verticalTriggerReach: Double @@ -25,6 +26,7 @@ protocol NotchHoverPanelControlling: AnyObject, PluginMenuBarPanelPresenting, func refresh() func setEnabled(_ isEnabled: Bool) func setShowsMenuBarIcon(_ showsMenuBarIcon: Bool) + func setPanelStyle(_ style: NotchHoverPanelStyle) func setEnableBelowTrigger(_ enabled: Bool) func setTriggerWidth(_ width: Double) func setVerticalTriggerReach(_ reach: Double) @@ -171,6 +173,7 @@ final class NotchHoverPanelController: NotchHoverPanelControlling { isEnabled: isEnabled, hasSupportedDisplay: !displays.isEmpty, showsMenuBarIcon: showsMenuBarIcon, + panelStyle: NotchHoverPanelStyle.stored(in: storage), isBelowTriggerEnabled: enableBelowTrigger, triggerWidth: triggerWidth, verticalTriggerReach: verticalTriggerReach, @@ -258,6 +261,12 @@ final class NotchHoverPanelController: NotchHoverPanelControlling { onStateChange?() } + func setPanelStyle(_ style: NotchHoverPanelStyle) { + guard style != NotchHoverPanelStyle.stored(in: storage) else { return } + storage.set(style.rawValue, forKey: NotchHoverPanelStyle.storageKey) + onStateChange?() + } + func setTriggerWidth(_ width: Double) { let clamped = Self.clampedTriggerWidth(width) guard triggerWidth != clamped else { return } @@ -303,6 +312,7 @@ final class NotchHoverPanelController: NotchHoverPanelControlling { storage.set(isEnabled, forKey: StorageKey.enabled) storage.set(showsMenuBarIcon, forKey: StorageKey.showsMenuBarIcon) + storage.removeObject(forKey: NotchHoverPanelStyle.storageKey) storage.set(enableBelowTrigger, forKey: StorageKey.enableBelowTrigger) storage.set(Int(triggerWidth.rounded()), forKey: StorageKey.triggerWidth) storage.set(Int(verticalTriggerReach.rounded()), forKey: StorageKey.verticalTriggerReach) diff --git a/Plugins/NotchHoverPanel/Sources/NotchHoverPanelPlugin.swift b/Plugins/NotchHoverPanel/Sources/NotchHoverPanelPlugin.swift index 88687ec46..1ad512845 100644 --- a/Plugins/NotchHoverPanel/Sources/NotchHoverPanelPlugin.swift +++ b/Plugins/NotchHoverPanel/Sources/NotchHoverPanelPlugin.swift @@ -29,6 +29,7 @@ final class NotchHoverPanelPlugin: MacToolsPlugin, PluginMenuBarPanelPresenting, static let section = "hover" static let enabled = "enabled" static let showsMenuBarIcon = "show-menu-bar-icon" + static let panelStyle = "panel-style" static let enableBelowTrigger = "enable-below-trigger" static let triggerWidth = "trigger-width" static let verticalTriggerReach = "vertical-trigger-reach" @@ -40,7 +41,7 @@ final class NotchHoverPanelPlugin: MacToolsPlugin, PluginMenuBarPanelPresenting, var metadata: PluginMetadata { PluginMetadata( - id: "notch-hover-panel", + id: NotchHoverPanelStyle.pluginID, title: localization.string("metadata.title", defaultValue: "灵动岛悬浮面板"), iconName: "rectangle.topthird.inset.filled", iconTint: Color(nsColor: .systemTeal), @@ -85,6 +86,30 @@ final class NotchHoverPanelPlugin: MacToolsPlugin, PluginMenuBarPanelPresenting, systemImage: "rectangle.topthird.inset.filled", control: .toggle(isOn: snapshot.isEnabled) ), + ] + if supportsPanelStyleSelection { + rows.append(PluginSettingsRow( + id: SettingsID.panelStyle, + title: localization.string("settings.style.title", defaultValue: "面板样式"), + systemImage: "rectangle.inset.filled", + isEnabled: snapshot.isEnabled, + control: .picker( + selectionID: snapshot.panelStyle.rawValue, + options: [ + PluginSettingsOption( + id: NotchHoverPanelStyle.morph.rawValue, + title: localization.string("settings.style.morph", defaultValue: "灵动岛") + ), + PluginSettingsOption( + id: NotchHoverPanelStyle.classic.rawValue, + title: localization.string("settings.style.classic", defaultValue: "经典") + ), + ], + style: .menu + ) + )) + } + rows += [ PluginSettingsRow( id: SettingsID.showsMenuBarIcon, title: localization.string( @@ -197,7 +222,7 @@ final class NotchHoverPanelPlugin: MacToolsPlugin, PluginMenuBarPanelPresenting, ), description: localization.string( "settings.reset.description", - defaultValue: "将触发范围、显示延迟和菜单栏图标恢复为初始状态。" + defaultValue: "恢复悬浮面板的默认设置。" ), systemImage: "arrow.counterclockwise", control: .action( @@ -292,14 +317,17 @@ final class NotchHoverPanelPlugin: MacToolsPlugin, PluginMenuBarPanelPresenting, private let controller: any NotchHoverPanelControlling private let localization: PluginLocalization + private let supportsPanelStyleSelection: Bool init( - context: PluginRuntimeContext = PluginRuntimeContext(pluginID: "notch-hover-panel"), + context: PluginRuntimeContext = PluginRuntimeContext(pluginID: NotchHoverPanelStyle.pluginID), controller: (any NotchHoverPanelControlling)? = nil, - localization: PluginLocalization = PluginLocalization(bundle: .main) + localization: PluginLocalization = PluginLocalization(bundle: .main), + supportsPanelStyleSelection: Bool = Bundle.main.object(forInfoDictionaryKey: NotchHoverPanelStyle.hostSupportKey) as? Bool == true ) { self.localization = localization self.controller = controller ?? NotchHoverPanelController(storage: context.storage) + self.supportsPanelStyleSelection = supportsPanelStyleSelection } var rowState: PluginPanelRowState { @@ -344,6 +372,9 @@ final class NotchHoverPanelPlugin: MacToolsPlugin, PluginMenuBarPanelPresenting, controller.setShowsMenuBarIcon(value) case let .setBoolean(controlID, value) where controlID == SettingsID.enableBelowTrigger: controller.setEnableBelowTrigger(value) + case let .setSelection(controlID, optionID) where controlID == SettingsID.panelStyle && supportsPanelStyleSelection: + guard let style = NotchHoverPanelStyle(rawValue: optionID) else { return } + controller.setPanelStyle(style) case let .invoke(controlID) where controlID == SettingsID.reset: controller.resetToDefaults() case let .setNumber(controlID, value, phase) where phase == .committed: diff --git a/Plugins/NotchHoverPanel/Tests/NotchHoverPanelControllerTests.swift b/Plugins/NotchHoverPanel/Tests/NotchHoverPanelControllerTests.swift index e52042521..06ecf09ed 100644 --- a/Plugins/NotchHoverPanel/Tests/NotchHoverPanelControllerTests.swift +++ b/Plugins/NotchHoverPanel/Tests/NotchHoverPanelControllerTests.swift @@ -33,6 +33,34 @@ private final class TestState { @MainActor final class NotchHoverPanelControllerTests: XCTestCase { + func testPanelStylePickerChangesPersistedStyle() throws { + let storage = NotchHoverMemoryStorage() + let controller = makeController(storage: storage) + let plugin = NotchHoverPanelPlugin(controller: controller, supportsPanelStyleSelection: true) + let row = try XCTUnwrap(panelStyleRow(in: plugin)) + guard case let .picker(selectionID, options, _) = row.control else { + return XCTFail("Panel style should use a picker") + } + XCTAssertEqual(selectionID, "morph") + XCTAssertEqual(options.map(\.id), ["morph", "classic"]) + + plugin.handleSettingsAction(.setSelection(controlID: row.id, optionID: "classic")) + XCTAssertEqual(controller.snapshot.panelStyle, .classic) + XCTAssertEqual(makeController(storage: storage).snapshot.panelStyle, .classic) + + plugin.handleSettingsAction(.setSelection(controlID: row.id, optionID: "morph")) + XCTAssertEqual(makeController(storage: storage).snapshot.panelStyle, .morph) + } + + func testPanelStylePickerRequiresHostSupport() { + let controller = makeController(storage: NotchHoverMemoryStorage()) + let plugin = NotchHoverPanelPlugin(controller: controller, supportsPanelStyleSelection: false) + + XCTAssertNil(panelStyleRow(in: plugin)) + plugin.handleSettingsAction(.setSelection(controlID: "panel-style", optionID: "classic")) + XCTAssertEqual(controller.snapshot.panelStyle, .morph) + } + func testMenuBarIconDefaultsToVisibleWithoutOverridingSavedPreferences() { for savedPreference: Bool? in [nil, false, true] { let storage = NotchHoverMemoryStorage() @@ -134,6 +162,7 @@ final class NotchHoverPanelControllerTests: XCTestCase { let storage = NotchHoverMemoryStorage() let controller = makeController(storage: storage) controller.setShowsMenuBarIcon(false) + controller.setPanelStyle(.classic) controller.setEnableBelowTrigger(false) controller.setTriggerWidth(NotchHoverGeometry.allowedTriggerWidthRange.upperBound) controller.setVerticalTriggerReach(NotchHoverGeometry.allowedVerticalTriggerReachRange.upperBound) @@ -143,6 +172,7 @@ final class NotchHoverPanelControllerTests: XCTestCase { controller.resetToDefaults() let snapshot = controller.snapshot + XCTAssertEqual(snapshot.panelStyle, .morph) XCTAssertTrue(snapshot.isEnabled) XCTAssertTrue(snapshot.showsMenuBarIcon) XCTAssertTrue(snapshot.isBelowTriggerEnabled) @@ -294,6 +324,12 @@ final class NotchHoverPanelControllerTests: XCTestCase { private static let triggerPoint = NSPoint(x: 700, y: 960) private static let triggerPointBelowNotch = NSPoint(x: 700, y: 900) + private func panelStyleRow(in plugin: NotchHoverPanelPlugin) -> PluginSettingsRow? { + guard case let .form(sections) = plugin.settingsPage?.body, + case let .rows(rows) = sections.first?.content else { return nil } + return rows.first { $0.id == "panel-style" } + } + private func waitForScheduledWork() { RunLoop.current.run(until: Date().addingTimeInterval(0.15)) } diff --git a/Plugins/NotchHoverPanel/project.yml b/Plugins/NotchHoverPanel/project.yml new file mode 100644 index 000000000..651f0df3b --- /dev/null +++ b/Plugins/NotchHoverPanel/project.yml @@ -0,0 +1,3 @@ +core: + sources: + - ../../Sources/PluginSupport/NotchHoverPanelStyle.swift diff --git a/Sources/App/MenuBarPanelPresenter.swift b/Sources/App/MenuBarPanelPresenter.swift index 28ad76cd9..758dca28e 100644 --- a/Sources/App/MenuBarPanelPresenter.swift +++ b/Sources/App/MenuBarPanelPresenter.swift @@ -299,6 +299,9 @@ final class MenuBarPanelPresenter: NSObject { private var popoverSafeAreaInsets = MenuBarPopoverGeometry.fallbackSafeAreaInsets private var hoverAnchorPanel: NSPanel? private var notchPanel: NotchMenuBarPanel? + private var isClassicHoverPopover = false + private var classicHoverRestingFrame: NSRect? + private var classicHoverDismissGeneration: UInt = 0 init( pluginHost: PluginHost, @@ -498,9 +501,9 @@ final class MenuBarPanelPresenter: NSObject { present(panel, relativeTo: hoverAnchorView(for: anchorRect)) } - /// Presents the regular panel inside a shape anchored to the camera housing. + /// Presents the panel from a plugin-owned screen anchor. @discardableResult - func presentPanelBelowAnchor(panelID: String?, anchorRect: NSRect) -> Bool { + func presentPanelBelowAnchor(panelID: String?, anchorRect: NSRect, style: NotchHoverPanelStyle) -> Bool { guard !anchorRect.isEmpty, anchorRect.width.isFinite, anchorRect.height.isFinite, @@ -512,11 +515,25 @@ final class MenuBarPanelPresenter: NSObject { notchPanel.reopen() return true } + if popover.isShown { + guard isClassicHoverPopover else { return false } + cancelClassicHoverDismissalIfNeeded() + return true + } + + guard let selected = resolvedPanelForAnchor(panelID: panelID) else { return false } + if style == .classic { + present(selected, relativeTo: hoverAnchorView(for: anchorRect), asClassicHover: true) + guard popover.isShown else { + cleanupHoverAnchor() + finishDismissal() + return false + } + return true + } let systemPanel = NotchMenuBarPanel.systemPanelDetector(over: anchorRect) - guard !popover.isShown, !systemPanel.isVisible, - let selected = resolvedPanelForAnchor(panelID: panelID) - else { return false } + guard !systemPanel.isVisible else { return false } selectedPanel = selected popover.contentViewController = nil @@ -543,7 +560,10 @@ final class MenuBarPanelPresenter: NSObject { @discardableResult func dismissPanelBelowAnchor(animated: Bool) -> Bool { guard !panelModel.preventDismissalWhileEditing() else { return false } - guard let notchPanel else { return true } + guard let notchPanel else { + dismissClassicHoverPopover(animated: animated) + return true + } notchPanel.dismiss(animated: animated) { [weak self, weak notchPanel] in guard let self, let notchPanel, self.notchPanel === notchPanel else { return } @@ -563,6 +583,7 @@ final class MenuBarPanelPresenter: NSObject { if notchPanel != nil { dismissPanelBelowAnchor(animated: true) } else { + resetClassicHoverDismissal() popover.performClose(nil) } } @@ -620,7 +641,7 @@ final class MenuBarPanelPresenter: NSObject { present(panel, relativeTo: anchorView) } - private func present(_ panel: PanelKind, relativeTo anchorView: NSView) { + private func present(_ panel: PanelKind, relativeTo anchorView: NSView, asClassicHover: Bool = false) { let action = MenuBarPanelPresentationAction.resolve( isPanelShown: isAnyPanelShown, selectedTab: tab(for: selectedPanel), @@ -640,6 +661,7 @@ final class MenuBarPanelPresenter: NSObject { return } + isClassicHoverPopover = asClassicHover show(popover, relativeTo: anchorView) scheduleHeightRefresh(for: tab(for: panel)) } @@ -674,9 +696,72 @@ final class MenuBarPanelPresenter: NSObject { PluginPresentationSafety.prepareForWindowOrdering() popover.show(relativeTo: anchorView.bounds, of: anchorView, preferredEdge: .minY) applyCurrentAppearance() + if let window = presentedWindow { + if isClassicHoverPopover && !NSWorkspace.shared.accessibilityDisplayShouldReduceMotion { + animateClassicHoverPopoverIn(window) + } else { + window.alphaValue = 1 + } + } focusPresentedWindow() } + private static let classicHoverSlideDistance: CGFloat = 18 + + private func animateClassicHoverPopoverIn(_ window: NSWindow) { + let targetFrame = window.frame + window.setFrame(targetFrame.offsetBy(dx: 0, dy: Self.classicHoverSlideDistance), display: false) + window.alphaValue = 0 + NSAnimationContext.runAnimationGroup { context in + context.duration = 0.22 + context.timingFunction = CAMediaTimingFunction(name: .easeOut) + window.animator().setFrame(targetFrame, display: true) + window.animator().alphaValue = 1 + } + } + + private func dismissClassicHoverPopover(animated: Bool) { + guard isClassicHoverPopover, popover.isShown else { return } + guard animated, !NSWorkspace.shared.accessibilityDisplayShouldReduceMotion, let window = presentedWindow else { + resetClassicHoverDismissal() + popover.performClose(nil) + return + } + guard classicHoverRestingFrame == nil else { return } + + classicHoverDismissGeneration &+= 1 + let generation = classicHoverDismissGeneration + let restingFrame = window.frame + classicHoverRestingFrame = restingFrame + NSAnimationContext.runAnimationGroup({ context in + context.duration = 0.16 + context.timingFunction = CAMediaTimingFunction(name: .easeIn) + window.animator().setFrame(restingFrame.offsetBy(dx: 0, dy: Self.classicHoverSlideDistance), display: true) + window.animator().alphaValue = 0 + }, completionHandler: { [weak self] in + Task { @MainActor [weak self] in + guard let self, self.classicHoverDismissGeneration == generation else { return } + self.popover.performClose(nil) + } + }) + } + + private func cancelClassicHoverDismissalIfNeeded() { + guard let restingFrame = classicHoverRestingFrame, let window = presentedWindow else { return } + resetClassicHoverDismissal() + NSAnimationContext.runAnimationGroup { context in + context.duration = 0.14 + context.timingFunction = CAMediaTimingFunction(name: .easeOut) + window.animator().setFrame(restingFrame, display: true) + window.animator().alphaValue = 1 + } + } + + private func resetClassicHoverDismissal() { + classicHoverDismissGeneration &+= 1 + classicHoverRestingFrame = nil + } + private func resolvedPanelForAnchor(panelID: String?) -> MenuBarPanelTab? { let visiblePanels = pluginHost.visibleMenuBarPanels guard !visiblePanels.isEmpty else { return nil } @@ -724,6 +809,8 @@ final class MenuBarPanelPresenter: NSObject { private func cleanupHoverAnchor() { hoverAnchorPanel?.orderOut(nil) hoverAnchorPanel = nil + isClassicHoverPopover = false + resetClassicHoverDismissal() } private func installKeyboardShortcutMonitorIfNeeded() { diff --git a/Sources/App/MenuBarStatusItemController.swift b/Sources/App/MenuBarStatusItemController.swift index b3397753d..9e4b3d764 100644 --- a/Sources/App/MenuBarStatusItemController.swift +++ b/Sources/App/MenuBarStatusItemController.swift @@ -171,11 +171,15 @@ final class MenuBarStatusItemController: NSObject { } self.handlePresentationResult() } - pluginHost.anchoredMenuBarPanelPresentationHandler = { [weak self] request in + pluginHost.anchoredMenuBarPanelPresentationHandler = { [weak self] request, pluginID, storage in guard let self else { return false } + let style: NotchHoverPanelStyle = pluginID == NotchHoverPanelStyle.pluginID + ? .stored(in: storage) + : .classic let presented = self.panelPresenter.presentPanelBelowAnchor( panelID: request.panelID, - anchorRect: request.anchorRect + anchorRect: request.anchorRect, + style: style ) if presented { self.handlePresentationResult() } return presented diff --git a/Sources/Core/Plugins/Dynamic/DynamicPluginManager.swift b/Sources/Core/Plugins/Dynamic/DynamicPluginManager.swift index 73a7c915c..82b35bd28 100644 --- a/Sources/Core/Plugins/Dynamic/DynamicPluginManager.swift +++ b/Sources/Core/Plugins/Dynamic/DynamicPluginManager.swift @@ -245,6 +245,10 @@ final class DynamicPluginManager: ObservableObject { self.pluginLoader = pluginLoader ?? DynamicPluginLoader(packageStore: packageStore) } + func storage(for pluginID: String) -> UserDefaultsPluginStorage { + packageStore.storage(for: pluginID) + } + func loadInstalledPlugins() -> [any MacToolsPlugin] { loadInstalledPluginsAndMetadata().plugins } diff --git a/Sources/Core/Plugins/Dynamic/PluginPackageStore.swift b/Sources/Core/Plugins/Dynamic/PluginPackageStore.swift index 4500d8842..02ef73d52 100644 --- a/Sources/Core/Plugins/Dynamic/PluginPackageStore.swift +++ b/Sources/Core/Plugins/Dynamic/PluginPackageStore.swift @@ -512,6 +512,10 @@ final class PluginPackageStore { } } + func storage(for pluginID: String) -> UserDefaultsPluginStorage { + UserDefaultsPluginStorage(pluginID: pluginID, userDefaults: userDefaults) + } + func runtimeContext(for record: PluginPackageRecord) -> PluginRuntimeContext { let pluginID = record.id @@ -526,7 +530,7 @@ final class PluginPackageStore { return PluginRuntimeContext( pluginID: pluginID, resourceBundle: Bundle(url: record.bundleURL) ?? .main, - storage: UserDefaultsPluginStorage(pluginID: pluginID, userDefaults: userDefaults), + storage: storage(for: pluginID), supportDirectory: supportURL, cacheDirectory: cacheURL, temporaryDirectory: tempURL diff --git a/Sources/Core/Plugins/PluginHost.swift b/Sources/Core/Plugins/PluginHost.swift index 1e2ed9238..130aae59c 100644 --- a/Sources/Core/Plugins/PluginHost.swift +++ b/Sources/Core/Plugins/PluginHost.swift @@ -403,7 +403,7 @@ final class PluginHost: ObservableObject { /// Injected by the app shell for plugins that present the regular menu-bar /// panel at an explicit screen anchor. var anchoredMenuBarPanelPresentationHandler: - ((PluginMenuBarPanelPresentationRequest) -> Bool)? + ((PluginMenuBarPanelPresentationRequest, _ pluginID: String, any PluginStorage) -> Bool)? var anchoredMenuBarPanelDismissalHandler: ((_ animated: Bool) -> Bool)? var anchoredMenuBarPanelFrameProvider: (() -> NSRect?)? var anchoredMenuBarPanelVisibilityProvider: (() -> Bool)? @@ -3493,8 +3493,10 @@ final class PluginHost: ObservableObject { } } if let anchoredPanelPresenting = plugin as? any PluginMenuBarPanelPresenting { + let storage = dynamicPluginManager?.storage(for: pluginID) + ?? UserDefaultsPluginStorage(pluginID: pluginID, userDefaults: shortcutStore.userDefaults) anchoredPanelPresenting.requestMenuBarPanelPresentation = { [weak self] request in - self?.anchoredMenuBarPanelPresentationHandler?(request) ?? false + self?.anchoredMenuBarPanelPresentationHandler?(request, pluginID, storage) ?? false } anchoredPanelPresenting.requestMenuBarPanelDismissal = { [weak self] animated in self?.anchoredMenuBarPanelDismissalHandler?(animated) ?? false diff --git a/Sources/PluginSupport/NotchHoverPanelStyle.swift b/Sources/PluginSupport/NotchHoverPanelStyle.swift new file mode 100644 index 000000000..99fcc0b42 --- /dev/null +++ b/Sources/PluginSupport/NotchHoverPanelStyle.swift @@ -0,0 +1,15 @@ +import MacToolsPluginKit + +enum NotchHoverPanelStyle: String, Sendable { + case morph + case classic + + static let pluginID = "notch-hover-panel" + static let storageKey = "notch-hover.panel-style" + static let hostSupportKey = "MTSupportsNotchHoverPanelStyles" + + @MainActor + static func stored(in storage: any PluginStorage) -> Self { + storage.string(forKey: storageKey).flatMap(Self.init(rawValue:)) ?? .morph + } +} diff --git a/changes/unreleased/notch-hover-island-trigger.md b/changes/unreleased/notch-hover-island-trigger.md index 5ddfe9fae..515c5bdc8 100644 --- a/changes/unreleased/notch-hover-island-trigger.md +++ b/changes/unreleased/notch-hover-island-trigger.md @@ -3,4 +3,4 @@ release: plugin type: changed --- -The Dynamic Island Hover Panel now opens only when the pointer is over the island. Trigger Width and Lower Trigger Reach can still widen the area. +Hover directly over the notch by default. Adjust the trigger area or choose Dynamic Island or Classic under Panel style. diff --git a/docs/plugins/notch-hover-panel.md b/docs/plugins/notch-hover-panel.md index 6b7e6f35f..86eba0886 100644 --- a/docs/plugins/notch-hover-panel.md +++ b/docs/plugins/notch-hover-panel.md @@ -1,6 +1,6 @@ # Dynamic Island Hover Panel -`Plugins/NotchHoverPanel/` opens the regular MacTools menu-bar panel when the pointer rests over the Dynamic Island. The panel expands from the notch and contracts back into it when it closes. The plugin handles hover detection, delays, and which presentation it owns. The host handles panel content, positioning, and animation. +`Plugins/NotchHoverPanel/` opens the regular MacTools menu-bar panel when the pointer rests over the Dynamic Island. In **Panel style**, **Dynamic Island** expands from the notch and contracts into it when it closes. **Classic** slides the original popover below the notch. Both styles are available on Macs with a notch and use the same hover area and delays. The plugin handles hover detection, delays, and which presentation it owns. The host handles panel content, positioning, and animation. The default trigger matches the Dynamic Island. The side-reach setting extends the trigger into the adjacent menu-bar areas. When enabled, the lower trigger extends below the island by the configured lower reach. The panel stays open while the pointer is over the island or inside the panel. It hides after the configured delay once the pointer leaves both. Mirrored secondary displays are ignored. From a4fe094f4fc4df60ec80aae059523f4cf2f3a31e Mon Sep 17 00:00:00 2001 From: Niko Eltarenko <61957857+nikoelt@users.noreply.github.com> Date: Sun, 15 Nov 2026 17:16:54 +1000 Subject: [PATCH 05/29] fix(notch-hover-panel): refine notch shape and click handoff --- Plugins/NotchHoverPanel/plugin.json | 26 +++---- Sources/App/MenuBarPanelPresenter.swift | 99 ++++++++++++++++--------- Sources/App/NotchMenuBarPanel.swift | 94 ++++++++++++++--------- Tests/App/NotchMenuBarPanelTests.swift | 37 +++++++++ site/src/generated/plugins.json | 74 +++++++++--------- 5 files changed, 209 insertions(+), 121 deletions(-) diff --git a/Plugins/NotchHoverPanel/plugin.json b/Plugins/NotchHoverPanel/plugin.json index 5ddcb15a4..16e8ffb03 100644 --- a/Plugins/NotchHoverPanel/plugin.json +++ b/Plugins/NotchHoverPanel/plugin.json @@ -1,55 +1,55 @@ { "id": "notch-hover-panel", "displayName": "灵动岛悬浮面板", - "summary": "鼠标悬停灵动岛两侧,或从灵动岛正下方往上移动时滑出 MacTools 面板", + "summary": "鼠标悬停在灵动岛上时打开 MacTools 面板", "localizedMetadata": { "ar": { "displayName": "لوحة تحويم Dynamic Island", - "summary": "أظهر لوحة MacTools عند تمرير المؤشر بجانب Dynamic Island أو التحرك لأعلى من أسفله." + "summary": "افتح لوحة MacTools عند إبقاء المؤشر فوق Dynamic Island." }, "de": { "displayName": "Dynamic-Island-Schwebepanel", - "summary": "MacTools-Bedienfeld einblenden, wenn der Zeiger neben der Dynamic Island schwebt oder von direkt darunter nach oben bewegt wird." + "summary": "MacTools-Bedienfeld öffnen, wenn der Zeiger auf der Dynamic Island ruht." }, "en": { "displayName": "Dynamic Island Hover Panel", - "summary": "Slide out the MacTools panel when the pointer hovers beside the Dynamic Island or moves up from directly below it." + "summary": "Open the MacTools panel when the pointer rests over the Dynamic Island." }, "es": { "displayName": "Panel al pasar por Dynamic Island", - "summary": "Muestra el panel de MacTools al pasar el puntero junto a Dynamic Island o moverlo hacia arriba desde justo debajo." + "summary": "Abre el panel de MacTools al dejar el puntero sobre Dynamic Island." }, "fr": { "displayName": "Panneau de survol de Dynamic Island", - "summary": "Affichez le panneau MacTools lorsque le pointeur survole le bord de Dynamic Island ou remonte depuis juste en dessous." + "summary": "Ouvrez le panneau MacTools lorsque le pointeur s’arrête sur Dynamic Island." }, "ja": { "displayName": "Dynamic Island ホバーパネル", - "summary": "ポインタを Dynamic Island の横に重ねるか、真下から上へ動かすと MacTools パネルを表示します。" + "summary": "ポインタを Dynamic Island の上に置くと MacTools パネルを開きます。" }, "ko": { "displayName": "Dynamic Island 호버 패널", - "summary": "포인터를 Dynamic Island 옆에 올리거나 바로 아래에서 위로 이동하면 MacTools 패널을 표시합니다." + "summary": "포인터를 Dynamic Island 위에 올리면 MacTools 패널을 엽니다." }, "pt": { "displayName": "Painel ao passar no Dynamic Island", - "summary": "Mostre o painel do MacTools ao passar o ponteiro ao lado do Dynamic Island ou movê-lo para cima a partir de baixo dele." + "summary": "Abra o painel do MacTools ao deixar o ponteiro sobre o Dynamic Island." }, "ru": { "displayName": "Панель при наведении на Dynamic Island", - "summary": "Показывать панель MacTools при наведении курсора рядом с Dynamic Island или движении вверх из-под него." + "summary": "Открывать панель MacTools при наведении курсора на Dynamic Island." }, "tr": { "displayName": "Dynamic Island Üzerine Gelme Paneli", - "summary": "İmleci Dynamic Island'ın yanına getirdiğinizde veya hemen altından yukarı hareket ettirdiğinizde MacTools panelini gösterin." + "summary": "İmleci Dynamic Island'ın üzerinde tuttuğunuzda MacTools panelini açın." }, "zh-Hans": { "displayName": "灵动岛悬浮面板", - "summary": "鼠标悬停灵动岛两侧,或从灵动岛正下方往上移动时滑出 MacTools 面板" + "summary": "鼠标悬停在灵动岛上时打开 MacTools 面板" }, "zh-Hant": { "displayName": "靈動島懸浮面板", - "summary": "滑鼠懸停靈動島兩側,或從靈動島正下方往上移動時滑出 MacTools 面板" + "summary": "滑鼠懸停在靈動島上時打開 MacTools 面板" } }, "productStrings": { diff --git a/Sources/App/MenuBarPanelPresenter.swift b/Sources/App/MenuBarPanelPresenter.swift index 758dca28e..5bdccd9f2 100644 --- a/Sources/App/MenuBarPanelPresenter.swift +++ b/Sources/App/MenuBarPanelPresenter.swift @@ -302,6 +302,9 @@ final class MenuBarPanelPresenter: NSObject { private var isClassicHoverPopover = false private var classicHoverRestingFrame: NSRect? private var classicHoverDismissGeneration: UInt = 0 + /// Set when a click or shortcut brings back a hover panel that was closing. + /// The panel then closes only as a click-opened panel does. + private var isHoverPanelClaimed = false init( pluginHost: PluginHost, @@ -488,17 +491,8 @@ final class MenuBarPanelPresenter: NSObject { func showPanel(id: String, toggle shouldToggle: Bool, anchorRect: NSRect) { guard pluginHost.menuBarPanels.contains(where: { $0.id == id }) else { return } let panel = MenuBarPanelTab(id: id) - if shouldToggle, - isAnyPanelShown, - tab(for: selectedPanel).id == id { - if panelModel.preventDismissalWhileEditing() { - focusPresentedWindow() - } else { - dismissPanels() - } - return - } - present(panel, relativeTo: hoverAnchorView(for: anchorRect)) + if shouldToggle { toggle(panel, relativeTo: hoverAnchorView(for: anchorRect)) } + else { present(panel, relativeTo: hoverAnchorView(for: anchorRect)) } } /// Presents the panel from a plugin-owned screen anchor. @@ -512,6 +506,7 @@ final class MenuBarPanelPresenter: NSObject { else { return false } if let notchPanel { + guard !isHoverPanelClaimed else { return false } notchPanel.reopen() return true } @@ -522,6 +517,7 @@ final class MenuBarPanelPresenter: NSObject { } guard let selected = resolvedPanelForAnchor(panelID: panelID) else { return false } + isHoverPanelClaimed = false if style == .classic { present(selected, relativeTo: hoverAnchorView(for: anchorRect), asClassicHover: true) guard popover.isShown else { @@ -549,8 +545,9 @@ final class MenuBarPanelPresenter: NSObject { PluginPresentationSafety.prepareForWindowOrdering() panel.present(size: panelContentSize) panel.watchForSystemPanel(systemPanel) { [weak self, weak panel] in - guard let self, let panel, self.notchPanel === panel else { return } - self.dismissPanelBelowAnchor(animated: false) + guard let self, let panel, self.notchPanel === panel, + !self.panelModel.preventDismissalWhileEditing() else { return } + self.closeNotchPanel(panel, animated: false) } focusPresentedWindow() scheduleHeightRefresh(for: selected) @@ -560,15 +557,35 @@ final class MenuBarPanelPresenter: NSObject { @discardableResult func dismissPanelBelowAnchor(animated: Bool) -> Bool { guard !panelModel.preventDismissalWhileEditing() else { return false } + // A claimed panel is no longer the hover owner's to close. + guard !isHoverPanelClaimed else { return true } guard let notchPanel else { dismissClassicHoverPopover(animated: animated) return true } + closeNotchPanel(notchPanel, animated: animated) + return true + } - notchPanel.dismiss(animated: animated) { [weak self, weak notchPanel] in - guard let self, let notchPanel, self.notchPanel === notchPanel else { return } - self.finishNotchPanelDismissal(notchPanel) + private func closeNotchPanel(_ panel: NotchMenuBarPanel, animated: Bool) { + panel.dismiss(animated: animated) { [weak self, weak panel] in + guard let self, let panel, self.notchPanel === panel else { return } + self.finishNotchPanelDismissal(panel) } + } + + /// A menu-bar click or panel shortcut during a hover panel's close animation + /// brings that panel back instead of being treated as a second close. + private func claimClosingHoverPanel() -> Bool { + if let notchPanel, notchPanel.isClosing { + notchPanel.reopen() + } else if isClassicHoverPopover, popover.isShown, classicHoverRestingFrame != nil { + cancelClassicHoverDismissalIfNeeded() + isClassicHoverPopover = false + } else { + return false + } + isHoverPanelClaimed = true return true } @@ -580,8 +597,8 @@ final class MenuBarPanelPresenter: NSObject { func dismissPanels() { nativeMenuPresenter.cancel() guard !panelModel.preventDismissalWhileEditing() else { return } - if notchPanel != nil { - dismissPanelBelowAnchor(animated: true) + if let notchPanel { + closeNotchPanel(notchPanel, animated: true) } else { resetClassicHoverDismissal() popover.performClose(nil) @@ -607,6 +624,7 @@ final class MenuBarPanelPresenter: NSObject { private func finishNotchPanelDismissal(_ panel: NotchMenuBarPanel) { panel.detachContent() notchPanel = nil + isHoverPanelClaimed = false panelModel.isNotchPresentation = false panelModel.setNotchHeader(besideIsland: false, topOffset: 0) containerController.setDrawsBackground(true) @@ -622,7 +640,11 @@ final class MenuBarPanelPresenter: NSObject { || MenuBarPanelWindowRegistry.containsAuxiliaryPanelWindow(window) } - private func toggle(_ panel: PanelKind, relativeTo anchorView: NSView) { + private func toggle(_ panel: PanelKind, relativeTo anchorView: @autoclosure () -> NSView) { + if claimClosingHoverPanel() { + present(panel, relativeTo: anchorView()) + return + } let action = MenuBarPanelToggleAction.resolve( isPanelShown: isAnyPanelShown, selectedTab: tab(for: selectedPanel), @@ -638,31 +660,40 @@ final class MenuBarPanelPresenter: NSObject { return } - present(panel, relativeTo: anchorView) + present(panel, relativeTo: anchorView()) } - private func present(_ panel: PanelKind, relativeTo anchorView: NSView, asClassicHover: Bool = false) { + private func present( + _ panel: PanelKind, + relativeTo anchorView: @autoclosure () -> NSView, + asClassicHover: Bool = false + ) { + if !asClassicHover { _ = claimClosingHoverPanel() } let action = MenuBarPanelPresentationAction.resolve( isPanelShown: isAnyPanelShown, selectedTab: tab(for: selectedPanel), requestedTab: tab(for: panel) ) + // An existing popover must keep its original anchor when a shortcut + // reclaims it or switches tabs. + let openingAnchor = action == .open ? anchorView() : nil + let screen = openingAnchor?.window?.screen ?? presentedWindow?.screen ?? NSScreen.main selectedPanel = panel updateContent( selectedTab: tab(for: panel), - screen: anchorView.window?.screen ?? NSScreen.main, + screen: screen, isPanelVisible: true ) updatePanelSurfaceVisibility(for: tab(for: panel), isPanelVisible: true) - if action != .open { + guard let openingAnchor else { focusPresentedWindow() scheduleHeightRefresh(for: tab(for: panel)) return } isClassicHoverPopover = asClassicHover - show(popover, relativeTo: anchorView) + show(popover, relativeTo: openingAnchor) scheduleHeightRefresh(for: tab(for: panel)) } @@ -810,6 +841,7 @@ final class MenuBarPanelPresenter: NSObject { hoverAnchorPanel?.orderOut(nil) hoverAnchorPanel = nil isClassicHoverPopover = false + isHoverPanelClaimed = false resetClassicHoverDismissal() } @@ -1161,7 +1193,9 @@ final class MenuBarPanelPresenter: NSObject { let maximumWidth = MenuBarPanelWidth.maximum(visibleFrameWidth: screen?.visibleFrame.width) let preferredWidth = MenuBarPanelWidth.resolved( preferred: pluginHost.preferredMenuBarPanelWidth, maximum: maximumWidth) - let widthForNotchHeader = notchPanel.map { + // Widen only while the header sits beside the notch. Layout editing moves + // it below, so editing keeps the width the user chose. + let widthForNotchHeader = panelModel.isEditingLayout ? 0 : notchPanel.map { NotchMenuBarPanel.minimumWidthForHeaderBesideIsland( tabCount: pluginHost.visibleMenuBarPanels.count, notchWidth: $0.anchor.width) } ?? 0 @@ -1695,8 +1729,6 @@ struct MenuBarPanelHeader: View { let onUndoLayout: () -> Void /// Tabs lead and the actions trail, leaving the middle clear for the camera island. var splitsAroundIsland = false - @Environment(\.menuBarPanelTheme) private var theme - @Environment(\.colorSchemeContrast) private var contrast var body: some View { if isEditingLayout { @@ -1708,17 +1740,10 @@ struct MenuBarPanelHeader: View { HStack(spacing: 0) { navigation.fixedSize() Spacer(minLength: 0) + // Standalone icons on the tab strip's grid: same pitch as the + // tabs, and the trailing icon mirrors the first tab's inset. HStack(spacing: MenuBarPanelTabLayout.spacing) { accessories } - .padding(MenuBarPanelLayout.tabCapsuleInset) - .background { - // Matches the tab strip's capsule so both groups read as a pair. - Capsule() - .fill(theme.surfaces.panel) - .overlay { - Capsule().strokeBorder(theme.surfaces.separator, - lineWidth: contrast == .increased ? 1 : 0.5) - } - } + .padding(.horizontal, MenuBarPanelLayout.tabCapsuleInset) } } else { ZStack { diff --git a/Sources/App/NotchMenuBarPanel.swift b/Sources/App/NotchMenuBarPanel.swift index 1fa7bcc9d..065595466 100644 --- a/Sources/App/NotchMenuBarPanel.swift +++ b/Sources/App/NotchMenuBarPanel.swift @@ -332,6 +332,9 @@ struct NotchMorphMetrics { let housingOffset: CGFloat /// Distance from the window top to the top of the hosted content. let contentTopInset: CGFloat + /// A wide camera cutout reaches the display edge, so the surface grows from + /// that edge with square top corners instead of floating below it. + let meetsDisplayTop: Bool init(anchor: CGRect, contentSize: CGSize) { self.anchor = anchor @@ -341,14 +344,18 @@ struct NotchMorphMetrics { let isWideCameraCutout = anchor.width >= anchor.height * 3 let housingInset = isWideCameraCutout ? 0 : min(Self.housingTopInset, anchor.height * 0.2) let expandedInset = min(Self.expandedTopInset, housingInset) + meetsDisplayTop = expandedInset == 0 housingOffset = housingInset - expandedInset housingSize = CGSize(width: anchor.width, height: max(anchor.height - housingInset, 1)) // Start one point inside the housing so the first frame is hidden by it. collapsedSize = CGSize(width: max(housingSize.width - 2, 2), height: max(housingSize.height - 2, 2)) - // The content's header row is centered on the island, beside it. + // The content's header row is centered on the island, beside it. The + // content's empty top padding may start above a surface that meets the + // display edge, but the header itself never does. let islandCenter = housingOffset + housingSize.height / 2 contentTopInset = max( - islandCenter - (MenuBarPanelLayout.panelTopPadding + MenuBarPanelLayout.headerHeight / 2), 0 + islandCenter - (MenuBarPanelLayout.panelTopPadding + MenuBarPanelLayout.headerHeight / 2), + -MenuBarPanelLayout.panelTopPadding ) expandedSize = CGSize( width: max(contentSize.width, housingSize.width), @@ -380,7 +387,8 @@ struct NotchMorphMetrics { let width = max(Self.lerp(collapsedSize.width, expandedSize.width, widthFraction), 2) let height = max(Self.lerp(collapsedSize.height, expandedSize.height, heightFraction), 2) // Rises from inside the housing to the expanded top as the surface deepens. - let collapsedTop = housingOffset + (housingSize.height - collapsedSize.height) / 2 + // A surface that meets the display edge stays pinned to it. + let collapsedTop = meetsDisplayTop ? 0 : housingOffset + (housingSize.height - collapsedSize.height) / 2 let topInset = Self.lerp(collapsedTop, 0, min(max(heightFraction, 0), 1)) return CGRect(x: size.width / 2 - width / 2, y: size.height - topInset - height, width: width, height: height) @@ -394,6 +402,10 @@ struct NotchMorphMetrics { return min(Self.lerp(pill, Self.expandedCornerRadius, settle), pill) } + func topCornerRadius(for rect: CGRect, heightFraction: Double) -> CGFloat { + meetsDisplayTop ? 0 : cornerRadius(for: rect, heightFraction: heightFraction) + } + func screenRect(fromSurfaceRect rect: CGRect) -> CGRect { rect.offsetBy(dx: windowFrame.minX, dy: windowFrame.minY) } @@ -406,42 +418,53 @@ struct NotchMorphMetrics { enum NotchSurfacePath { /// A rounded rectangle whose corners ease into the straight edges /// (continuous curvature) when there is room, and become exact circular - /// arcs as the shape approaches a pill, so morphing never changes the - /// path structure. - static func make(in rect: CGRect, radius requestedRadius: CGFloat) -> CGPath { + /// arcs as the shape approaches a pill. The top corners can use a smaller + /// radius, down to square, for a surface that meets the display edge. + static func make(in rect: CGRect, radius: CGFloat, topRadius: CGFloat? = nil) -> CGPath { let limit = min(rect.width, rect.height) / 2 - let radius = max(min(requestedRadius, limit), 0) - let path = CGMutablePath() - guard radius > 0 else { - path.addRect(rect) - return path - } - - let smoothing = min(max((limit / radius - 1) / 0.4, 0), 1) - let extent = radius * (1 + 0.4 * smoothing) - let handle = extent * (0.5523 + (0.8 - 0.5523) * smoothing) + let bottom = Corner(radius: radius, limit: limit) + let top = Corner(radius: topRadius ?? radius, limit: limit) let minX = rect.minX, maxX = rect.maxX, minY = rect.minY, maxY = rect.maxY + let path = CGMutablePath() - path.move(to: CGPoint(x: minX + extent, y: maxY)) - path.addLine(to: CGPoint(x: maxX - extent, y: maxY)) - path.addCurve(to: CGPoint(x: maxX, y: maxY - extent), - control1: CGPoint(x: maxX - extent + handle, y: maxY), - control2: CGPoint(x: maxX, y: maxY - extent + handle)) - path.addLine(to: CGPoint(x: maxX, y: minY + extent)) - path.addCurve(to: CGPoint(x: maxX - extent, y: minY), - control1: CGPoint(x: maxX, y: minY + extent - handle), - control2: CGPoint(x: maxX - extent + handle, y: minY)) - path.addLine(to: CGPoint(x: minX + extent, y: minY)) - path.addCurve(to: CGPoint(x: minX, y: minY + extent), - control1: CGPoint(x: minX + extent - handle, y: minY), - control2: CGPoint(x: minX, y: minY + extent - handle)) - path.addLine(to: CGPoint(x: minX, y: maxY - extent)) - path.addCurve(to: CGPoint(x: minX + extent, y: maxY), - control1: CGPoint(x: minX, y: maxY - extent + handle), - control2: CGPoint(x: minX + extent - handle, y: maxY)) + path.move(to: CGPoint(x: minX + top.extent, y: maxY)) + path.addLine(to: CGPoint(x: maxX - top.extent, y: maxY)) + path.addCurve(to: CGPoint(x: maxX, y: maxY - top.extent), + control1: CGPoint(x: maxX - top.extent + top.handle, y: maxY), + control2: CGPoint(x: maxX, y: maxY - top.extent + top.handle)) + path.addLine(to: CGPoint(x: maxX, y: minY + bottom.extent)) + path.addCurve(to: CGPoint(x: maxX - bottom.extent, y: minY), + control1: CGPoint(x: maxX, y: minY + bottom.extent - bottom.handle), + control2: CGPoint(x: maxX - bottom.extent + bottom.handle, y: minY)) + path.addLine(to: CGPoint(x: minX + bottom.extent, y: minY)) + path.addCurve(to: CGPoint(x: minX, y: minY + bottom.extent), + control1: CGPoint(x: minX + bottom.extent - bottom.handle, y: minY), + control2: CGPoint(x: minX, y: minY + bottom.extent - bottom.handle)) + path.addLine(to: CGPoint(x: minX, y: maxY - top.extent)) + path.addCurve(to: CGPoint(x: minX + top.extent, y: maxY), + control1: CGPoint(x: minX, y: maxY - top.extent + top.handle), + control2: CGPoint(x: minX + top.extent - top.handle, y: maxY)) path.closeSubpath() return path } + + /// One corner's reach along each edge and its Bézier handle length. + private struct Corner { + let extent: CGFloat + let handle: CGFloat + + init(radius requested: CGFloat, limit: CGFloat) { + let radius = max(min(requested, limit), 0) + guard radius > 0 else { + extent = 0 + handle = 0 + return + } + let smoothing = min(max((limit / radius - 1) / 0.4, 0), 1) + extent = radius * (1 + 0.4 * smoothing) + handle = extent * (0.5523 + (0.8 - 0.5523) * smoothing) + } + } } // MARK: - Views @@ -504,7 +527,10 @@ final class NotchMorphView: NSView { func apply(model: NotchMorphModel, metrics: NotchMorphMetrics) { let rect = metrics.surfaceRect(for: model) let radius = metrics.cornerRadius(for: rect, heightFraction: model.height.value) - let path = NotchSurfacePath.make(in: rect, radius: radius) + let path = NotchSurfacePath.make( + in: rect, radius: radius, + topRadius: metrics.topCornerRadius(for: rect, heightFraction: model.height.value) + ) surfacePath = path CATransaction.begin() diff --git a/Tests/App/NotchMenuBarPanelTests.swift b/Tests/App/NotchMenuBarPanelTests.swift index af31fe710..c58097370 100644 --- a/Tests/App/NotchMenuBarPanelTests.swift +++ b/Tests/App/NotchMenuBarPanelTests.swift @@ -24,6 +24,43 @@ final class NotchMenuBarPanelTests: XCTestCase { XCTAssertEqual(expandedSurface.maxY, anchor.maxY) } + func testWideCameraCutoutSurfaceHasSquareTopCornersAtEveryStage() { + let anchor = CGRect(x: 663.5, y: 950, width: 185, height: 32) + let metrics = NotchMorphMetrics(anchor: anchor, contentSize: CGSize(width: 349, height: 114.5)) + + for fraction in [0.0, 0.3, 1.0] { + let rect = metrics.surfaceRect(expandedFraction: fraction) + let path = NotchSurfacePath.make( + in: rect, + radius: metrics.cornerRadius(for: rect, heightFraction: fraction), + topRadius: metrics.topCornerRadius(for: rect, heightFraction: fraction) + ) + + XCTAssertEqual(rect.maxY, metrics.windowSize.height, "The surface stays pinned to the display edge.") + XCTAssertTrue(path.contains(CGPoint(x: rect.minX + 0.5, y: rect.maxY - 0.5))) + XCTAssertTrue(path.contains(CGPoint(x: rect.maxX - 0.5, y: rect.maxY - 0.5))) + XCTAssertFalse(path.contains(CGPoint(x: rect.minX + 0.5, y: rect.minY + 0.5)), + "Bottom corners stay rounded.") + } + } + + func testHeaderRowIsCenteredOnTheCameraHousing() { + let anchors = [ + CGRect(x: 838.5, y: 1093, width: 59, height: 40), // compact island + CGRect(x: 663.5, y: 950, width: 185, height: 32), // wide camera cutout + ] + for anchor in anchors { + let metrics = NotchMorphMetrics(anchor: anchor, contentSize: CGSize(width: 349, height: 114)) + let headerCenter = metrics.contentTopInset + + MenuBarPanelLayout.panelTopPadding + MenuBarPanelLayout.headerHeight / 2 + let housingCenter = metrics.housingOffset + metrics.housingSize.height / 2 + + XCTAssertEqual(headerCenter, housingCenter, accuracy: 0.5, "\(anchor.size)") + XCTAssertGreaterThanOrEqual(headerCenter - MenuBarPanelLayout.headerHeight / 2, 0, + "The header stays inside the surface.") + } + } + func testCompactIslandKeepsAnInsetFromDisplayTop() { let anchor = CGRect(x: 838.5, y: 1093, width: 59, height: 40) let metrics = NotchMorphMetrics(anchor: anchor, contentSize: CGSize(width: 316, height: 114)) diff --git a/site/src/generated/plugins.json b/site/src/generated/plugins.json index c1beac304..6e27ba86f 100644 --- a/site/src/generated/plugins.json +++ b/site/src/generated/plugins.json @@ -18346,51 +18346,51 @@ "localizedMetadata": { "ar": { "displayName": "لوحة تحويم Dynamic Island", - "summary": "أظهر لوحة MacTools عند تمرير المؤشر بجانب Dynamic Island أو التحرك لأعلى من أسفله." + "summary": "افتح لوحة MacTools عند إبقاء المؤشر فوق Dynamic Island." }, "de": { "displayName": "Dynamic-Island-Schwebepanel", - "summary": "MacTools-Bedienfeld einblenden, wenn der Zeiger neben der Dynamic Island schwebt oder von direkt darunter nach oben bewegt wird." + "summary": "MacTools-Bedienfeld öffnen, wenn der Zeiger auf der Dynamic Island ruht." }, "en": { "displayName": "Dynamic Island Hover Panel", - "summary": "Slide out the MacTools panel when the pointer hovers beside the Dynamic Island or moves up from directly below it." + "summary": "Open the MacTools panel when the pointer rests over the Dynamic Island." }, "es": { "displayName": "Panel al pasar por Dynamic Island", - "summary": "Muestra el panel de MacTools al pasar el puntero junto a Dynamic Island o moverlo hacia arriba desde justo debajo." + "summary": "Abre el panel de MacTools al dejar el puntero sobre Dynamic Island." }, "fr": { "displayName": "Panneau de survol de Dynamic Island", - "summary": "Affichez le panneau MacTools lorsque le pointeur survole le bord de Dynamic Island ou remonte depuis juste en dessous." + "summary": "Ouvrez le panneau MacTools lorsque le pointeur s’arrête sur Dynamic Island." }, "ja": { "displayName": "Dynamic Island ホバーパネル", - "summary": "ポインタを Dynamic Island の横に重ねるか、真下から上へ動かすと MacTools パネルを表示します。" + "summary": "ポインタを Dynamic Island の上に置くと MacTools パネルを開きます。" }, "ko": { "displayName": "Dynamic Island 호버 패널", - "summary": "포인터를 Dynamic Island 옆에 올리거나 바로 아래에서 위로 이동하면 MacTools 패널을 표시합니다." + "summary": "포인터를 Dynamic Island 위에 올리면 MacTools 패널을 엽니다." }, "pt": { "displayName": "Painel ao passar no Dynamic Island", - "summary": "Mostre o painel do MacTools ao passar o ponteiro ao lado do Dynamic Island ou movê-lo para cima a partir de baixo dele." + "summary": "Abra o painel do MacTools ao deixar o ponteiro sobre o Dynamic Island." }, "ru": { "displayName": "Панель при наведении на Dynamic Island", - "summary": "Показывать панель MacTools при наведении курсора рядом с Dynamic Island или движении вверх из-под него." + "summary": "Открывать панель MacTools при наведении курсора на Dynamic Island." }, "tr": { "displayName": "Dynamic Island Üzerine Gelme Paneli", - "summary": "İmleci Dynamic Island'ın yanına getirdiğinizde veya hemen altından yukarı hareket ettirdiğinizde MacTools panelini gösterin." + "summary": "İmleci Dynamic Island'ın üzerinde tuttuğunuzda MacTools panelini açın." }, "zh-Hans": { "displayName": "灵动岛悬浮面板", - "summary": "鼠标悬停灵动岛两侧,或从灵动岛正下方往上移动时滑出 MacTools 面板" + "summary": "鼠标悬停在灵动岛上时打开 MacTools 面板" }, "zh-Hant": { "displayName": "靈動島懸浮面板", - "summary": "滑鼠懸停靈動島兩側,或從靈動島正下方往上移動時滑出 MacTools 面板" + "summary": "滑鼠懸停在靈動島上時打開 MacTools 面板" } }, "openInMacToolsURL": "mactools://app/settings/plugins/marketplace/notch-hover-panel", @@ -18475,35 +18475,35 @@ { "id": "primary-use", "text": { - "ar": "أظهر لوحة MacTools عند تمرير المؤشر بجانب Dynamic Island أو التحرك لأعلى من أسفله.", - "de": "MacTools-Bedienfeld einblenden, wenn der Zeiger neben der Dynamic Island schwebt oder von direkt darunter nach oben bewegt wird.", - "en": "Slide out the MacTools panel when the pointer hovers beside the Dynamic Island or moves up from directly below it.", - "es": "Muestra el panel de MacTools al pasar el puntero junto a Dynamic Island o moverlo hacia arriba desde justo debajo.", - "fr": "Affichez le panneau MacTools lorsque le pointeur survole le bord de Dynamic Island ou remonte depuis juste en dessous.", - "ja": "ポインタを Dynamic Island の横に重ねるか、真下から上へ動かすと MacTools パネルを表示します。", - "ko": "포인터를 Dynamic Island 옆에 올리거나 바로 아래에서 위로 이동하면 MacTools 패널을 표시합니다.", - "pt": "Mostre o painel do MacTools ao passar o ponteiro ao lado do Dynamic Island ou movê-lo para cima a partir de baixo dele.", - "ru": "Показывать панель MacTools при наведении курсора рядом с Dynamic Island или движении вверх из-под него.", - "tr": "İmleci Dynamic Island'ın yanına getirdiğinizde veya hemen altından yukarı hareket ettirdiğinizde MacTools panelini gösterin.", - "zh-Hans": "鼠标悬停灵动岛两侧,或从灵动岛正下方往上移动时滑出 MacTools 面板", - "zh-Hant": "滑鼠懸停靈動島兩側,或從靈動島正下方往上移動時滑出 MacTools 面板" + "ar": "افتح لوحة MacTools عند إبقاء المؤشر فوق Dynamic Island.", + "de": "MacTools-Bedienfeld öffnen, wenn der Zeiger auf der Dynamic Island ruht.", + "en": "Open the MacTools panel when the pointer rests over the Dynamic Island.", + "es": "Abre el panel de MacTools al dejar el puntero sobre Dynamic Island.", + "fr": "Ouvrez le panneau MacTools lorsque le pointeur s’arrête sur Dynamic Island.", + "ja": "ポインタを Dynamic Island の上に置くと MacTools パネルを開きます。", + "ko": "포인터를 Dynamic Island 위에 올리면 MacTools 패널을 엽니다.", + "pt": "Abra o painel do MacTools ao deixar o ponteiro sobre o Dynamic Island.", + "ru": "Открывать панель MacTools при наведении курсора на Dynamic Island.", + "tr": "İmleci Dynamic Island'ın üzerinde tuttuğunuzda MacTools panelini açın.", + "zh-Hans": "鼠标悬停在灵动岛上时打开 MacTools 面板", + "zh-Hant": "滑鼠懸停在靈動島上時打開 MacTools 面板" } } ], "license": "GPL-3.0-only", "longDescription": { - "ar": "أظهر لوحة MacTools عند تمرير المؤشر بجانب Dynamic Island أو التحرك لأعلى من أسفله.", - "de": "MacTools-Bedienfeld einblenden, wenn der Zeiger neben der Dynamic Island schwebt oder von direkt darunter nach oben bewegt wird.", - "en": "Slide out the MacTools panel when the pointer hovers beside the Dynamic Island or moves up from directly below it.", - "es": "Muestra el panel de MacTools al pasar el puntero junto a Dynamic Island o moverlo hacia arriba desde justo debajo.", - "fr": "Affichez le panneau MacTools lorsque le pointeur survole le bord de Dynamic Island ou remonte depuis juste en dessous.", - "ja": "ポインタを Dynamic Island の横に重ねるか、真下から上へ動かすと MacTools パネルを表示します。", - "ko": "포인터를 Dynamic Island 옆에 올리거나 바로 아래에서 위로 이동하면 MacTools 패널을 표시합니다.", - "pt": "Mostre o painel do MacTools ao passar o ponteiro ao lado do Dynamic Island ou movê-lo para cima a partir de baixo dele.", - "ru": "Показывать панель MacTools при наведении курсора рядом с Dynamic Island или движении вверх из-под него.", - "tr": "İmleci Dynamic Island'ın yanına getirdiğinizde veya hemen altından yukarı hareket ettirdiğinizde MacTools panelini gösterin.", - "zh-Hans": "鼠标悬停灵动岛两侧,或从灵动岛正下方往上移动时滑出 MacTools 面板", - "zh-Hant": "滑鼠懸停靈動島兩側,或從靈動島正下方往上移動時滑出 MacTools 面板" + "ar": "افتح لوحة MacTools عند إبقاء المؤشر فوق Dynamic Island.", + "de": "MacTools-Bedienfeld öffnen, wenn der Zeiger auf der Dynamic Island ruht.", + "en": "Open the MacTools panel when the pointer rests over the Dynamic Island.", + "es": "Abre el panel de MacTools al dejar el puntero sobre Dynamic Island.", + "fr": "Ouvrez le panneau MacTools lorsque le pointeur s’arrête sur Dynamic Island.", + "ja": "ポインタを Dynamic Island の上に置くと MacTools パネルを開きます。", + "ko": "포인터를 Dynamic Island 위에 올리면 MacTools 패널을 엽니다.", + "pt": "Abra o painel do MacTools ao deixar o ponteiro sobre o Dynamic Island.", + "ru": "Открывать панель MacTools при наведении курсора на Dynamic Island.", + "tr": "İmleci Dynamic Island'ın üzerinde tuttuğunuzda MacTools panelini açın.", + "zh-Hans": "鼠标悬停在灵动岛上时打开 MacTools 面板", + "zh-Hant": "滑鼠懸停在靈動島上時打開 MacTools 面板" }, "publisher": "MacTools", "screenshots": [], @@ -18554,7 +18554,7 @@ "releaseChannel": null, "releaseNotesURL": null, "route": "/plugins/notch-hover-panel/", - "summary": "鼠标悬停灵动岛两侧,或从灵动岛正下方往上移动时滑出 MacTools 面板", + "summary": "鼠标悬停在灵动岛上时打开 MacTools 面板", "version": "2.2.0" }, { From b950523020f30ac01944940180b253631193c69d Mon Sep 17 00:00:00 2001 From: Niko Eltarenko <61957857+nikoelt@users.noreply.github.com> Date: Tue, 17 Nov 2026 17:09:13 +1000 Subject: [PATCH 06/29] feat(island-notifications): notification cards from the Dynamic Island An opt-in plugin for the MacBook Pro camera island (macOS 27) that shows each notification as a card growing out of the island, the way iPhone does: hover to keep it, swipe up to dismiss, pull down to open, click to open the exact item, and reply inline to Messages and Claude. A Notifications widget lists recent notifications stacked by app and opens or clears them through Notification Centre. Notification Centre stays the record: banners are hidden through Accessibility while a card shows and still go into its history; nothing is stored and notification text never reaches the logs. Accessibility work runs off the main thread with bounded timeouts. Off on every other Mac. The notch morph surface moves from NotchMenuBarPanel into Sources/PluginSupport/NotchMorphSurface.swift so the plugin can compile it; PluginKit is unchanged. The hover panel no longer opens under a card. Co-Authored-By: Claude Opus 5.5 --- CONTRIBUTING.md | 2 + ...dNotificationsPluginBundleEntrypoint.swift | 3 + .../Resources/Localizable.xcstrings | 2316 +++++++++++++++++ .../Sources/IslandCenterPress.swift | 192 ++ .../Sources/IslandLiveActivityGeometry.swift | 128 + .../Sources/IslandLiveActivityObserver.swift | 229 ++ .../Sources/IslandNotificationAX.swift | 1106 ++++++++ .../Sources/IslandNotificationHistory.swift | 132 + .../IslandNotificationHistoryView.swift | 309 +++ .../Sources/IslandNotificationPresenter.swift | 1269 +++++++++ .../Sources/IslandNotificationState.swift | 325 +++ .../IslandNotificationsController.swift | 912 +++++++ .../Sources/IslandNotificationsPlugin.swift | 125 + .../Sources/IslandSplitMorphView.swift | 62 + .../IslandLiveActivityGeometryTests.swift | 69 + .../IslandNotificationHistoryTests.swift | 56 + .../Tests/IslandNotificationStateTests.swift | 70 + Plugins/IslandNotifications/plugin.json | 236 ++ Plugins/IslandNotifications/project.yml | 3 + .../Sources/NotchHoverPanelController.swift | 19 +- Sources/App/NotchMenuBarPanel.swift | 328 +-- Sources/PluginSupport/NotchMorphSurface.swift | 335 +++ changes/unreleased/island-notifications.md | 7 + docs/plugins/island-notifications.md | 51 + docs/plugins/preferences-backup-inventory.md | 3 +- site/src/generated/plugins.json | 252 ++ 26 files changed, 8214 insertions(+), 325 deletions(-) create mode 100644 Plugins/IslandNotifications/Bundle/IslandNotificationsPluginBundleEntrypoint.swift create mode 100644 Plugins/IslandNotifications/Resources/Localizable.xcstrings create mode 100644 Plugins/IslandNotifications/Sources/IslandCenterPress.swift create mode 100644 Plugins/IslandNotifications/Sources/IslandLiveActivityGeometry.swift create mode 100644 Plugins/IslandNotifications/Sources/IslandLiveActivityObserver.swift create mode 100644 Plugins/IslandNotifications/Sources/IslandNotificationAX.swift create mode 100644 Plugins/IslandNotifications/Sources/IslandNotificationHistory.swift create mode 100644 Plugins/IslandNotifications/Sources/IslandNotificationHistoryView.swift create mode 100644 Plugins/IslandNotifications/Sources/IslandNotificationPresenter.swift create mode 100644 Plugins/IslandNotifications/Sources/IslandNotificationState.swift create mode 100644 Plugins/IslandNotifications/Sources/IslandNotificationsController.swift create mode 100644 Plugins/IslandNotifications/Sources/IslandNotificationsPlugin.swift create mode 100644 Plugins/IslandNotifications/Sources/IslandSplitMorphView.swift create mode 100644 Plugins/IslandNotifications/Tests/IslandLiveActivityGeometryTests.swift create mode 100644 Plugins/IslandNotifications/Tests/IslandNotificationHistoryTests.swift create mode 100644 Plugins/IslandNotifications/Tests/IslandNotificationStateTests.swift create mode 100644 Plugins/IslandNotifications/plugin.json create mode 100644 Plugins/IslandNotifications/project.yml create mode 100644 Sources/PluginSupport/NotchMorphSurface.swift create mode 100644 changes/unreleased/island-notifications.md create mode 100644 docs/plugins/island-notifications.md diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 41fd4cb77..72bdb9145 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -68,6 +68,8 @@ Stable plugin publication reuses one aggregate `Release` build for package signi Ordinary plugins do not need root `project.yml` edits. Put necessary build overrides in the plugin's own `project.yml`; app extensions such as Finder Sync must be embedded by the host. +The notch morph surface shared by the hover panel and the [Dynamic Island Notifications plugin](docs/plugins/island-notifications.md) lives in `Sources/PluginSupport/NotchMorphSurface.swift`. A plugin that draws its own island window compiles that file through its `project.yml`; PluginKit is unchanged. + Voice state queries require host 2.2.0 or later. Declare only the state the query reads, preserve unavailable observations, and use native approval for private content; see [Voice Assistant](docs/plugins/voice-control.md). General Voice Assistant tasks and managed commands retain the host executor and the user's chosen control mode. New primitives must preserve scoped app identities, cancellation, bounded work and observed-result reporting; see [computer tasks](docs/plugins/voice-computer-tasks.md). The optional in-panel confirmation companion requires host 2.2.4 or later and retains the same host admission checks. diff --git a/Plugins/IslandNotifications/Bundle/IslandNotificationsPluginBundleEntrypoint.swift b/Plugins/IslandNotifications/Bundle/IslandNotificationsPluginBundleEntrypoint.swift new file mode 100644 index 000000000..0fefa365a --- /dev/null +++ b/Plugins/IslandNotifications/Bundle/IslandNotificationsPluginBundleEntrypoint.swift @@ -0,0 +1,3 @@ +import IslandNotificationsPlugin + +private let islandNotificationsPluginFactoryAnchor: Any.Type = IslandNotificationsPluginFactory.self diff --git a/Plugins/IslandNotifications/Resources/Localizable.xcstrings b/Plugins/IslandNotifications/Resources/Localizable.xcstrings new file mode 100644 index 000000000..1b303fd37 --- /dev/null +++ b/Plugins/IslandNotifications/Resources/Localizable.xcstrings @@ -0,0 +1,2316 @@ +{ + "sourceLanguage": "zh-Hans", + "strings": { + "metadata.title": { + "extractionState": "manual", + "localizations": { + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "灵动岛通知" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Dynamic Island Notifications" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "靈動島通知" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Dynamic-Island-Mitteilungen" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Notificaciones de Dynamic Island" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Notifications Dynamic Island" + } + }, + "pt": { + "stringUnit": { + "state": "translated", + "value": "Notificações da Dynamic Island" + } + }, + "ru": { + "stringUnit": { + "state": "translated", + "value": "Уведомления Dynamic Island" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "Dynamic Island 通知" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "Dynamic Island 알림" + } + }, + "ar": { + "stringUnit": { + "state": "translated", + "value": "إشعارات Dynamic Island" + } + }, + "tr": { + "stringUnit": { + "state": "translated", + "value": "Dynamic Island Bildirimleri" + } + } + } + }, + "metadata.description": { + "extractionState": "manual", + "localizations": { + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "在灵动岛显示通知,保留通知中心历史记录。" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Show notifications at the camera island while preserving Notification Centre history." + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "在靈動島顯示通知,保留通知中心歷史記錄。" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Mitteilungen an der Kamera-Insel anzeigen und im Mitteilungszentrum behalten." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Muestra notificaciones junto a la cámara y conserva el historial del Centro de notificaciones." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Affiche les notifications près de la caméra et conserve l’historique du Centre de notifications." + } + }, + "pt": { + "stringUnit": { + "state": "translated", + "value": "Mostra notificações junto à câmara e mantém o histórico da Central de Notificações." + } + }, + "ru": { + "stringUnit": { + "state": "translated", + "value": "Показывает уведомления у камеры, сохраняя историю Центра уведомлений." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "カメラ部分に通知を表示し、通知センターの履歴を保持します。" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "카메라 영역에 알림을 표시하고 알림 센터 기록을 유지합니다." + } + }, + "ar": { + "stringUnit": { + "state": "translated", + "value": "عرض الإشعارات عند الكاميرا مع الاحتفاظ بسجل مركز الإشعارات." + } + }, + "tr": { + "stringUnit": { + "state": "translated", + "value": "Bildirimleri kamera çevresinde gösterir ve Bildirim Merkezi geçmişini korur." + } + } + } + }, + "settings.enabled": { + "extractionState": "manual", + "localizations": { + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "启用灵动岛通知" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Enable Dynamic Island notifications" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "啟用靈動島通知" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Dynamic-Island-Mitteilungen aktivieren" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Activar notificaciones de Dynamic Island" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Activer les notifications Dynamic Island" + } + }, + "pt": { + "stringUnit": { + "state": "translated", + "value": "Ativar notificações da Dynamic Island" + } + }, + "ru": { + "stringUnit": { + "state": "translated", + "value": "Включить уведомления Dynamic Island" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "Dynamic Island 通知を有効にする" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "Dynamic Island 알림 활성화" + } + }, + "ar": { + "stringUnit": { + "state": "translated", + "value": "تمكين إشعارات Dynamic Island" + } + }, + "tr": { + "stringUnit": { + "state": "translated", + "value": "Dynamic Island bildirimlerini etkinleştir" + } + } + } + }, + "settings.previewLines": { + "extractionState": "manual", + "localizations": { + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "预览行数" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Preview lines" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "預覽行數" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Vorschauzeilen" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Líneas de vista previa" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Lignes d’aperçu" + } + }, + "pt": { + "stringUnit": { + "state": "translated", + "value": "Linhas de pré-visualização" + } + }, + "ru": { + "stringUnit": { + "state": "translated", + "value": "Строк в превью" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "プレビューの行数" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "미리보기 줄 수" + } + }, + "ar": { + "stringUnit": { + "state": "translated", + "value": "أسطر المعاينة" + } + }, + "tr": { + "stringUnit": { + "state": "translated", + "value": "Önizleme satırları" + } + } + } + }, + "settings.previewLines.description": { + "extractionState": "manual", + "localizations": { + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "展开前显示的消息行数。向下滚动卡片可查看全文。" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Message lines shown before expanding. Scroll down on a card to see it all." + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "展開前顯示的訊息行數。向下捲動卡片可查看全文。" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Nachrichtenzeilen vor dem Erweitern. Auf einer Karte nach unten scrollen, um alles zu sehen." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Líneas del mensaje antes de expandir. Desplázate hacia abajo en una tarjeta para verlo todo." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Lignes du message avant développement. Faites défiler une carte vers le bas pour tout voir." + } + }, + "pt": { + "stringUnit": { + "state": "translated", + "value": "Linhas da mensagem antes de expandir. Role para baixo num cartão para ver tudo." + } + }, + "ru": { + "stringUnit": { + "state": "translated", + "value": "Строки сообщения до раскрытия. Прокрутите карточку вниз, чтобы увидеть всё." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "展開前に表示するメッセージの行数。カードを下にスクロールすると全文を表示します。" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "펼치기 전에 표시할 메시지 줄 수입니다. 카드를 아래로 스크롤하면 전체가 표시됩니다." + } + }, + "ar": { + "stringUnit": { + "state": "translated", + "value": "عدد أسطر الرسالة قبل التوسيع. مرّر لأسفل على البطاقة لعرضها كاملة." + } + }, + "tr": { + "stringUnit": { + "state": "translated", + "value": "Genişletmeden önce gösterilen ileti satırları. Tamamını görmek için kartta aşağı kaydırın." + } + } + } + }, + "status.noDisplay": { + "extractionState": "manual", + "localizations": { + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "需要配备摄像头岛的 MacBook Pro(macOS 27 或更高版本)" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Requires a MacBook Pro with the camera island (macOS 27 or later)" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "需要配備攝影機島的 MacBook Pro(macOS 27 或更新版本)" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Erfordert ein MacBook Pro mit Kamera-Insel (macOS 27 oder neuer)" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Requiere un MacBook Pro con isla de cámara (macOS 27 o posterior)" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Nécessite un MacBook Pro avec îlot de caméra (macOS 27 ou version ultérieure)" + } + }, + "pt": { + "stringUnit": { + "state": "translated", + "value": "Requer um MacBook Pro com ilha da câmara (macOS 27 ou posterior)" + } + }, + "ru": { + "stringUnit": { + "state": "translated", + "value": "Требуется MacBook Pro с островом камеры (macOS 27 или новее)" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "カメラアイランド搭載の MacBook Pro(macOS 27 以降)が必要です" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "카메라 아일랜드가 있는 MacBook Pro(macOS 27 이상)가 필요합니다" + } + }, + "ar": { + "stringUnit": { + "state": "translated", + "value": "يتطلب MacBook Pro مزودًا بجزيرة الكاميرا (macOS 27 أو أحدث)" + } + }, + "tr": { + "stringUnit": { + "state": "translated", + "value": "Kamera adası olan bir MacBook Pro gerektirir (macOS 27 veya üstü)" + } + } + } + }, + "status.enabled": { + "extractionState": "manual", + "localizations": { + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "已开启" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Enabled" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "已開啟" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Aktiviert" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Activado" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Activé" + } + }, + "pt": { + "stringUnit": { + "state": "translated", + "value": "Ativado" + } + }, + "ru": { + "stringUnit": { + "state": "translated", + "value": "Включено" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "オン" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "켜짐" + } + }, + "ar": { + "stringUnit": { + "state": "translated", + "value": "مفعّل" + } + }, + "tr": { + "stringUnit": { + "state": "translated", + "value": "Etkin" + } + } + } + }, + "status.disabled": { + "extractionState": "manual", + "localizations": { + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "已关闭" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Disabled" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "已關閉" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Deaktiviert" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Desactivado" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Désactivé" + } + }, + "pt": { + "stringUnit": { + "state": "translated", + "value": "Desativado" + } + }, + "ru": { + "stringUnit": { + "state": "translated", + "value": "Выключено" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "オフ" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "꺼짐" + } + }, + "ar": { + "stringUnit": { + "state": "translated", + "value": "معطّل" + } + }, + "tr": { + "stringUnit": { + "state": "translated", + "value": "Kapalı" + } + } + } + }, + "permission.title": { + "extractionState": "manual", + "localizations": { + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "辅助功能授权" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Accessibility Permission" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "輔助使用授權" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Bedienungshilfen erlauben" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Permiso de Accesibilidad" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Autorisation d’accessibilité" + } + }, + "pt": { + "stringUnit": { + "state": "translated", + "value": "Permissão de Acessibilidade" + } + }, + "ru": { + "stringUnit": { + "state": "translated", + "value": "Разрешение универсального доступа" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "アクセシビリティの許可" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "손쉬운 사용 권한" + } + }, + "ar": { + "stringUnit": { + "state": "translated", + "value": "إذن تسهيلات الاستخدام" + } + }, + "tr": { + "stringUnit": { + "state": "translated", + "value": "Erişilebilirlik İzni" + } + } + } + }, + "permission.description": { + "extractionState": "manual", + "localizations": { + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "用于读取和移动系统通知横幅。" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Read and move native notification banners." + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "用於讀取和移動系統通知橫幅。" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Systemmitteilungen lesen und verschieben." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Leer y mover los avisos de notificación del sistema." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Lire et déplacer les bannières de notification du système." + } + }, + "pt": { + "stringUnit": { + "state": "translated", + "value": "Ler e mover faixas de notificação do sistema." + } + }, + "ru": { + "stringUnit": { + "state": "translated", + "value": "Чтение и перемещение системных баннеров уведомлений." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "システムの通知バナーを読み取り、移動します。" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "시스템 알림 배너를 읽고 이동합니다." + } + }, + "ar": { + "stringUnit": { + "state": "translated", + "value": "قراءة لافتات إشعارات النظام ونقلها." + } + }, + "tr": { + "stringUnit": { + "state": "translated", + "value": "Sistem bildirim başlıklarını okuma ve taşıma." + } + } + } + }, + "card.close": { + "extractionState": "manual", + "localizations": { + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "关闭通知" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Dismiss notification" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "關閉通知" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Mitteilung schließen" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Cerrar notificación" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Fermer la notification" + } + }, + "pt": { + "stringUnit": { + "state": "translated", + "value": "Fechar notificação" + } + }, + "ru": { + "stringUnit": { + "state": "translated", + "value": "Закрыть уведомление" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "通知を閉じる" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "알림 닫기" + } + }, + "ar": { + "stringUnit": { + "state": "translated", + "value": "إغلاق الإشعار" + } + }, + "tr": { + "stringUnit": { + "state": "translated", + "value": "Bildirimi kapat" + } + } + } + }, + "card.expand": { + "extractionState": "manual", + "localizations": { + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "展开" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Show More" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "展開" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Mehr anzeigen" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Mostrar más" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Afficher plus" + } + }, + "pt": { + "stringUnit": { + "state": "translated", + "value": "Mostrar mais" + } + }, + "ru": { + "stringUnit": { + "state": "translated", + "value": "Показать больше" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "さらに表示" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "더 보기" + } + }, + "ar": { + "stringUnit": { + "state": "translated", + "value": "عرض المزيد" + } + }, + "tr": { + "stringUnit": { + "state": "translated", + "value": "Daha fazla göster" + } + } + } + }, + "card.collapse": { + "extractionState": "manual", + "localizations": { + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "收起" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Show Less" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "收起" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Weniger anzeigen" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Mostrar menos" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Afficher moins" + } + }, + "pt": { + "stringUnit": { + "state": "translated", + "value": "Mostrar menos" + } + }, + "ru": { + "stringUnit": { + "state": "translated", + "value": "Показать меньше" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "表示を減らす" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "간단히 보기" + } + }, + "ar": { + "stringUnit": { + "state": "translated", + "value": "عرض أقل" + } + }, + "tr": { + "stringUnit": { + "state": "translated", + "value": "Daha az göster" + } + } + } + }, + "reply.placeholder": { + "extractionState": "manual", + "localizations": { + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "信息" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Message" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "訊息" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Nachricht" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Mensaje" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Message" + } + }, + "pt": { + "stringUnit": { + "state": "translated", + "value": "Mensagem" + } + }, + "ru": { + "stringUnit": { + "state": "translated", + "value": "Сообщение" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "メッセージ" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "메시지" + } + }, + "ar": { + "stringUnit": { + "state": "translated", + "value": "رسالة" + } + }, + "tr": { + "stringUnit": { + "state": "translated", + "value": "Mesaj" + } + } + } + }, + "reply.send": { + "extractionState": "manual", + "localizations": { + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "发送" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Send" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "傳送" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Senden" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Enviar" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Envoyer" + } + }, + "pt": { + "stringUnit": { + "state": "translated", + "value": "Enviar" + } + }, + "ru": { + "stringUnit": { + "state": "translated", + "value": "Отправить" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "送信" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "보내기" + } + }, + "ar": { + "stringUnit": { + "state": "translated", + "value": "إرسال" + } + }, + "tr": { + "stringUnit": { + "state": "translated", + "value": "Gönder" + } + } + } + }, + "reply.sent": { + "extractionState": "manual", + "localizations": { + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "已发送" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Sent" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "已傳送" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Gesendet" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Enviado" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Envoyé" + } + }, + "pt": { + "stringUnit": { + "state": "translated", + "value": "Enviado" + } + }, + "ru": { + "stringUnit": { + "state": "translated", + "value": "Отправлено" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "送信済み" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "보냄" + } + }, + "ar": { + "stringUnit": { + "state": "translated", + "value": "تم الإرسال" + } + }, + "tr": { + "stringUnit": { + "state": "translated", + "value": "Gönderildi" + } + } + } + }, + "reply.error.conversation": { + "extractionState": "manual", + "localizations": { + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "找不到这个对话。点按卡片以打开“信息”。" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Couldn’t find this conversation. Click the card to open Messages." + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "找不到這個對話。點按卡片以打開「訊息」。" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Konversation nicht gefunden. Klicke auf die Karte, um Nachrichten zu öffnen." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "No se encontró esta conversación. Haz clic en la tarjeta para abrir Mensajes." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Conversation introuvable. Cliquez sur la carte pour ouvrir Messages." + } + }, + "pt": { + "stringUnit": { + "state": "translated", + "value": "Conversa não encontrada. Clique no cartão para abrir o Mensagens." + } + }, + "ru": { + "stringUnit": { + "state": "translated", + "value": "Беседа не найдена. Нажмите на карточку, чтобы открыть «Сообщения»." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "この会話が見つかりません。カードをクリックしてメッセージを開きます。" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "이 대화를 찾을 수 없습니다. 카드를 클릭해 메시지를 여세요." + } + }, + "ar": { + "stringUnit": { + "state": "translated", + "value": "تعذر العثور على هذه المحادثة. انقر على البطاقة لفتح الرسائل." + } + }, + "tr": { + "stringUnit": { + "state": "translated", + "value": "Bu konuşma bulunamadı. Mesajlar’ı açmak için karta tıklayın." + } + } + } + }, + "reply.error.permission": { + "extractionState": "manual", + "localizations": { + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "请在“隐私与安全性 > 自动化”中允许 MacTools 控制“信息”。" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Allow MacTools to control Messages in Privacy & Security > Automation." + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "請在「隱私權與安全性 > 自動化」中允許 MacTools 控制「訊息」。" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Erlaube MacTools unter Datenschutz & Sicherheit > Automation, Nachrichten zu steuern." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Permite que MacTools controle Mensajes en Privacidad y seguridad > Automatización." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Autorisez MacTools à contrôler Messages dans Confidentialité et sécurité > Automatisation." + } + }, + "pt": { + "stringUnit": { + "state": "translated", + "value": "Permita que o MacTools controle o Mensagens em Privacidade e Segurança > Automação." + } + }, + "ru": { + "stringUnit": { + "state": "translated", + "value": "Разрешите MacTools управлять «Сообщениями» в разделе «Конфиденциальность и безопасность» > «Автоматизация»." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "「プライバシーとセキュリティ」>「オートメーション」で MacTools にメッセージの制御を許可してください。" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "개인정보 보호 및 보안 > 자동화에서 MacTools가 메시지를 제어하도록 허용하세요." + } + }, + "ar": { + "stringUnit": { + "state": "translated", + "value": "اسمح لـ MacTools بالتحكم في الرسائل من الخصوصية والأمن > الأتمتة." + } + }, + "tr": { + "stringUnit": { + "state": "translated", + "value": "Gizlilik ve Güvenlik > Otomasyon’da MacTools’un Mesajlar’ı denetlemesine izin verin." + } + } + } + }, + "reply.error.failed": { + "extractionState": "manual", + "localizations": { + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "无法发送。点按卡片以打开应用。" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Couldn’t send. Click the card to open the app." + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "無法傳送。點按卡片以打開 App。" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Senden fehlgeschlagen. Klicke auf die Karte, um die App zu öffnen." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "No se pudo enviar. Haz clic en la tarjeta para abrir la app." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Envoi impossible. Cliquez sur la carte pour ouvrir l’app." + } + }, + "pt": { + "stringUnit": { + "state": "translated", + "value": "Não foi possível enviar. Clique no cartão para abrir a app." + } + }, + "ru": { + "stringUnit": { + "state": "translated", + "value": "Не удалось отправить. Нажмите на карточку, чтобы открыть приложение." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "送信できませんでした。カードをクリックしてアプリを開きます。" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "보낼 수 없습니다. 카드를 클릭해 앱을 여세요." + } + }, + "ar": { + "stringUnit": { + "state": "translated", + "value": "تعذر الإرسال. انقر على البطاقة لفتح التطبيق." + } + }, + "tr": { + "stringUnit": { + "state": "translated", + "value": "Gönderilemedi. Uygulamayı açmak için karta tıklayın." + } + } + } + }, + "reply.error.claudeDraft": { + "extractionState": "manual", + "localizations": { + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "这个对话在 Claude 中有未发送的文字。点按卡片以打开。" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "That chat has unsent text in Claude. Click the card to open it." + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "這個對話在 Claude 中有未傳送的文字。點按卡片以打開。" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Dieser Chat hat ungesendeten Text in Claude. Klicke auf die Karte, um ihn zu öffnen." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Ese chat tiene texto sin enviar en Claude. Haz clic en la tarjeta para abrirlo." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Cette conversation contient du texte non envoyé dans Claude. Cliquez sur la carte pour l’ouvrir." + } + }, + "pt": { + "stringUnit": { + "state": "translated", + "value": "Essa conversa tem texto por enviar no Claude. Clique no cartão para a abrir." + } + }, + "ru": { + "stringUnit": { + "state": "translated", + "value": "В этом чате Claude есть неотправленный текст. Нажмите на карточку, чтобы открыть его." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "このチャットには Claude で未送信のテキストがあります。カードをクリックして開きます。" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "이 채팅에 Claude에서 보내지 않은 텍스트가 있습니다. 카드를 클릭해 여세요." + } + }, + "ar": { + "stringUnit": { + "state": "translated", + "value": "تحتوي هذه الدردشة على نص غير مُرسل في Claude. انقر على البطاقة لفتحها." + } + }, + "tr": { + "stringUnit": { + "state": "translated", + "value": "Bu sohbette Claude’da gönderilmemiş metin var. Açmak için karta tıklayın." + } + } + } + }, + "reply.error.duplicateChat": { + "extractionState": "manual", + "localizations": { + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "有多个 Claude 对话使用这个名称。点按卡片以打开 Claude。" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "More than one Claude chat has this name. Click the card to open Claude." + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "有多個 Claude 對話使用這個名稱。點按卡片以打開 Claude。" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Mehrere Claude-Chats haben diesen Namen. Klicke auf die Karte, um Claude zu öffnen." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Hay más de un chat de Claude con este nombre. Haz clic en la tarjeta para abrir Claude." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Plusieurs conversations Claude portent ce nom. Cliquez sur la carte pour ouvrir Claude." + } + }, + "pt": { + "stringUnit": { + "state": "translated", + "value": "Há mais de uma conversa do Claude com este nome. Clique no cartão para abrir o Claude." + } + }, + "ru": { + "stringUnit": { + "state": "translated", + "value": "Несколько чатов Claude называются так же. Нажмите на карточку, чтобы открыть Claude." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "この名前の Claude チャットが複数あります。カードをクリックして Claude を開きます。" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "이 이름의 Claude 채팅이 여러 개 있습니다. 카드를 클릭해 Claude를 여세요." + } + }, + "ar": { + "stringUnit": { + "state": "translated", + "value": "هناك أكثر من دردشة Claude بهذا الاسم. انقر على البطاقة لفتح Claude." + } + }, + "tr": { + "stringUnit": { + "state": "translated", + "value": "Bu ada sahip birden fazla Claude sohbeti var. Claude’u açmak için karta tıklayın." + } + } + } + }, + "card.open": { + "extractionState": "manual", + "localizations": { + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "打开通知" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Open notification" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "打開通知" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Mitteilung öffnen" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Abrir notificación" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Ouvrir la notification" + } + }, + "pt": { + "stringUnit": { + "state": "translated", + "value": "Abrir notificação" + } + }, + "ru": { + "stringUnit": { + "state": "translated", + "value": "Открыть уведомление" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "通知を開く" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "알림 열기" + } + }, + "ar": { + "stringUnit": { + "state": "translated", + "value": "فتح الإشعار" + } + }, + "tr": { + "stringUnit": { + "state": "translated", + "value": "Bildirimi aç" + } + } + } + }, + "card.waiting": { + "extractionState": "manual", + "localizations": { + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "还有 %@ 条通知" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "%@ more waiting" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "還有 %@ 則通知" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "%@ weitere warten" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "%@ más en espera" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "%@ autres en attente" + } + }, + "pt": { + "stringUnit": { + "state": "translated", + "value": "%@ mais em espera" + } + }, + "ru": { + "stringUnit": { + "state": "translated", + "value": "Ещё в очереди: %@" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "ほか %@ 件待機中" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "%@개 더 대기 중" + } + }, + "ar": { + "stringUnit": { + "state": "translated", + "value": "%@ أخرى قيد الانتظار" + } + }, + "tr": { + "stringUnit": { + "state": "translated", + "value": "%@ bildirim daha bekliyor" + } + } + } + }, + "history.title": { + "extractionState": "manual", + "localizations": { + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "通知" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Notifications" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "通知" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Mitteilungen" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Notificaciones" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Notifications" + } + }, + "pt": { + "stringUnit": { + "state": "translated", + "value": "Notificações" + } + }, + "ru": { + "stringUnit": { + "state": "translated", + "value": "Уведомления" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "通知" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "알림" + } + }, + "ar": { + "stringUnit": { + "state": "translated", + "value": "الإشعارات" + } + }, + "tr": { + "stringUnit": { + "state": "translated", + "value": "Bildirimler" + } + } + } + }, + "history.empty": { + "extractionState": "manual", + "localizations": { + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "没有通知" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "No Notifications" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "沒有通知" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Keine Mitteilungen" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "No hay notificaciones" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Aucune notification" + } + }, + "pt": { + "stringUnit": { + "state": "translated", + "value": "Sem notificações" + } + }, + "ru": { + "stringUnit": { + "state": "translated", + "value": "Нет уведомлений" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "通知はありません" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "알림 없음" + } + }, + "ar": { + "stringUnit": { + "state": "translated", + "value": "لا توجد إشعارات" + } + }, + "tr": { + "stringUnit": { + "state": "translated", + "value": "Bildirim Yok" + } + } + } + }, + "history.showLess": { + "extractionState": "manual", + "localizations": { + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "收起" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Show Less" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "顯示較少" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Weniger anzeigen" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Mostrar menos" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Afficher moins" + } + }, + "pt": { + "stringUnit": { + "state": "translated", + "value": "Mostrar menos" + } + }, + "ru": { + "stringUnit": { + "state": "translated", + "value": "Свернуть" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "表示を減らす" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "간단히 보기" + } + }, + "ar": { + "stringUnit": { + "state": "translated", + "value": "عرض أقل" + } + }, + "tr": { + "stringUnit": { + "state": "translated", + "value": "Daha Az Göster" + } + } + } + }, + "history.clearAll": { + "extractionState": "manual", + "localizations": { + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "全部清除" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Clear All" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "全部清除" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Alle löschen" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Borrar todo" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Tout effacer" + } + }, + "pt": { + "stringUnit": { + "state": "translated", + "value": "Limpar tudo" + } + }, + "ru": { + "stringUnit": { + "state": "translated", + "value": "Очистить все" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "すべて消去" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "모두 지우기" + } + }, + "ar": { + "stringUnit": { + "state": "translated", + "value": "مسح الكل" + } + }, + "tr": { + "stringUnit": { + "state": "translated", + "value": "Tümünü Temizle" + } + } + } + }, + "history.close": { + "extractionState": "manual", + "localizations": { + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "关闭" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Close" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "關閉" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Schließen" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Cerrar" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Fermer" + } + }, + "pt": { + "stringUnit": { + "state": "translated", + "value": "Fechar" + } + }, + "ru": { + "stringUnit": { + "state": "translated", + "value": "Закрыть" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "閉じる" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "닫기" + } + }, + "ar": { + "stringUnit": { + "state": "translated", + "value": "إغلاق" + } + }, + "tr": { + "stringUnit": { + "state": "translated", + "value": "Kapat" + } + } + } + }, + "history.now": { + "extractionState": "manual", + "localizations": { + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "现在" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "now" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "現在" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "jetzt" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "ahora" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "maintenant" + } + }, + "pt": { + "stringUnit": { + "state": "translated", + "value": "agora" + } + }, + "ru": { + "stringUnit": { + "state": "translated", + "value": "сейчас" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "今" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "지금" + } + }, + "ar": { + "stringUnit": { + "state": "translated", + "value": "الآن" + } + }, + "tr": { + "stringUnit": { + "state": "translated", + "value": "şimdi" + } + } + } + }, + "history.ago": { + "extractionState": "manual", + "localizations": { + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "%@前" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "%@ ago" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "%@前" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "vor %@" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "hace %@" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "il y a %@" + } + }, + "pt": { + "stringUnit": { + "state": "translated", + "value": "há %@" + } + }, + "ru": { + "stringUnit": { + "state": "translated", + "value": "%@ назад" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "%@前" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "%@ 전" + } + }, + "ar": { + "stringUnit": { + "state": "translated", + "value": "قبل %@" + } + }, + "tr": { + "stringUnit": { + "state": "translated", + "value": "%@ önce" + } + } + } + } + }, + "version": "1.0" +} \ No newline at end of file diff --git a/Plugins/IslandNotifications/Sources/IslandCenterPress.swift b/Plugins/IslandNotifications/Sources/IslandCenterPress.swift new file mode 100644 index 000000000..23747610b --- /dev/null +++ b/Plugins/IslandNotifications/Sources/IslandCenterPress.swift @@ -0,0 +1,192 @@ +import AppKit +import ApplicationServices +import OSLog + +/// Opens or clears a notification the way a click in Notification Centre does, without showing +/// Notification Centre. Only Notification Centre can hand an app the notification it posted, which +/// is how Mail, Spark and the rest open the exact item; once a banner has gone, its row there is the +/// only way in. +/// +/// Notification Centre opens through its own accessibility action (the one VoiceOver uses). Its +/// window appears about 70 ms later, before its panel starts sliding in, and moves off screen as it +/// appears, so nothing is seen. Its rows stay pressable off screen. macOS makes a new window every +/// time it opens, so nothing needs putting back. +/// +/// The whole press runs on a short-lived thread of its own, whose run loop also receives the window +/// notification: Accessibility calls to Notification Centre never wait on the main thread, and every +/// one of them is bounded by a messaging timeout. +enum IslandCenterPress { + enum Action: Sendable { case open, clear } + + struct Target: Sendable { + let app: String + let title: String + let body: String + } + + private static let logger = Logger(subsystem: "MacTools.IslandNotifications", category: "center") + private static let bundleIdentifier = "com.apple.notificationcenterui" + private static let timeout: Float = 0.3 + + /// True when Notification Centre had the notification and acted on it. + @MainActor + static func perform(_ action: Action, on target: Target) async -> Bool { + guard AXIsProcessTrusted(), + let pid = NSRunningApplication.runningApplications(withBundleIdentifier: bundleIdentifier).first?.processIdentifier + else { return false } + // Screens are AppKit state, so where the window goes is worked out here. + let minX = NSScreen.screens.map(\.frame.minX).min() ?? 0 + let offscreen = CGPoint(x: minX - 100_000, y: -100_000) + return await withCheckedContinuation { continuation in + let thread = Thread { + continuation.resume(returning: run(action, target: target, pid: pid, offscreen: offscreen)) + } + thread.name = "MacTools.IslandNotifications.center" + thread.qualityOfService = .userInitiated + thread.start() + } + } + + /// Moves Notification Centre's new window off screen. Lives on the press thread only. + fileprivate final class WindowMover: @unchecked Sendable { + let offscreen: CGPoint + var moved = false + init(offscreen: CGPoint) { self.offscreen = offscreen } + } + + /// The press itself, on its own thread. + private static func run(_ action: Action, target: Target, pid: pid_t, offscreen: CGPoint) -> Bool { + let application = AXUIElementCreateApplication(pid) + AXUIElementSetMessagingTimeout(application, timeout) + let wasOpen = value(application, "AXExpanded") as? Bool == true + let mover = WindowMover(offscreen: offscreen) + let runLoop = CFRunLoopGetCurrent() + var observer: AXObserver? + if !wasOpen { + // Without the observer the window could not be hidden in time: leave Notification Centre shut. + guard AXObserverCreate(pid, islandCenterWindowCreated, &observer) == .success, let observer, + AXObserverAddNotification(observer, application, kAXWindowCreatedNotification as CFString, + Unmanaged.passUnretained(mover).toOpaque()) == .success + else { logger.error("Could not watch Notification Centre"); return false } + CFRunLoopAddSource(runLoop, AXObserverGetRunLoopSource(observer), .defaultMode) + } + defer { + if let observer { + AXObserverRemoveNotification(observer, application, kAXWindowCreatedNotification as CFString) + CFRunLoopRemoveSource(runLoop, AXObserverGetRunLoopSource(observer), .defaultMode) + } + withExtendedLifetime(mover) {} + } + let started = ProcessInfo.processInfo.systemUptime + if !wasOpen { + // The action reports an error although it opens the centre, so the window is what counts. + _ = AXUIElementPerformAction(application, "AXToggleUI" as CFString) + // Nothing is read until the window is off screen; if it never moves, the centre closes again. + while !mover.moved, ProcessInfo.processInfo.systemUptime - started < 0.5 { + CFRunLoopRunInMode(.defaultMode, 0.01, false) + } + guard mover.moved else { + logger.error("Notification Centre's window did not move off screen") + _ = AXUIElementPerformAction(application, "AXCloseNotificationCenter" as CFString) + return false + } + } + let names: Set = action == .open ? [kAXPressAction as String] : IslandAX.centerAction("Close") + let done = findRow(application, target: target).map { perform(anyOf: names, on: $0) } ?? false + let elapsed = Int((ProcessInfo.processInfo.systemUptime - started) * 1000) + logger.notice("center \(action == .open ? "open" : "clear", privacy: .public) found=\(done, privacy: .public) ms=\(elapsed, privacy: .public) wasOpen=\(wasOpen, privacy: .public)") + guard !wasOpen else { return done } + // A press closes the centre itself; anything else leaves it shut, as it was found. + if !(done && action == .open) { + _ = AXUIElementPerformAction(application, "AXCloseNotificationCenter" as CFString) + } + // Return once it has closed, so its closing isn't taken for the user opening it. + for _ in 0..<20 where value(application, "AXExpanded") as? Bool == true { + CFRunLoopRunInMode(.defaultMode, 0.05, false) + } + return done + } + + /// Waits for the centre's rows, then the notification: a single row, or inside its app's stack, + /// which a press expands as it does on screen. + private static func findRow(_ application: AXUIElement, target: Target) -> AXUIElement? { + // Rows before the stack was pressed; nil until then. + var before: Int? + let deadline = ProcessInfo.processInfo.systemUptime + 1.5 + while ProcessInfo.processInfo.systemUptime < deadline { + let rows = rows(application) + if let row = rows.first(where: { $0.single && IslandCenterMatch.row($0.description, matchesApp: target.app, + title: target.title, body: target.body) }) { + return row.element + } + if let before { + // The stack opened and the notification isn't in it. + if rows.count != before { return nil } + } else if !rows.isEmpty { + guard let stack = rows.first(where: { !$0.single && IslandCenterMatch.stack($0.description, isApp: target.app) }), + perform(anyOf: [kAXPressAction as String], on: stack.element) else { return nil } + before = rows.count + } + CFRunLoopRunInMode(.defaultMode, 0.04, false) + } + return nil + } + + private struct Row { + let element: AXUIElement + let description: String + let single: Bool + } + + private static func rows(_ application: AXUIElement) -> [Row] { + guard let window = (value(application, kAXWindowsAttribute as String) as? [AXUIElement])?.first else { return [] } + var found: [Row] = [] + var budget = 600 + func walk(_ element: AXUIElement, depth: Int) { + budget -= 1 + guard budget > 0, depth < 14 else { return } + let subrole = value(element, kAXSubroleAttribute as String) as? String ?? "" + let description = { value(element, kAXDescriptionAttribute as String) as? String ?? "" } + if IslandNotificationStyle(subrole: subrole) != nil { + found.append(Row(element: element, description: description(), single: true)) + return + } + if IslandNotificationStyle(stackSubrole: subrole) != nil { + found.append(Row(element: element, description: description(), single: false)) + } + for child in value(element, kAXChildrenAttribute as String) as? [AXUIElement] ?? [] { walk(child, depth: depth + 1) } + } + walk(window, depth: 0) + return found + } + + /// An attribute, waiting at most `timeout` for Notification Centre to answer. + private static func value(_ element: AXUIElement, _ attribute: String) -> CFTypeRef? { + AXUIElementSetMessagingTimeout(element, timeout) + var result: CFTypeRef? + guard AXUIElementCopyAttributeValue(element, attribute as CFString, &result) == .success else { return nil } + return result + } + + /// Performs the first action named in `names` (a custom action reads "Name:\n…"). + private static func perform(anyOf names: Set, on element: AXUIElement) -> Bool { + AXUIElementSetMessagingTimeout(element, timeout) + var raw: CFArray? + guard AXUIElementCopyActionNames(element, &raw) == .success, let actions = raw as? [String], + let action = actions.first(where: { action in + names.contains(action) || names.contains { action.hasPrefix("Name:\($0)\n") } + }) else { return false } + return AXUIElementPerformAction(element, action as CFString) == .success + } +} + +/// Notification Centre's window appeared: off screen at once, before its panel draws. Runs on the +/// press thread's run loop; `context` is that press's WindowMover. +private func islandCenterWindowCreated(_ observer: AXObserver, _ element: AXUIElement, _ notification: CFString, + _ context: UnsafeMutableRawPointer?) { + guard let context else { return } + let mover = Unmanaged.fromOpaque(context).takeUnretainedValue() + var point = mover.offscreen + guard let value = AXValueCreate(.cgPoint, &point) else { return } + if AXUIElementSetAttributeValue(element, kAXPositionAttribute as CFString, value) == .success { mover.moved = true } +} diff --git a/Plugins/IslandNotifications/Sources/IslandLiveActivityGeometry.swift b/Plugins/IslandNotifications/Sources/IslandLiveActivityGeometry.swift new file mode 100644 index 000000000..431d6a097 --- /dev/null +++ b/Plugins/IslandNotifications/Sources/IslandLiveActivityGeometry.swift @@ -0,0 +1,128 @@ +import CoreGraphics + +/// All frames here use AppKit's desktop coordinates, except at the AX conversion boundary. +enum IslandLiveActivityPlacement: Equatable { + case camera + case split(CGRect) + case native + + static func resolve(axFrames: [CGRect?], complete: Bool, desktopTop: CGFloat, + screen: CGRect, anchor: CGRect) -> Self { + evaluate(axFrames: axFrames, complete: complete, desktopTop: desktopTop, screen: screen, anchor: anchor).placement + } + + static func evaluate(axFrames: [CGRect?], complete: Bool, desktopTop: CGFloat, + screen: CGRect, anchor: CGRect) -> (placement: Self, reason: String) { + guard complete else { return (.native, "incomplete-ax-tree") } + guard desktopTop.isFinite else { return (.native, "invalid-primary-screen-height") } + var activities: [CGRect] = [] + for raw in axFrames { + guard let raw, raw.origin.x.isFinite, raw.origin.y.isFinite, + raw.width.isFinite, raw.height.isFinite, raw.width > 0, raw.height > 0 else { return (.native, "unreadable-or-invalid-activity-frame") } + let frame = CGRect(x: raw.minX, y: desktopTop - raw.maxY, width: raw.width, height: raw.height) + guard frame.intersects(screen) else { continue } + // Only the island at the camera can be an attachment. Expanded activities + // and unexpected positions must not strand a native banner off screen. + guard frame.height <= 60, frame.width <= screen.width * 0.8 else { return (.native, "expanded-activity") } + guard screen.contains(frame), + frame.minY >= anchor.minY - 60, frame.maxY <= screen.maxY, + abs(frame.midX - anchor.midX) <= screen.width * 0.25 else { return (.native, "activity-outside-camera-region") } + activities.append(frame) + } + guard let first = activities.first else { return (.camera, "no-visible-activity-on-screen") } + let union = activities.dropFirst().reduce(first) { $0.union($1) } + guard union.height <= 60, union.width <= screen.width * 0.8 else { return (.native, "expanded-activity-envelope") } + // Use an actual capsule, never an envelope across separate activities: + // an envelope would paint visible black into the system's gaps at rest. + // The lowest capsule keeps the destination below every visible activity. + let attachment = activities.min { + if $0.minY != $1.minY { return $0.minY < $1.minY } + return abs($0.midX - anchor.midX) < abs($1.midX - anchor.midX) + } ?? first + return (.split(attachment), "compact-live-activity") + } +} + +struct IslandSplitGeometry { + static let gap: CGFloat = 6 + static let margin: CGFloat = 28 + let activity: CGRect + let expandedSize: CGSize + /// Matches camera mode: one-line cards stay a pill, longer cards relax to the expanded radius. + var staysPill = true + /// See `NotchMorphMetrics.pillAmount`. + var pillAmount: Double = 0 + + func radius(for rect: CGRect, heightFraction: Double) -> CGFloat { + let pill = min(rect.width, rect.height) / 2 + guard !staysPill else { return pill } + let settle = NotchMorphModel.smoothstep(0.12, 1, heightFraction) + let radius = min(NotchMorphMetrics.lerp(pill, NotchMorphMetrics.expandedCornerRadius, settle), pill) + return pillAmount > 0 ? NotchMorphMetrics.lerp(radius, pill, min(pillAmount, 1)) : radius + } + + var windowFrame: CGRect { + let width = max(activity.width, expandedSize.width) + Self.margin * 2 + let height = activity.height + Self.gap + expandedSize.height + Self.margin * 2 + return CGRect(x: activity.midX - width / 2, y: activity.maxY + Self.margin - height, + width: width, height: height) + } + + var source: CGRect { activity.offsetBy(dx: -windowFrame.minX, dy: -windowFrame.minY) } + var destination: CGRect { + CGRect(x: source.midX - expandedSize.width / 2, y: source.minY - Self.gap - expandedSize.height, + width: expandedSize.width, height: expandedSize.height) + } + + func capsule(widthFraction: Double, heightFraction: Double) -> CGRect { + let h = max(0, heightFraction) + // Move the top ahead of the growing height so a visible neck stretches + // before detachment. The spring's small overshoot survives at the endpoint. + let travel = h + 0.35 * sin(.pi * min(h, 1)) + // Widen only as the capsule travels out from under the system pill, so it never + // shows black "ears" beside the music island while still overlapping it. + let width = max(2, NotchMorphMetrics.lerp(source.width, destination.width, min(widthFraction, h))) + let height = max(2, NotchMorphMetrics.lerp(source.height, destination.height, h)) + let top = NotchMorphMetrics.lerp(source.maxY, destination.maxY, travel) + return CGRect(x: source.midX - width / 2, y: top - height, width: width, height: height) + } + + func neckWidth(heightFraction: Double, reduceMotion: Bool) -> CGFloat { + guard !reduceMotion else { return 0 } + return min(source.width * 0.34, expandedSize.width * 0.2) + * CGFloat(1 - NotchMorphModel.smoothstep(0.5, 0.94, heightFraction)) + } + + func path(widthFraction: Double, heightFraction: Double, reduceMotion: Bool = false) -> CGPath { + let lower = reduceMotion ? destination : capsule(widthFraction: widthFraction, heightFraction: heightFraction) + let path = CGMutablePath() + path.addPath(NotchSurfacePath.make(in: lower, radius: radius(for: lower, heightFraction: reduceMotion ? 1 : heightFraction))) + // The hidden copy of the system pill is only needed while the neck attaches the card. + // Dropping it once detached avoids a stray black capsule if the system island changes. + guard !reduceMotion, heightFraction < 0.97 else { return path } + // This capsule is occluded by the system island, including at both endpoints. + path.addPath(NotchSurfacePath.make(in: source, radius: min(source.width, source.height) / 2)) + let width = neckWidth(heightFraction: heightFraction, reduceMotion: false) + guard width > 0.01, lower.maxY < source.minY else { return path } + let x = source.midX + let top = source.minY + 0.5, bottom = lower.maxY - 0.5 + let mid = (top + bottom) / 2 + let shoulder = min(max(source.width / 2 - source.height / 2, source.width * 0.15), width * 0.9) + let waist = width * 0.18 + // Clockwise contour, matching the capsules' winding: concave sides + // tighten to zero, then disappear. Dismissal traverses the same geometry. + path.move(to: CGPoint(x: x - shoulder, y: top)) + path.addLine(to: CGPoint(x: x + shoulder, y: top)) + path.addCurve(to: CGPoint(x: x + waist, y: mid), + control1: CGPoint(x: x + waist, y: top), control2: CGPoint(x: x + waist, y: top)) + path.addCurve(to: CGPoint(x: x + shoulder, y: bottom), + control1: CGPoint(x: x + waist, y: bottom), control2: CGPoint(x: x + waist, y: bottom)) + path.addLine(to: CGPoint(x: x - shoulder, y: bottom)) + path.addCurve(to: CGPoint(x: x - waist, y: mid), + control1: CGPoint(x: x - waist, y: bottom), control2: CGPoint(x: x - waist, y: bottom)) + path.addCurve(to: CGPoint(x: x - shoulder, y: top), + control1: CGPoint(x: x - waist, y: top), control2: CGPoint(x: x - waist, y: top)) + path.closeSubpath() + return path + } +} diff --git a/Plugins/IslandNotifications/Sources/IslandLiveActivityObserver.swift b/Plugins/IslandNotifications/Sources/IslandLiveActivityObserver.swift new file mode 100644 index 000000000..9c256c0fc --- /dev/null +++ b/Plugins/IslandNotifications/Sources/IslandLiveActivityObserver.swift @@ -0,0 +1,229 @@ +import AppKit +import ApplicationServices +import OSLog + +private final class IslandActivitySession: @unchecked Sendable { + let pid: pid_t + let application: AXUIElement + let observer: AXObserver? + var observed: [AXUIElement] = [] + init(pid: pid_t, application: AXUIElement, observer: AXObserver?) { + self.pid = pid; self.application = application; self.observer = observer + } +} + +/// Notifications are best effort: some macOS versions do not publish layout +/// changes. Every incoming banner and queued presentation also reads on demand. +@MainActor +final class IslandLiveActivityObserver { + var onChange: (() -> Void)? + private var session: IslandActivitySession? + private var generation = 0 + private var reading: Task? + private var change: DispatchWorkItem? + nonisolated private static let logger = Logger(subsystem: "MacTools.IslandNotifications", category: "liveactivity") + nonisolated private static let messagingTimeout: Float = 0.2 + + nonisolated static func isMenuBarAgent(_ app: NSRunningApplication) -> Bool { + app.executableURL?.lastPathComponent == "MenuBarAgent" || app.localizedName == "MenuBarAgent" || + app.bundleURL?.lastPathComponent == "MenuBarAgent.app" + } + + func refresh(anchor: CGRect) async -> IslandLiveActivityPlacement { + guard let app = NSWorkspace.shared.runningApplications.first(where: Self.isMenuBarAgent) else { + Self.logger.debug("appFound=false decision=native reason=menubaragent-not-found") + return .native + } + Self.logger.debug("appFound=true pid=\(app.processIdentifier, privacy: .public)") + guard let screen = NSScreen.screens.first(where: { $0.frame.contains(anchor) }), + let desktopTop = NSScreen.screens.first?.frame.maxY else { + Self.logger.debug("decision=native reason=anchor-screen-not-found") + return .native + } + let screenFrame = screen.frame + let pid = app.processIdentifier + if let reading { return await reading.value } + if session?.pid != pid { stop() } + let revision = generation + let task = Task { await read(pid: pid, screen: screenFrame, desktopTop: desktopTop, anchor: anchor) } + reading = task + let result = await task.value + if generation == revision { reading = nil } + return result + } + + private func read(pid: pid_t, screen: CGRect, desktopTop: CGFloat, anchor: CGRect) async -> IslandLiveActivityPlacement { + let currentGeneration = generation + let context = UInt(bitPattern: Unmanaged.passUnretained(self).toOpaque()) + let existing = session + let result = await IslandAX.run { () -> (IslandActivitySession, [CGRect?], Bool) in + let active: IslandActivitySession + if let existing { active = existing } + else { + let application = AXUIElementCreateApplication(pid) + _ = IslandAX.setMessagingTimeout(application, timeout: Self.messagingTimeout) + var observer: AXObserver? + _ = AXObserverCreate(pid, islandActivityCallback, &observer) + active = IslandActivitySession(pid: pid, application: application, observer: observer) + } + // Replace element subscriptions rather than retaining stale AX handles. + if let observer = active.observer { + for element in active.observed { + for name in Self.notifications { + AXObserverRemoveNotification(observer, element, name as CFString) + } + } + } + active.observed = [active.application] + var frames: [CGRect?] = [] + var complete = true + var budget = 250 + // Every helper otherwise resets the element timeout to 0.05 seconds. + // Scope the probe's 0.2-second allowance to MenuBarAgent on the AX executor. + @IslandAXExecutor func value(_ element: AXUIElement, _ attribute: String) -> CFTypeRef? { + IslandAX.value(element, attribute, timeout: Self.messagingTimeout) + } + @IslandAXExecutor func walk(_ element: AXUIElement, depth: Int) { + guard complete else { return } + guard budget > 0, depth < 16 else { + Self.logger.debug("scanIncomplete reason=traversal-limit depth=\(depth, privacy: .public)") + complete = false; return + } + budget -= 1 + guard let role = value(element, kAXRoleAttribute) as? String else { + Self.logger.debug("scanIncomplete reason=role-unreadable depth=\(depth, privacy: .public)") + complete = false; return + } + // AXUnknown windows and missing structural subroles are valid wrappers. + let subrole = value(element, kAXSubroleAttribute) as? String ?? "" + if depth <= 1 || subrole == "AXLiveActivity" { + Self.logger.debug("item depth=\(depth, privacy: .public) role=\(role, privacy: .public) subrole=\(subrole, privacy: .public)") + } + if subrole == "AXLiveActivity" { + if (value(element, "AXHidden") as? Bool) == true { + Self.logger.debug("activity hidden=true") + return + } + active.observed.append(element) + guard let point = IslandAX.position(element, timeout: Self.messagingTimeout), + let raw = value(element, kAXSizeAttribute), CFGetTypeID(raw) == AXValueGetTypeID() else { + Self.logger.debug("activity frame=unreadable") + frames.append(nil); return + } + let value = unsafeDowncast(raw, to: AXValue.self) + var size = CGSize.zero + guard AXValueGetType(value) == .cgSize, AXValueGetValue(value, .cgSize, &size) else { + Self.logger.debug("activity frame=invalid-size") + frames.append(nil); return + } + frames.append(CGRect(origin: point, size: size)) + Self.logger.debug("activity AXFrame x=\(point.x, privacy: .public) y=\(point.y, privacy: .public) width=\(size.width, privacy: .public) height=\(size.height, privacy: .public)") + return + } + visitChildren(element, depth: depth) + } + @IslandAXExecutor func visitChildren(_ element: AXUIElement, depth: Int) { + guard let children = IslandAX.children(element, timeout: Self.messagingTimeout) else { + Self.logger.debug("scanIncomplete reason=children-unreadable depth=\(depth, privacy: .public)") + complete = false; return + } + for child in children { walk(child, depth: depth + 1) } + } + if let windows = value(active.application, kAXWindowsAttribute) as? [AXUIElement] { + Self.logger.debug("windows=\(windows.count, privacy: .public) timeout=0.2") + // Live Activities live only in MenuBarAgent's full-screen AXUnknown host window. Its other + // windows (e.g. an AXDialog of groups) are unrelated and may contain unreadable elements, + // which must not veto the decision. + for window in windows where (value(window, kAXSubroleAttribute) as? String) == "AXUnknown" { + active.observed.append(window) + walk(window, depth: 0) + } + } else { + Self.logger.debug("scanIncomplete reason=windows-unreadable timeout=0.2") + complete = false + } + Self.logger.debug("activities=\(frames.count, privacy: .public) nodes=\(250 - budget, privacy: .public) complete=\(complete, privacy: .public)") + if let observer = active.observer { + for element in active.observed { + for name in Self.notifications { + _ = AXObserverAddNotification(observer, element, name as CFString, + UnsafeMutableRawPointer(bitPattern: context)) + } + } + } + return (active, frames, complete) + } + // The initial stop for a changed process is intentional; a subsequent stop + // invalidates this result and prevents an unloaded observer reattaching. + guard generation == currentGeneration else { + await Self.remove(result.0) + Self.logger.debug("decision=native reason=observer-stopped-during-read") + return .native + } + if session == nil { + session = result.0 + if let observer = result.0.observer { + CFRunLoopAddSource(CFRunLoopGetMain(), AXObserverGetRunLoopSource(observer), .commonModes) + } + } + let decision = IslandLiveActivityPlacement.evaluate(axFrames: result.1, complete: result.2, + desktopTop: desktopTop, screen: screen, anchor: anchor) + switch decision.placement { + case .split(let frame): + Self.logger.debug("decision=split reason=\(decision.reason, privacy: .public) AppKitFrame x=\(frame.minX, privacy: .public) y=\(frame.minY, privacy: .public) width=\(frame.width, privacy: .public) height=\(frame.height, privacy: .public) primaryTop=\(desktopTop, privacy: .public)") + case .camera: + Self.logger.debug("decision=camera reason=\(decision.reason, privacy: .public)") + case .native: + Self.logger.debug("decision=native reason=\(decision.reason, privacy: .public)") + } + return decision.placement + } + + nonisolated private static let notifications = [kAXCreatedNotification, kAXUIElementDestroyedNotification, + kAXLayoutChangedNotification, kAXMovedNotification, kAXResizedNotification] + + fileprivate func changed() { + guard change == nil else { return } + let work = DispatchWorkItem { [weak self] in + guard let self else { return } + self.change = nil + self.onChange?() + } + change = work + DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(20), execute: work) + } + + private static func remove(_ session: IslandActivitySession) async { + await IslandAX.run { + guard let observer = session.observer else { return } + for element in session.observed { + for name in notifications { AXObserverRemoveNotification(observer, element, name as CFString) } + } + } + } + + func stop() { + generation += 1 + reading?.cancel(); reading = nil + change?.cancel(); change = nil + if let session { + if let observer = session.observer { + CFRunLoopRemoveSource(CFRunLoopGetMain(), AXObserverGetRunLoopSource(observer), .commonModes) + } + Task { await Self.remove(session) } + } + session = nil + } + + isolated deinit { stop() } +} + +private func islandActivityCallback(_ observer: AXObserver, _ element: AXUIElement, + _ notification: CFString, _ context: UnsafeMutableRawPointer?) { + guard let context else { return } + let address = UInt(bitPattern: context) + MainActor.assumeIsolated { + guard let pointer = UnsafeMutableRawPointer(bitPattern: address) else { return } + Unmanaged.fromOpaque(pointer).takeUnretainedValue().changed() + } +} diff --git a/Plugins/IslandNotifications/Sources/IslandNotificationAX.swift b/Plugins/IslandNotifications/Sources/IslandNotificationAX.swift new file mode 100644 index 000000000..6bedd8390 --- /dev/null +++ b/Plugins/IslandNotifications/Sources/IslandNotificationAX.swift @@ -0,0 +1,1106 @@ +import AppKit +import ApplicationServices +import OSLog + +// Ordinary cross-process AX messaging runs on this serial executor. Lifecycle +// restoration is synchronous so plugin unload and app exit cannot abandon alerts. +@globalActor +actor IslandAXExecutor { + static let shared = IslandAXExecutor() +} + +struct IslandAXElement: @unchecked Sendable { + let value: AXUIElement +} + +@IslandAXExecutor +enum IslandAX { + static func run(_ operation: @IslandAXExecutor @Sendable () -> T) -> T { operation() } + + @discardableResult + nonisolated static func setMessagingTimeout(_ element: AXUIElement, timeout: Float = 0.05) -> Bool { + // Elements returned by AX reads and callbacks do not inherit the app timeout. + return AXUIElementSetMessagingTimeout(element, timeout) == .success + } + + nonisolated static func value(_ element: AXUIElement, _ attribute: String, timeout: Float = 0.05) -> CFTypeRef? { + guard setMessagingTimeout(element, timeout: timeout) else { return nil } + var result: CFTypeRef? + guard AXUIElementCopyAttributeValue(element, attribute as CFString, &result) == .success else { return nil } + return result + } + + static func string(_ element: AXUIElement, _ attribute: String) -> String { + value(element, attribute) as? String ?? "" + } + + static func children(_ element: AXUIElement, timeout: Float = 0.05) -> [AXUIElement]? { + guard setMessagingTimeout(element, timeout: timeout) else { return nil } + var result: CFTypeRef? + let error = AXUIElementCopyAttributeValue(element, kAXChildrenAttribute as CFString, &result) + if error == .noValue || error == .attributeUnsupported { return [] } + guard error == .success else { return nil } + return result as? [AXUIElement] + } + + static func containingWindow(_ element: AXUIElement) -> AXUIElement? { + if string(element, kAXRoleAttribute) == kAXWindowRole { return element } + guard let raw = value(element, kAXWindowAttribute), CFGetTypeID(raw) == AXUIElementGetTypeID() else { return nil } + return unsafeDowncast(raw, to: AXUIElement.self) + } + + nonisolated static func isInvalid(_ element: AXUIElement) -> Bool { + guard setMessagingTimeout(element) else { return false } + var result: CFTypeRef? + return AXUIElementCopyAttributeValue(element, kAXRoleAttribute as CFString, &result) == .invalidUIElement + } + + nonisolated static func position(_ element: AXUIElement, timeout: Float = 0.05) -> CGPoint? { + guard let raw = value(element, kAXPositionAttribute, timeout: timeout), CFGetTypeID(raw) == AXValueGetTypeID() else { return nil } + let value = unsafeDowncast(raw, to: AXValue.self) + var point = CGPoint.zero + guard AXValueGetType(value) == .cgPoint, AXValueGetValue(value, .cgPoint, &point), + point.x.isFinite, point.y.isFinite else { return nil } + return point + } + + nonisolated static func move(_ window: AXUIElement, to point: CGPoint) -> Bool { + guard setMessagingTimeout(window) else { return false } + var point = point + guard let value = AXValueCreate(.cgPoint, &point) else { return false } + return AXUIElementSetAttributeValue(window, kAXPositionAttribute as CFString, value) == .success + } + + nonisolated static func frame(_ element: AXUIElement) -> CGRect? { + guard let origin = position(element), + let raw = value(element, kAXSizeAttribute), CFGetTypeID(raw) == AXValueGetTypeID() else { return nil } + let value = unsafeDowncast(raw, to: AXValue.self) + var size = CGSize.zero + guard AXValueGetType(value) == .cgSize, AXValueGetValue(value, .cgSize, &size), + size.width.isFinite, size.height.isFinite else { return nil } + return CGRect(origin: origin, size: size) + } + + /// Display rectangles in the global top-left coordinates AX positions use. + nonisolated static func displayBounds() -> [CGRect] { + var count: UInt32 = 0 + guard CGGetActiveDisplayList(0, nil, &count) == .success, count > 0 else { return [] } + var ids = [CGDirectDisplayID](repeating: 0, count: Int(count)) + guard CGGetActiveDisplayList(count, &ids, &count) == .success else { return [] } + return ids.prefix(Int(count)).map { CGDisplayBounds($0) } + } + + /// nil when the frame can't be read: unknown is never treated as off screen. + nonisolated static func isOnAnyDisplay(_ window: AXUIElement) -> Bool? { + guard let frame = frame(window) else { return nil } + let displays = displayBounds() + guard !displays.isEmpty else { return nil } + return displays.contains { $0.intersects(frame) } + } + + enum OffScreenMove: Sendable { + /// Moved, and confirmed to be on no display. `from` is where it was. + case moved(from: CGPoint) + /// Already on no display (moved earlier); `at` is where it sits now. + case alreadyOff(at: CGPoint) + case failed + } + + /// Moves a NotificationCenter window off screen and re-reads it to confirm. A window that ignores + /// the move, or still lands on a display, is put back where it was and reported as failed. + nonisolated static func moveOffScreen(_ window: AXUIElement, to offscreen: CGPoint) -> OffScreenMove { + let displays = displayBounds() + guard let before = frame(window), !displays.isEmpty else { return .failed } + guard displays.contains(where: { $0.intersects(before) }) else { return .alreadyOff(at: before.origin) } + guard isPositionSettable(window), move(window, to: offscreen) else { return .failed } + guard isOnAnyDisplay(window) == false else { + _ = move(window, to: before.origin) + return .failed + } + return .moved(from: before.origin) + } + + /// Puts a window MacTools moved back where it was, unless NotificationCenter already placed it + /// again itself or it is gone. Returns false only when a needed move failed. + @discardableResult + nonisolated static func restore(_ window: AXUIElement, to original: CGPoint) -> Bool { + guard !isInvalid(window), isOnAnyDisplay(window) == false else { return true } + return move(window, to: original) + } + + /// Notification Centre has a focused window only while its own panel is open; banners never take + /// focus (AXFocusedWindow is AXNoValue while one shows). nil = the query failed: unknown. + nonisolated static func hasFocusedWindow(_ application: AXUIElement) -> Bool? { + guard setMessagingTimeout(application) else { return nil } + var result: CFTypeRef? + let error = AXUIElementCopyAttributeValue(application, kAXFocusedWindowAttribute as CFString, &result) + if error == .noValue { return false } + guard error == .success, let result, CFGetTypeID(result) == AXUIElementGetTypeID() else { return nil } + return true + } + + /// Synchronous so stop, unload and quit never leave a window off screen. + nonisolated static func restoreMovedWindows(_ records: [IslandMovedWindow]) { + for record in records where !restore(record.window, to: record.original) { + Logger(subsystem: "MacTools.IslandNotifications", category: "lifecycle") + .error("Could not put back a moved notification window") + } + } + + // The caller must finish restoration before returning from deactivate/quit. + // Every remote operation below uses the same 0.05-second element timeout. + nonisolated static func restorePersistentWindows(_ notifications: [IslandNotification], desktopMinX: CGFloat) { + let logger = Logger(subsystem: "MacTools.IslandNotifications", category: "lifecycle") + var restored: [AXUIElement] = [] + for notification in notifications where notification.style == .persistent { + guard !restored.contains(where: { CFEqual($0, notification.window) }), + !isInvalid(notification.element) else { continue } + if let position = position(notification.window), position.x >= desktopMinX - 5000 { continue } + if !move(notification.window, to: notification.originalPosition) { + logger.error("Could not restore a hidden persistent notification window") + } + restored.append(notification.window) + } + } + + static func perform(_ name: String, on element: AXUIElement) -> Bool { + perform(anyOf: [name], on: element) + } + + /// Performs the first action whose name is one of `names` (a custom action reads "Name:\n…"). + static func perform(anyOf names: Set, on element: AXUIElement) -> Bool { + guard setMessagingTimeout(element) else { return false } + var raw: CFArray? + guard AXUIElementCopyActionNames(element, &raw) == .success, + let actions = raw as? [String], + let action = actions.first(where: { action in + names.contains(action) || names.contains { action.hasPrefix("Name:\($0)\n") } + }) else { return false } + return AXUIElementPerformAction(element, action as CFString) == .success + } + + /// A Notification Centre action ("Close", "Show", "Clear All") under every name it has in the + /// languages Notification Centre ships, read from its own strings: the action is named in the + /// system language ("Schließen", "閉じる"), whatever language MacTools runs in. + nonisolated static func centerAction(_ key: String) -> Set { + centerActionNames[key] ?? [key] + } + + private nonisolated static let centerActionNames: [String: Set] = { + let path = "/System/Library/CoreServices/NotificationCenter.app/Contents/Resources/Localizable.loctable" + guard let data = FileManager.default.contents(atPath: path), + let table = try? PropertyListSerialization.propertyList(from: data, format: nil) as? [String: [String: Any]] + else { return [:] } + var names: [String: Set] = [:] + for key in ["Close", "Show", "Clear All"] { + names[key] = Set(table.values.compactMap { $0[key] as? String }).union([key]) + } + return names + }() + + nonisolated static func isPositionSettable(_ window: AXUIElement) -> Bool { + guard setMessagingTimeout(window) else { return false } + var settable = DarwinBoolean(false) + return AXUIElementIsAttributeSettable(window, kAXPositionAttribute as CFString, &settable) == .success && settable.boolValue + } +} + +// AX handles and captured content are immutable; UI metadata stays on MainActor. +final class IslandNotification: @unchecked Sendable { + let element: AXUIElement + let window: AXUIElement + let originalPosition: CGPoint + let style: IslandNotificationStyle + let title: String + let body: String + let identityHints: [String] + /// Text lines in the banner. A third line is a subtitle, which group conversations use. + let lineCount: Int + /// When MacTools received it (system uptime). + let arrivedAt = ProcessInfo.processInfo.systemUptime + /// A header label from the banner, e.g. "TIME-SENSITIVE". + @MainActor var label: String? + @MainActor var appURL: URL? + @MainActor var appName: String? + @MainActor var appIcon: NSImage? + @MainActor var bundleIdentifier: String? { appURL.flatMap { Bundle(url: $0)?.bundleIdentifier } } + /// Set for a card made from a finished Claude chat turn (no system banner behind it). + @MainActor var claudeChat: IslandClaudeChat? + /// Claude chat cards and Messages banners get the inline reply field. Messages replies go only + /// to the exact conversation id from Messages' history, so they need that history to be readable. + @MainActor var canReply: Bool { + claudeChat != nil || (bundleIdentifier == "com.apple.MobileSMS" && IslandMessagesChat.isAvailable) + } + + /// A banner with a third line has a subtitle between the title and the message: for a group + /// conversation, the group's name. Apple draws it in the title's weight, the message in grey. + @MainActor var subtitle: String? { + guard lineCount > 2, let first = body.components(separatedBy: "\n").first, !first.isEmpty else { return nil } + return first + } + + /// The message alone, without the subtitle line. + @MainActor var message: String { + guard let subtitle else { return displayBody } + return String(displayBody.dropFirst(subtitle.count)).trimmingCharacters(in: .newlines) + } + + /// Banners carry at most 1,024 characters; a body cut at that limit ends with "…". + @MainActor var displayBody: String { + claudeChat == nil && body.count == 1024 ? body + "…" : body + } + + init(element: AXUIElement, window: AXUIElement, originalPosition: CGPoint, + style: IslandNotificationStyle, title: String, body: String, identityHints: [String], lineCount: Int = 2) { + self.element = element + self.window = window + self.originalPosition = originalPosition + self.style = style + self.title = title + self.body = body + self.identityHints = identityHints + self.lineCount = lineCount + } + + /// The marks Notification Centre puts between the parts of a description, in every language it + /// ships: "Messages, Alex, Hi", "メッセージ、Alex、Hi", "信息,Alex,Hi", Arabic "،" with direction marks. + nonisolated static let descriptionSeparators = CharacterSet(charactersIn: ",、,،\u{200E}\u{200F}").union(.whitespaces) + + /// Extracts the sending app from a banner description: the app comes first, then the title. + nonisolated static func appName(fromDescription description: String, title: String, body: String) -> String? { + let trimmed = description.trimmingCharacters(in: descriptionSeparators) + guard !trimmed.isEmpty else { return nil } + if !title.isEmpty { + // The title where it starts a part (after a separator), not inside the app's own name. + var from = trimmed.startIndex + while let range = trimmed.range(of: title, range: from.. URL? { + guard !name.isEmpty, !name.contains("/") else { return nil } + let folders = ["/Applications", "/System/Applications", "/System/Applications/Utilities", + NSHomeDirectory() + "/Applications", "/System/Library/CoreServices"] + for folder in folders { + let url = URL(fileURLWithPath: folder).appendingPathComponent(name + ".app") + if FileManager.default.fileExists(atPath: url.path) { return url } + } + return nil + } +} + +/// A complete structural read is required before moving a full-screen AX window. +struct IslandAXWindowSnapshot: @unchecked Sendable { + struct Group { + var lines = 2 + /// A small all-caps header above the title, e.g. "TIME-SENSITIVE". + var label: String? + let element: AXUIElement + let style: IslandNotificationStyle + let title: String + let body: String + let hints: [String] + } + var groups: [Group] = [] + var unexpected = false + var complete = true + + @IslandAXExecutor init(window: AXUIElement) { + var budget = 300 + func card(_ element: AXUIElement, style: IslandNotificationStyle, children: [AXUIElement]) { + var text: [String] = [] + var hints = [kAXDescriptionAttribute, kAXTitleAttribute, kAXIdentifierAttribute].map { IslandAX.string(element, $0) } + for child in children { + let role = IslandAX.string(child, kAXRoleAttribute) + if role == kAXStaticTextRole { + text.append(IslandAX.string(child, kAXValueAttribute)) + } else if role == kAXImageRole { + hints += [kAXDescriptionAttribute, kAXTitleAttribute, kAXIdentifierAttribute].map { IslandAX.string(child, $0) } + } + } + guard !text.isEmpty, text.contains(where: { !$0.isEmpty }) else { complete = false; return } + // Time Sensitive (and similar) banners put a short all-caps label above the title. + var label: String? + if text.count >= 3, let first = text.first, first.count <= 24, + first.rangeOfCharacter(from: .letters) != nil, first.rangeOfCharacter(from: .lowercaseLetters) == nil { + label = first + text.removeFirst() + } + let title = text.first ?? "" + let body = text.dropFirst().joined(separator: "\n") + // macOS 27 describes a banner as ", , <body>"; the app comes first. + if let app = IslandNotification.appName(fromDescription: hints.first ?? "", title: title, body: body) { + hints.insert(app, at: 0) + } + var group = Group(element: element, style: style, title: title, body: body, hints: hints) + group.lines = text.count + group.label = label + groups.append(group) + } + /// `stack` is set inside a grouped stack: a plain group there that directly holds the text is + /// one complete card of that stack (Vorssaint's findStackCards does the same). + func walk(_ element: AXUIElement, depth: Int, stack: IslandNotificationStyle? = nil) { + guard complete, !unexpected else { return } + guard budget > 0, depth < 20 else { complete = false; return } + budget -= 1 + let role = IslandAX.string(element, kAXRoleAttribute) + let subrole = IslandAX.string(element, kAXSubroleAttribute) + if role == kAXGroupRole, let stackStyle = IslandNotificationStyle(stackSubrole: subrole) { + guard let children = IslandAX.children(element) else { complete = false; return } + // A stack that holds the text itself is a single card; otherwise descend into its cards. + if children.contains(where: { IslandAX.string($0, kAXRoleAttribute) == kAXStaticTextRole }) { + card(element, style: stackStyle, children: children) + return + } + for child in children { + walk(child, depth: depth + 1, stack: stackStyle) + if unexpected || !complete { return } + } + return + } + if role == kAXGroupRole, let style = IslandNotificationStyle(subrole: subrole) { + guard let children = IslandAX.children(element) else { complete = false; return } + card(element, style: style, children: children) + return + } + if let stack, role == kAXGroupRole, subrole.isEmpty { + guard let children = IslandAX.children(element) else { complete = false; return } + if children.contains(where: { IslandAX.string($0, kAXRoleAttribute) == kAXStaticTextRole }) { + card(element, style: stack, children: children) + return + } + for child in children { + walk(child, depth: depth + 1, stack: stack) + if unexpected || !complete { return } + } + return + } + // Structural wrappers are allowed; history, controls and unrelated text aren't. + // macOS 27 wraps banners in a SwiftUI hosting container (AXGroup/AXHostingView) under the window. + // Since 2026-11-16 the banner scroll area can also be AXScrollArea/AXScrollAreaAutoFocus. + let structuralSubrole = subrole.isEmpty || subrole == "AXSystemDialog" || (role == kAXGroupRole && subrole == "AXHostingView") + || (role == kAXScrollAreaRole && subrole == "AXScrollAreaAutoFocus") + guard [kAXWindowRole, kAXGroupRole, kAXScrollAreaRole].contains(role), structuralSubrole else { + unexpected = true; return + } + guard let children = IslandAX.children(element) else { complete = false; return } + for child in children { + walk(child, depth: depth + 1) + if unexpected || !complete { return } + } + } + guard IslandAX.string(window, kAXRoleAttribute) == kAXWindowRole, + IslandAX.string(window, kAXSubroleAttribute) == "AXSystemDialog" else { + unexpected = true + return + } + walk(window, depth: 0) + } +} + +// The run-loop source is managed on main; registration and removal can message +// the remote process, so they belong to the AX executor too. +private final class IslandAXSession: @unchecked Sendable { + let observer: AXObserver + let application: AXUIElement + init(observer: AXObserver, application: AXUIElement) { + self.observer = observer; self.application = application + } +} + +@MainActor +final class IslandNotificationObserver { + var onWindow: ((IslandAXElement) -> Void)? + var onRemoved: ((IslandAXElement) -> Void)? + /// Notification Centre's focused window changed: its panel opened or closed. + var onFocusChanged: (() -> Void)? + private var session: IslandAXSession? + private var generation = 0 + private var starting = false + private var retry: DispatchWorkItem? + private var processSource: DispatchSourceProcess? + private(set) var pid: pid_t? + private var pendingElements: [IslandAXElement] = [] + private var flush: DispatchWorkItem? + + func start(onAttached: @escaping () -> Void, onExit: @escaping () -> Void) { + guard session == nil, !starting, retry == nil else { return } + attach(remaining: 10, generation: generation, onAttached: onAttached, onExit: onExit) + } + + private func attach(remaining: Int, generation: Int, + onAttached: @escaping () -> Void, onExit: @escaping () -> Void) { + guard self.generation == generation, AXIsProcessTrusted() else { return } + guard let app = NSWorkspace.shared.runningApplications.first(where: { + $0.bundleURL?.path == "/System/Library/CoreServices/NotificationCenter.app" + }) else { + scheduleRetry(remaining: remaining, generation: generation, onAttached: onAttached, onExit: onExit) + return + } + starting = true + let pid = app.processIdentifier + // Keep self alive until registration either attaches or removes its context. + let context = UInt(bitPattern: Unmanaged.passUnretained(self).toOpaque()) + Task { + let next = await IslandAX.run { () -> IslandAXSession? in + let application = AXUIElementCreateApplication(pid) + guard IslandAX.setMessagingTimeout(application) else { return nil } + var observer: AXObserver? + let status = AXObserverCreate(pid, islandAXObserverCallback, &observer) + guard status == .success, let observer, + AXObserverAddNotification(observer, application, kAXCreatedNotification as CFString, + UnsafeMutableRawPointer(bitPattern: context)) == .success else { return nil } + // Optional: without it, every read still checks focus first. + _ = AXObserverAddNotification(observer, application, kAXFocusedWindowChangedNotification as CFString, + UnsafeMutableRawPointer(bitPattern: context)) + return IslandAXSession(observer: observer, application: application) + } + guard self.generation == generation else { + if let next { await Self.remove(next) } + return + } + starting = false + guard let next else { + scheduleRetry(remaining: remaining, generation: generation, onAttached: onAttached, onExit: onExit) + return + } + session = next + self.pid = pid + CFRunLoopAddSource(CFRunLoopGetMain(), AXObserverGetRunLoopSource(next.observer), .commonModes) + let source = DispatchSource.makeProcessSource(identifier: pid, eventMask: .exit, queue: .main) + source.setEventHandler { [weak owner = self] in + MainActor.assumeIsolated { + guard let owner, owner.generation == generation else { return } + owner.stop() + onExit() + } + } + processSource = source + source.resume() + onAttached() + } + } + + private func scheduleRetry(remaining: Int, generation: Int, + onAttached: @escaping () -> Void, onExit: @escaping () -> Void) { + guard remaining > 1, self.generation == generation else { return } + let work = DispatchWorkItem { [weak self] in + guard let self, self.generation == generation else { return } + self.retry = nil + self.attach(remaining: remaining - 1, generation: generation, onAttached: onAttached, onExit: onExit) + } + retry = work + DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(200), execute: work) + } + + func windows() async -> [IslandAXElement] { + guard let session else { return [] } + return await IslandAX.run { + (IslandAX.value(session.application, kAXWindowsAttribute) as? [AXUIElement] ?? []).map { IslandAXElement(value: $0) } + } + } + + /// Whether Notification Centre's own panel is open. nil when unknown (not attached, or the query failed). + func centerFocus() async -> Bool? { + guard let session else { return nil } + return await IslandAX.run { IslandAX.hasFocusedWindow(session.application) } + } + + fileprivate func focusChanged() { onFocusChanged?() } + + func observeRemoval(of elements: [IslandAXElement]) async { + guard let session else { return } + let context = UInt(bitPattern: Unmanaged.passUnretained(self).toOpaque()) + await IslandAX.run { + for element in elements where IslandAX.setMessagingTimeout(element.value) { + _ = AXObserverAddNotification(session.observer, element.value, kAXUIElementDestroyedNotification as CFString, + UnsafeMutableRawPointer(bitPattern: context)) + } + } + } + + fileprivate func created(_ element: AXUIElement) { + if !pendingElements.contains(where: { CFEqual($0.value, element) }) { pendingElements.append(IslandAXElement(value: element)) } + guard flush == nil else { return } + let generation = generation + // Fixed from the first event: a busy event stream must not postpone hiding. + let work = DispatchWorkItem { [weak self] in + guard let self, self.session != nil, self.generation == generation else { return } + let elements = self.pendingElements + self.pendingElements.removeAll() + self.flush = nil + Task { + let windows = await IslandAX.run { + var windows: [IslandAXElement] = [] + for element in elements { + if let window = IslandAX.containingWindow(element.value), + !windows.contains(where: { CFEqual($0.value, window) }) { + windows.append(IslandAXElement(value: window)) + } + } + return windows + } + guard self.generation == generation else { return } + for window in windows { self.onWindow?(window) } + } + } + flush = work + DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(2), execute: work) + } + + private static func remove(_ session: IslandAXSession) async { + await IslandAX.run { + if IslandAX.setMessagingTimeout(session.application) { + AXObserverRemoveNotification(session.observer, session.application, kAXCreatedNotification as CFString) + AXObserverRemoveNotification(session.observer, session.application, kAXFocusedWindowChangedNotification as CFString) + } + } + } + + func stop() { + generation += 1; starting = false + retry?.cancel(); retry = nil + processSource?.cancel(); processSource = nil + flush?.cancel(); flush = nil; pendingElements.removeAll() + if let session { + CFRunLoopRemoveSource(CFRunLoopGetMain(), AXObserverGetRunLoopSource(session.observer), .commonModes) + Task { await Self.remove(session) } + } + session = nil; pid = nil + } + + isolated deinit { stop() } +} + +/// AX delivers observer callbacks on the run loop that owns the observer's source, which is the +/// main run loop here. Declaring the callback at file scope keeps it nonisolated: written inside an +/// `@IslandAXExecutor` closure, Swift 6 would infer that actor's isolation and abort on the first +/// callback when its executor check fails on the main thread. +private func islandAXObserverCallback(_ observer: AXObserver, _ element: AXUIElement, + _ notification: CFString, _ context: UnsafeMutableRawPointer?) { + guard let context else { return } + let address = UInt(bitPattern: context) + let wrapped = IslandAXElement(value: element) + let removed = CFEqual(notification, kAXUIElementDestroyedNotification as CFString) + let focus = CFEqual(notification, kAXFocusedWindowChangedNotification as CFString) + MainActor.assumeIsolated { + guard let context = UnsafeMutableRawPointer(bitPattern: address) else { return } + let owner = Unmanaged<IslandNotificationObserver>.fromOpaque(context).takeUnretainedValue() + if removed { owner.onRemoved?(wrapped) } + else if focus { owner.focusChanged() } + else { owner.created(wrapped.value) } + } +} + +/// Replies into a Claude Code chat in the desktop app without bringing Claude forward. Claude has no +/// scripting interface, so this drives its accessibility interface: when another chat is open, that +/// chat's sidebar entry is pressed in the background; nothing is typed until the window shows exactly +/// the expected chat; an unsent draft in Claude is never overwritten, and a failed send leaves the +/// box as it was. Claude is never brought forward: its own chat link (which always activates it) is +/// used only while Claude is already in front. +enum IslandClaudeReply { + static let bundleIdentifier = "com.anthropic.claudefordesktop" + /// Steps only, never message text. + private static let logger = Logger(subsystem: "MacTools.IslandNotifications", category: "reply") + + /// One pass over Claude's focused window (a few hundred elements). + fileprivate struct Scan: @unchecked Sendable { + var chatTitle = "" + var prompt: AXUIElement? + var send: AXUIElement? + var busy = false + var sidebarEntries: [AXUIElement] = [] + } + + @MainActor + static func send(_ text: String, to chat: IslandClaudeChat) async -> IslandReplyOutcome { + guard chat.isUnique else { return .ambiguousChat } + guard let claude = NSRunningApplication.runningApplications(withBundleIdentifier: bundleIdentifier).first else { + return .failed + } + let pid = claude.processIdentifier + // Electron exposes its page only while asked to. It stays on afterwards: switching it off + // makes every later reply wait about two seconds while Claude rebuilds its page. + await IslandAX.run { enableWebAccessibility(pid: pid) } + return await deliver(text, pid: pid, chat: chat) + } + + /// The page title is exactly "<chat title> - Claude Code" (so "Foo" never matches "Foo bar"). + nonisolated static func isShowing(_ title: String, in pageTitle: String) -> Bool { + pageTitle == title + " - Claude Code" || pageTitle == title + " - Claude" + } + + @MainActor + private static func deliver(_ text: String, pid: pid_t, chat: IslandClaudeChat) async -> IslandReplyOutcome { + let title = chat.title + // Right after accessibility is switched on, Claude needs a moment to expose its page. + var scan = IslandClaudeReply.Scan() + var attempts = 0 + while attempts < 16 { + attempts += 1 + scan = await IslandAX.run { read(pid: pid, sidebarTitle: title) } + if scan.prompt != nil, !scan.chatTitle.isEmpty { break } + try? await Task.sleep(for: .milliseconds(150)) + } + logger.notice("claude page ready=\(scan.prompt != nil, privacy: .public) attempts=\(attempts, privacy: .public) showing=\(isShowing(title, in: scan.chatTitle), privacy: .public) entries=\(scan.sidebarEntries.count, privacy: .public)") + guard scan.prompt != nil, !scan.chatTitle.isEmpty else { return .failed } + if !isShowing(title, in: scan.chatTitle) { + if scan.sidebarEntries.count == 1, let entry = scan.sidebarEntries.first.map(IslandAXElement.init) { + _ = await IslandAX.run { AXUIElementPerformAction(entry.value, kAXPressAction as CFString) == .success } + } else if NSWorkspace.shared.frontmostApplication?.processIdentifier == pid, let link = chat.link { + // Claude's link always brings Claude forward, so it is used only when Claude is + // already in front. Otherwise the reply fails and the card offers to open the chat: + // Claude never flashes up behind a reply. + _ = try? await NSWorkspace.shared.open(link) + } else { + logger.notice("claude chat not in the sidebar") + return .failed + } + // Wait until the chat has opened and stayed open for two checks in a row. + var matches = 0 + for _ in 0..<20 where matches < 2 { + try? await Task.sleep(for: .milliseconds(150)) + scan = await IslandAX.run { read(pid: pid, sidebarTitle: nil) } + matches = scan.prompt != nil && isShowing(title, in: scan.chatTitle) ? matches + 1 : 0 + } + logger.notice("claude chat opened=\(matches >= 2, privacy: .public)") + guard matches >= 2 else { return .failed } + } + guard let prompt = scan.prompt.map(IslandAXElement.init) else { return .failed } + // "Stop" is the English label; the session's own log says the same in every language. + let localID = chat.localID + let working = await Task.detached(priority: .userInitiated) { IslandClaudeTurnWatcher.isWorking(localID: localID) }.value + let busy = scan.busy || working + // Never overwrite text the user left unsent in that chat. + let existing = await IslandAX.run { promptText(prompt.value) } + guard let existing else { return .failed } + guard existing.isEmpty else { logger.notice("claude chat has an unsent draft"); return .claudeDraft } + let filled = await IslandAX.run { () -> Bool in + guard AXUIElementSetAttributeValue(prompt.value, kAXValueAttribute as CFString, text as CFString) == .success else { return false } + return AXUIElementSetAttributeValue(prompt.value, kAXFocusedAttribute as CFString, kCFBooleanTrue) == .success + } + guard filled else { return .failed } + try? await Task.sleep(for: .milliseconds(150)) + // Idle: press Claude's Send button (it appears once there is text). Working: Command-Return + // queues the reply instead of interrupting. Both work with Claude in the background. + let pressed = busy ? false : await IslandAX.run { () -> Bool in + guard let send = read(pid: pid, sidebarTitle: nil).send else { return false } + return AXUIElementPerformAction(send, kAXPressAction as CFString) == .success + } + if !pressed { + let source = CGEventSource(stateID: .privateState) + for down in [true, false] { + let event = CGEvent(keyboardEventSource: source, virtualKey: 36, keyDown: down) + if busy { event?.flags = .maskCommand } + event?.postToPid(pid) + } + } + logger.notice("claude submit busy=\(busy, privacy: .public) sendButton=\(pressed, privacy: .public)") + // Sent (or queued) once the message box has emptied. + for _ in 0..<10 { + try? await Task.sleep(for: .milliseconds(150)) + if await IslandAX.run({ promptText(prompt.value) })?.isEmpty == true { return .sent } + } + logger.notice("claude send not confirmed") + // Not sent: leave the box as it was (empty) rather than holding a stray reply. + _ = await IslandAX.run { AXUIElementSetAttributeValue(prompt.value, kAXValueAttribute as CFString, "" as CFString) } + return .failed + } + + @IslandAXExecutor + private static func promptText(_ prompt: AXUIElement) -> String? { + (IslandAX.value(prompt, kAXValueAttribute, timeout: 0.5) as? String)?.trimmingCharacters(in: .whitespacesAndNewlines) + } + + private static let manualAccessibility = "AXManualAccessibility" + + @IslandAXExecutor + fileprivate static func enableWebAccessibility(pid: pid_t) { + let app = AXUIElementCreateApplication(pid) + IslandAX.setMessagingTimeout(app, timeout: 0.5) + if (IslandAX.value(app, manualAccessibility, timeout: 0.5) as? Bool) == true { return } + AXUIElementSetAttributeValue(app, manualAccessibility as CFString, kCFBooleanTrue) + } + + /// Reads the open chat's title, the message box, the Send button, whether Claude is working and + /// (when `sidebarTitle` is set) the sidebar entries for that chat: "<title>" or "<title> Running". + /// Reads structure only. + @IslandAXExecutor + fileprivate static func read(pid: pid_t, sidebarTitle: String?) -> Scan { + let app = AXUIElementCreateApplication(pid) + IslandAX.setMessagingTimeout(app, timeout: 0.5) + var scan = Scan() + guard let window = IslandAX.value(app, kAXFocusedWindowAttribute, timeout: 0.5) else { return scan } + var budget = 3000 + func walk(_ element: AXUIElement, depth: Int) { + guard budget > 0, depth < 60 else { return } + budget -= 1 + let role = IslandAX.value(element, kAXRoleAttribute, timeout: 0.5) as? String ?? "" + switch role { + case "AXWebArea" where scan.chatTitle.isEmpty: + // The outer web area has no title; the chat page inside it does. + scan.chatTitle = IslandAX.value(element, kAXTitleAttribute, timeout: 0.5) as? String ?? "" + case "AXTextArea": + // Claude's message box is its ProseMirror editor; "Prompt" is its English label. + let classes = IslandAX.value(element, "AXDOMClassList", timeout: 0.5) as? [String] ?? [] + if classes.contains("ProseMirror") + || IslandAX.value(element, kAXDescriptionAttribute, timeout: 0.5) as? String == "Prompt" { scan.prompt = element } + return + case "AXButton": + let label = IslandAX.value(element, kAXDescriptionAttribute, timeout: 0.5) as? String ?? "" + if label == "Stop" { scan.busy = true } + if label == "Send" { scan.send = element } + if let sidebarTitle, let title = IslandAX.value(element, kAXTitleAttribute, timeout: 0.5) as? String, + title.hasPrefix(sidebarTitle), entryTitle(element) == sidebarTitle { + scan.sidebarEntries.append(element) + } + return + case "AXStaticText", "AXImage": + return + default: + break + } + for child in IslandAX.children(element, timeout: 0.5) ?? [] { walk(child, depth: depth + 1) } + } + walk(window as! AXUIElement, depth: 0) + return scan + } + + /// A sidebar entry is a button around a label whose first text is the chat's title; status text + /// such as "Running" or "Forked from …" follows it. Links to a chat inside a transcript have no + /// such label, so they never count as its entry. + @IslandAXExecutor + private static func entryTitle(_ button: AXUIElement) -> String? { + guard let label = IslandAX.children(button, timeout: 0.5)?.first, + IslandAX.value(label, kAXRoleAttribute, timeout: 0.5) as? String == kAXGroupRole, + let text = IslandAX.children(label, timeout: 0.5)?.first, + IslandAX.value(text, kAXRoleAttribute, timeout: 0.5) as? String == kAXStaticTextRole else { return nil } + return IslandAX.value(text, kAXValueAttribute, timeout: 0.5) as? String + } +} + +/// A Claude Code chat in the desktop app: its app-side id (for Claude's own chat link) and title. +struct IslandClaudeChat: Equatable, Sendable { + let localID: String + let title: String + /// False when another open chat has the same title: the chat could not be told apart on screen. + var isUnique = true + + var link: URL? { + var components = URLComponents(string: "claude://code/continue") + components?.queryItems = [URLQueryItem(name: "session", value: localID), URLQueryItem(name: "source", value: "desktop_action")] + return components?.url + } +} + +/// Follows Claude Code's own session logs (`~/.claude/projects/<project>/<session>.jsonl`), which every +/// session writes, terminal and desktop alike, so nothing needs setting up. macOS reports changes +/// to those files (FSEvents); nothing is polled, and only the lines added since the last read are +/// decoded. Claude's reply that ends a turn becomes a card. +@MainActor +final class IslandClaudeTurnWatcher { + struct Turn: Sendable { + let chat: IslandClaudeChat + let message: String + } + + /// The folder the old Stop-hook route wrote to; removed so a leftover hook stops writing. + static var legacyDirectory: URL { + FileManager.default.homeDirectoryForCurrentUser + .appendingPathComponent("Library/Application Support/MacTools/ClaudeTurns", isDirectory: true) + } + + nonisolated static var logRoots: [URL] { + let home = FileManager.default.homeDirectoryForCurrentUser + return [".claude/projects", ".config/claude/projects"].map { home.appendingPathComponent($0, isDirectory: true) } + .filter { FileManager.default.fileExists(atPath: $0.path) } + } + + var onTurn: ((Turn) -> Void)? + private var stream: FSEventStreamRef? + private var reader: IslandClaudeTranscriptReader? + private let queue = DispatchQueue(label: "MacTools.IslandNotifications.ClaudeLogs", qos: .utility) + + func start() { + guard stream == nil else { return } + try? FileManager.default.removeItem(at: Self.legacyDirectory) + let roots = Self.logRoots + guard !roots.isEmpty else { return } + let reader = IslandClaudeTranscriptReader(roots: roots) { [weak self] turn in + DispatchQueue.main.async { [weak self] in + MainActor.assumeIsolated { self?.onTurn?(turn) } + } + } + guard let stream = Self.makeStream(paths: roots.map(\.path), reader: reader, queue: queue) else { return } + self.reader = reader + self.stream = stream + } + + /// Built outside the main actor: FSEvents calls back on `queue`. + nonisolated private static func makeStream(paths: [String], reader: IslandClaudeTranscriptReader, + queue: DispatchQueue) -> FSEventStreamRef? { + var context = FSEventStreamContext(version: 0, info: Unmanaged.passUnretained(reader).toOpaque(), + retain: nil, release: nil, copyDescription: nil) + let callback: FSEventStreamCallback = { _, info, _, eventPaths, _, _ in + guard let info else { return } + let reader = Unmanaged<IslandClaudeTranscriptReader>.fromOpaque(info).takeUnretainedValue() + let paths = (unsafeBitCast(eventPaths, to: NSArray.self) as? [String]) ?? [] + reader.changed(paths) + } + let flags = FSEventStreamCreateFlags(kFSEventStreamCreateFlagFileEvents | kFSEventStreamCreateFlagUseCFTypes + | kFSEventStreamCreateFlagNoDefer) + // 0.3 s coalesces Claude's bursts of writes into one read. + guard let stream = FSEventStreamCreate(kCFAllocatorDefault, callback, &context, paths as CFArray, + FSEventStreamEventId(kFSEventStreamEventIdSinceNow), 0.3, flags) else { return nil } + FSEventStreamSetDispatchQueue(stream, queue) + guard FSEventStreamStart(stream) else { + FSEventStreamInvalidate(stream); FSEventStreamRelease(stream) + return nil + } + return stream + } + + func stop() { + if let stream { + FSEventStreamStop(stream); FSEventStreamInvalidate(stream); FSEventStreamRelease(stream) + // Let any callback already queued finish before the reader goes. + queue.sync {} + } + stream = nil; reader = nil + } + + isolated deinit { stop() } + + /// Whether this desktop chat is in the middle of a turn, from its Claude Code session log: the + /// last entry is not Claude's reply that ends a turn, and the log moved in the last 15 minutes. + nonisolated static func isWorking(localID: String) -> Bool { + let root = FileManager.default.homeDirectoryForCurrentUser + .appendingPathComponent("Library/Application Support/Claude/claude-code-sessions", isDirectory: true) + guard let enumerator = FileManager.default.enumerator(at: root, includingPropertiesForKeys: nil) else { return false } + var session: String? + for case let file as URL in enumerator where file.lastPathComponent.hasPrefix("local_") && file.pathExtension == "json" { + guard let data = try? Data(contentsOf: file), + let info = try? JSONSerialization.jsonObject(with: data) as? [String: Any], + info["sessionId"] as? String == localID else { continue } + session = info["cliSessionId"] as? String ?? info["lastAssistantCliSessionId"] as? String + break + } + guard let session else { return false } + for root in logRoots { + guard let projects = try? FileManager.default.contentsOfDirectory(at: root, includingPropertiesForKeys: nil) else { continue } + for project in projects { + let log = project.appendingPathComponent(session + ".jsonl") + guard let attributes = try? FileManager.default.attributesOfItem(atPath: log.path), + let modified = attributes[.modificationDate] as? Date else { continue } + guard Date().timeIntervalSince(modified) < 15 * 60, let handle = try? FileHandle(forReadingFrom: log) else { return false } + defer { try? handle.close() } + let size = (attributes[.size] as? UInt64) ?? 0 + try? handle.seek(toOffset: size > 65_536 ? size - 65_536 : 0) + let tail = handle.readDataToEndOfFile() + for line in tail.split(separator: 0x0A).reversed() { + guard let entry = try? JSONSerialization.jsonObject(with: Data(line)) as? [String: Any], + let type = entry["type"] as? String else { continue } + if type == "assistant" { + let stop = (entry["message"] as? [String: Any])?["stop_reason"] as? String + return !["end_turn", "stop_sequence", "max_tokens", "refusal"].contains(stop ?? "") + } + if type == "user" { + return !String(decoding: line, as: UTF8.self).contains("[Request interrupted") + } + } + return false + } + } + return false + } + + /// The desktop chat that runs this Claude Code session (none for terminal sessions). + nonisolated static func desktopChat(forSession sessionID: String) -> IslandClaudeChat? { + let root = FileManager.default.homeDirectoryForCurrentUser + .appendingPathComponent("Library/Application Support/Claude/claude-code-sessions", isDirectory: true) + guard let enumerator = FileManager.default.enumerator(at: root, includingPropertiesForKeys: nil) else { return nil } + var match: IslandClaudeChat? + var titles: [String] = [] + for case let file as URL in enumerator where file.lastPathComponent.hasPrefix("local_") && file.pathExtension == "json" { + guard let data = try? Data(contentsOf: file), + let info = try? JSONSerialization.jsonObject(with: data) as? [String: Any], + (info["isArchived"] as? Bool) != true, + let localID = info["sessionId"] as? String else { continue } + let title = info["title"] as? String ?? "Claude" + titles.append(title) + if info["cliSessionId"] as? String == sessionID || info["lastAssistantCliSessionId"] as? String == sessionID { + match = IslandClaudeChat(localID: localID, title: title) + } + } + guard var chat = match else { return nil } + chat.isUnique = titles.filter { $0 == chat.title }.count == 1 + return chat + } + + /// The text of the last assistant entry in a Claude Code transcript (JSON lines), read from its tail. + nonisolated static func lastAssistantMessage(in path: String) -> String? { + guard let handle = FileHandle(forReadingAtPath: path) else { return nil } + defer { try? handle.close() } + let size = (try? handle.seekToEnd()) ?? 0 + try? handle.seek(toOffset: size > 512_000 ? size - 512_000 : 0) + guard let data = try? handle.readToEnd(), let tail = String(data: data, encoding: .utf8) else { return nil } + for line in tail.split(separator: "\n").reversed() { + guard line.contains("\"assistant\""), + let entry = try? JSONSerialization.jsonObject(with: Data(line.utf8)) as? [String: Any], + entry["type"] as? String == "assistant", + let message = entry["message"] as? [String: Any], + let content = message["content"] as? [[String: Any]] else { continue } + let text = content.filter { $0["type"] as? String == "text" }.compactMap { $0["text"] as? String }.joined(separator: "\n") + if !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { return text } + } + return nil + } + + /// Plain text for the card: Markdown marks removed, links reduced to their text, and extremely + /// long messages cut (the card scrolls; the full message stays in Claude). + nonisolated static func cleaned(_ markdown: String) -> String { + var text = markdown + let replacements: [(String, String)] = [ + (#"\[([^\]]+)\]\([^)]+\)"#, "$1"), + (#"(?m)^#{1,6}\s+"#, ""), + (#"(?m)^\s*[-*]\s+"#, "• "), + (#"\*\*|__|`"#, ""), + (#"\n{3,}"#, "\n\n"), + ] + for (pattern, template) in replacements { + text = text.replacingOccurrences(of: pattern, with: template, options: .regularExpression) + } + text = text.trimmingCharacters(in: .whitespacesAndNewlines) + return text.count > 12000 ? String(text.prefix(12000)) + "…" : text + } +} + +/// Reads the lines Claude Code appends to its session logs. Used only on the watcher's queue. +final class IslandClaudeTranscriptReader: @unchecked Sendable { + /// Only this much of an existing log is read the first time it changes (once per session per launch). + private static let firstReadLimit: UInt64 = 1024 * 1024 + + private struct LogFile { + var offset: UInt64 + /// Lines older than this were written before MacTools was watching: not new. + var notBefore: Date? + } + + private let roots: [String] + private let deliver: @Sendable (IslandClaudeTurnWatcher.Turn) -> Void + private let started = Date() + private var files: [String: LogFile] = [:] + private let timestampFormatter: ISO8601DateFormatter = { + let formatter = ISO8601DateFormatter() + formatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds] + return formatter + }() + + init(roots: [URL], deliver: @escaping @Sendable (IslandClaudeTurnWatcher.Turn) -> Void) { + self.roots = roots.map { $0.standardizedFileURL.path } + self.deliver = deliver + } + + /// Called with the paths FSEvents reported. + func changed(_ paths: [String]) { + for path in Set(paths) where isSessionLog(path) { read(path) } + } + + /// `<root>/<project>/<session>.jsonl` only: subagent logs live one folder deeper. + private func isSessionLog(_ path: String) -> Bool { + guard path.hasSuffix(".jsonl"), let root = roots.first(where: { path.hasPrefix($0 + "/") }) else { return false } + let parts = path.dropFirst(root.count + 1).split(separator: "/") + return parts.count == 2 && !parts[0].hasPrefix(".") + } + + private func read(_ path: String) { + guard let handle = FileHandle(forReadingAtPath: path) else { files[path] = nil; return } + defer { try? handle.close() } + guard let size = try? handle.seekToEnd() else { return } + let firstSight = files[path] == nil + var file = files[path] ?? Self.firstSight(path, size: size, started: started) + if size < file.offset { file = LogFile(offset: 0, notBefore: nil) } + guard size > file.offset else { files[path] = file; return } + try? handle.seek(toOffset: file.offset) + guard let data = try? handle.read(upToCount: Int(size - file.offset)), + let lastNewline = data.lastIndex(of: 0x0A) else { files[path] = file; return } + // A line still being written stays for the next read. + let complete = data[data.startIndex...lastNewline] + var lines = complete.split(separator: 0x0A, omittingEmptySubsequences: true) + if firstSight, file.offset > 0, !lines.isEmpty { lines.removeFirst() } // cut mid-line + file.offset += UInt64(complete.count) + files[path] = file + let fallbackSession = URL(fileURLWithPath: path).deletingPathExtension().lastPathComponent + for line in lines { apply(line, path: path, fallbackSession: fallbackSession, notBefore: file.notBefore) } + } + + private static func firstSight(_ path: String, size: UInt64, started: Date) -> LogFile { + let created = (try? FileManager.default.attributesOfItem(atPath: path)[.creationDate] as? Date) ?? .distantPast + // A log created while watching is read whole; an older one only from near its end, and only + // its lines written since MacTools started count. + if created >= started.addingTimeInterval(-2) { return LogFile(offset: 0, notBefore: nil) } + return LogFile(offset: size > firstReadLimit ? size - firstReadLimit : 0, notBefore: started) + } + + /// Claude's reply that ends a turn (`stop_reason` end_turn and the like) becomes a card. + private func apply(_ line: Data.SubSequence, path: String, fallbackSession: String, notBefore: Date?) { + // Cheap test before decoding anything. + guard line.range(of: Data("\"type\":\"assistant\"".utf8)) != nil, + line.range(of: Data("\"stop_reason\":\"".utf8)) != nil, + let entry = try? JSONSerialization.jsonObject(with: Data(line)) as? [String: Any], + entry["type"] as? String == "assistant", entry["isSidechain"] as? Bool != true, + let message = entry["message"] as? [String: Any], + let stop = message["stop_reason"] as? String, + ["end_turn", "stop_sequence", "max_tokens", "refusal"].contains(stop) else { return } + if let notBefore { + let time = (entry["timestamp"] as? String).flatMap { timestampFormatter.date(from: $0) } ?? .distantPast + guard time >= notBefore else { return } + } + let session = entry["sessionId"] as? String ?? fallbackSession + let blocks = message["content"] as? [[String: Any]] ?? [] + var text = blocks.filter { $0["type"] as? String == "text" }.compactMap { $0["text"] as? String }.joined(separator: "\n") + if text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { + text = IslandClaudeTurnWatcher.lastAssistantMessage(in: path) ?? "" + } + let cleaned = IslandClaudeTurnWatcher.cleaned(text) + // Only desktop chats get a card: a reply goes into the chat in the Claude app. + guard !cleaned.isEmpty, let chat = IslandClaudeTurnWatcher.desktopChat(forSession: session) else { return } + deliver(IslandClaudeTurnWatcher.Turn(chat: chat, message: cleaned)) + } +} diff --git a/Plugins/IslandNotifications/Sources/IslandNotificationHistory.swift b/Plugins/IslandNotifications/Sources/IslandNotificationHistory.swift new file mode 100644 index 000000000..a8b42437e --- /dev/null +++ b/Plugins/IslandNotifications/Sources/IslandNotificationHistory.swift @@ -0,0 +1,132 @@ +import AppKit +import Combine +import MacToolsPluginKit + +/// One notification the island showed, as the panel's Notifications list keeps it. +struct IslandHistoryEntry: Identifiable, Equatable { + let id = UUID() + let date: Date + /// The name the list groups and labels by. + let appName: String + /// The app as Notification Centre's own rows name it ("Spark Desktop, <title>, <body>"). + let centerApp: String? + let appURL: URL? + let bundleIdentifier: String? + let title: String + let body: String + /// A Claude chat turn: there is no Notification Centre row behind it, only the chat. + let claudeChat: IslandClaudeChat? + /// Banner text lines, for finding a Messages conversation if Notification Centre no longer has it. + let lineCount: Int + + var groupKey: String { bundleIdentifier ?? appName } + + /// A third banner line is a subtitle (a group conversation's name), drawn in the title's weight. + var subtitle: String? { + guard lineCount > 2, let first = body.components(separatedBy: "\n").first, !first.isEmpty else { return nil } + return first + } + + var message: String { + guard let subtitle else { return body } + return String(body.dropFirst(subtitle.count)).trimmingCharacters(in: .newlines) + } +} + +/// The notifications the island has shown since MacTools started, newest first, as Notification +/// Centre lists them. Kept in memory only: Notification Centre stays the record, this list only +/// mirrors what passed through the island so the panel can show it. +@MainActor +final class IslandNotificationHistory: ObservableObject { + @Published private(set) var entries: [IslandHistoryEntry] = [] + static let limit = 64 + + func add(_ entry: IslandHistoryEntry) { + entries.insert(entry, at: 0) + if entries.count > Self.limit { entries.removeLast(entries.count - Self.limit) } + } + + func remove(_ entry: IslandHistoryEntry) { entries.removeAll { $0.id == entry.id } } + func removeGroup(_ key: String) { entries.removeAll { $0.groupKey == key } } + func removeAll() { entries.removeAll() } + + struct Group: Identifiable, Equatable { + let id: String + let entries: [IslandHistoryEntry] + var newest: IslandHistoryEntry { entries[0] } + } + + /// Notification Centre's automatic grouping: one stack per app, ordered by each app's newest. + static func groups(_ entries: [IslandHistoryEntry]) -> [Group] { + var order: [String] = [] + var byApp: [String: [IslandHistoryEntry]] = [:] + for entry in entries { + if byApp[entry.groupKey] == nil { order.append(entry.groupKey) } + byApp[entry.groupKey, default: []].append(entry) + } + return order.map { Group(id: $0, entries: byApp[$0] ?? []) } + } +} + +/// Matches the panel's entries to Notification Centre's rows. A row reads "<App>, <title>, <body>". +enum IslandCenterMatch { + static func normalized(_ text: String) -> String { + text.unicodeScalars.filter { $0 != "\u{200E}" && $0 != "\u{200F}" }.map(String.init).joined() + .split(whereSeparator: { $0.isWhitespace || $0.isNewline }).joined(separator: " ") + } + + /// The row is this notification: it starts with the app, then has the title and the start of + /// its text. The marks between the parts depend on the language (", " "、" "," "،"). + static func row(_ description: String, matchesApp app: String, title: String, body: String) -> Bool { + let row = normalized(description) + let title = normalized(title) + // The title is the whole next part: it starts right after the app and ends at a mark. + guard let rest = afterApp(row, app: app), rest.hasPrefix(title) else { return false } + let afterTitle = rest.dropFirst(title.count) + guard afterTitle.isEmpty || isMark(afterTitle) else { return false } + let text = normalized(body).trimmingCharacters(in: CharacterSet(charactersIn: "…")) + guard !text.isEmpty else { return true } + return afterTitle.contains(String(text.prefix(40))) + } + + /// A collapsed stack of this app's notifications; only its newest shows in the description. + static func stack(_ description: String, isApp app: String) -> Bool { + afterApp(normalized(description), app: app) != nil + } + + /// What follows the app's name and the mark after it, when the description starts with the app. + private static func afterApp(_ row: String, app: String) -> Substring? { + let app = normalized(app) + guard !app.isEmpty, row.hasPrefix(app) else { return nil } + let rest = row.dropFirst(app.count) + guard isMark(rest) else { return nil } + return rest.drop { $0.unicodeScalars.allSatisfy(IslandNotification.descriptionSeparators.contains) } + } + + /// Text that starts with a list mark (", " "、" "," "،"), not just a space inside a name. + private static func isMark(_ text: Substring) -> Bool { + text.trimmingPrefix(while: { $0 == " " }).first.map { ",、,،".contains($0) } ?? false + } +} + +/// How Notification Centre writes a notification's time: "now", "53m ago", "10:29 am", +/// "Yesterday, 10:04 pm", then the date. +enum IslandHistoryTime { + static func text(for date: Date, now: Date, localization: PluginLocalization) -> String { + let elapsed = now.timeIntervalSince(date) + if elapsed < 60 { return localization.string("history.now", defaultValue: "现在") } + if elapsed < 3600 { + let minutes = Duration.seconds(Int(elapsed / 60) * 60) + .formatted(.units(allowed: [.minutes], width: .narrow)) + return String(format: localization.string("history.ago", defaultValue: "%@前"), minutes) + } + let calendar = Calendar.current + if calendar.isDate(date, inSameDayAs: now) { return date.formatted(date: .omitted, time: .shortened) } + let formatter = DateFormatter() + formatter.doesRelativeDateFormatting = true + formatter.dateStyle = .short + formatter.timeStyle = .short + formatter.locale = PluginRuntimeLocalization.locale + return formatter.string(from: date) + } +} diff --git a/Plugins/IslandNotifications/Sources/IslandNotificationHistoryView.swift b/Plugins/IslandNotifications/Sources/IslandNotificationHistoryView.swift new file mode 100644 index 000000000..51a347fa6 --- /dev/null +++ b/Plugins/IslandNotifications/Sources/IslandNotificationHistoryView.swift @@ -0,0 +1,309 @@ +import AppKit +import MacToolsPluginKit +import SwiftUI + +enum IslandHistoryLayout { + /// The widget grows with its list up to about five notifications, then scrolls. + static let maximumHeight: CGFloat = 560 + /// Opening, folding and clearing. The panel changes height on the same spring once the host has + /// passed the new size on (about 80 ms), so the list starts that much later and both move together. + static let motion = Animation.spring(response: 0.36, dampingFraction: 0.86).delay(0.09) + /// The "No Notifications" line. + static let emptyHeight: CGFloat = 64 + static let cornerRadius: CGFloat = 16 + static let iconSize: CGFloat = 32 + /// How far each card under a stack's top card shows below it. + static let peek: CGFloat = 10 + /// The dark line between a card and the one peeking out under it, which makes the stack read. + static let gap: CGFloat = 2 + /// Room around the list for the close button, which sits over a card's corner. + static let inset: CGFloat = 8 +} + +/// The panel's Notifications list, drawn as Notification Centre draws it: one stack per app with +/// the newest on top, a click on a stack fans it out with Show Less and Clear above it, and a click +/// on a notification opens it. Hovering shows the close button at the card's corner. +struct IslandNotificationHistoryView: View { + let size: CGSize + @ObservedObject var history: IslandNotificationHistory + let localization: PluginLocalization + let onOpen: (IslandHistoryEntry) -> Void + let onClear: ([IslandHistoryEntry]) -> Void + /// The list's full height (0 when empty), so the widget can fit it. + let onContentHeight: (CGFloat) -> Void + @State private var expanded: String? + @State private var listHeight: CGFloat = 0 + @Environment(\.accessibilityReduceMotion) private var reduceMotion + + private var animation: Animation? { reduceMotion ? nil : IslandHistoryLayout.motion } + + var body: some View { + VStack(alignment: .leading, spacing: 0) { + let groups = IslandNotificationHistory.groups(history.entries) + if groups.isEmpty { + Text(localization.string("history.empty", defaultValue: "没有通知")) + .font(.system(size: 13)) + .foregroundStyle(.secondary) + .frame(maxWidth: .infinity, maxHeight: .infinity) + .onAppear { onContentHeight(0) } + } else { + ScrollView { + TimelineView(.periodic(from: .now, by: 30)) { context in + VStack(spacing: 8) { + ForEach(groups) { group in + stack(group, now: context.date) + } + } + .padding(IslandHistoryLayout.inset) + .onGeometryChange(for: CGFloat.self) { $0.size.height } action: { height in + listHeight = height + onContentHeight(height) + } + } + } + .scrollIndicators(.automatic) + // While the list fits, it isn't cut at the widget's edge: the panel's own surface + // clips it, so a list changing height and the panel following it move as one. + .scrollClipDisabled(listHeight <= IslandHistoryLayout.maximumHeight + 1) + .modifier(IslandScrollFade(overflows: listHeight > IslandHistoryLayout.maximumHeight + 1)) + } + } + .frame(width: size.width, height: size.height, alignment: .topLeading) + // No heading on screen, as in Notification Centre's list; VoiceOver still names it. + .accessibilityElement(children: .contain) + .accessibilityLabel(localization.string("history.title", defaultValue: "通知")) + .environment(\.locale, PluginRuntimeLocalization.locale) + .onChange(of: history.entries) { _, entries in + if let expanded, !entries.contains(where: { $0.groupKey == expanded }) { self.expanded = nil } + } + } + + /// One view tree for both states, so opening a stack is one motion: the cards underneath grow + /// out from their edges below the top card into full cards, and fold back the same way. + private func stack(_ group: IslandNotificationHistory.Group, now: Date) -> some View { + let open = expanded == group.id && group.entries.count > 1 + let more = group.entries.count - 1 + return VStack(spacing: 0) { + if open { + HStack(spacing: 6) { + Text(group.newest.appName) + .font(.system(size: 13, weight: .semibold)) + .lineLimit(1) + Spacer(minLength: 4) + IslandHistoryPill(title: localization.string("history.showLess", defaultValue: "收起")) { + withAnimation(animation) { expanded = nil } + } + IslandHistoryCloseButton(title: localization.string("history.clearAll", defaultValue: "全部清除"), size: 22) { + withAnimation(animation) { onClear(group.entries) } + } + } + .padding(.horizontal, 4) + .padding(.bottom, 8) + .transition(.opacity.combined(with: .offset(y: 8))) + } + ForEach(Array(group.entries.enumerated()), id: \.element.id) { index, entry in + // 0: a full card; 1 and 2: an edge peeking out under the top card; 3: hidden behind. + let level = open ? 0 : min(index, 3) + let top = index == 0 + IslandHistoryCard(entry: entry, now: now, localization: localization, + closeTitle: localization.string(top && !open && more > 0 ? "history.clearAll" : "history.close", + defaultValue: top && !open && more > 0 ? "全部清除" : "关闭"), + folded: level, + onClick: { + if top, !open, more > 0 { withAnimation(animation) { expanded = group.id } } + else { onOpen(entry) } + }, + onClose: { withAnimation(animation) { onClear(top && !open ? group.entries : [entry]) } }) + .padding(.horizontal, CGFloat(min(level, 2)) * 12) + .padding(.top, top ? 0 : (open ? 8 : (level < 3 ? IslandHistoryLayout.gap : 0))) + .zIndex(Double(-index)) + } + } + } +} + +/// Notification Centre fades its list into the edge where more is scrolled out of sight. +private struct IslandScrollFade: ViewModifier { + let overflows: Bool + @State private var atTop = true + @State private var atBottom = false + private static let fade: CGFloat = 28 + + func body(content: Content) -> some View { + let faded = content.mask { + if overflows { + VStack(spacing: 0) { + edge(faded: !atTop, towardTop: true) + Color.black + edge(faded: !atBottom, towardTop: false) + } + } else { + // Nothing to fade: the mask reaches past the edges so it cuts nothing off. + Color.black.padding(-2000) + } + } + if #available(macOS 15, *) { + faded.onScrollGeometryChange(for: [Bool].self) { geometry in + let offset = geometry.contentOffset.y + geometry.contentInsets.top + return [offset <= 1, offset + geometry.containerSize.height >= geometry.contentSize.height - 1] + } action: { _, edges in + atTop = edges[0] + atBottom = edges[1] + } + } else { + faded + } + } + + private func edge(faded: Bool, towardTop: Bool) -> some View { + LinearGradient(colors: faded ? [.clear, .black] : [.black, .black], + startPoint: towardTop ? .top : .bottom, endPoint: towardTop ? .bottom : .top) + .frame(height: Self.fade) + .animation(.easeOut(duration: 0.2), value: faded) + } +} + +/// One notification, laid out like a Notification Centre row: icon, bold title with the time on +/// the right, then the message. +private struct IslandHistoryCard: View { + let entry: IslandHistoryEntry + let now: Date + let localization: PluginLocalization + let closeTitle: String + /// 0: the card in full. 1, 2: only its lower edge shows, under a stack's top card. 3: hidden. + var folded = 0 + let onClick: () -> Void + let onClose: () -> Void + @State private var hovered = false + @Environment(\.pluginComponentTheme) private var theme + @Environment(\.colorSchemeContrast) private var contrast + + var body: some View { + let shape = RoundedRectangle(cornerRadius: IslandHistoryLayout.cornerRadius, style: .continuous) + Button(action: onClick) { + HStack(alignment: .top, spacing: 10) { + IslandHistoryIcon(url: entry.appURL) + VStack(alignment: .leading, spacing: 2) { + HStack(alignment: .firstTextBaseline, spacing: 6) { + Text(entry.title.isEmpty ? entry.appName : entry.title) + .font(.system(size: 13, weight: .semibold)) + .lineLimit(2) + Spacer(minLength: 4) + Text(IslandHistoryTime.text(for: entry.date, now: now, localization: localization)) + .font(.system(size: 11)) + .foregroundStyle(.secondary) + .lineLimit(1) + .fixedSize() + } + if let subtitle = entry.subtitle { + Text(subtitle) + .font(.system(size: 13, weight: .semibold)) + .lineLimit(1) + } + if !entry.message.isEmpty { + Text(entry.message) + .font(.system(size: 13)) + .lineLimit(4) + .multilineTextAlignment(.leading) + .frame(maxWidth: .infinity, alignment: .leading) + } + } + } + .padding(.horizontal, 12) + .padding(.vertical, 11) + .opacity(folded > 0 ? 0 : 1) + .frame(maxWidth: .infinity, alignment: .leading) + .background(theme.surfaces.card, in: shape) + // An edge under the top card is a little brighter, the second one fainter, so the stack reads. + .overlay { shape.fill(Color.primary.opacity(folded == 1 ? 0.05 : 0)).allowsHitTesting(false) } + .opacity(folded == 2 ? 0.6 : (folded == 3 ? 0 : 1)) + .overlay { + shape.strokeBorder(Color.primary.opacity(contrast == .increased ? 0.5 : 0), lineWidth: 0.75) + .allowsHitTesting(false) + } + .contentShape(shape) + // Folded, only the bottom of the card is left: its rounded lower edge. + .frame(height: folded == 0 ? nil : (folded < 3 ? IslandHistoryLayout.peek - IslandHistoryLayout.gap : 0), + alignment: .bottom) + .clipped() + } + .buttonStyle(IslandHistoryPressStyle()) + .allowsHitTesting(folded == 0) + .accessibilityHidden(folded > 0) + .overlay(alignment: .topLeading) { + if hovered, folded == 0 { + IslandHistoryCloseButton(title: closeTitle, size: 18, action: onClose) + .offset(x: -6, y: -6) + .transition(.opacity) + } + } + .onHover { inside in withAnimation(.easeOut(duration: 0.12)) { hovered = inside } } + .accessibilityElement(children: .combine) + .accessibilityAction(named: closeTitle, onClose) + } +} + +private struct IslandHistoryIcon: View { + let url: URL? + + var body: some View { + Group { + if let url { + Image(nsImage: NSWorkspace.shared.icon(forFile: url.path)).resizable() + } else { + Image(systemName: "app.badge").resizable().scaledToFit().foregroundStyle(.secondary).padding(4) + } + } + .frame(width: IslandHistoryLayout.iconSize, height: IslandHistoryLayout.iconSize) + .accessibilityHidden(true) + } +} + +/// The round ✕ Notification Centre shows on a hovered notification, and beside an open stack. +private struct IslandHistoryCloseButton: View { + let title: String + let size: CGFloat + let action: () -> Void + + var body: some View { + Button(action: action) { + Image(systemName: "xmark") + .font(.system(size: size * 0.45, weight: .bold)) + .foregroundStyle(.secondary) + .frame(width: size, height: size) + .background(.regularMaterial, in: Circle()) + .overlay(Circle().strokeBorder(Color.primary.opacity(0.12), lineWidth: 0.5)) + .contentShape(Circle()) + } + .buttonStyle(.plain) + .help(title) + .accessibilityLabel(title) + } +} + +private struct IslandHistoryPill: View { + let title: String + let action: () -> Void + + var body: some View { + Button(action: action) { + Text(title) + .font(.system(size: 11, weight: .semibold)) + .foregroundStyle(.secondary) + .padding(.horizontal, 9) + .frame(height: 22) + .background(.regularMaterial, in: Capsule()) + .contentShape(Capsule()) + } + .buttonStyle(.plain) + } +} + +private struct IslandHistoryPressStyle: ButtonStyle { + func makeBody(configuration: Configuration) -> some View { + configuration.label + .opacity(configuration.isPressed ? 0.8 : 1) + .scaleEffect(configuration.isPressed ? 0.98 : 1) + .animation(.spring(response: 0.25, dampingFraction: 0.8), value: configuration.isPressed) + } +} diff --git a/Plugins/IslandNotifications/Sources/IslandNotificationPresenter.swift b/Plugins/IslandNotifications/Sources/IslandNotificationPresenter.swift new file mode 100644 index 000000000..29f340033 --- /dev/null +++ b/Plugins/IslandNotifications/Sources/IslandNotificationPresenter.swift @@ -0,0 +1,1269 @@ +import AppKit +import OSLog +import QuartzCore +import MacToolsPluginKit + +@MainActor +final class IslandNotificationPresenter { + private final class Panel: NSPanel { + /// Only a card with a reply field takes keyboard focus, and only without activating MacTools. + var allowsKey = false + override var canBecomeKey: Bool { allowsKey } + override var canBecomeMain: Bool { false } + } + + /// Fixed-size window root. The window is allocated at the card's largest (expanded) size so + /// it never resizes; the morph surface is pinned to the top and sized to the current card. + private final class Root: NSView { + override func hitTest(_ point: NSPoint) -> NSView? { + let hit = super.hitTest(point) + return hit === self ? nil : hit + } + } + + private(set) var window: NSPanel? + private var surface: NotchMorphView? + private var splitSurface: IslandSplitMorphView? + private var splitGeometry: IslandSplitGeometry? + private var reduceMotion = false + private var animationRevision = 0 + private var card: IslandNotificationCard? + private var model = NotchMorphModel() + private var metrics: NotchMorphMetrics? + private var link: CADisplayLink? + private let target = NotchDisplayLinkTarget() + private var timestamp: CFTimeInterval? + private var completion: (() -> Void)? + private let localization: PluginLocalization + private var anchor: CGRect = .zero + private var activity: CGRect? + private var compactSize: CGSize = .zero + private var fullSize: CGSize = .zero + private var windowSizeFrame: CGRect = .zero + /// 0 = compact card, 1 = full message. + private var size = NotchMorphModel.Spring() + private var sizeTarget: Double = 0 + private var closeHandler: (() -> Void)? + private var keyObservers: [NSObjectProtocol] = [] + var onHoverChange: (() -> Void)? + /// The user pressed Send (or Return) in the reply field. + var onReply: ((String) -> Void)? + /// A click anywhere outside an open (expanded) card. + var onOutsideClick: (() -> Void)? + private var outsideClickMonitor: Any? + var isSendingReply: Bool { card?.isSendingReply ?? false } + /// Swiping down holds a card on screen (opening it if it can grow) until the user dismisses it, + /// like pulling down an iOS banner. Only swiping up dismisses. + private(set) var isHeld = false + + /// Typing, or a reply is being sent: the card must stay. + var isReplying: Bool { card?.isReplying ?? false } + /// Unsent text in the reply field. + var hasDraft: Bool { card?.hasDraft ?? false } + var isHovered: Bool { card?.isHovered ?? false } + var isExpanded: Bool { sizeTarget > 0.5 } + static let defaultPreviewLines = 4 + static let previewLineRange = 1...10 + /// Message lines a card shows before it is expanded (a setting). Applies to the next card. + var previewLines = defaultPreviewLines + private var canExpand: Bool { fullSize.height > compactSize.height + 0.5 } + + init(localization: PluginLocalization) { + self.localization = localization + target.onFrame = { [weak self] in self?.step($0) } + } + + func present(_ notification: IslandNotification, anchor: CGRect, activity: CGRect? = nil, waiting: Int, + replyable: Bool = false, + onOpen: @escaping () -> Void, onClose: @escaping () -> Void) { + hide() + // iOS-style pill: "now" beside the camera, the title line just below it. + let housing = NotchMorphMetrics(anchor: anchor, contentSize: .zero, contentTopInset: 0) + let islandCenter = housing.housingOffset + housing.housingSize.height / 2 + let islandBottom = housing.housingOffset + housing.housingSize.height + typealias Layout = IslandNotificationCard.Layout + let pill = Layout.fitsOneLine(title: notification.title, body: notification.body) + compactSize = CGSize(width: Layout.width, + height: Layout.height(islandBottom: islandBottom, title: notification.title, body: notification.body, + lines: previewLines)) + // A pill already shows its whole message; a longer card can grow to show all of it, + // up to half the visible screen height. + let screen = NSScreen.screens.first(where: { $0.frame.intersects(anchor) }) ?? NSScreen.main + let maxHeight = (screen?.visibleFrame.height ?? 800) * 0.5 + // A card with a reply field always expands (iOS: the expanded notification holds the reply). + maxCardHeight = maxHeight + naturalFullHeight = pill && !replyable ? compactSize.height + : Layout.expandedHeight(islandBottom: islandBottom, body: notification.displayBody, maxHeight: .greatestFiniteMagnitude, reply: replyable) + replyExtra = 0 + fullSize = CGSize(width: Layout.width, height: fullHeight) + self.anchor = anchor + self.activity = activity + compactIsPill = pill + self.closeHandler = onClose + size = NotchMorphModel.Spring(); sizeTarget = 0 + reduceMotion = NSWorkspace.shared.accessibilityDisplayShouldReduceMotion + updateGeometry(height: compactSize.height) + // Room for the reply field to grow to its line limit without resizing the window. + windowSizeFrame = frame(height: replyable + ? max(fullSize.height, min(naturalFullHeight + Layout.replyMaxExtra, maxCardHeight)) : fullSize.height) + let card = IslandNotificationCard(notification: notification, localization: localization, previewLines: previewLines, + replyable: replyable, + islandCenter: islandCenter, islandBottom: islandBottom, + onOpen: onOpen, onClose: onClose, onHoverChange: { [weak self] in self?.onHoverChange?() }) + card.updateCount(waiting) + card.onSend = { [weak self] text in self?.onReply?(text) } + card.onCancelReply = { [weak self] in + guard let self else { return } + // Esc with an empty reply closes the card; with unsent text it only hands typing back. + if self.card?.hasDraft == true { self.returnKeyboard() } else { self.closeHandler?() } + } + card.onReplyHeightChange = { [weak self] extra in self?.replyHeightChanged(extra) } + card.onPullOpen = { [weak self] in self?.pullOpen() } + card.onPushDismiss = { [weak self] in self?.pushDismiss() } + card.onExpandRequest = { [weak self] on in + guard let self, on ? self.canExpand && !self.isExpanded : self.isExpanded else { return false } + self.setExpanded(on); return true + } + self.card = card + card.updateExpandActions(canExpand: canExpand, expanded: isExpanded) + card.showsGrabber = canExpand + let root = Root(frame: CGRect(origin: .zero, size: windowSizeFrame.size)) + if splitGeometry != nil { + let split = IslandSplitMorphView(content: card) + splitSurface = split + root.addSubview(split) + } else { + let surface = NotchMorphView(content: card) + self.surface = surface + root.addSubview(surface) + } + let panel = Panel(contentRect: windowSizeFrame, styleMask: [.borderless, .nonactivatingPanel], + backing: .buffered, defer: false) + panel.isFloatingPanel = true + panel.isOpaque = false + panel.backgroundColor = .clear + panel.hasShadow = false + // The system island composites above app windows at every tested level. + // Split geometry starts behind it and emerges below its bottom edge. + panel.level = NSWindow.Level(rawValue: NSWindow.Level.statusBar.rawValue + 2) + panel.hidesOnDeactivate = false + panel.isReleasedWhenClosed = false + panel.animationBehavior = .none + panel.collectionBehavior = [.canJoinAllSpaces, .fullScreenAuxiliary, .ignoresCycle, .stationary] + panel.contentView = root + panel.appearance = NSAppearance(named: .darkAqua) + panel.allowsKey = replyable + for name in [NSWindow.didBecomeKeyNotification, NSWindow.didResignKeyNotification] { + keyObservers.append(NotificationCenter.default.addObserver(forName: name, object: panel, queue: .main) { [weak self] _ in + MainActor.assumeIsolated { self?.onHoverChange?() } + }) + } + self.window = panel + model = NotchMorphModel() + render() + panel.orderFrontRegardless() + expand(true) + } + + func updateCount(_ count: Int) { card?.updateCount(count) } + + /// Rebuilds the morph geometry for a card of the given height. Both geometries keep their + /// top edge fixed, so only the bottom of the shape moves. + private func updateGeometry(height: CGFloat) { + let content = CGSize(width: compactSize.width, height: height) + var metrics = NotchMorphMetrics(anchor: anchor, contentSize: content, contentTopInset: 0) + // One-line notifications keep the compact pill; longer ones use the expanded island shape. + // A pill that expands relaxes its corners continuously into the card radius. + let opened = min(max(size.value, 0), 1) + metrics.staysPill = compactIsPill && opened <= 0.0001 + metrics.pillAmount = compactIsPill ? 1 - opened : 0 + self.metrics = metrics + splitGeometry = activity.map { + var geometry = IslandSplitGeometry(activity: $0, expandedSize: metrics.expandedSize) + geometry.staysPill = metrics.staysPill + geometry.pillAmount = metrics.pillAmount + return geometry + } + } + + private var compactIsPill = false + private var naturalFullHeight: CGFloat = 0 + private var maxCardHeight: CGFloat = 0 + /// Extra height of a reply field grown past one line. + private var replyExtra: CGFloat = 0 + private var fullHeight: CGFloat { + max(compactSize.height, min(naturalFullHeight + replyExtra, max(maxCardHeight, compactSize.height))) + } + + /// The reply field grew or shrank by a line: the card follows, its top staying put. + private func replyHeightChanged(_ extra: CGFloat) { + guard extra != replyExtra else { return } + replyExtra = extra + fullSize.height = fullHeight + render() + } + + private func frame(height: CGFloat) -> CGRect { + let content = CGSize(width: compactSize.width, height: height) + let metrics = NotchMorphMetrics(anchor: anchor, contentSize: content, contentTopInset: 0) + return activity.map { IslandSplitGeometry(activity: $0, expandedSize: metrics.expandedSize).windowFrame } ?? metrics.windowFrame + } + + /// Pulling a compact card opens it (reply box included); if there is nothing more to show it + /// is held on screen until dismissed, like pulling down an iOS banner. + private func pullOpen() { + if canExpand, !isExpanded { + setExpanded(true) + } else if !isHeld { + isHeld = true + watchOutsideClicks(true) + onHoverChange?() + } + } + + /// Pushing a compact card up sends it back into the island. + private func pushDismiss() { + guard !isExpanded, let card, !card.hasDraft, !card.isSendingReply else { return } + closeHandler?() + } + + private func setExpanded(_ on: Bool) { + guard let card, window != nil, completion == nil else { return } + sizeTarget = on ? 1 : 0 + // An open card is held until dismissed; folding it back lets it time out as usual. + isHeld = on + watchOutsideClicks(on) + card.isOpen = on + if on { + card.setExpandedMode(true) + // iOS: opening a message notification puts the cursor straight in the reply field. + card.focusReply() + } else { returnKeyboard() } + card.updateExpandActions(canExpand: canExpand, expanded: on) + reduceMotion = NSWorkspace.shared.accessibilityDisplayShouldReduceMotion + if reduceMotion { + size = NotchMorphModel.Spring(value: sizeTarget) + render(); finish() + } else { startLink() } + onHoverChange?() + } + + func refreshLocalization() { card?.refreshLocalization() } + + func setReplySending() { card?.setReplySending() } + func showReplySent() { card?.showReplySent() } + func showReplyError(_ message: String) { card?.showReplyError(message) } + + /// Hands typing back to the app the user was in. MacTools never became active, so + /// re-activating the frontmost app restores its key window. + func returnKeyboard() { + guard let panel = window as? Panel, panel.isKeyWindow else { return } + card?.endEditing() + // Ordering the key panel out (unable to take key back) resigns it, so the window server + // returns typing to the active app's window; the card reappears in the same frame. + let allowed = panel.allowsKey + panel.allowsKey = false + panel.orderOut(nil) + panel.orderFrontRegardless() + panel.allowsKey = allowed + NSWorkspace.shared.frontmostApplication?.activate() + } + + func announce(_ notification: IslandNotification) { + guard let card else { return } + NSAccessibility.post(element: card, notification: .announcementRequested, userInfo: [ + .announcement: [notification.appName, notification.title, notification.body].compactMap { $0 }.joined(separator: ". "), + .priority: NSAccessibilityPriorityLevel.high.rawValue, + ]) + } + + func dismiss(completion: @escaping () -> Void) { + guard window != nil else { completion(); return } + self.completion = completion + window?.ignoresMouseEvents = true + expand(false) + } + + /// Clicks in other apps close an open card, like tapping away on iOS. A global monitor only + /// sees events for other apps, so every click it reports is outside the card. + private func watchOutsideClicks(_ on: Bool) { + if let outsideClickMonitor { NSEvent.removeMonitor(outsideClickMonitor) } + outsideClickMonitor = nil + guard on else { return } + // Left clicks only: a two-finger tap (secondary click) must not close the card. + outsideClickMonitor = NSEvent.addGlobalMonitorForEvents(matching: [.leftMouseDown]) { [weak self] _ in + MainActor.assumeIsolated { + // The window is sized for the fully open card and is mostly transparent; only a click + // on the visible card counts as inside. + guard let self, !self.visibleCardContains(NSEvent.mouseLocation) else { return } + self.onOutsideClick?() + } + } + } + + /// Whether a screen point lies on the card as drawn (not the larger transparent window). + private func visibleCardContains(_ point: NSPoint) -> Bool { + guard let card, let window = card.window else { return false } + let onScreen = window.convertToScreen(card.convert(card.bounds, to: nil)) + return onScreen.insetBy(dx: -4, dy: -4).contains(point) + } + + func hide() { + isHeld = false + watchOutsideClicks(false) + returnKeyboard() + for observer in keyObservers { NotificationCenter.default.removeObserver(observer) } + keyObservers.removeAll() + link?.invalidate(); link = nil; timestamp = nil + window?.orderOut(nil) + surface?.releaseContent() + splitSurface?.releaseContent() + splitSurface = nil; splitGeometry = nil + window = nil; surface = nil; card = nil; completion = nil; closeHandler = nil + size = NotchMorphModel.Spring(); sizeTarget = 0 + } + + isolated deinit { hide() } + + private func expand(_ expanded: Bool) { + animationRevision += 1 + let revision = animationRevision + reduceMotion = NSWorkspace.shared.accessibilityDisplayShouldReduceMotion + model.target = expanded ? 1 : 0 + if reduceMotion, splitGeometry != nil, let panel = window { + model.snapToTarget(); render() + panel.alphaValue = expanded ? 0 : 1 + NSAnimationContext.runAnimationGroup { context in + context.duration = 0.16 + panel.animator().alphaValue = expanded ? 1 : 0 + } completionHandler: { [weak self, weak panel] in + Task { @MainActor in + guard let self, let panel, self.window === panel, self.animationRevision == revision else { return } + self.finish() + } + } + } else if reduceMotion { + model.snapToTarget(); render(); finish() + } else { startLink() } + } + + private func startLink() { + guard link == nil, let root = window?.contentView else { return } + let link = root.displayLink(target: target, selector: #selector(NotchDisplayLinkTarget.step(_:))) + link.add(to: .main, forMode: .common) + self.link = link + } + + private func step(_ link: CADisplayLink) { + let now = link.targetTimestamp + let elapsed = timestamp.map { now - $0 } ?? (link.targetTimestamp - link.timestamp) + timestamp = now + let dt = min(max(elapsed, 0), 1.0 / 30.0) + model.advance(by: dt) + var remaining = dt + while remaining > 0 { + let slice = min(remaining, 1.0 / 480.0) + size.step(toward: sizeTarget, response: 0.42, dampingRatio: 0.84, dt: slice) + remaining -= slice + } + render(); finish() + } + + private func render() { + guard card != nil else { return } + let height = NotchMorphMetrics.lerp(compactSize.height, fullSize.height, max(size.value, 0)) + if metrics?.contentSize.height != height { updateGeometry(height: height) } + card?.expansion = CGFloat(min(max(size.value, 0), 1)) + guard let metrics else { return } + let current = frame(height: height).offsetBy(dx: -windowSizeFrame.minX, dy: -windowSizeFrame.minY) + let morph: NSView? = splitSurface ?? surface + if morph?.frame != current { morph?.frame = current } + if let splitGeometry { + splitSurface?.apply(model: model, geometry: splitGeometry, contentSize: metrics.contentSize, reduceMotion: reduceMotion) + } else { surface?.apply(model: model, metrics: metrics) } + } + + private func finish() { + guard model.isSettled, size.isSettled(at: sizeTarget) else { return } + model.snapToTarget() + size = NotchMorphModel.Spring(value: sizeTarget) + if sizeTarget == 0 { card?.setExpandedMode(false) } + render() + link?.invalidate(); link = nil; timestamp = nil + if model.target == 0, let completion { + hide(); completion() + } + } +} + +@MainActor +private final class IslandNotificationCard: NSView { + /// iOS notification pill, adapted to the Mac island: icon on the left, "now" beside the + /// camera, then one line with the bold title and grey message below the camera. + enum Layout { + static let width: CGFloat = 450 + static let iconSize: CGFloat = 46 + static let iconToText: CGFloat = 12 + static let metaHeight: CGFloat = 16 + static let lineHeight: CGFloat = 19 + static let belowIsland: CGFloat = 2 + static let badgeSize: CGFloat = 18 + + /// The two text lines form one block: "now" sits low beside the camera and the title + /// line starts just below it. The pill is as tall as that block plus equal padding + /// above and below, so the block and the icon are centred and the icon is concentric + /// with the pill's round end. + static func metaTop(islandBottom: CGFloat) -> CGFloat { islandBottom - metaHeight - 1 } + static func lineTop(islandBottom: CGFloat) -> CGFloat { islandBottom + belowIsland } + static var metaFont: NSFont { NSFont.systemFont(ofSize: 12, weight: .semibold) } + static var titleFont: NSFont { NSFont.systemFont(ofSize: 14, weight: .semibold) } + static var bodyFont: NSFont { NSFont.systemFont(ofSize: 14, weight: .regular) } + + static let bodyGap: CGFloat = 3 + static let bottomPadding: CGFloat = 18 + static let approxTextLeading: CGFloat = 20 + 46 + 12 + + /// True when "Title Message" fits the single pill line next to the close button. + static func fitsOneLine(title: String, body: String) -> Bool { + let available = width - approxTextLeading - 22 + let titleWidth = (title as NSString).size(withAttributes: [.font: titleFont]).width + let bodyText = body.replacingOccurrences(of: "\n", with: " ") + let bodyWidth = bodyText.isEmpty ? 0 : (" " + bodyText as NSString).size(withAttributes: [.font: bodyFont]).width + return ceil(titleWidth + bodyWidth) <= available + } + + static var bodyWidth: CGFloat { width - (20 + 46 + 14) - 22 } + + static func bodyHeight(_ body: String, lines: Int) -> CGFloat { + guard !body.isEmpty else { return 0 } + let line = ceil(bodyFont.ascender - bodyFont.descender + bodyFont.leading) + let measured = (body as NSString).boundingRect( + with: CGSize(width: bodyWidth, height: .greatestFiniteMagnitude), + options: [.usesLineFragmentOrigin, .usesFontLeading], attributes: [.font: bodyFont]).height + return min(ceil(measured), line * CGFloat(lines)) + } + + static func height(islandBottom: CGFloat, title: String, body: String, lines: Int) -> CGFloat { + if fitsOneLine(title: title, body: body) { return height(islandBottom: islandBottom) } + let bodyBlock = body.isEmpty ? 0 : bodyGap + bodyHeight(body, lines: lines) + return lineTop(islandBottom: islandBottom) + lineHeight + bodyBlock + bottomPadding + } + + /// Height that shows the whole message, capped (e.g. at half the screen). + static func expandedHeight(islandBottom: CGFloat, body: String, maxHeight: CGFloat, reply: Bool) -> CGFloat { + let text = body + let measured = text.isEmpty ? 0 : (text as NSString).boundingRect( + with: CGSize(width: bodyWidth, height: .greatestFiniteMagnitude), + options: [.usesLineFragmentOrigin, .usesFontLeading], attributes: [.font: bodyFont]).height + let bodyBlock = text.isEmpty ? 0 : bodyGap + ceil(measured) + let bottom = reply ? replyGap + replyHeight + replyBottom : bottomPadding + let full = lineTop(islandBottom: islandBottom) + lineHeight + bodyBlock + bottom + return min(full, maxHeight) + } + + /// iOS-style reply field: a capsule under the message with a round send button. + static let replyHeight: CGFloat = 34 + /// The field grows to five lines (Apple's lineLimit pattern), then scrolls inside. + static let replyMaxLines = 5 + static var replyLineHeight: CGFloat { + let font = NSFont.systemFont(ofSize: 14) + return ceil(font.ascender - font.descender + font.leading) + } + static var replyMaxExtra: CGFloat { CGFloat(replyMaxLines - 1) * replyLineHeight } + static let replyGap: CGFloat = 12 + static let replyBottom: CGFloat = 16 + static let replyStatusHeight: CGFloat = 18 + + static func smoothstep(_ edge0: CGFloat, _ edge1: CGFloat, _ x: CGFloat) -> CGFloat { + let t = min(max((x - edge0) / (edge1 - edge0), 0), 1) + return t * t * (3 - 2 * t) + } + + static func height(islandBottom: CGFloat) -> CGFloat { + let blockBottom = lineTop(islandBottom: islandBottom) + lineHeight + return blockBottom + metaTop(islandBottom: islandBottom) + } + } + + private let onOpen: () -> Void + private let onClose: () -> Void + private let onHoverChange: () -> Void + private let localization: PluginLocalization + private let islandCenter: CGFloat + private let islandBottom: CGFloat + private let icon = NSImageView() + private let now = NSTextField(labelWithString: "") + private let line = NSTextField(labelWithString: "") + /// Title-only line that cross-fades over the one-line pill text as a pill expands. + private let titleLine = NSTextField(labelWithString: "") + private let reply: IslandReplyBar? + private let replyStatus = NSTextField(labelWithString: "") + var onSend: ((String) -> Void)? + var onCancelReply: (() -> Void)? + var onReplyHeightChange: ((CGFloat) -> Void)? + var isReplying: Bool { reply?.isActive ?? false } + var hasDraft: Bool { reply?.hasDraft ?? false } + var isSendingReply: Bool { reply?.isSendingReply ?? false } + private let bodyField = NSTextField(wrappingLabelWithString: "") + /// The message scrolls inside the expanded card when it is taller than the card can grow. + private let bodyScroll = IslandBodyScrollView() + private let singleLine: Bool + private let compactHeight: CGFloat + private let previewLines: Int + private lazy var previewBodyHeight = Layout.bodyHeight(bodyField.stringValue, lines: previewLines) + /// Full message height for the last measured width; layout runs every animation frame. + private var measuredBody: (width: CGFloat, height: CGFloat)? + private var combinedText = NSAttributedString() + private var titleText = NSAttributedString() + /// True while showing (or animating to/from) the full message. + private(set) var expandedMode = false + /// 0 = compact layout, 1 = fully expanded; driven by the presenter's size spring. + var expansion: CGFloat = 0 { didSet { needsLayout = true } } + /// Scroll gestures (true = fingers up) and explicit expand/collapse requests (VoiceOver). + /// Gesture results; the card's router decides them (see `route`). + var onPullOpen: (() -> Void)? + var onPushDismiss: (() -> Void)? + /// Set by the presenter: an open card only scrolls its message, never opens or dismisses. + var isOpen = false + /// The "pull to open" hint, shown when the card has more (cut-off text or a reply box). + var showsGrabber = false { didSet { needsLayout = true } } + private let grabber = NSView() + var onExpandRequest: ((Bool) -> Bool)? + private let close = NSButton() + private let count = NSTextField(labelWithString: "") + private(set) var isHovered = false + private var tracking: NSTrackingArea? + private var waiting = 0 + + override var isFlipped: Bool { true } + + init(notification: IslandNotification, localization: PluginLocalization, previewLines: Int, replyable: Bool, + islandCenter: CGFloat, islandBottom: CGFloat, + onOpen: @escaping () -> Void, onClose: @escaping () -> Void, onHoverChange: @escaping () -> Void) { + self.onHoverChange = onHoverChange + self.onOpen = onOpen; self.onClose = onClose; self.localization = localization + self.islandCenter = islandCenter; self.islandBottom = islandBottom + singleLine = Layout.fitsOneLine(title: notification.title, body: notification.body) + self.previewLines = previewLines + reply = replyable ? IslandReplyBar(placeholder: localization.string("reply.placeholder", defaultValue: "信息"), + sendLabel: localization.string("reply.send", defaultValue: "发送")) : nil + compactHeight = Layout.height(islandBottom: islandBottom, title: notification.title, body: notification.body, + lines: previewLines) + super.init(frame: CGRect(x: 0, y: 0, width: Layout.width, height: compactHeight)) + setAccessibilityElement(true) + setAccessibilityRole(.button) + setAccessibilityLabel([notification.appName, notification.title, notification.body] + .compactMap { $0 }.filter { !$0.isEmpty }.joined(separator: ". ")) + updateActions() + + if let appIcon = notification.appIcon { + icon.image = appIcon + } else { + icon.image = NSImage(systemSymbolName: "bell.fill", accessibilityDescription: nil) + icon.symbolConfiguration = .init(pointSize: 20, weight: .semibold) + icon.contentTintColor = .white + } + icon.imageScaling = .scaleProportionallyUpOrDown + + let relative = RelativeDateTimeFormatter() + relative.locale = PluginRuntimeLocalization.locale + relative.dateTimeStyle = .named + // The small tinted line names the sending app (the banner is always "now" while shown). + // "Calendar · Time-Sensitive" when the banner carries a label, as iOS shows it. + now.stringValue = [notification.appName ?? relative.localizedString(fromTimeInterval: 0), + notification.label?.capitalized].compactMap { $0 }.joined(separator: " · ") + now.lineBreakMode = .byTruncatingTail + now.font = Layout.metaFont + now.textColor = Self.accent(from: notification.appIcon) + count.font = Layout.metaFont + count.textColor = NSColor.white.withAlphaComponent(0.5) + count.alignment = .right + + // Title in bold, message in grey, on one truncating line like iOS. + let text = NSMutableAttributedString(string: notification.title, attributes: [ + .font: Layout.titleFont, .foregroundColor: NSColor.white, + ]) + if let subtitle = notification.subtitle { + text.append(NSAttributedString(string: (notification.title.isEmpty ? "" : " ") + subtitle, attributes: [ + .font: Layout.titleFont, .foregroundColor: NSColor.white, + ])) + } + if !notification.message.isEmpty { + let oneLine = notification.message.replacingOccurrences(of: "\n", with: " ") + text.append(NSAttributedString(string: (text.length == 0 ? "" : " ") + oneLine, attributes: [ + .font: Layout.bodyFont, .foregroundColor: NSColor.white.withAlphaComponent(0.55), + ])) + } + let truncating = NSMutableParagraphStyle() + truncating.lineBreakMode = .byTruncatingTail + text.addAttribute(.paragraphStyle, value: truncating, range: NSRange(location: 0, length: text.length)) + combinedText = text + titleText = NSAttributedString(string: notification.title, attributes: [ + .font: Layout.titleFont, .foregroundColor: NSColor.white, .paragraphStyle: truncating, + ]) + // macOS banners carry at most 1,024 characters; mark a body cut at that limit. + bodyField.font = Layout.bodyFont + bodyField.textColor = NSColor.white.withAlphaComponent(0.7) + // A subtitle (a group's name) heads the message in the title's weight, as Apple draws it. + let bodyText = NSMutableAttributedString() + if let subtitle = notification.subtitle { + bodyText.append(NSAttributedString(string: subtitle + (notification.message.isEmpty ? "" : "\n"), attributes: [ + .font: Layout.titleFont, .foregroundColor: NSColor.white, + ])) + } + bodyText.append(NSAttributedString(string: notification.message, attributes: [ + .font: Layout.bodyFont, .foregroundColor: NSColor.white.withAlphaComponent(0.7), + ])) + bodyField.attributedStringValue = bodyText + bodyField.maximumNumberOfLines = previewLines + bodyField.lineBreakMode = .byWordWrapping + bodyField.cell?.wraps = true + bodyField.cell?.truncatesLastVisibleLine = true + // Compact pill: title and message share one line. Compact card: title, then message. + line.attributedStringValue = singleLine ? combinedText : titleText + titleLine.attributedStringValue = titleText + titleLine.lineBreakMode = .byTruncatingTail + titleLine.isHidden = true + bodyScroll.isHidden = singleLine || notification.body.isEmpty + replyStatus.font = NSFont.systemFont(ofSize: 12, weight: .medium) + replyStatus.textColor = .systemOrange + replyStatus.lineBreakMode = .byTruncatingTail + replyStatus.isHidden = true + line.lineBreakMode = .byTruncatingTail + line.maximumNumberOfLines = 1 + line.toolTip = [notification.title, notification.body].filter { !$0.isEmpty }.joined(separator: "\n") + + close.image = NSImage(systemSymbolName: "xmark", accessibilityDescription: localization.string("card.close", defaultValue: "关闭通知")) + // macOS-style close badge: small, on the icon's top-left corner, only while hovered. + close.symbolConfiguration = .init(pointSize: 7.5, weight: .heavy) + close.contentTintColor = NSColor.white.withAlphaComponent(0.9) + close.isBordered = false; close.target = self; close.action = #selector(dismissCard) + close.wantsLayer = true + close.layer?.cornerRadius = Layout.badgeSize / 2 + close.layer?.backgroundColor = NSColor(white: 0.24, alpha: 1).cgColor + close.layer?.borderWidth = 0.5 + close.layer?.borderColor = NSColor.white.withAlphaComponent(0.22).cgColor + close.alphaValue = 0 + close.setAccessibilityLabel(localization.string("card.close", defaultValue: "关闭通知")) + close.toolTip = localization.string("card.close", defaultValue: "关闭通知") + bodyScroll.setContent(bodyField) + bodyScroll.router = self + grabber.wantsLayer = true + grabber.layer?.backgroundColor = NSColor.white.withAlphaComponent(0.35).cgColor + grabber.layer?.cornerRadius = 2 + grabber.alphaValue = 0 + addSubview(grabber) + for view in [icon, now, count, line, titleLine, bodyScroll, replyStatus, close] as [NSView] { addSubview(view) } + if let reply { + reply.onSend = { [weak self] text in self?.onSend?(text) } + reply.router = self + reply.onCancel = { [weak self] in self?.onCancelReply?() } + reply.onHeightChange = { [weak self] height in + self?.onReplyHeightChange?(height - Layout.replyHeight) + self?.needsLayout = true + } + reply.isHidden = true + addSubview(reply, positioned: .below, relativeTo: close) + } + layoutCard() + } + + @available(*, unavailable) + required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } + + /// A readable accent from the app icon's most saturated colour (Messages green, Reminders red). + /// Icons without a real colour (Script Editor, System Settings) get the plain secondary grey, + /// as Apple's own banners do. + private static func accent(from image: NSImage?) -> NSColor { + let fallback = NSColor.white.withAlphaComponent(0.6) + guard let image, let cg = image.cgImage(forProposedRect: nil, context: nil, hints: nil) else { return fallback } + let side = 12 + var pixels = [UInt8](repeating: 0, count: side * side * 4) + guard let context = CGContext(data: &pixels, width: side, height: side, bitsPerComponent: 8, bytesPerRow: side * 4, + space: CGColorSpace(name: CGColorSpace.sRGB)!, + bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue) else { return fallback } + context.draw(cg, in: CGRect(x: 0, y: 0, width: side, height: side)) + var best: (score: CGFloat, color: NSColor)? + for index in stride(from: 0, to: pixels.count, by: 4) where pixels[index + 3] > 200 { + let color = NSColor(srgbRed: CGFloat(pixels[index]) / 255, green: CGFloat(pixels[index + 1]) / 255, + blue: CGFloat(pixels[index + 2]) / 255, alpha: 1) + let score = color.saturationComponent * color.brightnessComponent + if score > (best?.score ?? 0.25) { best = (score, color) } + } + guard let color = best?.color else { return fallback } + return NSColor(hue: color.hueComponent, saturation: min(color.saturationComponent, 0.8), + brightness: max(color.brightnessComponent, 0.85), alpha: 1) + } + + private func layoutCard() { + let bleed: CGFloat = icon.image?.isTemplate == true ? 0 : 4 + let pillHeight = Layout.height(islandBottom: islandBottom) + let e = min(max(expansion, 0), 1) + // The grabber sits at the bottom centre and fades out as the card opens. + grabber.frame = CGRect(x: ((bounds.width - 28) / 2).rounded(), y: bounds.height - 9, width: 28, height: 4) + grabber.alphaValue = showsGrabber ? 1 - min(e * 2, 1) : 0 + // Compact pill: icon concentric with the round end. Compact card: icon centred on the + // card with a 20 pt inset. Expanded (iOS): the icon's top lines up with the top of the + // app-name text. + let compactInset = singleLine ? (pillHeight - Layout.iconSize) / 2 : 20 + let compactTop = (singleLine ? pillHeight / 2 : compactHeight / 2) - Layout.iconSize / 2 + let metaFont = Layout.metaFont + let textTop = Layout.metaTop(islandBottom: islandBottom) + (metaFont.ascender - metaFont.capHeight).rounded() + let iconRect = CGRect(x: Self.lerp(compactInset, 20, e), y: Self.lerp(compactTop, textTop, e), + width: Layout.iconSize, height: Layout.iconSize) + icon.frame = iconRect.insetBy(dx: -bleed, dy: -bleed) + close.frame = CGRect(x: iconRect.minX - 5, y: iconRect.minY - 5, width: Layout.badgeSize, height: Layout.badgeSize) + let compactLeading = singleLine ? compactInset + Layout.iconSize + Layout.iconToText : 20 + Layout.iconSize + 14 + let leading = Self.lerp(compactLeading, 20 + Layout.iconSize + 14, e) + let rightEdge = bounds.width - 20 + now.frame = CGRect(x: leading, y: Layout.metaTop(islandBottom: islandBottom), width: 110, height: Layout.metaHeight) + count.frame = CGRect(x: rightEdge - 34, y: Layout.metaTop(islandBottom: islandBottom), width: 34, height: Layout.metaHeight) + line.frame = CGRect(x: leading, y: Layout.lineTop(islandBottom: islandBottom), + width: rightEdge - leading, height: Layout.lineHeight) + titleLine.frame = line.frame + // A pill swaps "Title Message" for the title, with the message wrapping below it. + let fade = Layout.smoothstep(0.05, 0.55, e) + if singleLine { + line.alphaValue = 1 - fade + titleLine.alphaValue = fade + bodyScroll.alphaValue = fade + } + // The reply field sits at the bottom of the expanded card and fades in as it opens. + var bottomLimit = bounds.height - Layout.bottomPadding + if let reply { + let replyHeight = reply.preferredHeight + let replyRect = CGRect(x: 20, y: bounds.height - Layout.replyBottom - replyHeight, + width: bounds.width - 40, height: replyHeight) + reply.frame = replyRect + reply.alphaValue = Layout.smoothstep(0.5, 1, e) + reply.isHidden = e < 0.01 + bottomLimit = replyRect.minY - Layout.replyGap + if !replyStatus.isHidden { + replyStatus.frame = CGRect(x: 22, y: replyRect.minY - Layout.replyStatusHeight - 4, + width: replyRect.width - 4, height: Layout.replyStatusHeight) + bottomLimit = replyStatus.frame.minY - 2 + } + } + guard !singleLine || expandedMode else { return } + let bodyTop = Layout.lineTop(islandBottom: islandBottom) + Layout.lineHeight + Layout.bodyGap + let preview = previewBodyHeight + // Expanded: the message fills the growing card and is revealed as the shape opens. It never + // shrinks below the preview, so the reply field fades in over space that is opening up. + let height = expandedMode ? max(singleLine ? 0 : preview, bottomLimit - bodyTop) : preview + let width = rightEdge - leading + let visible = max(0, height) + bodyScroll.frame = CGRect(x: leading, y: bodyTop, width: width, height: visible) + // Expanded: the field is as tall as the whole message; the scroll view shows what fits. + var full: CGFloat = 0 + if expandedMode { + if measuredBody?.width != width { + let size = bodyField.cell?.cellSize(forBounds: CGRect(x: 0, y: 0, width: width, height: .greatestFiniteMagnitude)) + measuredBody = (width, ceil(size?.height ?? 0)) + } + full = measuredBody?.height ?? 0 + } + let fieldFrame = CGRect(x: 0, y: 0, width: width, height: max(visible, full)) + if bodyField.frame != fieldFrame { + bodyField.frame = fieldFrame + bodyField.preferredMaxLayoutWidth = width + bodyScroll.documentView?.frame = CGRect(origin: .zero, size: fieldFrame.size) + } + } + + override func layout() { + super.layout() + layoutCard() + } + + /// Switches between the compact text arrangement and the full message. + func setExpandedMode(_ on: Bool) { + guard on != expandedMode else { return } + expandedMode = on + if singleLine { + titleLine.isHidden = !on + bodyScroll.isHidden = !on || bodyField.stringValue.isEmpty + if !on { line.alphaValue = 1 } + } + bodyField.maximumNumberOfLines = on ? 0 : previewLines + if !on { bodyScroll.contentView.scroll(to: .zero) } + needsLayout = true + } + + private static func lerp(_ a: CGFloat, _ b: CGFloat, _ t: CGFloat) -> CGFloat { a + (b - a) * t } + + func endEditing() { reply?.endEditing() } + func focusReply() { reply?.focus() } + func setReplySending() { + replyStatus.isHidden = true + reply?.setSending(true) + needsLayout = true + } + func showReplySent() { reply?.showSent(localization.string("reply.sent", defaultValue: "已发送")) } + func showReplyError(_ message: String) { + reply?.setSending(false) + replyStatus.stringValue = message + replyStatus.toolTip = message + replyStatus.isHidden = false + needsLayout = true + } + + func updateCount(_ waiting: Int) { + self.waiting = waiting + count.stringValue = waiting == 0 ? "" : "+\(waiting)" + count.setAccessibilityLabel(waiting == 0 ? nil : localization.format("card.waiting", defaultValue: "还有 %@ 条通知", + waiting.formatted(.number.locale(PluginRuntimeLocalization.locale)))) + } + + func refreshLocalization() { + close.setAccessibilityLabel(localization.string("card.close", defaultValue: "关闭通知")) + close.toolTip = localization.string("card.close", defaultValue: "关闭通知") + updateActions() + updateCount(waiting) + } + + private var canExpand = false + private var showsFullMessage = false + + /// VoiceOver actions: open, dismiss, and Show More / Show Less when the message is cut off. + func updateExpandActions(canExpand: Bool, expanded: Bool) { + self.canExpand = canExpand; showsFullMessage = expanded + updateActions() + } + + private func updateActions() { + var actions = [ + NSAccessibilityCustomAction(name: localization.string("card.open", defaultValue: "打开通知"), handler: { [weak self] in self?.onOpen(); return true }), + NSAccessibilityCustomAction(name: localization.string("card.close", defaultValue: "关闭通知"), handler: { [weak self] in self?.onClose(); return true }), + ] + if canExpand { + let expand = !showsFullMessage + let name = expand ? localization.string("card.expand", defaultValue: "展开") + : localization.string("card.collapse", defaultValue: "收起") + actions.append(NSAccessibilityCustomAction(name: name, handler: { [weak self] in + self?.onExpandRequest?(expand) ?? false + })) + } + setAccessibilityCustomActions(actions) + } + + override func updateTrackingAreas() { + super.updateTrackingAreas() + if let tracking { removeTrackingArea(tracking) } + let area = NSTrackingArea(rect: .zero, options: [.mouseEnteredAndExited, .activeAlways, .inVisibleRect], owner: self) + addTrackingArea(area); tracking = area + } + + /// One click opens the card, like Apple's banners. A card with a reply field can take key, so + /// AppKit asks the clicked view whether that first click counts; the icon and grabber would + /// say no, so they answer as the card. + override func hitTest(_ point: NSPoint) -> NSView? { + let hit = super.hitTest(point) + return hit === icon || hit === grabber ? self : hit + } + + override func acceptsFirstMouse(for event: NSEvent?) -> Bool { true } + override func mouseEntered(with event: NSEvent) { + armedAt = max(armedAt, ProcessInfo.processInfo.systemUptime + 0.3) + isHovered = true; close.animator().alphaValue = 1; onHoverChange() + } + override func mouseExited(with event: NSEvent) { isHovered = false; close.animator().alphaValue = 0; onHoverChange() } + override func mouseUp(with event: NSEvent) { onOpen() } + + // MARK: Gestures + // + // One rule: each gesture does one thing, decided when it starts, and keeps that owner to the + // end (momentum included). + // Compact card: pull (content moves down) opens it, or holds it if there's nothing more; + // push (content moves up) dismisses it into the island. 30 pt of net finger + // travel acts; the glide after the fingers lift never counts. + // Open card: a long message scrolls (bouncing at its ends); nothing else happens. + // Directions come from the raw scrollingDeltaY, the same sign NSScrollView scrolls by. + // A card arms 0.3 s after it appears and after the pointer arrives, so a scroll meant for the + // app underneath can't hit it. + private enum GestureOwner { case none, ignored, card, spent, scroll } + private var gestureOwner = GestureOwner.none + private weak var scrollOwner: IslandRoutedScrollView? + private var travel: CGFloat = 0 + private var armedAt = ProcessInfo.processInfo.systemUptime + 0.3 + private var lastWheelTick: TimeInterval = 0 + private static let actTravel: CGFloat = 30 + private let gestureLog = Logger(subsystem: "MacTools.IslandNotifications", category: "gesture") + + override func scrollWheel(with event: NSEvent) { route(event, from: nil) } + + /// Every scroll over the card arrives here: from the card itself, the message and the reply field. + func route(_ event: NSEvent, from source: IslandRoutedScrollView?) { + let now = ProcessInfo.processInfo.systemUptime + let wheel = event.phase.isEmpty && event.momentumPhase.isEmpty + let starts = event.phase == .began || (wheel && now - lastWheelTick > 0.25) + if wheel { lastWheelTick = now } + if starts { + travel = 0 + if now < armedAt { + gestureOwner = .ignored + } else if !isOpen { + gestureOwner = .card + } else if let source, source.canScroll { + gestureOwner = .scroll + scrollOwner = source + } else { + gestureOwner = .ignored + } + } + switch gestureOwner { + case .scroll: + scrollOwner?.scrollContent(event) + case .card: + guard event.momentumPhase.isEmpty else { break } + travel += event.hasPreciseScrollingDeltas ? event.scrollingDeltaY : event.scrollingDeltaY * 10 + if travel >= Self.actTravel { + gestureOwner = .spent + gestureLog.notice("pull: open travel=\(Int(self.travel), privacy: .public)") + onPullOpen?() + } else if travel <= -Self.actTravel { + gestureOwner = .spent + gestureLog.notice("push: dismiss travel=\(Int(self.travel), privacy: .public)") + // The card goes, but the fingers are still moving: the rest of this swipe must not + // scroll whatever is under the card. + if let window { + IslandScrollSink.hold(over: window.convertToScreen(convert(bounds, to: nil)), level: window.level) + } + onPushDismiss?() + } + case .none, .ignored, .spent: + break + } + if event.phase == .ended || event.phase == .cancelled, gestureOwner == .card { + gestureLog.notice("gesture ended without acting travel=\(Int(self.travel), privacy: .public)") + } + if (event.phase == .ended || event.phase == .cancelled) && gestureOwner != .scroll { gestureOwner = .none } + if event.momentumPhase == .ended { gestureOwner = .none } + } + override func accessibilityPerformPress() -> Bool { onOpen(); return true } + override func keyDown(with event: NSEvent) { + if event.keyCode == 53 { onClose() } + else if event.keyCode == 36 || event.keyCode == 49 { onOpen() } + else { super.keyDown(with: event) } + } + override var acceptsFirstResponder: Bool { true } + @objc private func dismissCard() { onClose() } +} + +/// The reply capsule, like the Messages input on iOS: it grows a line at a time up to +/// `replyMaxLines`, then scrolls inside. Return sends, Shift- or Option-Return adds a line, +/// Esc hands typing back to the previous app. +@MainActor +private final class IslandReplyBar: NSView, NSTextViewDelegate { + private final class TextView: NSTextView { + // The first click on a non-key panel goes straight into the field. + override func acceptsFirstMouse(for event: NSEvent?) -> Bool { true } + } + + private static var font: NSFont { NSFont.systemFont(ofSize: 14) } + private static let verticalPadding: CGFloat = 8.5 + private let scroll = IslandRoutedScrollView() + weak var router: IslandNotificationCard? { + get { scroll.router } + set { scroll.router = newValue } + } + private let textView = TextView() + private let placeholder = NSTextField(labelWithString: "") + private let send = NSButton() + private var isSending = false + private(set) var preferredHeight = IslandNotificationCard.Layout.replyHeight + var onSend: ((String) -> Void)? + var onCancel: (() -> Void)? + var onHeightChange: ((CGFloat) -> Void)? + + override var isFlipped: Bool { true } + + /// Typing in the field, or a reply is on its way. + var isActive: Bool { + isSending || (window?.isKeyWindow == true && window?.firstResponder === textView) + } + + init(placeholder text: String, sendLabel: String) { + super.init(frame: .zero) + wantsLayer = true + layer?.backgroundColor = NSColor.white.withAlphaComponent(0.12).cgColor + layer?.cornerCurve = .continuous + layer?.borderWidth = 0.5 + layer?.borderColor = NSColor.white.withAlphaComponent(0.1).cgColor + + textView.isRichText = false + textView.importsGraphics = false + textView.allowsUndo = true + textView.font = Self.font + textView.textColor = .white + textView.drawsBackground = false + textView.textContainerInset = .zero + textView.textContainer?.lineFragmentPadding = 0 + textView.textContainer?.widthTracksTextView = true + textView.isVerticallyResizable = true + textView.isHorizontallyResizable = false + textView.autoresizingMask = [.width] + textView.isAutomaticQuoteSubstitutionEnabled = true + textView.delegate = self + textView.setAccessibilityLabel(text) + scroll.documentView = textView + scroll.drawsBackground = false + scroll.borderType = .noBorder + scroll.hasVerticalScroller = true + scroll.autohidesScrollers = true + scroll.scrollerStyle = .overlay + scroll.verticalScrollElasticity = .none + + placeholder.stringValue = text + placeholder.font = Self.font + placeholder.textColor = NSColor.white.withAlphaComponent(0.4) + + send.image = NSImage(systemSymbolName: "arrow.up", accessibilityDescription: sendLabel) + send.symbolConfiguration = .init(pointSize: 12, weight: .bold) + send.imagePosition = .imageOnly + send.isBordered = false + send.wantsLayer = true + send.contentTintColor = .white + send.target = self + send.action = #selector(sendTapped) + send.toolTip = sendLabel + send.setAccessibilityLabel(sendLabel) + for view in [scroll, placeholder, send] as [NSView] { addSubview(view) } + updateSend() + } + + @available(*, unavailable) + required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } + + override func layout() { + super.layout() + let h = bounds.height + // A pill while it is one line; a rounded rectangle with the same corners as it grows. + layer?.cornerRadius = IslandNotificationCard.Layout.replyHeight / 2 + let button = IslandNotificationCard.Layout.replyHeight - 8 + // The send button stays at the bottom right, beside the last line (iOS). + send.frame = CGRect(x: bounds.width - 4 - button, y: h - 4 - button, width: button, height: button) + send.layer?.cornerRadius = button / 2 + let textFrame = CGRect(x: 14, y: Self.verticalPadding, width: send.frame.minX - 20, + height: max(0, h - Self.verticalPadding * 2)) + if scroll.frame != textFrame { + scroll.frame = textFrame + textView.frame.size.width = textFrame.width + textView.textContainer?.containerSize = CGSize(width: textFrame.width, height: .greatestFiniteMagnitude) + updateHeight() + } + placeholder.frame = CGRect(x: 14, y: Self.verticalPadding, width: textFrame.width, height: IslandNotificationCard.Layout.replyLineHeight) + } + + // Clicks on the capsule focus the field and never fall through to "open the app". + override func acceptsFirstMouse(for event: NSEvent?) -> Bool { true } + override func mouseDown(with event: NSEvent) { focus() } + override func mouseUp(with event: NSEvent) {} + + func focus() { + guard !isSending else { return } + window?.makeKeyAndOrderFront(nil) + window?.makeFirstResponder(textView) + } + + func endEditing() { + if window?.firstResponder === textView { window?.makeFirstResponder(nil) } + } + + func setSending(_ sending: Bool) { + isSending = sending + textView.isEditable = !sending + textView.textColor = sending ? NSColor.white.withAlphaComponent(0.5) : .white + updateSend() + } + + func showSent(_ label: String) { + isSending = true + textView.isEditable = false + textView.string = "" + placeholder.stringValue = label + placeholder.font = NSFont.systemFont(ofSize: 14, weight: .medium) + placeholder.textColor = NSColor.white.withAlphaComponent(0.75) + placeholder.isHidden = false + send.image = NSImage(systemSymbolName: "checkmark", accessibilityDescription: label) + send.layer?.backgroundColor = NSColor.systemGreen.cgColor + send.isEnabled = false + updateHeight() + NSAccessibility.post(element: self, notification: .announcementRequested, + userInfo: [.announcement: label, .priority: NSAccessibilityPriorityLevel.high.rawValue]) + } + + private var trimmed: String { textView.string.trimmingCharacters(in: .whitespacesAndNewlines) } + var hasDraft: Bool { !isSending && !trimmed.isEmpty } + var isSendingReply: Bool { isSending } + + private func updateSend() { + let ready = !trimmed.isEmpty && !isSending + send.isEnabled = ready + send.layer?.backgroundColor = (ready ? NSColor.systemBlue : NSColor.white.withAlphaComponent(0.16)).cgColor + } + + /// One line up to `replyMaxLines`; past that the field keeps its height and scrolls. + private func updateHeight() { + guard let container = textView.textContainer, let manager = textView.layoutManager else { return } + manager.ensureLayout(for: container) + let line = IslandNotificationCard.Layout.replyLineHeight + let content = max(line, ceil(manager.usedRect(for: container).height)) + let visible = min(content, line * CGFloat(IslandNotificationCard.Layout.replyMaxLines)) + let height = max(IslandNotificationCard.Layout.replyHeight, visible + Self.verticalPadding * 2) + textView.scrollRangeToVisible(textView.selectedRange()) + guard height != preferredHeight else { return } + preferredHeight = height + onHeightChange?(height) + } + + func textDidChange(_ notification: Notification) { + placeholder.isHidden = !textView.string.isEmpty + updateSend() + updateHeight() + } + + func textView(_ textView: NSTextView, doCommandBy selector: Selector) -> Bool { + if selector == #selector(NSResponder.insertNewline(_:)) { + // Shift-Return adds a line; Option-Return arrives as insertNewlineIgnoringFieldEditor. + if NSApp.currentEvent?.modifierFlags.contains(.shift) == true { return false } + sendTapped(); return true + } + if selector == #selector(NSResponder.cancelOperation(_:)) { onCancel?(); return true } + return false + } + + @objc private func sendTapped() { + let text = trimmed + guard !text.isEmpty, !isSending else { return } + onSend?(text) + } +} + +/// A scroll view whose scroll gestures go through the card's router, so the card decides once per +/// gesture whether the content scrolls or nothing happens. +@MainActor +private class IslandRoutedScrollView: NSScrollView { + weak var router: IslandNotificationCard? + + var canScroll: Bool { + (documentView?.frame.height ?? 0) > contentView.bounds.height + 1 + } + + override func scrollWheel(with event: NSEvent) { + if let router { router.route(event, from: self) } else { super.scrollWheel(with: event) } + } + + func scrollContent(_ event: NSEvent) { super.scrollWheel(with: event) } + + // Clicks travel up to the card, so the first one must count (see the card's hitTest). + override func acceptsFirstMouse(for event: NSEvent?) -> Bool { true } +} + +/// The message inside an expanded card. Open cards scroll it; clicks always reach the card. +@MainActor +private final class IslandBodyScrollView: IslandRoutedScrollView { + private final class Document: NSView { + override var isFlipped: Bool { true } + } + + override init(frame: NSRect) { + super.init(frame: frame) + drawsBackground = false + borderType = .noBorder + hasVerticalScroller = true + autohidesScrollers = true + scrollerStyle = .overlay + horizontalScrollElasticity = .none + verticalScrollElasticity = .allowed + contentView.drawsBackground = false + } + + @available(*, unavailable) + required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } + + /// Hosts the message in a flipped document, so a long message starts at its first line. + func setContent(_ view: NSView) { + let document = Document() + document.addSubview(view) + documentView = document + } + + override func tile() { + super.tile() + guard let document = documentView, let content = document.subviews.first else { return } + if document.frame.size != content.frame.size { document.frame = CGRect(origin: .zero, size: content.frame.size) } + } + + override func hitTest(_ point: NSPoint) -> NSView? { + // Keep the scroller draggable; everything else is the scroll view itself, so clicks and + // unscrollable gestures travel up to the card. + let hit = super.hitTest(point) + return hit is NSScroller ? hit : (hit == nil ? nil : self) + } + + override func mouseDown(with event: NSEvent) { nextResponder?.mouseDown(with: event) } + override func mouseUp(with event: NSEvent) { nextResponder?.mouseUp(with: event) } +} + +/// Catches the rest of a swipe that dismissed a card. macOS sends scroll events to the window under +/// the pointer; once the card is gone that is the app behind it, which would scroll with the end of +/// the swipe and its momentum. This invisible window sits where the card was until the swipe ends. +@MainActor +final class IslandScrollSink { + private static var panel: NSPanel? + private static var release: DispatchWorkItem? + + static func hold(over rect: NSRect, level: NSWindow.Level) { + let panel = Self.panel ?? { + let panel = NSPanel(contentRect: rect, styleMask: [.borderless, .nonactivatingPanel], + backing: .buffered, defer: false) + panel.isOpaque = false + panel.backgroundColor = .clear + panel.hasShadow = false + panel.isReleasedWhenClosed = false + panel.collectionBehavior = [.canJoinAllSpaces, .stationary, .fullScreenAuxiliary, .ignoresCycle] + panel.contentView = SinkView() + return panel + }() + Self.panel = panel + // Clear windows let events through unless they are asked to take them. + panel.ignoresMouseEvents = false + panel.level = level + panel.setFrame(rect.insetBy(dx: -24, dy: -24), display: false) + panel.orderFrontRegardless() + // However the swipe ends, the window never stays long. + endSoon(after: 2) + } + + fileprivate static func endSoon(after delay: TimeInterval) { + release?.cancel() + let work = DispatchWorkItem { MainActor.assumeIsolated { end() } } + release = work + DispatchQueue.main.asyncAfter(deadline: .now() + delay, execute: work) + } + + static func end() { + release?.cancel(); release = nil + panel?.orderOut(nil) + } + + private final class SinkView: NSView { + override func scrollWheel(with event: NSEvent) { + if event.momentumPhase == .ended || event.momentumPhase == .cancelled { + IslandScrollSink.end() + } else if event.phase == .ended || event.phase == .cancelled { + // Momentum, if any, starts right after the fingers lift. + IslandScrollSink.endSoon(after: 0.15) + } else if event.phase.isEmpty && event.momentumPhase.isEmpty { + // A mouse wheel: done once the ticks stop. + IslandScrollSink.endSoon(after: 0.3) + } else if !event.momentumPhase.isEmpty { + IslandScrollSink.endSoon(after: 2) + } + } + // Anything but scrolling means the swipe is over; the click goes nowhere, so step aside first. + override func mouseDown(with event: NSEvent) { IslandScrollSink.end() } + override func rightMouseDown(with event: NSEvent) { IslandScrollSink.end() } + override func acceptsFirstMouse(for event: NSEvent?) -> Bool { true } + } +} diff --git a/Plugins/IslandNotifications/Sources/IslandNotificationState.swift b/Plugins/IslandNotifications/Sources/IslandNotificationState.swift new file mode 100644 index 000000000..54bbf0dc4 --- /dev/null +++ b/Plugins/IslandNotifications/Sources/IslandNotificationState.swift @@ -0,0 +1,325 @@ +import Foundation +import OSLog +import SQLite3 + +// These decisions stay independent of AX and AppKit so failure boundaries can be tested. +enum IslandNotificationStyle: Equatable { + case temporary, persistent + + init?(subrole: String) { + switch subrole { + case "AXNotificationCenterBanner": self = .temporary + case "AXNotificationCenterAlert": self = .persistent + default: return nil + } + } + + /// A grouped stack of banners or alerts (macOS 27 NotificationCenter has both subroles). + init?(stackSubrole subrole: String) { + switch subrole { + case "AXNotificationCenterBannerStack": self = .temporary + case "AXNotificationCenterAlertStack": self = .persistent + default: return nil + } + } +} + +enum IslandMovePolicy { + static func originalPosition(position: CGPoint, prior: CGPoint?, desktopMinX: CGFloat, + normalPosition: CGPoint) -> CGPoint { + prior ?? (position.x < desktopMinX - 5000 ? normalPosition : position) + } + + static func allowsRecovery(position: CGPoint?, desktopMinX: CGFloat, + notificationCount: Int, hasUnexpectedContent: Bool, complete: Bool) -> Bool { + guard let position, position.x.isFinite, position.y.isFinite else { return false } + return position.x < desktopMinX - 5000 && notificationCount > 0 && !hasUnexpectedContent && complete + } + + static func allowsMove(enabled: Bool, trusted: Bool, hasNotch: Bool, + notificationCount: Int, hasUnexpectedContent: Bool, complete: Bool) -> Bool { + enabled && trusted && hasNotch && notificationCount > 0 && !hasUnexpectedContent && complete + } +} + +struct IslandNotificationQueue<Item> { + private(set) var current: Item? + private(set) var waiting: [Item] = [] + + mutating func append(_ item: Item) { waiting.append(item) } + + @discardableResult + mutating func presentNext(blocked: Bool) -> Item? { + guard !blocked, current == nil, !waiting.isEmpty else { return nil } + let item = waiting.removeFirst() + current = item + return item + } + + mutating func finish() { current = nil } + + /// Removes waiting items that match, returning them. + @discardableResult + mutating func removeWaiting(where shouldRemove: (Item) -> Bool) -> [Item] { + let removed = waiting.filter(shouldRemove) + waiting.removeAll(where: shouldRemove) + return removed + } + mutating func removeAll() { current = nil; waiting.removeAll() } +} + +struct IslandNotificationLifetime { + private(set) var remaining: TimeInterval? + private var paused = false + private var lastUpdate: TimeInterval + + init(style: IslandNotificationStyle, now: TimeInterval) { + remaining = style == .temporary ? 5 : nil + lastUpdate = now + } + + mutating func advance(to now: TimeInterval, paused: Bool) -> Bool { + let elapsed = max(0, now - lastUpdate) + lastUpdate = now + let wasPaused = self.paused + self.paused = paused + guard let remaining else { return false } + self.remaining = max(0, remaining - (wasPaused ? 0 : elapsed)) + return self.remaining == 0 + } +} + + +/// How an inline reply ended (Messages or Claude). +enum IslandReplyOutcome: Equatable, Sendable { + case sent + /// Messages: no conversation, or more than one, matches the banner title. + case noConversation + /// MacTools is not allowed to control Messages (Privacy & Security > Automation). + case notAuthorized + /// Claude: that chat already has unsent text in its message box. + case claudeDraft + /// Claude: more than one open chat has this title. + case ambiguousChat + case failed +} + +/// Sends an inline reply through Messages' scripting interface, to the exact conversation found +/// in Messages' history (`IslandMessagesChat`). Nothing is ever matched by name. +enum IslandMessagesReply { + /// The reply and the conversation travel as script arguments, never as script source. + /// Every service's copy of one conversation (iMessage, SMS, RCS, any) has an id ending with the + /// same identifier, and the ";+;" / ";-;" marker says group or one-to-one. + private static let script = """ + on run argv + set theText to item 1 of argv + set theSuffix to ";" & (item 2 of argv) + set theMarker to ";" & (item 3 of argv) & ";" + tell application "Messages" + -- Send to the chat itself (not "chat id ..."), preferring iMessage, then any, RCS, SMS. + set chosenChat to missing value + set chosenRank to 99 + repeat with c in (every chat) + set chatID to (id of c) as text + if chatID ends with theSuffix and chatID contains theMarker then + set rank to 5 + if chatID starts with "iMessage;" then set rank to 1 + if chatID starts with "any;" then set rank to 2 + if chatID starts with "RCS;" then set rank to 3 + if chatID starts with "SMS;" then set rank to 4 + if rank < chosenRank then + set chosenRank to rank + set chosenChat to contents of c + end if + end if + end repeat + if chosenChat is missing value then return "none" + send theText to chosenChat + return "sent" + end tell + end run + """ + + static func send(_ text: String, toChat chat: IslandMessagesChat.Conversation) async -> IslandReplyOutcome { + let (status, output, errors) = await run([text, chat.identifier, chat.isGroup ? "+" : "-"]) + if status == 0 { return output == "sent" ? .sent : .noConversation } + // The AppleScript error number only, never the reply text. + let code = errors.range(of: #"\(-?\d+\)"#, options: .regularExpression).map { String(errors[$0]) } ?? "none" + logger.notice("send failed status=\(status, privacy: .public) error=\(code, privacy: .public)") + return errors.contains("-1743") ? .notAuthorized : .failed + } + + private static let logger = Logger(subsystem: "MacTools.IslandNotifications", category: "messages") + + private static func run(_ arguments: [String]) async -> (Int32, String, String) { + await withCheckedContinuation { continuation in + let process = Process() + process.executableURL = URL(fileURLWithPath: "/usr/bin/osascript") + // "--" ends osascript's options, so a reply starting with "-" stays an argument. + process.arguments = ["-e", script, "--"] + arguments + let output = Pipe(), errors = Pipe() + process.standardOutput = output + process.standardError = errors + process.terminationHandler = { process in + let out = String(data: output.fileHandleForReading.readDataToEndOfFile(), encoding: .utf8)? + .trimmingCharacters(in: .whitespacesAndNewlines) ?? "" + let err = String(data: errors.fileHandleForReading.readDataToEndOfFile(), encoding: .utf8) ?? "" + continuation.resume(returning: (process.terminationStatus, out, err)) + } + do { try process.run() } catch { continuation.resume(returning: (-1, "", "")); return } + // Messages (or its first-use permission prompt) must not leave the card sending forever. + DispatchQueue.global(qos: .utility).asyncAfter(deadline: .now() + 20) { + if process.isRunning { process.terminate() } + } + } + } +} + +/// Finds the exact Messages conversation a banner belongs to, from Messages' own history +/// (`~/Library/Messages/chat.db`, read-only; needs Full Disk Access for MacTools). The banner's +/// message text is matched against messages received in the last few minutes, and only a single +/// matching conversation counts. Nothing is stored and nothing but the conversation id leaves here. +enum IslandMessagesChat { + struct Conversation: Equatable, Sendable { + /// The part after the service: the person's number or address, or "chat123456789" for a group. + let identifier: String + let isGroup: Bool + /// A group's id for Messages' open link. + var groupID: String? + + /// Opens this conversation in Messages. + var openURL: URL? { + var components = URLComponents() + if isGroup { + guard let groupID else { return nil } + components.scheme = "sms" + components.host = "open" + components.queryItems = [URLQueryItem(name: "groupid", value: groupID)] + } else { + components.scheme = identifier.contains("@") ? "imessage" : "sms" + components.path = identifier + } + return components.url + } + } + + enum Lookup: Equatable, Sendable { + case found(Conversation) + /// No conversation, or more than one, matches. + case notFound + /// Messages' history can't be read (no Full Disk Access). + case unavailable + } + + private static let logger = Logger(subsystem: "MacTools.IslandNotifications", category: "messages") + + private static var databasePath: String { + FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent("Library/Messages/chat.db").path + } + + /// True when Messages' history can be read (Full Disk Access granted). + static var isAvailable: Bool { + guard let db = open() else { return false } + sqlite3_close(db) + return true + } + + private static func open() -> OpaquePointer? { + var db: OpaquePointer? + guard sqlite3_open_v2(databasePath, &db, SQLITE_OPEN_READONLY, nil) == SQLITE_OK, let db else { + if let db { sqlite3_close(db) } + return nil + } + sqlite3_busy_timeout(db, 500) + // Opening succeeds lazily; a query proves access. + guard sqlite3_exec(db, "SELECT 1 FROM chat LIMIT 1", nil, nil, nil) == SQLITE_OK else { + sqlite3_close(db) + return nil + } + return db + } + + /// `bannerLines`: the banner's text lines after its title. A group banner (three lines) must lead + /// to a group conversation and a one-to-one banner to a one-to-one conversation. + static func resolve(bannerLines: [String], isGroupBanner: Bool) -> Lookup { + guard let db = open() else { return .unavailable } + defer { sqlite3_close(db) } + let candidates = Set(bannerLines.map(normalized).filter { !$0.isEmpty }) + guard !candidates.isEmpty else { return .notFound } + // Message dates are nanoseconds since 2001; look back five minutes. + let since = Int64((Date().timeIntervalSinceReferenceDate - 300) * 1_000_000_000) + let sql = """ + SELECT c.guid, m.text, m.attributedBody, c.group_id FROM message m + JOIN chat_message_join j ON j.message_id = m.ROWID + JOIN chat c ON c.ROWID = j.chat_id + WHERE m.is_from_me = 0 AND m.date > ?1 + ORDER BY m.date DESC LIMIT 200 + """ + var statement: OpaquePointer? + guard sqlite3_prepare_v2(db, sql, -1, &statement, nil) == SQLITE_OK, let statement else { return .notFound } + defer { sqlite3_finalize(statement) } + sqlite3_bind_int64(statement, 1, since) + var rows = 0 + var chats = Set<String>() + var groupIDs: [String: String] = [:] + while sqlite3_step(statement) == SQLITE_ROW { + rows += 1 + guard let guid = sqlite3_column_text(statement, 0).map({ String(cString: $0) }) else { continue } + var text = sqlite3_column_text(statement, 1).map { String(cString: $0) } + if text == nil, let blob = sqlite3_column_blob(statement, 2) { + text = attributedBodyText(Data(bytes: blob, count: Int(sqlite3_column_bytes(statement, 2)))) + } + guard let text, matches(normalized(text), candidates) else { continue } + chats.insert(guid) + if let groupID = sqlite3_column_text(statement, 3).map({ String(cString: $0) }), !groupID.isEmpty { + groupIDs[guid] = groupID + } + } + // Copies of one conversation on different services share the identifier after the service. + let conversations = Set(chats.compactMap(conversation(fromGUID:)).map { "\($0.isGroup ? "+" : "-");\($0.identifier)" }) + logger.notice("lookup rows=\(rows, privacy: .public) matchingChats=\(chats.count, privacy: .public) conversations=\(conversations.count, privacy: .public) groupBanner=\(isGroupBanner, privacy: .public)") + guard conversations.count == 1, let guid = chats.first, var found = conversation(fromGUID: guid) else { return .notFound } + found.groupID = chats.lazy.compactMap { groupIDs[$0] }.first + guard found.isGroup == isGroupBanner else { + logger.notice("lookup refused: banner and conversation kinds differ") + return .notFound + } + return .found(found) + } + + /// "iMessage;+;chat123" → group "chat123"; "any;-;+61400000000" → one-to-one "+61400000000". + static func conversation(fromGUID guid: String) -> Conversation? { + let parts = guid.split(separator: ";", maxSplits: 2, omittingEmptySubsequences: false) + guard parts.count == 3, parts[1] == "+" || parts[1] == "-", !parts[2].isEmpty else { return nil } + return Conversation(identifier: String(parts[2]), isGroup: parts[1] == "+") + } + + private static func normalized(_ text: String) -> String { + text.split(whereSeparator: { $0.isWhitespace || $0.isNewline }).joined(separator: " ") + } + + /// Banners can shorten long messages, so a long enough banner line may be a prefix. + private static func matches(_ text: String, _ candidates: Set<String>) -> Bool { + candidates.contains { $0 == text || ($0.count >= 12 && text.hasPrefix($0.trimmingCharacters(in: CharacterSet(charactersIn: "…")))) } + } + + /// Newer macOS stores some message text only in `attributedBody` (an archived NSAttributedString): + /// the string follows the "NSString" class marker as a length-prefixed UTF-8 run. + private static func attributedBodyText(_ data: Data) -> String? { + let bytes = [UInt8](data) + guard let marker = bytes.firstRange(of: Array("NSString".utf8)) else { return nil } + var index = marker.upperBound + while index < bytes.count, bytes[index] != 0x2B { index += 1 } // "+" precedes the length + index += 1 + guard index < bytes.count else { return nil } + var length = Int(bytes[index]); index += 1 + if length == 0x81, index + 1 < bytes.count { + length = Int(bytes[index]) | Int(bytes[index + 1]) << 8; index += 2 + } else if length == 0x82, index + 3 < bytes.count { + length = Int(bytes[index]) | Int(bytes[index + 1]) << 8 | Int(bytes[index + 2]) << 16 | Int(bytes[index + 3]) << 24 + index += 4 + } + guard length > 0, index + length <= bytes.count else { return nil } + return String(bytes: bytes[index..<(index + length)], encoding: .utf8) + } +} diff --git a/Plugins/IslandNotifications/Sources/IslandNotificationsController.swift b/Plugins/IslandNotifications/Sources/IslandNotificationsController.swift new file mode 100644 index 000000000..4e514e65e --- /dev/null +++ b/Plugins/IslandNotifications/Sources/IslandNotificationsController.swift @@ -0,0 +1,912 @@ +import AppKit +import Combine +import ApplicationServices +import MacToolsPluginKit +import OSLog + +/// A NotificationCenter window MacTools moved off screen. `taken`: the island shows its banner. +struct IslandMovedWindow: @unchecked Sendable { + let window: AXUIElement + let original: CGPoint + let since: TimeInterval + var taken: Bool +} + +@MainActor +final class IslandNotificationsController { + var onStateChange: (() -> Void)? + private(set) var enabled: Bool + private(set) var trusted = AXIsProcessTrusted() + private(set) var hasDisplay = false + private var active = false + private let storage: any PluginStorage + private let localization: PluginLocalization + private let observer = IslandNotificationObserver() + private let activities = IslandLiveActivityObserver() + private var placement = IslandLiveActivityPlacement.camera + private var preparing = false + private var fallingBack = false + private let presenter: IslandNotificationPresenter + private let logger = Logger(subsystem: "MacTools.IslandNotifications", category: "lifecycle") + private var queue = IslandNotificationQueue<IslandNotification>() + private let claudeTurns = IslandClaudeTurnWatcher() + /// What the panel's Notifications list shows. + let history = IslandNotificationHistory() + /// The Notifications widget's height in panel rows: it fits its list, up to a limit, then scrolls. + private(set) var historySpan = PluginPanelWidgetLayoutMetrics.default.heightSpan(fittingContentHeight: IslandHistoryLayout.emptyHeight) + /// MacTools is opening Notification Centre out of sight for the list: its opening isn't the user's. + private var centerPressing = false + private var currentShownAt: TimeInterval = 0 + private var replaceWork: DispatchWorkItem? + private var lastRescan: TimeInterval = 0 + /// Every banner already turned into a card. macOS keeps a banner in its (hidden) window for a + /// while after the card is gone; re-reading the window must not show it again. + private var seen: [IslandNotification] = [] + private var loggedHistoryAccess = false + private var hidden: [IslandNotification] = [] + private var moved: [IslandMovedWindow] = [] + /// Notification Centre's own panel is open. + private var centerOpen = false + /// How long a window moved on arrival may wait for its banner before it goes back. + private static let prehideGrace: TimeInterval = 0.5 + private var ignored: [IslandAXElement] = [] + private var receiving: [IslandAXElement] = [] + private var pending: [IslandAXElement] = [] + private var generation = 0 + private var ready = false + private var lifetime: IslandNotificationLifetime? + private var closing = false + private var anchor: CGRect? + private var trustTimer: Timer? + private var hoverTimer: Timer? + private var lifetimeTimer: Timer? + private var blocked = false + private var localeSubscription: AnyCancellable? + private var appObservers: [NSObjectProtocol] = [] + private var workspaceObserver: NSObjectProtocol? + + init(storage: any PluginStorage, localization: PluginLocalization) { + self.storage = storage + self.localization = localization + enabled = storage.bool(forKey: "enabled") + presenter = IslandNotificationPresenter(localization: localization) + let lines = storage.integer(forKey: "previewLines") + if IslandNotificationPresenter.previewLineRange.contains(lines) { presenter.previewLines = lines } + activities.onChange = { [weak self] in self?.activityChanged() } + observer.onWindow = { [weak self] in self?.receive($0) } + observer.onFocusChanged = { [weak self] in self?.centerFocusChanged() } + observer.onRemoved = { [weak self] element in + self?.hidden.removeAll { CFEqual($0.element, element.value) } + self?.seen.removeAll { CFEqual($0.element, element.value) } + self?.ignored.removeAll { CFEqual($0.value, element.value) } + } + presenter.onHoverChange = { [weak self] in self?.updateLifetime() } + presenter.onReply = { [weak self] text in self?.reply(text) } + presenter.onOutsideClick = { [weak self] in + guard let self, !self.presenter.isSendingReply else { return } + self.finishCurrent(dismissNative: false, reason: "outside click") + } + claudeTurns.onTurn = { [weak self] turn in self?.receive(turn) } + localeSubscription = PluginRuntimeLocalization.source.$revision.dropFirst().sink { [weak self] _ in + DispatchQueue.main.async { [weak self] in self?.presenter.refreshLocalization() } + } + } + + func activate() { + guard !active else { return } + active = true + for name in [NSApplication.didChangeScreenParametersNotification, NSApplication.didBecomeActiveNotification, NSApplication.willTerminateNotification] { + appObservers.append(NotificationCenter.default.addObserver(forName: name, object: nil, queue: .main) { [weak self] note in + let isTermination = note.name == NSApplication.willTerminateNotification + MainActor.assumeIsolated { + if isTermination { self?.deactivate() } + else { self?.refresh() } + } + }) + } + workspaceObserver = NSWorkspace.shared.notificationCenter.addObserver( + forName: NSWorkspace.didLaunchApplicationNotification, object: nil, queue: .main + ) { [weak self] note in + guard let app = note.userInfo?[NSWorkspace.applicationUserInfoKey] as? NSRunningApplication, + app.bundleURL?.path == "/System/Library/CoreServices/NotificationCenter.app" || IslandLiveActivityObserver.isMenuBarAgent(app) else { return } + MainActor.assumeIsolated { self?.refresh(); self?.activityChanged() } + } + refresh() + } + + var previewLines: Int { presenter.previewLines } + + func setPreviewLines(_ value: Int) { + guard IslandNotificationPresenter.previewLineRange.contains(value) else { return } + presenter.previewLines = value; storage.set(value, forKey: "previewLines") + onStateChange?() + } + + func setEnabled(_ value: Bool) { + enabled = value; storage.set(value, forKey: "enabled") + refresh(); onStateChange?() + } + + func refresh() { + trusted = AXIsProcessTrusted() + let nextAnchor = Self.notchAnchor() + hasDisplay = nextAnchor != nil + if nextAnchor != anchor { stop(); anchor = nextAnchor } + guard active, enabled else { + stop(); onStateChange?(); return + } + updateTimer() + guard trusted, anchor != nil else { stop(); onStateChange?(); return } + claudeTurns.start() + if !loggedHistoryAccess { + loggedHistoryAccess = true + let logger = logger + Task.detached(priority: .utility) { + logger.notice("messages history readable=\(IslandMessagesChat.isAvailable, privacy: .public)") + } + } + if observer.pid == nil { + observer.start(onAttached: { [weak self] in self?.recoverStrandedWindows() }, onExit: { [weak self] in + guard let self else { return } + self.stop() + self.refresh() + }) + } + onStateChange?() + } + + private func recoverStrandedWindows() { + guard let anchor, let normalPosition = Self.normalPosition(for: anchor) else { return } + let desktopMinX = Self.desktopMinX + let generation = generation + let logger = logger + Task { + let windows = await observer.windows() + await IslandAX.run { + for window in windows { + let snapshot = IslandAXWindowSnapshot(window: window.value) + if IslandMovePolicy.allowsRecovery(position: IslandAX.position(window.value), desktopMinX: desktopMinX, + notificationCount: snapshot.groups.count, + hasUnexpectedContent: snapshot.unexpected, complete: snapshot.complete) { + if IslandAX.move(window.value, to: normalPosition) { logger.info("Recovered a stranded notification window") } + else { logger.error("Could not recover a stranded notification window") } + } + } + } + guard self.generation == generation else { return } + ready = true + // Notifications already on screen when MacTools starts become cards too. macOS keeps them + // in one window with any that arrive later, so skipping them would leave those native. + for window in windows { receive(window) } + } + } + + private func updateTimer() { + let waitingForTrust = active && enabled && !trusted + if !waitingForTrust { trustTimer?.invalidate(); trustTimer = nil } + else if trustTimer == nil { + let timer = Timer(timeInterval: 1, repeats: true) { [weak self] _ in + MainActor.assumeIsolated { self?.refresh() } + } + timer.tolerance = 0.2 + RunLoop.main.add(timer, forMode: .common) + trustTimer = timer + } + let hasCards = queue.current != nil || !queue.waiting.isEmpty + guard active, enabled, trusted, anchor != nil, hasCards else { + hoverTimer?.invalidate(); hoverTimer = nil + return + } + guard hoverTimer == nil else { return } + let timer = Timer(timeInterval: 0.2, repeats: true) { [weak self] _ in + MainActor.assumeIsolated { self?.tick() } + } + timer.tolerance = 0.04 + RunLoop.main.add(timer, forMode: .common) + hoverTimer = timer + } + + private func updateLifetime() { + lifetimeTimer?.invalidate(); lifetimeTimer = nil + let hovered = presenter.isHovered + guard !closing, queue.current != nil else { return } + // The pointer left or the card was released: a waiting newer notification can take over. + replaceCurrentIfIdle() + guard !closing else { return } + // A held card (swiped down / opened) stays until dismissed; unsent reply text, typing or + // sending keep a card up too. + let paused = blocked || hovered || presenter.isHeld || presenter.isReplying || presenter.hasDraft + if lifetime?.advance(to: ProcessInfo.processInfo.systemUptime, paused: paused) == true { + finishCurrent(dismissNative: false, reason: "timed out") + return + } + guard !paused, let remaining = lifetime?.remaining else { return } + let timer = Timer(timeInterval: remaining, repeats: false) { [weak self] _ in + MainActor.assumeIsolated { self?.updateLifetime() } + } + RunLoop.main.add(timer, forMode: .common) + lifetimeTimer = timer + } + + func deactivate() { + active = false + for token in appObservers { NotificationCenter.default.removeObserver(token) } + appObservers.removeAll() + if let workspaceObserver { NSWorkspace.shared.notificationCenter.removeObserver(workspaceObserver) } + workspaceObserver = nil + stop() + } + + isolated deinit { deactivate() } + + private func stop() { + generation += 1; ready = false; receiving.removeAll(); pending.removeAll() + replaceWork?.cancel(); replaceWork = nil + observer.stop() + claudeTurns.stop() + activities.stop() + preparing = false; fallingBack = false; placement = .camera + presenter.hide() + // Every window MacTools moved goes back now: with no card on screen its banner is shown natively. + IslandAX.restoreMovedWindows(moved) + IslandAX.restorePersistentWindows(hidden, desktopMinX: Self.desktopMinX) + moved.removeAll(); centerOpen = false + // `seen` survives a restart of the pipeline so banners already shown aren't shown again; + // its entries are pruned once macOS removes them. + self.hidden.removeAll(); ignored.removeAll(); queue.removeAll() + lifetimeTimer?.invalidate(); lifetimeTimer = nil + lifetime = nil; closing = false; blocked = false + updateTimer() + } + + /// A Claude chat finished a turn while the user is elsewhere: show Claude's reply as a card. + private func receive(_ turn: IslandClaudeTurnWatcher.Turn) { + guard active, enabled, trusted, anchor != nil, !fallingBack, !centerOpen, + NSWorkspace.shared.frontmostApplication?.bundleIdentifier != IslandClaudeReply.bundleIdentifier else { return } + // There is no system banner behind this card; the system-wide element is only a placeholder. + let placeholder = AXUIElementCreateSystemWide() + let notification = IslandNotification(element: placeholder, window: placeholder, originalPosition: .zero, + style: .temporary, title: turn.chat.title, body: turn.message, + identityHints: [IslandClaudeReply.bundleIdentifier]) + notification.claudeChat = turn.chat + notification.resolveIdentity() + record(notification) + enqueue([notification]) + } + + private func receive(_ window: IslandAXElement) { + guard active, ready, !fallingBack, !centerPressing else { return } + if receiving.contains(where: { CFEqual($0.value, window.value) }) { + if !pending.contains(where: { CFEqual($0.value, window.value) }) { pending.append(window) } + return + } + receiving.append(window) + let generation = generation + Task { + defer { + if self.generation == generation { + receiving.removeAll { CFEqual($0.value, window.value) } + if pending.contains(where: { CFEqual($0.value, window.value) }) { + pending.removeAll { CFEqual($0.value, window.value) } + receive(window) + } + } + } + // While Notification Centre's own panel is open its list is not new banners: hands off. + // A failed query is unknown, never "closed". + let focus = await observer.centerFocus() + guard self.generation == generation, active else { return } + if focus == true { await centerOpened(); return } + guard focus == false else { return } + centerOpen = false + // Hide a new banner window at once, before reading it, so the banner never draws its first + // frames natively. A window the island doesn't take comes back (see settleUntaken). + let offscreen = Self.offscreenPosition + let early = await IslandAX.run { () -> IslandAX.OffScreenMove? in + guard AXIsProcessTrusted(), IslandAX.string(window.value, kAXRoleAttribute) == kAXWindowRole, + IslandAX.string(window.value, kAXSubroleAttribute) == "AXSystemDialog" else { return nil } + return IslandAX.moveOffScreen(window.value, to: offscreen) + } + switch early { + case .moved(let from)?: + remember(window.value, original: from, taken: false) + guard self.generation == generation, active, !fallingBack else { await release(window.value); return } + try? await Task.sleep(for: .milliseconds(30)) + case .failed?: + logger.error("Could not hide a new notification window; it stays native") + return + case .alreadyOff?, nil: + break + } + let snapshot = await IslandAX.run { IslandAXWindowSnapshot(window: window.value) } + // Check live hardware/permission immediately before submitting the mutation. + guard self.generation == generation, active else { return } + let currentTrust = AXIsProcessTrusted() + let nextAnchor = Self.notchAnchor() + if currentTrust != trusted || nextAnchor != anchor { + logger.notice("receive refresh trust=\(currentTrust, privacy: .public) anchorChanged=\(nextAnchor != self.anchor, privacy: .public)") + refresh(); return + } + await pruneStaleElements() + guard self.generation == generation else { return } + if snapshot.complete, !snapshot.unexpected { + hidden.removeAll { item in + item.style == .temporary && CFEqual(item.window, window.value) && + !snapshot.groups.contains { CFEqual($0.element, item.element) } + } + } + let ignoredHit = snapshot.groups.contains { group in ignored.contains { CFEqual($0.value, group.element) } } + let taken = movedIndex(window.value).map { moved[$0].taken } ?? false + if !taken, snapshot.unexpected || !snapshot.complete { + logger.notice("banner left native groups=\(snapshot.groups.count, privacy: .public) complete=\(snapshot.complete, privacy: .public) unexpected=\(snapshot.unexpected, privacy: .public) hidden=\(self.hidden.count, privacy: .public) seen=\(self.seen.count, privacy: .public)") + } + guard let nextAnchor, let normalPosition = Self.normalPosition(for: nextAnchor), + IslandMovePolicy.allowsMove(enabled: enabled, trusted: currentTrust, hasNotch: true, + notificationCount: snapshot.groups.count, + hasUnexpectedContent: snapshot.unexpected, complete: snapshot.complete), + !ignoredHit else { + // A new window the island can't read comes straight back on screen; one still filling in + // gets until the end of the grace. A window already taken stays hidden: while a banner + // is being removed macOS strips its subrole, and putting that back would flash it. + await settleUntaken(window, definitive: snapshot.unexpected || ignoredHit || !enabled) + return + } + let fresh = snapshot.groups.filter { group in + !hidden.contains { CFEqual($0.element, group.element) } && !seen.contains { CFEqual($0.element, group.element) } + } + // macOS shows one banner per app and updates it in place when a newer notification from + // that app arrives. A held banner whose text changed is that newer notification. + var replacements: [IslandNotification] = [] + for group in snapshot.groups { + guard let old = hidden.first(where: { CFEqual($0.element, group.element) }) + ?? seen.last(where: { CFEqual($0.element, group.element) }), + old.title != group.title || old.body != group.body else { continue } + let original = movedIndex(window.value).map { moved[$0].original } ?? old.originalPosition + let notification = IslandNotification(element: group.element, window: window.value, originalPosition: original, + style: group.style, title: group.title, body: group.body, + identityHints: group.hints, lineCount: group.lines) + notification.label = group.label + notification.resolveIdentity() + hidden.removeAll { $0 === old } + seen.removeAll { $0 === old } + hidden.append(notification) + seen.append(notification) + dropWaiting { $0 === old } + record(notification) + replacements.append(notification) + } + if !replacements.isEmpty { + if let index = movedIndex(window.value) { moved[index].taken = true } + enqueue(replacements) + } + guard !fresh.isEmpty else { + // Nothing new for the island in a window moved on arrival: it goes straight back. + if replacements.isEmpty { await settleUntaken(window, definitive: true) } + return + } + // Read before any mutation: a failed or expanded system activity keeps + // the native banner visible. Never rely on an idle geometry cache. + let nextPlacement = await activities.refresh(anchor: nextAnchor) + guard self.generation == generation, !fallingBack else { return } + guard nextPlacement != .native else { + // Nothing held yet: just give this banner back. Otherwise every card goes native. + if hidden.isEmpty { await release(window.value) } else { await fallBackToNative() } + return + } + // A visible card keeps its place (and any typed reply); the next card uses the new one. + placement = nextPlacement + let prior = movedIndex(window.value).map { moved[$0].original } + ?? hidden.first(where: { CFEqual($0.window, window.value) })?.originalPosition + let desktopMinX = Self.desktopMinX + // Confirmed move: a window that ignores it, or still lands on a display, goes back and + // no card is made, so the native banner and a card never show together. + let result = await IslandAX.run { () -> IslandAX.OffScreenMove in + guard AXIsProcessTrusted() else { return .failed } + return IslandAX.moveOffScreen(window.value, to: offscreen) + } + let original: CGPoint + switch result { + case .moved(let from): original = from + case .alreadyOff(let at): + original = IslandMovePolicy.originalPosition(position: at, prior: prior, + desktopMinX: desktopMinX, normalPosition: normalPosition) + case .failed: + logger.error("A notification window did not leave the screen; it stays native") + await release(window.value) + return + } + guard self.generation == generation, !fallingBack else { + // Disable/display changes or native fallback can race an in-flight move. Roll it back. + _ = await IslandAX.run { IslandAX.restore(window.value, to: original) } + return + } + remember(window.value, original: original, taken: true) + var arrivals: [IslandNotification] = [] + for group in fresh { + let notification = IslandNotification(element: group.element, window: window.value, originalPosition: original, + style: group.style, title: group.title, body: group.body, + identityHints: group.hints, lineCount: group.lines) + notification.label = group.label + hidden.append(notification) + seen.append(notification) + notification.resolveIdentity() + record(notification) + arrivals.append(notification) + } + await observer.observeRemoval(of: fresh.map { IslandAXElement(value: $0.element) }) + guard self.generation == generation else { return } + enqueue(arrivals) + } + } + + // MARK: Windows MacTools moved off screen + // + // Every NotificationCenter window MacTools moved is recorded with where it was, so it can always + // go back: when its banner isn't for the island, when Notification Centre opens, on fallback to + // native banners and on stop. A window moved on arrival ("untaken") gets `prehideGrace` for its + // banner to fill in; one the island took stays off screen until macOS removes it. + + private func movedIndex(_ window: AXUIElement) -> Int? { moved.firstIndex { CFEqual($0.window, window) } } + + private func remember(_ window: AXUIElement, original: CGPoint, taken: Bool) { + let now = ProcessInfo.processInfo.systemUptime + if let index = movedIndex(window) { + moved[index] = IslandMovedWindow(window: window, original: original, since: taken ? moved[index].since : now, + taken: taken || moved[index].taken) + } else { + moved.append(IslandMovedWindow(window: window, original: original, since: now, taken: taken)) + } + } + + /// Puts a moved window back and drops the cards made from it: its banners are visible again. + private func release(_ window: AXUIElement) async { + guard let index = movedIndex(window) else { return } + let record = moved.remove(at: index) + let restored = await IslandAX.run { IslandAX.restore(record.window, to: record.original) } + if !restored { logger.error("Could not put back a notification window") } + dropWaiting { CFEqual($0.window, window) } + hidden.removeAll { CFEqual($0.window, window) } + if let current = queue.current, current.claudeChat == nil, CFEqual(current.window, window) { + finishCurrent(dismissNative: false, reason: "banner back to native") + } + } + + /// A window moved on arrival that the island didn't take goes back: at once when nothing in it is + /// for the island, otherwise when the grace ends (its banner may still be filling in). + private func settleUntaken(_ window: IslandAXElement, definitive: Bool) async { + guard let index = movedIndex(window.value), !moved[index].taken else { return } + let waited = ProcessInfo.processInfo.systemUptime - moved[index].since + if definitive || waited >= Self.prehideGrace { await release(window.value); return } + let generation = generation + Task { + try? await Task.sleep(for: .seconds(Self.prehideGrace - waited + 0.02)) + guard self.generation == generation, let index = movedIndex(window.value), !moved[index].taken else { return } + receive(window) + } + } + + /// Notification Centre's panel opened: every moved window goes back (its list may live in the + /// same window as the banners) and cards close, like banners do when the centre opens on iPhone. + private func centerOpened() async { + guard !centerOpen, !centerPressing else { return } + centerOpen = true + logger.notice("Notification Centre opened; native windows restored") + replaceWork?.cancel(); replaceWork = nil + lifetimeTimer?.invalidate(); lifetimeTimer = nil + presenter.hide() + queue.removeAll(); hidden.removeAll() + lifetime = nil; closing = false + let records = moved + moved.removeAll() + await IslandAX.run { + for record in records where !IslandAX.restore(record.window, to: record.original) { + Logger(subsystem: "MacTools.IslandNotifications", category: "lifecycle") + .error("Could not put back a notification window for Notification Centre") + } + } + updateTimer() + } + + private func centerFocusChanged() { + guard active, ready, !centerPressing else { return } + Task { + let focus = await observer.centerFocus() + if focus == true { await centerOpened() } else if focus == false { centerOpen = false } + } + } + + private func pruneStaleElements() async { + let hidden = hidden + let ignored = ignored + let seen = seen + let generation = generation + let moved = moved + let (invalid, invalidIgnored, invalidSeen, invalidMoved) = await IslandAX.run { + (hidden.filter { IslandAX.isInvalid($0.element) }, ignored.filter { IslandAX.isInvalid($0.value) }, + seen.filter { IslandAX.isInvalid($0.element) }, moved.filter { IslandAX.isInvalid($0.window) }) + } + guard self.generation == generation else { return } + self.moved.removeAll { item in invalidMoved.contains { CFEqual($0.window, item.window) } } + self.seen.removeAll { item in invalidSeen.contains { $0 === item } } + self.hidden.removeAll { item in invalid.contains { $0 === item } } + self.ignored.removeAll { item in invalidIgnored.contains { CFEqual($0.value, item.value) } } + } + + // MARK: Several notifications (Apple: one banner at a time, the newest wins) + // + // - A new notification replaces a small card that is just sitting there, once that card has been + // up for at least 1 s (so a burst doesn't strobe). Older temporary ones that never got shown are + // skipped; they stay in Notification Centre like any other. + // - The pointer on the card, an open or held card, typing or sending: nothing is interrupted. + // The newest arrival waits; when the card closes it shows only if it's still fresh (6 s). + // - Persistent alerts are never skipped or replaced; they wait their turn. + // - No count on the card: neither iPhone nor Mac banners show one. Grouped stacks live in + // Notification Centre, which is left untouched. + + private func enqueue(_ arrivals: [IslandNotification]) { + guard !arrivals.isEmpty else { return } + dropWaiting { $0.style == .temporary } + for notification in arrivals { queue.append(notification) } + // Only the newest temporary arrival of a batch is worth showing. + let newest = arrivals.last + dropWaiting { $0.style == .temporary && $0 !== newest } + replaceCurrentIfIdle() + presentNext() + } + + /// Skipped notifications stay in Notification Centre; temporary banners expire on their own. + private func dropWaiting(where shouldDrop: (IslandNotification) -> Bool) { + let dropped = queue.removeWaiting(where: shouldDrop) + hidden.removeAll { item in dropped.contains { $0 === item } } + } + + /// The card is in use: pointer on it, opened or held, typing, a draft, or a reply sending. + private var presenterIsBusy: Bool { + presenter.isHovered || presenter.isHeld || presenter.isReplying || presenter.hasDraft || presenter.isSendingReply + } + + /// Replaces an idle small card with the newest waiting notification (after its first second). + private func replaceCurrentIfIdle() { + replaceWork?.cancel(); replaceWork = nil + guard let current = queue.current, !closing, current.style == .temporary, !presenterIsBusy, + queue.waiting.contains(where: { $0.style == .temporary }) else { return } + let shownFor = ProcessInfo.processInfo.systemUptime - currentShownAt + guard shownFor >= 1 else { + let work = DispatchWorkItem { [weak self] in + MainActor.assumeIsolated { self?.replaceCurrentIfIdle() } + } + replaceWork = work + DispatchQueue.main.asyncAfter(deadline: .now() + (1 - shownFor), execute: work) + return + } + finishCurrent(dismissNative: false, reason: "replaced by newer") + } + + private func presentNext(checkBlocking: Bool = true) { + guard let anchor, !closing, !preparing, !fallingBack, queue.current == nil else { updateTimer(); return } + if checkBlocking { blocked = hoverPanelVisible(over: anchor) } + guard !blocked, !queue.waiting.isEmpty else { updateTimer(); return } + preparing = true + let generation = generation + Task { + let nextPlacement = await activities.refresh(anchor: anchor) + guard self.generation == generation, !fallingBack else { return } + preparing = false + guard nextPlacement != .native else { await fallBackToNative(); return } + placement = nextPlacement + blocked = hoverPanelVisible(over: anchor) + // After an open or held card, only a fresh arrival is still worth showing. + let now = ProcessInfo.processInfo.systemUptime + dropWaiting { $0.style == .temporary && now - $0.arrivedAt > 6 } + guard let notification = queue.presentNext(blocked: blocked) else { updateTimer(); return } + lifetime = IslandNotificationLifetime(style: notification.style, now: ProcessInfo.processInfo.systemUptime) + show(notification, anchor: anchor) + presenter.announce(notification) + updateLifetime() + updateTimer() + } + } + + private func show(_ notification: IslandNotification, anchor: CGRect) { + let activity: CGRect? + if case .split(let frame) = placement { activity = frame } else { activity = nil } + currentShownAt = ProcessInfo.processInfo.systemUptime + presenter.present(notification, anchor: anchor, activity: activity, waiting: 0, + replyable: notification.canReply, + onOpen: { [weak self] in self?.openCurrent() }, + onClose: { [weak self] in self?.finishCurrent(dismissNative: true, reason: "closed") }) + } + + private func activityChanged() { + // No AX traversal or polling while idle. The next banner always refreshes. + guard active, !fallingBack, !closing, let anchor, queue.current != nil else { return } + let generation = generation + Task { + let next = await activities.refresh(anchor: anchor) + guard self.generation == generation, !fallingBack, !closing else { return } + guard next != .native else { await fallBackToNative(); return } + // A card that is on screen keeps the place it appeared in: pausing or starting music + // must not flip it between the camera and the Live Activity. The next card re-reads it. + guard presenter.window == nil else { return } + placement = next + // A Live Activity appearing or ending moves the card; keep it expanded if it was. + if let current = queue.current, !blocked { show(current, anchor: anchor) } + } + } + + private func fallBackToNative() async { + guard !fallingBack else { return } + fallingBack = true + logger.notice("falling back to native banners hidden=\(self.hidden.count, privacy: .public)") + presenter.hide() + lifetimeTimer?.invalidate(); lifetimeTimer = nil + let records = moved + let notifications = hidden + let generation = generation + let desktopMinX = Self.desktopMinX + await IslandAX.run { + IslandAX.restoreMovedWindows(records) + // Windows moved before they were recorded (none normally) go to their saved position. + for item in notifications where !records.contains(where: { CFEqual($0.window, item.window) }) { + if let position = IslandAX.position(item.window), position.x < desktopMinX - 5000 { + _ = IslandAX.move(item.window, to: item.originalPosition) + } + } + } + guard self.generation == generation else { return } + moved.removeAll() + // Reattach. Recovery re-reads the windows; while the placement is native, each banner found + // is simply left (or put back) on screen, since nothing is held. + stop() + refresh() + } + + private func reply(_ text: String) { + guard !closing, let notification = queue.current else { return } + presenter.setReplySending() + updateLifetime() + let generation = generation + Task { + let outcome = if let chat = notification.claudeChat { + await IslandClaudeReply.send(text, to: chat) + } else { + await Self.replyInMessages(text, to: notification) + } + guard self.generation == generation, queue.current === notification, !closing else { return } + logger.notice("reply outcome=\(String(describing: outcome), privacy: .public)") + switch outcome { + case .sent: + presenter.showReplySent() + try? await Task.sleep(for: .milliseconds(900)) + guard self.generation == generation, queue.current === notification else { return } + presenter.returnKeyboard() + finishCurrent(dismissNative: true, reason: "replied") + case .noConversation: + presenter.showReplyError(localization.string("reply.error.conversation", defaultValue: "找不到这个对话。点按卡片以打开“信息”。")) + case .notAuthorized: + presenter.showReplyError(localization.string("reply.error.permission", defaultValue: "请在“隐私与安全性 > 自动化”中允许 MacTools 控制“信息”。")) + case .claudeDraft: + presenter.showReplyError(localization.string("reply.error.claudeDraft", defaultValue: "这个对话在 Claude 中有未发送的文字。点按卡片以打开。")) + case .ambiguousChat: + presenter.showReplyError(localization.string("reply.error.duplicateChat", defaultValue: "有多个 Claude 对话使用这个名称。点按卡片以打开 Claude。")) + case .failed: + presenter.showReplyError(localization.string("reply.error.failed", defaultValue: "无法发送。点按卡片以打开应用。")) + } + updateLifetime() + } + } + + /// The exact conversation comes from Messages' history; the message may land there a moment + /// after its banner. No match (or no access) means no reply, never a guess. + private static func messagesConversation(body: String, lineCount: Int) async -> IslandMessagesChat.Lookup { + let lines = body.components(separatedBy: "\n") + [body] + let isGroup = lineCount > 2 + var lookup = IslandMessagesChat.Lookup.notFound + for _ in 0..<4 { + lookup = await Task.detached(priority: .userInitiated) { + IslandMessagesChat.resolve(bannerLines: lines, isGroupBanner: isGroup) + }.value + guard lookup == .notFound else { break } + try? await Task.sleep(for: .milliseconds(500)) + } + return lookup + } + + private static func replyInMessages(_ text: String, to notification: IslandNotification) async -> IslandReplyOutcome { + guard case .found(let chat) = await messagesConversation(body: notification.body, lineCount: notification.lineCount) else { return .noConversation } + return await IslandMessagesReply.send(text, toChat: chat) + } + + private func openCurrent() { + guard !closing, let notification = queue.current else { return } + closing = true + lifetimeTimer?.invalidate(); lifetimeTimer = nil + let generation = generation + if let link = notification.claudeChat?.link { + // A Claude chat card opens its chat with Claude's own link. + NSWorkspace.shared.open(link) + closing = false + finishCurrent(dismissNative: false, reason: "opened") + return + } + Task { + // The banner's own click: macOS hands the app this exact notification, so Mail, Spark, + // Messages and the rest open the item it is about. macOS 27 names it AXPress; earlier + // releases offered "Show". A banner lives about 5 s; after that only the app can open. + let opened = await IslandAX.run { () -> Bool in + IslandAX.perform(kAXPressAction as String, on: notification.element) + || IslandAX.perform(anyOf: IslandAX.centerAction("Show"), on: notification.element) + } + logger.notice("card open banner=\(opened, privacy: .public)") + guard self.generation == generation else { return } + // macOS removes a banner after a few seconds; a Messages card that outlives it still + // opens its conversation, found the same way replies are. + if !opened, notification.bundleIdentifier == "com.apple.MobileSMS", + case .found(let chat) = await Self.messagesConversation(body: notification.body, lineCount: notification.lineCount), + let url = chat.openURL, NSWorkspace.shared.open(url) { + // Opened the exact conversation. + } else if !opened, let url = notification.appURL { + NSWorkspace.shared.openApplication(at: url, configuration: NSWorkspace.OpenConfiguration(), completionHandler: nil) + } + closing = false + finishCurrent(dismissNative: !opened, reason: "opened") + } + } + + // MARK: The panel's Notifications list + // + // Opening or clearing an entry acts on its row in Notification Centre, out of sight, as a click + // there would (see IslandCenterPress); the list and Notification Centre stay one record. + + private func record(_ notification: IslandNotification) { + // The description is the longest hint: it holds the app, the title and the message. + let description = notification.identityHints.max { $0.count < $1.count } ?? "" + let centerApp = notification.claudeChat == nil + ? IslandNotification.appName(fromDescription: description, title: notification.title, body: notification.body) + : nil + history.add(IslandHistoryEntry(date: Date(), appName: notification.appName ?? centerApp ?? notification.title, + centerApp: centerApp, appURL: notification.appURL, + bundleIdentifier: notification.bundleIdentifier, + title: notification.title, body: notification.body, + claudeChat: notification.claudeChat, lineCount: notification.lineCount)) + } + + func setHistoryContentHeight(_ height: CGFloat) { + let total = height > 0 + ? min(IslandHistoryLayout.maximumHeight, height) + : IslandHistoryLayout.emptyHeight + let span = PluginPanelWidgetLayoutMetrics.default.heightSpan(fittingContentHeight: total) + // At once, both ways: the panel glides to the new height on the same spring the list + // uses, and the list waits the panel's short update delay (see IslandHistoryLayout.motion). + guard span != historySpan else { return } + historySpan = span + onStateChange?() + } + + func openHistory(_ entry: IslandHistoryEntry) { + logger.notice("list open inCentre=\(entry.centerApp != nil, privacy: .public) claude=\(entry.claudeChat != nil, privacy: .public)") + history.remove(entry) + if let link = entry.claudeChat?.link { NSWorkspace.shared.open(link); return } + Task { + var opened = await inCenter(.open, entry) + // Gone from Notification Centre (the app withdrew it, or it was cleared there). + if !opened, entry.bundleIdentifier == "com.apple.MobileSMS", + case .found(let chat) = await Self.messagesConversation(body: entry.body, lineCount: entry.lineCount), + let url = chat.openURL { + opened = NSWorkspace.shared.open(url) + } + if !opened, let url = entry.appURL { + NSWorkspace.shared.openApplication(at: url, configuration: NSWorkspace.OpenConfiguration(), completionHandler: nil) + } + } + } + + func clearHistory(_ entries: [IslandHistoryEntry]) { + for entry in entries { history.remove(entry) } + Task { + for entry in entries { _ = await inCenter(.clear, entry) } + } + } + + /// One at a time: each opens Notification Centre out of sight and closes it again. + private func inCenter(_ action: IslandCenterPress.Action, _ entry: IslandHistoryEntry) async -> Bool { + guard let app = entry.centerApp else { return false } + while centerPressing { try? await Task.sleep(for: .milliseconds(50)) } + centerPressing = true + defer { centerPressing = false } + return await IslandCenterPress.perform(action, on: IslandCenterPress.Target(app: app, title: entry.title, body: entry.body)) + } + + private func finishCurrent(dismissNative: Bool, reason: String) { + guard !closing, let notification = queue.current else { return } + logger.notice("card closed reason=\(reason, privacy: .public) held=\(self.presenter.isHeld, privacy: .public) hovered=\(self.presenter.isHovered, privacy: .public)") + closing = true + lifetimeTimer?.invalidate(); lifetimeTimer = nil + let generation = generation + let desktopMinX = Self.desktopMinX + Task { + if dismissNative, notification.style == .persistent { + await IslandAX.run { + if let position = IslandAX.position(notification.window), position.x < desktopMinX - 5000, + !IslandAX.perform(anyOf: IslandAX.centerAction("Close"), on: notification.element) { + _ = IslandAX.move(notification.window, to: notification.originalPosition) + } + } + } + guard self.generation == generation else { return } + presenter.dismiss { [weak controller = self] in + guard let self = controller, self.generation == generation else { return } + if notification.style == .temporary { self.hidden.removeAll { $0 === notification } } + self.queue.finish(); self.lifetime = nil; self.closing = false + self.presentNext() + } + } + } + + private func tick() { + guard active else { return } + guard enabled, trusted, let anchor else { return } + // macOS swaps a newer notification from the same app into its existing banner without any + // creation event, so re-read the shown card's hidden banner window twice a second. + let now = ProcessInfo.processInfo.systemUptime + if now - lastRescan >= 0.5, let current = queue.current, current.claudeChat == nil, !closing { + lastRescan = now + receive(IslandAXElement(value: current.window)) + } + let wasBlocked = blocked + blocked = hoverPanelVisible(over: anchor) + if !closing, queue.current != nil { + // Hiding rebuilds the card later as a small card, so one in use stays: an opened or held + // card (iOS keeps an expanded notification until it is dismissed) or a reply in progress. + if blocked, presenter.window != nil, !presenter.isHeld, !presenter.isReplying, !presenter.hasDraft { + logger.notice("card hidden under a hover panel") + presenter.hide() + } + else if !blocked, presenter.window == nil { activityChanged() } + if blocked != wasBlocked { updateLifetime() } + } else { presentNext(checkBlocking: false) } + } + + private static var desktopMinX: CGFloat { NSScreen.screens.map(\.frame.minX).min() ?? 0 } + private static var offscreenPosition: CGPoint { CGPoint(x: desktopMinX - 100_000, y: -100_000) } + + private static func normalPosition(for anchor: CGRect) -> CGPoint? { + guard let screen = NSScreen.screens.first(where: { $0.frame.contains(anchor) }), + let id = screen.deviceDescription[NSDeviceDescriptionKey("NSScreenNumber")] as? NSNumber else { return nil } + return CGDisplayBounds(id.uint32Value).origin + } + + /// These features are built for the floating camera island of the MacBook Pro that came with + /// macOS 27: a short pill just below the top of the display. A classic notch (wide, reaching + /// the display edge) is not one, and neither is an earlier macOS; there the feature stays off. + static func isCameraIsland(_ anchor: CGRect) -> Bool { + ProcessInfo.processInfo.isOperatingSystemAtLeast(OperatingSystemVersion(majorVersion: 27, minorVersion: 0, patchVersion: 0)) + && anchor.width < anchor.height * 3 + } + + private static func notchAnchor() -> CGRect? { + for screen in NSScreen.screens { + guard let id = screen.deviceDescription[NSDeviceDescriptionKey("NSScreenNumber")] as? NSNumber, + CGDisplayIsBuiltin(id.uint32Value) != 0, CGDisplayIsActive(id.uint32Value) != 0, + let left = screen.auxiliaryTopLeftArea, let right = screen.auxiliaryTopRightArea, + !left.isEmpty, !right.isEmpty else { continue } + let height = max(left.height, right.height) + let width = screen.frame.width - left.width - right.width + guard height > 0, width > 0 else { continue } + let anchor = CGRect(x: screen.frame.minX + left.width, y: screen.frame.maxY - height, width: width, height: height) + return isCameraIsland(anchor) ? anchor : nil + } + return nil + } + + private func hoverPanelVisible(over anchor: CGRect) -> Bool { + // Host-owned hover panels and this plugin's panel share the process. No + // public PluginKit layout change or host coordination hook is necessary. + let area = anchor.insetBy(dx: 0, dy: -64) + return NSApp.windows.contains { window in + window !== presenter.window && window.isVisible && window is NSPanel && + window.styleMask.contains(.nonactivatingPanel) && window.frame.width >= 260 && + window.frame.height > 64 && window.frame.intersects(area) + } + } +} diff --git a/Plugins/IslandNotifications/Sources/IslandNotificationsPlugin.swift b/Plugins/IslandNotifications/Sources/IslandNotificationsPlugin.swift new file mode 100644 index 000000000..9afdff20d --- /dev/null +++ b/Plugins/IslandNotifications/Sources/IslandNotificationsPlugin.swift @@ -0,0 +1,125 @@ +import AppKit +@preconcurrency import ApplicationServices +import SwiftUI +import MacToolsPluginKit + +public final class IslandNotificationsPluginFactory: NSObject, MacToolsPluginBundleFactory { + public static func makeProvider(context: PluginRuntimeContext) throws -> any PluginProvider { + IslandNotificationsProvider(context: context) + } +} + +@MainActor +private struct IslandNotificationsProvider: PluginProvider { + let context: PluginRuntimeContext + func makePlugins() -> [any MacToolsPlugin] { [IslandNotificationsPlugin(context: context)] } +} + +@MainActor +final class IslandNotificationsPlugin: MacToolsPlugin { + private let controller: IslandNotificationsController + private let localization: PluginLocalization + var shortcutBindingResolver: ((String) -> ShortcutBinding?)? + var requestPermissionGuidance: ((String) -> Void)? + var onStateChange: (() -> Void)? { + get { controller.onStateChange } + set { controller.onStateChange = newValue } + } + + init(context: PluginRuntimeContext) { + localization = PluginLocalization(bundle: context.resourceBundle) + controller = IslandNotificationsController(storage: context.storage, localization: localization) + } + + var metadata: PluginMetadata { + PluginMetadata(id: "island-notifications", + title: localization.string("metadata.title", defaultValue: "灵动岛通知"), + iconName: "bell.badge.fill", iconTint: .cyan, order: 42, + defaultDescription: localization.string("metadata.description", defaultValue: "在灵动岛显示通知,保留通知中心历史记录。")) + } + + var panelItems: [PluginPanelItem] { + // The list only exists where the island does, so other Macs never get a Notifications panel. + (controller.hasDisplay ? [historyWidget] : []) + [enabledRow] + } + + private var historyWidget: PluginPanelItem { + .widget(id: "history", initialPlacement: .dashboard, + descriptor: PluginPanelWidgetDescriptor(span: PluginPanelWidgetSpan( + width: PluginPanelWidgetSpan.maximumWidth, + height: controller.historySpan)!), + state: PluginPanelWidgetState(subtitle: metadata.defaultDescription, isActive: false, + isEnabled: true, isAvailable: true, errorMessage: nil), + content: { [controller, localization] _ in + GeometryReader { proxy in + IslandNotificationHistoryView(size: proxy.size, history: controller.history, localization: localization, + onOpen: { controller.openHistory($0) }, + onClear: { controller.clearHistory($0) }, + onContentHeight: { controller.setHistoryContentHeight($0) }) + } + }) + } + + private var enabledRow: PluginPanelItem { + .row(id: "enabled", initialPlacement: .featurePanel, + descriptor: PluginPanelRowDescriptor(controlStyle: .switch, menuActionBehavior: .keepPresented), + state: PluginPanelRowState(subtitle: status, isOn: controller.enabled, isEnabled: true, isAvailable: true, detail: nil, errorMessage: nil), + action: { [weak self] action in + if case let .setSwitch(value) = action { self?.setEnabled(value) } + }) + } + + private var status: String { + if !controller.hasDisplay { return localization.string("status.noDisplay", defaultValue: "需要配备摄像头岛的 MacBook Pro(macOS 27 或更高版本)") } + return controller.enabled ? localization.string("status.enabled", defaultValue: "已开启") : localization.string("status.disabled", defaultValue: "已关闭") + } + + var settingsPage: PluginSettingsPage? { + .form(description: localization.string("metadata.description", defaultValue: "在灵动岛显示通知,保留通知中心历史记录。"), sections: [ + PluginSettingsSection(id: "notifications", title: localization.string("metadata.title", defaultValue: "灵动岛通知"), systemImage: "bell.badge.fill", rows: [ + PluginSettingsRow(id: "enabled", title: localization.string("settings.enabled", defaultValue: "启用灵动岛通知"), description: status, + systemImage: "bell.badge.fill", control: .toggle(isOn: controller.enabled)), + PluginSettingsRow(id: "previewLines", title: localization.string("settings.previewLines", defaultValue: "预览行数"), + description: localization.string("settings.previewLines.description", defaultValue: "展开前显示的消息行数。向下滚动卡片可查看全文。"), + systemImage: "text.alignleft", + control: .picker(selectionID: String(controller.previewLines), + options: IslandNotificationPresenter.previewLineRange.map { + PluginSettingsOption(id: String($0), title: $0.formatted(.number.locale(PluginRuntimeLocalization.locale))) + }, style: .menu)), + ]), + ]) + } + + var permissionRequirements: [PluginPermissionRequirement] { + [PluginPermissionRequirement(id: "accessibility", kind: .accessibility, + title: localization.string("permission.title", defaultValue: "辅助功能授权"), + description: localization.string("permission.description", defaultValue: "用于读取和移动系统通知横幅。"))] + } + + func permissionState(for permissionID: String) -> PluginPermissionState { + PluginPermissionState(isGranted: controller.trusted, footnote: nil) + } + + func handlePermissionAction(id: String) { + guard id == "accessibility" else { return } + let options = [kAXTrustedCheckOptionPrompt.takeUnretainedValue() as String: true] as CFDictionary + _ = AXIsProcessTrustedWithOptions(options) + controller.refresh() + } + + private func setEnabled(_ value: Bool) { + controller.setEnabled(value) + if value, !controller.trusted { requestPermissionGuidance?("accessibility") } + } + + func handleSettingsAction(_ action: PluginSettingsAction) { + switch action { + case let .setBoolean(id, value) where id == "enabled": setEnabled(value) + case let .setSelection(id, option) where id == "previewLines": Int(option).map(controller.setPreviewLines) + default: break + } + } + func activate(context: PluginRuntimeContext) { controller.activate() } + func deactivate(reason: PluginDeactivationReason) { controller.deactivate() } + func refresh() { controller.refresh() } +} diff --git a/Plugins/IslandNotifications/Sources/IslandSplitMorphView.swift b/Plugins/IslandNotifications/Sources/IslandSplitMorphView.swift new file mode 100644 index 000000000..90bd68779 --- /dev/null +++ b/Plugins/IslandNotifications/Sources/IslandSplitMorphView.swift @@ -0,0 +1,62 @@ +import AppKit +import QuartzCore + +/// Plugin-owned surface: the shared host morph and its layout stay unchanged. +@MainActor +final class IslandSplitMorphView: NSView { + private let mask = CAShapeLayer() + private let surface = NSView() + private let shadowView = NSView() + private weak var content: NSView? + private var path: CGPath? + + init(content: NSView) { + self.content = content + super.init(frame: .zero) + wantsLayer = true + layer?.masksToBounds = false + shadowView.wantsLayer = true + shadowView.layer?.shadowColor = NSColor.black.cgColor + shadowView.layer?.shadowRadius = 16 + shadowView.layer?.shadowOffset = CGSize(width: 0, height: -6) + shadowView.layer?.masksToBounds = false + addSubview(shadowView) + surface.wantsLayer = true + surface.layer?.backgroundColor = NSColor.black.cgColor + surface.layer?.mask = mask + addSubview(surface) + content.wantsLayer = true + surface.addSubview(content) + } + + @available(*, unavailable) + required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } + + override var isOpaque: Bool { false } + override func hitTest(_ point: NSPoint) -> NSView? { + guard let path, path.contains(convert(point, from: superview)) else { return nil } + return super.hitTest(point) + } + + func releaseContent() { content?.removeFromSuperview(); content = nil } + + func apply(model: NotchMorphModel, geometry: IslandSplitGeometry, contentSize: CGSize, reduceMotion: Bool) { + let capsule = reduceMotion ? geometry.destination + : geometry.capsule(widthFraction: model.width.value, heightFraction: model.height.value) + let path = geometry.path(widthFraction: model.width.value, heightFraction: model.height.value, reduceMotion: reduceMotion) + self.path = path + CATransaction.begin() + CATransaction.setDisableActions(true) + surface.frame = bounds + shadowView.frame = bounds + // Only the emerging capsule casts a shadow; the system owns the upper pill. + shadowView.layer?.shadowPath = NotchSurfacePath.make(in: capsule, radius: geometry.radius(for: capsule, heightFraction: reduceMotion ? 1 : model.height.value)) + shadowView.layer?.shadowOpacity = Float(0.38 * NotchMorphModel.smoothstep(0.2, 1, model.height.value)) + mask.frame = bounds + mask.path = path + content?.frame = CGRect(x: capsule.midX - contentSize.width / 2, + y: capsule.maxY - contentSize.height, width: contentSize.width, height: contentSize.height) + content?.alphaValue = reduceMotion ? 1 : CGFloat(min(max(model.contentOpacity, 0), 1)) + CATransaction.commit() + } +} diff --git a/Plugins/IslandNotifications/Tests/IslandLiveActivityGeometryTests.swift b/Plugins/IslandNotifications/Tests/IslandLiveActivityGeometryTests.swift new file mode 100644 index 000000000..23936b158 --- /dev/null +++ b/Plugins/IslandNotifications/Tests/IslandLiveActivityGeometryTests.swift @@ -0,0 +1,69 @@ +import XCTest +@testable import IslandNotificationsPlugin + +final class IslandLiveActivityGeometryTests: XCTestCase { + private let screen = CGRect(x: 0, y: 0, width: 1732, height: 1120) + private let anchor = CGRect(x: 836, y: 1080, width: 60, height: 40) + private let activityAX = CGRect(x: 799, y: 6, width: 134, height: 34) + + func testPlacementConvertsAXAndAttachesBehindAnActualCapsule() { + XCTAssertEqual(resolve([]), .camera) + XCTAssertEqual(resolve([activityAX]), .split(CGRect(x: 799, y: 1080, width: 134, height: 34))) + // Reported MenuBarAgent geometry: only the 134x34 child is an activity; + // the 1736x1133 AXUnknown window is a structural wrapper. + let probeScreen = CGRect(x: 0, y: 0, width: 1736, height: 1133) + XCTAssertEqual(IslandLiveActivityPlacement.resolve(axFrames: [activityAX], complete: true, + desktopTop: 1133, screen: probeScreen, anchor: anchor.offsetBy(dx: 0, dy: 13)), + .split(CGRect(x: 799, y: 1093, width: 134, height: 34))) + let second = CGRect(x: 940, y: 6, width: 40, height: 34) + XCTAssertEqual(resolve([activityAX, second]), resolve([activityAX])) + let lower = CGRect(x: 940, y: 6, width: 70, height: 40) + XCTAssertEqual(resolve([activityAX, lower]), .split(CGRect(x: 940, y: 1074, width: 70, height: 40))) + XCTAssertEqual(resolve([CGRect(x: -1000, y: 6, width: 134, height: 34)]), .camera) + // AX's desktop origin stays on the primary screen with another screen above it. + let upperScreen = CGRect(x: 0, y: 1120, width: 1732, height: 1120) + XCTAssertEqual(IslandLiveActivityPlacement.resolve(axFrames: [CGRect(x: 799, y: -1114, width: 134, height: 34)], + complete: true, desktopTop: 1120, screen: upperScreen, anchor: anchor.offsetBy(dx: 0, dy: 1120)), + .split(CGRect(x: 799, y: 2200, width: 134, height: 34))) + } + + func testUnreadableExpandedAndInvalidActivitiesKeepNativeBanners() { + XCTAssertEqual(resolve([nil]), .native) + XCTAssertEqual(resolve([activityAX], complete: false), .native) + for frame in [CGRect(x: 799, y: 6, width: 134, height: 61), + CGRect(x: 799, y: 6, width: 0, height: 34), + CGRect(x: 799, y: 6, width: CGFloat.infinity, height: 34), + CGRect(x: 799, y: 200, width: 134, height: 34)] { + XCTAssertEqual(resolve([frame]), .native) + } + } + + func testSplitStartsOccludedThenConnectsAndDetachesAndCanReverse() { + let geometry = IslandSplitGeometry(activity: CGRect(x: 799, y: 1080, width: 134, height: 34), + expandedSize: CGSize(width: 370, height: 80)) + XCTAssertEqual(geometry.capsule(widthFraction: 0, heightFraction: 0), geometry.source) + XCTAssertEqual(geometry.capsule(widthFraction: 1, heightFraction: 1), geometry.destination) + XCTAssertEqual(geometry.source.minY - geometry.destination.maxY, IslandSplitGeometry.gap) + let pouring = geometry.capsule(widthFraction: 0.8, heightFraction: 0.7) + let bridgePoint = CGPoint(x: geometry.source.midX, y: (geometry.source.minY + pouring.maxY) / 2) + XCTAssertLessThan(pouring.maxY, geometry.source.minY) + XCTAssertTrue(geometry.path(widthFraction: 0.8, heightFraction: 0.7).contains(bridgePoint)) + let gapPoint = CGPoint(x: geometry.source.midX, y: (geometry.source.minY + geometry.destination.maxY) / 2) + XCTAssertFalse(geometry.path(widthFraction: 1, heightFraction: 1).contains(gapPoint)) + XCTAssertGreaterThan(geometry.neckWidth(heightFraction: 0.7, reduceMotion: false), + geometry.neckWidth(heightFraction: 0.9, reduceMotion: false)) + XCTAssertEqual(geometry.neckWidth(heightFraction: 0.7, reduceMotion: true), 0) + XCTAssertFalse(geometry.path(widthFraction: 0.8, heightFraction: 0.7, reduceMotion: true).contains(gapPoint)) + var closing = NotchMorphModel() + closing.target = 1; closing.snapToTarget(); closing.target = 0 + while closing.height.value > 0.8 { closing.advance(by: 1.0 / 480.0) } + let reconnecting = geometry.capsule(widthFraction: closing.width.value, heightFraction: closing.height.value) + let reconnectPoint = CGPoint(x: geometry.source.midX, y: (geometry.source.minY + reconnecting.maxY) / 2) + XCTAssertLessThan(reconnecting.maxY, geometry.source.minY) + XCTAssertTrue(geometry.path(widthFraction: closing.width.value, heightFraction: closing.height.value).contains(reconnectPoint)) + } + + private func resolve(_ frames: [CGRect?], complete: Bool = true) -> IslandLiveActivityPlacement { + .resolve(axFrames: frames, complete: complete, desktopTop: 1120, screen: screen, anchor: anchor) + } +} diff --git a/Plugins/IslandNotifications/Tests/IslandNotificationHistoryTests.swift b/Plugins/IslandNotifications/Tests/IslandNotificationHistoryTests.swift new file mode 100644 index 000000000..0badd7f7e --- /dev/null +++ b/Plugins/IslandNotifications/Tests/IslandNotificationHistoryTests.swift @@ -0,0 +1,56 @@ +import XCTest +@testable import IslandNotificationsPlugin + +final class IslandNotificationHistoryTests: XCTestCase { + /// Opening or clearing acts on the row in Notification Centre this matches, so a wrong match + /// would open or delete a different notification. + func testCentreRowMatchesOnlyTheSameAppTitleAndText() { + let row = "Spark Desktop, 💬 Yannis › Please Respond: New Booking, Confirmed on Viator." + XCTAssertTrue(IslandCenterMatch.row(row, matchesApp: "Spark Desktop", title: "💬 Yannis › Please Respond: New Booking", + body: "Confirmed on Viator.")) + // Banners and Notification Centre may wrap or shorten the text differently. + XCTAssertTrue(IslandCenterMatch.row(row, matchesApp: "Spark Desktop", title: "💬 Yannis › Please Respond: New Booking", + body: "Confirmed\non Viator.…")) + XCTAssertFalse(IslandCenterMatch.row(row, matchesApp: "Mail", title: "💬 Yannis › Please Respond: New Booking", + body: "Confirmed on Viator.")) + XCTAssertFalse(IslandCenterMatch.row(row, matchesApp: "Spark Desktop", title: "💬 Yannis › Please Respond", + body: "Confirmed on Viator.")) + XCTAssertFalse(IslandCenterMatch.row(row, matchesApp: "Spark Desktop", title: "💬 Yannis › Please Respond: New Booking", + body: "Cancelled.")) + XCTAssertTrue(IslandCenterMatch.stack(row, isApp: "Spark Desktop")) + XCTAssertFalse(IslandCenterMatch.stack(row, isApp: "Spark")) + } + + /// Notification Centre separates the parts of a description the way the system language does. + func testDescriptionsInOtherLanguagesStillMatchAndNameTheApp() { + let rows = ["メッセージ、Alex、明日会える?", "信息,Alex,明日会える?", + "\u{200F}الرسائل،\u{200F} Alex،明日会える?"] + for (row, app) in zip(rows, ["メッセージ", "信息", "الرسائل"]) { + XCTAssertTrue(IslandCenterMatch.row(row, matchesApp: app, title: "Alex", body: "明日会える?"), row) + XCTAssertTrue(IslandCenterMatch.stack(row, isApp: app), row) + XCTAssertEqual(IslandNotification.appName(fromDescription: row, title: "Alex", body: "明日会える?"), app) + } + // The title inside the app's own name is not where the title starts. + XCTAssertEqual(IslandNotification.appName(fromDescription: "Mail Plus, Mail, Hello", title: "Mail", body: "Hello"), + "Mail Plus") + XCTAssertEqual(IslandNotification.appName(fromDescription: "Spark Desktop, Desktop, Hi", title: "Desktop", body: "Hi"), + "Spark Desktop") + } + + @MainActor + func testListGroupsByAppNewestFirstAndKeepsALimit() { + let history = IslandNotificationHistory() + func entry(_ app: String, _ title: String) -> IslandHistoryEntry { + IslandHistoryEntry(date: Date(), appName: app, centerApp: app, appURL: nil, bundleIdentifier: app, + title: title, body: "", claudeChat: nil, lineCount: 2) + } + history.add(entry("Mail", "1")) + history.add(entry("Messages", "2")) + history.add(entry("Mail", "3")) + let groups = IslandNotificationHistory.groups(history.entries) + XCTAssertEqual(groups.map(\.id), ["Mail", "Messages"]) + XCTAssertEqual(groups[0].entries.map(\.title), ["3", "1"]) + for index in 0..<(IslandNotificationHistory.limit + 5) { history.add(entry("Mail", "\(index)")) } + XCTAssertEqual(history.entries.count, IslandNotificationHistory.limit) + } +} diff --git a/Plugins/IslandNotifications/Tests/IslandNotificationStateTests.swift b/Plugins/IslandNotifications/Tests/IslandNotificationStateTests.swift new file mode 100644 index 000000000..b53c6d4c2 --- /dev/null +++ b/Plugins/IslandNotifications/Tests/IslandNotificationStateTests.swift @@ -0,0 +1,70 @@ +import XCTest +@testable import IslandNotificationsPlugin + +final class IslandNotificationStateTests: XCTestCase { + func testFIFOBlocksForHoverPanelAndKeepsCurrentUntilFinished() { + var queue = IslandNotificationQueue<String>() + queue.append("first"); queue.append("second") + XCTAssertNil(queue.presentNext(blocked: true)) + XCTAssertEqual(queue.waiting.count, 2) + XCTAssertEqual(queue.presentNext(blocked: false), "first") + XCTAssertNil(queue.presentNext(blocked: false)) + queue.finish() + XCTAssertEqual(queue.presentNext(blocked: false), "second") + queue.removeAll() + XCTAssertNil(queue.current) + XCTAssertTrue(queue.waiting.isEmpty) + } + + func testOnlyKnownBannerStylesMayMoveAndAllSafetyGatesAreRequired() { + XCTAssertEqual(IslandNotificationStyle(subrole: "AXNotificationCenterBanner"), .temporary) + XCTAssertEqual(IslandNotificationStyle(subrole: "AXNotificationCenterAlert"), .persistent) + XCTAssertNil(IslandNotificationStyle(subrole: "AXNotificationCenter")) + XCTAssertTrue(IslandMovePolicy.allowsMove(enabled: true, trusted: true, hasNotch: true, notificationCount: 1, hasUnexpectedContent: false, complete: true)) + for gate in 0..<6 { + XCTAssertFalse(IslandMovePolicy.allowsMove(enabled: gate != 0, trusted: gate != 1, hasNotch: gate != 2, + notificationCount: gate == 3 ? 0 : 1, + hasUnexpectedContent: gate == 4, complete: gate != 5)) + } + } + + func testTemporaryTimePausesAndPersistentNeverExpires() { + var temporary = IslandNotificationLifetime(style: .temporary, now: 10) + XCTAssertFalse(temporary.advance(to: 12, paused: true)) + XCTAssertFalse(temporary.advance(to: 100, paused: true)) + XCTAssertEqual(temporary.remaining, 3) + XCTAssertFalse(temporary.advance(to: 100, paused: false)) + XCTAssertFalse(temporary.advance(to: 102, paused: false)) + XCTAssertTrue(temporary.advance(to: 103, paused: false)) + var persistent = IslandNotificationLifetime(style: .persistent, now: 10) + XCTAssertFalse(persistent.advance(to: 1000, paused: false)) + XCTAssertNil(persistent.remaining) + } + + func testRestorePositionPreservesKnownOriginAndRecoversAnAlreadyHiddenWindow() { + let normal = CGPoint(x: -8000, y: 400) + let hidden = CGPoint(x: -108_000, y: -100_000) + let original = CGPoint(x: -7900, y: 500) + XCTAssertEqual(IslandMovePolicy.originalPosition(position: hidden, prior: nil, desktopMinX: -8000, + normalPosition: normal), normal) + XCTAssertEqual(IslandMovePolicy.originalPosition(position: hidden, prior: original, desktopMinX: -8000, + normalPosition: normal), original) + XCTAssertEqual(IslandMovePolicy.originalPosition(position: original, prior: nil, desktopMinX: -8000, + normalPosition: normal), original) + } + + func testRecoveryRequiresOffscreenPositionAndSafeNotificationSnapshot() { + let hidden = CGPoint(x: -108_000, y: -100_000) + XCTAssertTrue(IslandMovePolicy.allowsRecovery(position: hidden, desktopMinX: -8000, + notificationCount: 1, hasUnexpectedContent: false, complete: true)) + for position in [nil, CGPoint(x: -13_000, y: 0), .zero, CGPoint(x: -.infinity, y: 0)] as [CGPoint?] { + XCTAssertFalse(IslandMovePolicy.allowsRecovery(position: position, desktopMinX: -8000, + notificationCount: 1, hasUnexpectedContent: false, complete: true)) + } + for gate in 0..<3 { + XCTAssertFalse(IslandMovePolicy.allowsRecovery(position: hidden, desktopMinX: -8000, + notificationCount: gate == 0 ? 0 : 1, + hasUnexpectedContent: gate == 1, complete: gate != 2)) + } + } +} diff --git a/Plugins/IslandNotifications/plugin.json b/Plugins/IslandNotifications/plugin.json new file mode 100644 index 000000000..2b32f3afd --- /dev/null +++ b/Plugins/IslandNotifications/plugin.json @@ -0,0 +1,236 @@ +{ + "id": "island-notifications", + "displayName": "灵动岛通知", + "summary": "在灵动岛显示通知,保留通知中心历史记录。", + "localizedMetadata": { + "zh-Hans": { + "displayName": "灵动岛通知", + "summary": "在灵动岛显示通知,保留通知中心历史记录。" + }, + "en": { + "displayName": "Dynamic Island Notifications", + "summary": "Show notifications at the camera island while preserving Notification Centre history." + }, + "zh-Hant": { + "displayName": "靈動島通知", + "summary": "在靈動島顯示通知,保留通知中心歷史記錄。" + }, + "de": { + "displayName": "Dynamic-Island-Mitteilungen", + "summary": "Mitteilungen an der Kamera-Insel anzeigen und im Mitteilungszentrum behalten." + }, + "es": { + "displayName": "Notificaciones de Dynamic Island", + "summary": "Muestra notificaciones junto a la cámara y conserva el historial del Centro de notificaciones." + }, + "fr": { + "displayName": "Notifications Dynamic Island", + "summary": "Affiche les notifications près de la caméra et conserve l’historique du Centre de notifications." + }, + "pt": { + "displayName": "Notificações da Dynamic Island", + "summary": "Mostra notificações junto à câmara e mantém o histórico da Central de Notificações." + }, + "ru": { + "displayName": "Уведомления Dynamic Island", + "summary": "Показывает уведомления у камеры, сохраняя историю Центра уведомлений." + }, + "ja": { + "displayName": "Dynamic Island 通知", + "summary": "カメラ部分に通知を表示し、通知センターの履歴を保持します。" + }, + "ko": { + "displayName": "Dynamic Island 알림", + "summary": "카메라 영역에 알림을 표시하고 알림 센터 기록을 유지합니다." + }, + "ar": { + "displayName": "إشعارات Dynamic Island", + "summary": "عرض الإشعارات عند الكاميرا مع الاحتفاظ بسجل مركز الإشعارات." + }, + "tr": { + "displayName": "Dynamic Island Bildirimleri", + "summary": "Bildirimleri kamera çevresinde gösterir ve Bildirim Merkezi geçmişini korur." + } + }, + "productStrings": { + "display-name": "@displayName", + "summary": "@summary", + "discovery.notification-history": { + "ar": "سجل الإشعارات", + "de": "Mitteilungsverlauf", + "en": "Notification history", + "es": "Historial de notificaciones", + "fr": "Historique des notifications", + "ja": "通知履歴", + "ko": "알림 기록", + "pt": "Histórico de notificações", + "ru": "История уведомлений", + "tr": "Bildirim geçmişi", + "zh-Hans": "通知历史", + "zh-Hant": "通知歷史" + }, + "discovery.reply-to-notifications": { + "ar": "الرد على الإشعارات", + "de": "Auf Mitteilungen antworten", + "en": "Reply to notifications", + "es": "Responder a notificaciones", + "fr": "Répondre aux notifications", + "ja": "通知に返信", + "ko": "알림에 답장", + "pt": "Responder a notificações", + "ru": "Ответ на уведомления", + "tr": "Bildirimleri yanıtla", + "zh-Hans": "回复通知", + "zh-Hant": "回覆通知" + } + }, + "version": "1.0.0", + "minHostVersion": "2.2.0", + "pluginKitVersion": 7, + "bundleRelativePath": "IslandNotifications.bundle", + "factoryClass": "IslandNotificationsPlugin.IslandNotificationsPluginFactory", + "build": { + "project": "../../MacTools.xcodeproj", + "scheme": "IslandNotificationsPlugin" + }, + "capabilities": { + "panelItems": [ + "row", + "widget" + ], + "settings": "form" + }, + "permissions": [ + "accessibility" + ], + "category": "display", + "presentation": { + "longDescription": "@productStrings.summary", + "examples": [ + { + "id": "primary-use", + "text": "@productStrings.summary" + } + ], + "screenshots": [], + "documentationURL": "https://github.com/ggbond268/MacTools#plugins-and-settings", + "supportURL": "https://github.com/ggbond268/MacTools/issues", + "publisher": "MacTools", + "license": "GPL-3.0-only" + }, + "discovery": { + "keywords": [ + "dynamic island", + "notifications", + "notch", + "notification history", + "notification center", + "reply" + ], + "localizedSynonyms": { + "zh-Hans": [ + "灵动岛通知" + ], + "en": [ + "Dynamic Island Notifications" + ], + "zh-Hant": [ + "靈動島通知" + ], + "de": [ + "Dynamic-Island-Mitteilungen" + ], + "es": [ + "Notificaciones de Dynamic Island" + ], + "fr": [ + "Notifications Dynamic Island" + ], + "pt": [ + "Notificações da Dynamic Island" + ], + "ru": [ + "Уведомления Dynamic Island" + ], + "ja": [ + "Dynamic Island 通知" + ], + "ko": [ + "Dynamic Island 알림" + ], + "ar": [ + "إشعارات Dynamic Island" + ], + "tr": [ + "Dynamic Island Bildirimleri" + ] + }, + "localizedSynonymRefs": [ + "@productStrings.discovery.notification-history", + "@productStrings.discovery.reply-to-notifications" + ], + "useCases": [ + { + "id": "primary-use", + "title": "@productStrings.display-name" + } + ], + "goalCategories": [ + "display" + ], + "relatedPluginIDs": [], + "alternativePluginIDs": [] + }, + "requirements": { + "minimumMacOSVersion": "27.0", + "architectures": [ + "arm64", + "x86_64" + ], + "hardware": [ + "MacBook Pro camera island" + ], + "applications": [], + "executables": [], + "permissionIDs": [ + "accessibility" + ], + "setupComplexity": "simple", + "requiresRelaunch": false + }, + "privacy": { + "dataObserved": [ + "notification-content", + "display-state" + ], + "dataPersisted": [ + "plugin-configuration" + ], + "retention": { + "policy": "user-controlled" + }, + "networkUse": "none", + "networkDomains": [], + "allowsUserConfiguredDomains": false, + "telemetry": "none", + "processesSensitiveUserContent": true, + "diagnosticExportsContainUserData": false + }, + "setup": { + "steps": [], + "optionalSurfaces": [] + }, + "relationships": { + "relatedPluginIDs": [], + "includedPackIDs": [], + "suggestedRecipeIDs": [], + "supersedesPluginIDs": [] + }, + "preferencesBackup": { + "status": "localOnly", + "exclusions": [ + "local-activation", + "private-content" + ] + } +} diff --git a/Plugins/IslandNotifications/project.yml b/Plugins/IslandNotifications/project.yml new file mode 100644 index 000000000..f46b742ee --- /dev/null +++ b/Plugins/IslandNotifications/project.yml @@ -0,0 +1,3 @@ +core: + sources: + - ../../Sources/PluginSupport/NotchMorphSurface.swift diff --git a/Plugins/NotchHoverPanel/Sources/NotchHoverPanelController.swift b/Plugins/NotchHoverPanel/Sources/NotchHoverPanelController.swift index 83a9a9d9e..a9df54d1c 100644 --- a/Plugins/NotchHoverPanel/Sources/NotchHoverPanelController.swift +++ b/Plugins/NotchHoverPanel/Sources/NotchHoverPanelController.swift @@ -344,7 +344,9 @@ final class NotchHoverPanelController: NotchHoverPanelControlling { } let panelFrame = presentedMenuBarPanelScreenFrame?() - let isInsideTrigger = triggerDisplay != nil + // A MacTools window floating above the menu bar (an island notification card) owns the + // pointer there, so the panel must not open underneath it. + let isInsideTrigger = triggerDisplay != nil && !Self.isCoveredByOwnFloatingWindow(point) let isInsideActiveArea = pointerIsActive( point, triggerDisplay: triggerDisplay, @@ -403,6 +405,19 @@ final class NotchHoverPanelController: NotchHoverPanelControlling { ) } + /// True when one of this app's windows above the menu-bar level (an island notification card) + /// has visible content under the point. macOS draws its own island above every window, so the + /// topmost window at the camera is never ours; check our windows' shapes directly instead. + private static func isCoveredByOwnFloatingWindow(_ point: NSPoint) -> Bool { + NSApp.windows.contains { window in + guard window.isVisible, !window.ignoresMouseEvents, + window.level.rawValue > NSWindow.Level.statusBar.rawValue, + window.frame.contains(point), let content = window.contentView else { return false } + let local = window.convertPoint(fromScreen: point) + return content.hitTest(content.superview.map { $0.convert(local, from: nil) } ?? local) != nil + } + } + private func displayContainingTrigger(_ point: NSPoint) -> NotchHoverDisplay? { displays.first { display in display.triggerRects.contains(where: { $0.contains(point) }) @@ -457,7 +472,7 @@ final class NotchHoverPanelController: NotchHoverPanelControlling { guard isPresentedMenuBarPanelVisible?() != true else { return } let point = mouseLocationProvider() - guard let display = displayContainingTrigger(point) else { return } + guard let display = displayContainingTrigger(point), !Self.isCoveredByOwnFloatingWindow(point) else { return } activeDisplay = display let request = PluginMenuBarPanelPresentationRequest(anchorRect: display.notchFrame) diff --git a/Sources/App/NotchMenuBarPanel.swift b/Sources/App/NotchMenuBarPanel.swift index 065595466..a6e641f64 100644 --- a/Sources/App/NotchMenuBarPanel.swift +++ b/Sources/App/NotchMenuBarPanel.swift @@ -239,332 +239,16 @@ final class NotchMenuBarPanel { } } -// MARK: - Spring model - -/// Two critically tuned springs: width leads on the way out and height leads on -/// the way back, which produces the "widen, then deepen" feel of the system island. -struct NotchMorphModel { - struct Spring { - var value: Double = 0 - var velocity: Double = 0 - - mutating func step(toward target: Double, response: Double, dampingRatio: Double, dt: Double) { - let stiffness = pow(2 * Double.pi / response, 2) - let damping = 4 * Double.pi * dampingRatio / response - velocity += (-stiffness * (value - target) - damping * velocity) * dt - value += velocity * dt - } - - func isSettled(at target: Double) -> Bool { - abs(value - target) < 0.001 && abs(velocity) < 0.01 - } - } - - private static let substep = 1.0 / 480.0 - - var target: Double = 0 - private(set) var width = Spring() - private(set) var height = Spring() - private(set) var contentOpacity: Double = 0 - - var isSettled: Bool { - width.isSettled(at: target) && height.isSettled(at: target) - && abs(contentOpacity - target) < 0.01 - } - - mutating func snapToTarget() { - width = Spring(value: target) - height = Spring(value: target) - contentOpacity = target - } - - mutating func advance(by elapsed: Double) { - var remaining = elapsed - while remaining > 0 { - let dt = min(Self.substep, remaining) - remaining -= dt - if target > 0.5 { - width.step(toward: target, response: 0.36, dampingRatio: 0.76, dt: dt) - height.step(toward: target, response: 0.46, dampingRatio: 0.82, dt: dt) - } else { - width.step(toward: target, response: 0.34, dampingRatio: 1, dt: dt) - height.step(toward: target, response: 0.27, dampingRatio: 1, dt: dt) - } - // Content follows the surface in, but leaves ahead of it so nothing is - // still legible while the shape folds back into the camera housing. - let opacityTarget = target > 0.5 ? Self.smoothstep(0.42, 0.92, height.value) : 0 - let timeConstant = target > 0.5 ? 0.035 : 0.045 - contentOpacity += (opacityTarget - contentOpacity) * (1 - exp(-dt / timeConstant)) - } - } - - static func smoothstep(_ edge0: Double, _ edge1: Double, _ x: Double) -> Double { - let t = min(max((x - edge0) / (edge1 - edge0), 0), 1) - return t * t * (3 - 2 * t) - } -} - -// MARK: - Geometry - -/// Geometry in window coordinates (origin at the bottom left). The window's top -/// edge is aligned with the top of the expanded surface. -struct NotchMorphMetrics { - /// The compact island sits a few points below the top of the screen. - static let housingTopInset: CGFloat = 6 - /// The system draws its own island around the housing and grows it upward - /// (to about 4pt) while the pointer is on it, so the expanded surface rises - /// above that to keep the island inside it in every state. - static let expandedTopInset: CGFloat = 3 - static let contentGap: CGFloat = 4 - /// Space kept between the header capsules and the island on each side. - static let islandClearance: CGFloat = 12 - static let bottomInset: CGFloat = 6 - static let expandedCornerRadius: CGFloat = 26 - /// Room for spring overshoot and the soft drop shadow. - static let margin: CGFloat = 28 - - let anchor: CGRect - let contentSize: CGSize - let housingSize: CGSize - let collapsedSize: CGSize - let expandedSize: CGSize - /// Distance from the window top (the expanded surface top) to the housing top. - let housingOffset: CGFloat - /// Distance from the window top to the top of the hosted content. - let contentTopInset: CGFloat - /// A wide camera cutout reaches the display edge, so the surface grows from - /// that edge with square top corners instead of floating below it. - let meetsDisplayTop: Bool - +// Header placement belongs to the menu-bar panel, not the shared surface. +extension NotchMorphMetrics { init(anchor: CGRect, contentSize: CGSize) { - self.anchor = anchor - self.contentSize = contentSize - // AppKit reports the housing rectangle. A wide camera cutout reaches the - // display edge, while the compact island has space above it. - let isWideCameraCutout = anchor.width >= anchor.height * 3 - let housingInset = isWideCameraCutout ? 0 : min(Self.housingTopInset, anchor.height * 0.2) - let expandedInset = min(Self.expandedTopInset, housingInset) - meetsDisplayTop = expandedInset == 0 - housingOffset = housingInset - expandedInset - housingSize = CGSize(width: anchor.width, height: max(anchor.height - housingInset, 1)) - // Start one point inside the housing so the first frame is hidden by it. - collapsedSize = CGSize(width: max(housingSize.width - 2, 2), height: max(housingSize.height - 2, 2)) - // The content's header row is centered on the island, beside it. The - // content's empty top padding may start above a surface that meets the - // display edge, but the header itself never does. - let islandCenter = housingOffset + housingSize.height / 2 - contentTopInset = max( + let housing = Self(anchor: anchor, contentSize: contentSize, contentTopInset: 0) + let islandCenter = housing.housingOffset + housing.housingSize.height / 2 + let inset = max( islandCenter - (MenuBarPanelLayout.panelTopPadding + MenuBarPanelLayout.headerHeight / 2), -MenuBarPanelLayout.panelTopPadding ) - expandedSize = CGSize( - width: max(contentSize.width, housingSize.width), - height: contentTopInset + contentSize.height + Self.bottomInset - ) - } - - var windowFrame: CGRect { - let width = expandedSize.width + Self.margin * 2 - let height = (expandedSize.height + Self.margin).rounded() - let top = anchor.maxY - (anchor.height - housingSize.height) + housingOffset - return CGRect(x: (anchor.midX - width / 2).rounded(), y: top - height, - width: width.rounded(), height: height) - } - - var windowSize: CGSize { windowFrame.size } - - - func surfaceRect(for model: NotchMorphModel) -> CGRect { - surfaceRect(widthFraction: model.width.value, heightFraction: model.height.value) - } - - func surfaceRect(expandedFraction fraction: Double) -> CGRect { - surfaceRect(widthFraction: fraction, heightFraction: fraction) - } - - func surfaceRect(widthFraction: Double, heightFraction: Double) -> CGRect { - let size = windowSize - let width = max(Self.lerp(collapsedSize.width, expandedSize.width, widthFraction), 2) - let height = max(Self.lerp(collapsedSize.height, expandedSize.height, heightFraction), 2) - // Rises from inside the housing to the expanded top as the surface deepens. - // A surface that meets the display edge stays pinned to it. - let collapsedTop = meetsDisplayTop ? 0 : housingOffset + (housingSize.height - collapsedSize.height) / 2 - let topInset = Self.lerp(collapsedTop, 0, min(max(heightFraction, 0), 1)) - return CGRect(x: size.width / 2 - width / 2, y: size.height - topInset - height, - width: width, height: height) - } - - /// Stays a pill while the surface is shallow, then relaxes toward the - /// expanded radius as it deepens, so the corners change continuously. - func cornerRadius(for rect: CGRect, heightFraction: Double) -> CGFloat { - let pill = min(rect.height, rect.width) / 2 - let settle = NotchMorphModel.smoothstep(0.12, 1, heightFraction) - return min(Self.lerp(pill, Self.expandedCornerRadius, settle), pill) - } - - func topCornerRadius(for rect: CGRect, heightFraction: Double) -> CGFloat { - meetsDisplayTop ? 0 : cornerRadius(for: rect, heightFraction: heightFraction) - } - - func screenRect(fromSurfaceRect rect: CGRect) -> CGRect { - rect.offsetBy(dx: windowFrame.minX, dy: windowFrame.minY) - } - - static func lerp(_ from: CGFloat, _ to: CGFloat, _ fraction: Double) -> CGFloat { - from + (to - from) * CGFloat(fraction) - } -} - -enum NotchSurfacePath { - /// A rounded rectangle whose corners ease into the straight edges - /// (continuous curvature) when there is room, and become exact circular - /// arcs as the shape approaches a pill. The top corners can use a smaller - /// radius, down to square, for a surface that meets the display edge. - static func make(in rect: CGRect, radius: CGFloat, topRadius: CGFloat? = nil) -> CGPath { - let limit = min(rect.width, rect.height) / 2 - let bottom = Corner(radius: radius, limit: limit) - let top = Corner(radius: topRadius ?? radius, limit: limit) - let minX = rect.minX, maxX = rect.maxX, minY = rect.minY, maxY = rect.maxY - let path = CGMutablePath() - - path.move(to: CGPoint(x: minX + top.extent, y: maxY)) - path.addLine(to: CGPoint(x: maxX - top.extent, y: maxY)) - path.addCurve(to: CGPoint(x: maxX, y: maxY - top.extent), - control1: CGPoint(x: maxX - top.extent + top.handle, y: maxY), - control2: CGPoint(x: maxX, y: maxY - top.extent + top.handle)) - path.addLine(to: CGPoint(x: maxX, y: minY + bottom.extent)) - path.addCurve(to: CGPoint(x: maxX - bottom.extent, y: minY), - control1: CGPoint(x: maxX, y: minY + bottom.extent - bottom.handle), - control2: CGPoint(x: maxX - bottom.extent + bottom.handle, y: minY)) - path.addLine(to: CGPoint(x: minX + bottom.extent, y: minY)) - path.addCurve(to: CGPoint(x: minX, y: minY + bottom.extent), - control1: CGPoint(x: minX + bottom.extent - bottom.handle, y: minY), - control2: CGPoint(x: minX, y: minY + bottom.extent - bottom.handle)) - path.addLine(to: CGPoint(x: minX, y: maxY - top.extent)) - path.addCurve(to: CGPoint(x: minX + top.extent, y: maxY), - control1: CGPoint(x: minX, y: maxY - top.extent + top.handle), - control2: CGPoint(x: minX + top.extent - top.handle, y: maxY)) - path.closeSubpath() - return path - } - - /// One corner's reach along each edge and its Bézier handle length. - private struct Corner { - let extent: CGFloat - let handle: CGFloat - - init(radius requested: CGFloat, limit: CGFloat) { - let radius = max(min(requested, limit), 0) - guard radius > 0 else { - extent = 0 - handle = 0 - return - } - let smoothing = min(max((limit / radius - 1) / 0.4, 0), 1) - extent = radius * (1 + 0.4 * smoothing) - handle = extent * (0.5523 + (0.8 - 0.5523) * smoothing) - } - } -} - -// MARK: - Views - -/// Root view: a shadow behind a black, shape-masked surface that hosts the content. -@MainActor -final class NotchMorphView: NSView { - private static let contentLift: CGFloat = 10 - - private let shadowView = NSView() - private let surfaceView = NSView() - private let surfaceMask = CAShapeLayer() - private weak var content: NSView? - private var surfacePath: CGPath? - - init(content: NSView) { - self.content = content - super.init(frame: .zero) - wantsLayer = true - layer?.masksToBounds = false - - shadowView.wantsLayer = true - shadowView.layer?.shadowColor = NSColor.black.cgColor - shadowView.layer?.shadowRadius = 16 - shadowView.layer?.shadowOffset = CGSize(width: 0, height: -6) - shadowView.layer?.shadowOpacity = 0 - shadowView.layer?.masksToBounds = false - addSubview(shadowView) - - surfaceView.wantsLayer = true - surfaceView.layer?.backgroundColor = NSColor.black.cgColor - surfaceView.layer?.mask = surfaceMask - addSubview(surfaceView) - - content.wantsLayer = true - content.autoresizingMask = [] - content.alphaValue = 0 - surfaceView.addSubview(content) - } - - @available(*, unavailable) - required init?(coder: NSCoder) { - fatalError("init(coder:) has not been implemented") - } - - override var isOpaque: Bool { false } - - /// Clicks outside the visible surface must not land on hidden content. - override func hitTest(_ point: NSPoint) -> NSView? { - let local = convert(point, from: superview) - guard let surfacePath, surfacePath.contains(local) else { return nil } - return super.hitTest(point) - } - - func releaseContent() { - content?.removeFromSuperview() - content = nil - } - - func apply(model: NotchMorphModel, metrics: NotchMorphMetrics) { - let rect = metrics.surfaceRect(for: model) - let radius = metrics.cornerRadius(for: rect, heightFraction: model.height.value) - let path = NotchSurfacePath.make( - in: rect, radius: radius, - topRadius: metrics.topCornerRadius(for: rect, heightFraction: model.height.value) - ) - surfacePath = path - - CATransaction.begin() - CATransaction.setDisableActions(true) - shadowView.frame = bounds - surfaceView.frame = bounds - surfaceMask.frame = surfaceView.bounds - surfaceMask.path = path - shadowView.layer?.shadowPath = path - let reveal = NotchMorphModel.smoothstep(0.2, 1, model.height.value) - shadowView.layer?.shadowOpacity = Float(0.38 * reveal) - - if let content { - let size = metrics.contentSize - let lift = Self.contentLift * CGFloat(1 - min(max(model.height.value, 0), 1)) - let top = bounds.height - metrics.contentTopInset + lift - let origin = CGPoint(x: ((bounds.width - size.width) / 2).rounded(), y: (top - size.height).rounded()) - if content.frame.size != size { - content.frame = CGRect(origin: origin, size: size) - } else if content.frame.origin != origin { - content.setFrameOrigin(origin) - } - content.alphaValue = CGFloat(min(max(model.contentOpacity, 0), 1)) - } - CATransaction.commit() - } -} - -@MainActor -private final class NotchDisplayLinkTarget: NSObject { - var onFrame: ((CADisplayLink) -> Void)? - - @objc func step(_ link: CADisplayLink) { - onFrame?(link) + self.init(anchor: anchor, contentSize: contentSize, contentTopInset: inset) } } diff --git a/Sources/PluginSupport/NotchMorphSurface.swift b/Sources/PluginSupport/NotchMorphSurface.swift new file mode 100644 index 000000000..f7e4a685b --- /dev/null +++ b/Sources/PluginSupport/NotchMorphSurface.swift @@ -0,0 +1,335 @@ +import AppKit +import QuartzCore + +// MARK: - Spring model + +/// Two critically tuned springs: width leads on the way out and height leads on +/// the way back, which produces the "widen, then deepen" feel of the system island. +struct NotchMorphModel { + struct Spring { + var value: Double = 0 + var velocity: Double = 0 + + mutating func step(toward target: Double, response: Double, dampingRatio: Double, dt: Double) { + let stiffness = pow(2 * Double.pi / response, 2) + let damping = 4 * Double.pi * dampingRatio / response + velocity += (-stiffness * (value - target) - damping * velocity) * dt + value += velocity * dt + } + + func isSettled(at target: Double) -> Bool { + abs(value - target) < 0.001 && abs(velocity) < 0.01 + } + } + + private static let substep = 1.0 / 480.0 + + var target: Double = 0 + private(set) var width = Spring() + private(set) var height = Spring() + private(set) var contentOpacity: Double = 0 + + var isSettled: Bool { + width.isSettled(at: target) && height.isSettled(at: target) + && abs(contentOpacity - target) < 0.01 + } + + mutating func snapToTarget() { + width = Spring(value: target) + height = Spring(value: target) + contentOpacity = target + } + + mutating func advance(by elapsed: Double) { + var remaining = elapsed + while remaining > 0 { + let dt = min(Self.substep, remaining) + remaining -= dt + if target > 0.5 { + width.step(toward: target, response: 0.36, dampingRatio: 0.76, dt: dt) + height.step(toward: target, response: 0.46, dampingRatio: 0.82, dt: dt) + } else { + width.step(toward: target, response: 0.34, dampingRatio: 1, dt: dt) + height.step(toward: target, response: 0.27, dampingRatio: 1, dt: dt) + } + // Content follows the surface in, but leaves ahead of it so nothing is + // still legible while the shape folds back into the camera housing. + let opacityTarget = target > 0.5 ? Self.smoothstep(0.42, 0.92, height.value) : 0 + let timeConstant = target > 0.5 ? 0.035 : 0.045 + contentOpacity += (opacityTarget - contentOpacity) * (1 - exp(-dt / timeConstant)) + } + } + + static func smoothstep(_ edge0: Double, _ edge1: Double, _ x: Double) -> Double { + let t = min(max((x - edge0) / (edge1 - edge0), 0), 1) + return t * t * (3 - 2 * t) + } +} + +// MARK: - Geometry + +/// Geometry in window coordinates (origin at the bottom left). The window's top +/// edge is aligned with the top of the expanded surface. +struct NotchMorphMetrics { + /// The compact island sits a few points below the top of the screen. + static let housingTopInset: CGFloat = 6 + /// The system draws its own island around the housing and grows it upward + /// (to about 4pt) while the pointer is on it, so the expanded surface rises + /// above that to keep the island inside it in every state. + static let expandedTopInset: CGFloat = 3 + static let contentGap: CGFloat = 4 + /// Space kept between the header capsules and the island on each side. + static let islandClearance: CGFloat = 12 + static let bottomInset: CGFloat = 6 + static let expandedCornerRadius: CGFloat = 26 + /// Room for spring overshoot and the soft drop shadow. + static let margin: CGFloat = 28 + + let anchor: CGRect + let contentSize: CGSize + let housingSize: CGSize + let collapsedSize: CGSize + let expandedSize: CGSize + /// Distance from the window top (the expanded surface top) to the housing top. + let housingOffset: CGFloat + /// Distance from the window top to the top of the hosted content. + let contentTopInset: CGFloat + /// A wide camera cutout reaches the display edge, so the surface grows from + /// that edge with square top corners instead of floating below it. + let meetsDisplayTop: Bool + + init(anchor: CGRect, contentSize: CGSize, contentTopInset: CGFloat) { + self.anchor = anchor + self.contentSize = contentSize + // AppKit reports the housing rectangle. A wide camera cutout reaches the + // display edge, while the compact island has space above it. + let isWideCameraCutout = anchor.width >= anchor.height * 3 + let housingInset = isWideCameraCutout ? 0 : min(Self.housingTopInset, anchor.height * 0.2) + let expandedInset = min(Self.expandedTopInset, housingInset) + meetsDisplayTop = expandedInset == 0 + housingOffset = housingInset - expandedInset + housingSize = CGSize(width: anchor.width, height: max(anchor.height - housingInset, 1)) + // Start one point inside the housing so the first frame is hidden by it. + collapsedSize = CGSize(width: max(housingSize.width - 2, 2), height: max(housingSize.height - 2, 2)) + self.contentTopInset = contentTopInset + expandedSize = CGSize( + width: max(contentSize.width, housingSize.width), + height: contentTopInset + contentSize.height + Self.bottomInset + ) + } + + var windowFrame: CGRect { + let width = expandedSize.width + Self.margin * 2 + let height = (expandedSize.height + Self.margin).rounded() + let top = anchor.maxY - (anchor.height - housingSize.height) + housingOffset + return CGRect(x: (anchor.midX - width / 2).rounded(), y: top - height, + width: width.rounded(), height: height) + } + + var windowSize: CGSize { windowFrame.size } + + + func surfaceRect(for model: NotchMorphModel) -> CGRect { + surfaceRect(widthFraction: model.width.value, heightFraction: model.height.value) + } + + func surfaceRect(expandedFraction fraction: Double) -> CGRect { + surfaceRect(widthFraction: fraction, heightFraction: fraction) + } + + func surfaceRect(widthFraction: Double, heightFraction: Double) -> CGRect { + let size = windowSize + let width = max(Self.lerp(collapsedSize.width, expandedSize.width, widthFraction), 2) + let height = max(Self.lerp(collapsedSize.height, expandedSize.height, heightFraction), 2) + // Rises from inside the housing to the expanded top as the surface deepens. + // A surface that meets the display edge stays pinned to it. + let collapsedTop = meetsDisplayTop ? 0 : housingOffset + (housingSize.height - collapsedSize.height) / 2 + let topInset = Self.lerp(collapsedTop, 0, min(max(heightFraction, 0), 1)) + return CGRect(x: size.width / 2 - width / 2, y: size.height - topInset - height, + width: width, height: height) + } + + /// Stays a pill while the surface is shallow, then relaxes toward the + /// expanded radius as it deepens, so the corners change continuously. + /// Set to stay a full pill at every stage (island notifications). The host + /// panel leaves it off and relaxes to `expandedCornerRadius`. + var staysPill = false + + /// Blends the corners back toward a full pill (0 = normal, 1 = pill) so a pill-shaped + /// notification can ease into a larger card. The host panel never sets it. + var pillAmount: Double = 0 + + func cornerRadius(for rect: CGRect, heightFraction: Double) -> CGFloat { + let pill = min(rect.height, rect.width) / 2 + if staysPill { return pill } + let settle = NotchMorphModel.smoothstep(0.12, 1, heightFraction) + let radius = min(Self.lerp(pill, Self.expandedCornerRadius, settle), pill) + return pillAmount > 0 ? Self.lerp(radius, pill, min(pillAmount, 1)) : radius + } + + func topCornerRadius(for rect: CGRect, heightFraction: Double) -> CGFloat { + meetsDisplayTop ? 0 : cornerRadius(for: rect, heightFraction: heightFraction) + } + + func screenRect(fromSurfaceRect rect: CGRect) -> CGRect { + rect.offsetBy(dx: windowFrame.minX, dy: windowFrame.minY) + } + + static func lerp(_ from: CGFloat, _ to: CGFloat, _ fraction: Double) -> CGFloat { + from + (to - from) * CGFloat(fraction) + } +} + +enum NotchSurfacePath { + /// A rounded rectangle whose corners ease into the straight edges + /// (continuous curvature) when there is room, and become exact circular + /// arcs as the shape approaches a pill. The top corners can use a smaller + /// radius, down to square, for a surface that meets the display edge. + static func make(in rect: CGRect, radius: CGFloat, topRadius: CGFloat? = nil) -> CGPath { + let limit = min(rect.width, rect.height) / 2 + let bottom = Corner(radius: radius, limit: limit) + let top = Corner(radius: topRadius ?? radius, limit: limit) + let minX = rect.minX, maxX = rect.maxX, minY = rect.minY, maxY = rect.maxY + let path = CGMutablePath() + + path.move(to: CGPoint(x: minX + top.extent, y: maxY)) + path.addLine(to: CGPoint(x: maxX - top.extent, y: maxY)) + path.addCurve(to: CGPoint(x: maxX, y: maxY - top.extent), + control1: CGPoint(x: maxX - top.extent + top.handle, y: maxY), + control2: CGPoint(x: maxX, y: maxY - top.extent + top.handle)) + path.addLine(to: CGPoint(x: maxX, y: minY + bottom.extent)) + path.addCurve(to: CGPoint(x: maxX - bottom.extent, y: minY), + control1: CGPoint(x: maxX, y: minY + bottom.extent - bottom.handle), + control2: CGPoint(x: maxX - bottom.extent + bottom.handle, y: minY)) + path.addLine(to: CGPoint(x: minX + bottom.extent, y: minY)) + path.addCurve(to: CGPoint(x: minX, y: minY + bottom.extent), + control1: CGPoint(x: minX + bottom.extent - bottom.handle, y: minY), + control2: CGPoint(x: minX, y: minY + bottom.extent - bottom.handle)) + path.addLine(to: CGPoint(x: minX, y: maxY - top.extent)) + path.addCurve(to: CGPoint(x: minX + top.extent, y: maxY), + control1: CGPoint(x: minX, y: maxY - top.extent + top.handle), + control2: CGPoint(x: minX + top.extent - top.handle, y: maxY)) + path.closeSubpath() + return path + } + + /// One corner's reach along each edge and its Bézier handle length. + private struct Corner { + let extent: CGFloat + let handle: CGFloat + + init(radius requested: CGFloat, limit: CGFloat) { + let radius = max(min(requested, limit), 0) + guard radius > 0 else { + extent = 0 + handle = 0 + return + } + let smoothing = min(max((limit / radius - 1) / 0.4, 0), 1) + extent = radius * (1 + 0.4 * smoothing) + handle = extent * (0.5523 + (0.8 - 0.5523) * smoothing) + } + } +} + +// MARK: - Views + +/// Root view: a shadow behind a black, shape-masked surface that hosts the content. +@MainActor +final class NotchMorphView: NSView { + private static let contentLift: CGFloat = 10 + + private let shadowView = NSView() + private let surfaceView = NSView() + private let surfaceMask = CAShapeLayer() + private weak var content: NSView? + private var surfacePath: CGPath? + + init(content: NSView) { + self.content = content + super.init(frame: .zero) + wantsLayer = true + layer?.masksToBounds = false + + shadowView.wantsLayer = true + shadowView.layer?.shadowColor = NSColor.black.cgColor + shadowView.layer?.shadowRadius = 16 + shadowView.layer?.shadowOffset = CGSize(width: 0, height: -6) + shadowView.layer?.shadowOpacity = 0 + shadowView.layer?.masksToBounds = false + addSubview(shadowView) + + surfaceView.wantsLayer = true + surfaceView.layer?.backgroundColor = NSColor.black.cgColor + surfaceView.layer?.mask = surfaceMask + addSubview(surfaceView) + + content.wantsLayer = true + content.autoresizingMask = [] + content.alphaValue = 0 + surfaceView.addSubview(content) + } + + @available(*, unavailable) + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + override var isOpaque: Bool { false } + + /// Clicks outside the visible surface must not land on hidden content. + override func hitTest(_ point: NSPoint) -> NSView? { + let local = convert(point, from: superview) + guard let surfacePath, surfacePath.contains(local) else { return nil } + return super.hitTest(point) + } + + func releaseContent() { + content?.removeFromSuperview() + content = nil + } + + func apply(model: NotchMorphModel, metrics: NotchMorphMetrics) { + let rect = metrics.surfaceRect(for: model) + let radius = metrics.cornerRadius(for: rect, heightFraction: model.height.value) + let path = NotchSurfacePath.make( + in: rect, radius: radius, + topRadius: metrics.topCornerRadius(for: rect, heightFraction: model.height.value) + ) + surfacePath = path + + CATransaction.begin() + CATransaction.setDisableActions(true) + shadowView.frame = bounds + surfaceView.frame = bounds + surfaceMask.frame = surfaceView.bounds + surfaceMask.path = path + shadowView.layer?.shadowPath = path + let reveal = NotchMorphModel.smoothstep(0.2, 1, model.height.value) + shadowView.layer?.shadowOpacity = Float(0.38 * reveal) + + if let content { + let size = metrics.contentSize + let lift = Self.contentLift * CGFloat(1 - min(max(model.height.value, 0), 1)) + let top = bounds.height - metrics.contentTopInset + lift + let origin = CGPoint(x: ((bounds.width - size.width) / 2).rounded(), y: (top - size.height).rounded()) + if content.frame.size != size { + content.frame = CGRect(origin: origin, size: size) + } else if content.frame.origin != origin { + content.setFrameOrigin(origin) + } + content.alphaValue = CGFloat(min(max(model.contentOpacity, 0), 1)) + } + CATransaction.commit() + } +} + +@MainActor +final class NotchDisplayLinkTarget: NSObject { + var onFrame: ((CADisplayLink) -> Void)? + + @objc func step(_ link: CADisplayLink) { + onFrame?(link) + } +} + diff --git a/changes/unreleased/island-notifications.md b/changes/unreleased/island-notifications.md new file mode 100644 index 000000000..b015118c3 --- /dev/null +++ b/changes/unreleased/island-notifications.md @@ -0,0 +1,7 @@ +--- +release: plugin +type: added +area: Dynamic Island Notifications +--- + +Add opt-in notification cards for the MacBook Pro camera island, with replies for Messages and Claude. A Notifications panel lists recent notifications, stacked by app, and opens the exact item. diff --git a/docs/plugins/island-notifications.md b/docs/plugins/island-notifications.md new file mode 100644 index 000000000..722a71e44 --- /dev/null +++ b/docs/plugins/island-notifications.md @@ -0,0 +1,51 @@ +# Dynamic Island Notifications + +Shows macOS notifications as cards that grow out of the camera island on the MacBook Pro introduced with macOS 27, the way iPhone shows them from the Dynamic Island. The plugin is off by default and stays local to this Mac. + +## Requirements + +- A MacBook Pro with the camera island and macOS 27 or later, with the built-in display active. On every other Mac, including notched ones, the plugin reports that it is unavailable and does nothing. +- Accessibility, granted through the plugin's permission card. The plugin uses it to read banners and keep their window out of sight. +- Full Disk Access is optional. It is used only to read Messages' own history, so that a reply goes to the exact conversation. + +## How it works + +The plugin watches Notification Centre's banner windows through Accessibility. When a banner appears, its window is moved off screen before it draws, and the plugin shows its own non-activating card in its place. + +Notification Centre stays the record. Every notification still goes into its history, and Focus, notification styles and preview privacy apply before a banner exists. The plugin never changes notification settings and never reads Notification Centre's database. + +Cards: + +- **Lifetime:** a temporary card stays for five seconds, paused while it is hovered, held open, being replied to, or under the MacTools hover panel. A persistent alert waits until it is dismissed. +- **Several notifications:** one card shows at a time. A newer temporary notification replaces an idle card after one second; a held or busy card is never interrupted. +- **Gestures:** swipe up to dismiss. Pull down to open the full message, or to hold a card that has nothing more to show. A click opens the exact item through the banner's own action, and Esc closes the card. +- **Replies:** Messages cards reply to the conversation found in Messages' history, never to one matched by name. Claude cards follow Claude Code's session logs and type the reply into that chat, without bringing Claude forward. +- **Live Activities:** with a compact system Live Activity showing, the card splits below it. With an expanded or unreadable activity, banners stay native. + +Notification text never leaves the Mac and is never written to disk. The logs record steps only. + +## Notifications list + +The list in the panel shows the notifications the island has shown since MacTools started, stacked by app. It lives in memory and is cleared when MacTools quits. + +Opening or clearing an entry acts on its row in Notification Centre, so the app opens the exact item. Notification Centre is opened through its own accessibility action on a short-lived background thread, its window is moved off screen as it appears, and the row is pressed. Notification Centre applies that move only after drawing its first frame, so on rare occasions a sliver of it shows at the screen edge for a few tens of milliseconds. + +If the row is gone, because the app withdrew it or it was cleared, Messages and Claude entries open their conversation or chat directly. Every other entry opens its app. + +## Recovery + +Turning the plugin off, unloading it and quitting normally put every hidden window back. A window left off screen by a forced quit is recovered the next time the plugin starts. Unknown windows, and windows that cannot be read completely, are left untouched. + +## Manual acceptance + +Automated tests cover the queue, safety decisions, list grouping and description matching. The checks below need the hardware. + +- With the switch off or Accessibility denied, confirm banners stay native and no card appears. Repeat with only an external display active. +- Send temporary banners, banners with private previews, and banners under Focus. Check that nothing flashes or ghosts, and that Notification Centre history is complete. +- While typing in another app, hover a card and close it, and confirm keyboard focus stays in that app. +- Test the gestures. Click a fresh card and confirm the exact item opens. +- Reply to a Messages card and a Claude card, and confirm the reply reaches the right conversation. +- Send several notifications in a row, and send one while the hover panel is open. +- Open and clear entries in the Notifications list, including one inside a stack. +- Test a persistent alert, a Notification Centre restart, sleep and wake, display changes, and opening Notification Centre while a card is showing. +- Check Reduce Motion, VoiceOver announcements and actions, long text, and another system language. diff --git a/docs/plugins/preferences-backup-inventory.md b/docs/plugins/preferences-backup-inventory.md index e70466f23..b59589622 100644 --- a/docs/plugins/preferences-backup-inventory.md +++ b/docs/plugins/preferences-backup-inventory.md @@ -6,7 +6,7 @@ Run `python3 scripts/plugins/generate-preferences-backup-inventory.py` after cha Declarations describe supported field boundaries. Runtime availability and export/restore failures are reported separately. See [the backup contract](preferences-backup.md) for exclusions and recovery limits. -localOnly: 2; none: 25; partial: 36; portable: 7. +localOnly: 3; none: 25; partial: 36; portable: 7. | Plugin | ID | Coverage | Exclusion codes | | --- | --- | --- | --- | @@ -45,6 +45,7 @@ localOnly: 2; none: 25; partial: 36; portable: 7. | [Homebrew Manager](../../Plugins/Homebrew) | `homebrew` | none | — | | [IP Check](../../Plugins/IPOverview) | `ip-overview` | partial | history, local-policy | | [Custom Shortcuts: Keyboard, Trackpad, Mouse](../../Plugins/InputRemapping) | `input-remapping` | partial | external-authorization | +| [Dynamic Island Notifications](../../Plugins/IslandNotifications) | `island-notifications` | localOnly | local-activation, private-content | | [Keep Awake](../../Plugins/KeepAwake) | `keep-awake` | partial | local-activation | | [Key Stats](../../Plugins/KeyStats) | `key-stats` | localOnly | local-activation, history | | [Launch Items](../../Plugins/LaunchControl) | `launch-control` | partial | private-content, local-activation, local-policy | diff --git a/site/src/generated/plugins.json b/site/src/generated/plugins.json index 6e27ba86f..62f418742 100644 --- a/site/src/generated/plugins.json +++ b/site/src/generated/plugins.json @@ -13871,6 +13871,258 @@ "summary": "查看出口 IP、本地 IP、归属地与网络测速摘要", "version": "2.2.0" }, + { + "capabilities": { + "panelItems": [ + "row", + "widget" + ], + "settings": "form" + }, + "category": "display", + "displayName": "灵动岛通知", + "id": "island-notifications", + "localizedMetadata": { + "ar": { + "displayName": "إشعارات Dynamic Island", + "summary": "عرض الإشعارات عند الكاميرا مع الاحتفاظ بسجل مركز الإشعارات." + }, + "de": { + "displayName": "Dynamic-Island-Mitteilungen", + "summary": "Mitteilungen an der Kamera-Insel anzeigen und im Mitteilungszentrum behalten." + }, + "en": { + "displayName": "Dynamic Island Notifications", + "summary": "Show notifications at the camera island while preserving Notification Centre history." + }, + "es": { + "displayName": "Notificaciones de Dynamic Island", + "summary": "Muestra notificaciones junto a la cámara y conserva el historial del Centro de notificaciones." + }, + "fr": { + "displayName": "Notifications Dynamic Island", + "summary": "Affiche les notifications près de la caméra et conserve l’historique du Centre de notifications." + }, + "ja": { + "displayName": "Dynamic Island 通知", + "summary": "カメラ部分に通知を表示し、通知センターの履歴を保持します。" + }, + "ko": { + "displayName": "Dynamic Island 알림", + "summary": "카메라 영역에 알림을 표시하고 알림 센터 기록을 유지합니다." + }, + "pt": { + "displayName": "Notificações da Dynamic Island", + "summary": "Mostra notificações junto à câmara e mantém o histórico da Central de Notificações." + }, + "ru": { + "displayName": "Уведомления Dynamic Island", + "summary": "Показывает уведомления у камеры, сохраняя историю Центра уведомлений." + }, + "tr": { + "displayName": "Dynamic Island Bildirimleri", + "summary": "Bildirimleri kamera çevresinde gösterir ve Bildirim Merkezi geçmişini korur." + }, + "zh-Hans": { + "displayName": "灵动岛通知", + "summary": "在灵动岛显示通知,保留通知中心历史记录。" + }, + "zh-Hant": { + "displayName": "靈動島通知", + "summary": "在靈動島顯示通知,保留通知中心歷史記錄。" + } + }, + "openInMacToolsURL": "mactools://app/settings/plugins/marketplace/island-notifications", + "product": { + "actions": null, + "discovery": { + "alternativePluginIDs": [], + "goalCategories": [ + "display" + ], + "keywords": [ + "dynamic island", + "notifications", + "notch", + "notification history", + "notification center", + "reply" + ], + "localizedSynonyms": { + "ar": [ + "إشعارات Dynamic Island", + "سجل الإشعارات", + "الرد على الإشعارات" + ], + "de": [ + "Dynamic-Island-Mitteilungen", + "Mitteilungsverlauf", + "Auf Mitteilungen antworten" + ], + "en": [ + "Dynamic Island Notifications", + "Notification history", + "Reply to notifications" + ], + "es": [ + "Notificaciones de Dynamic Island", + "Historial de notificaciones", + "Responder a notificaciones" + ], + "fr": [ + "Notifications Dynamic Island", + "Historique des notifications", + "Répondre aux notifications" + ], + "ja": [ + "Dynamic Island 通知", + "通知履歴", + "通知に返信" + ], + "ko": [ + "Dynamic Island 알림", + "알림 기록", + "알림에 답장" + ], + "pt": [ + "Notificações da Dynamic Island", + "Histórico de notificações", + "Responder a notificações" + ], + "ru": [ + "Уведомления Dynamic Island", + "История уведомлений", + "Ответ на уведомления" + ], + "tr": [ + "Dynamic Island Bildirimleri", + "Bildirim geçmişi", + "Bildirimleri yanıtla" + ], + "zh-Hans": [ + "灵动岛通知", + "通知历史", + "回复通知" + ], + "zh-Hant": [ + "靈動島通知", + "通知歷史", + "回覆通知" + ] + }, + "relatedPluginIDs": [], + "useCases": [ + { + "id": "primary-use", + "title": { + "ar": "إشعارات Dynamic Island", + "de": "Dynamic-Island-Mitteilungen", + "en": "Dynamic Island Notifications", + "es": "Notificaciones de Dynamic Island", + "fr": "Notifications Dynamic Island", + "ja": "Dynamic Island 通知", + "ko": "Dynamic Island 알림", + "pt": "Notificações da Dynamic Island", + "ru": "Уведомления Dynamic Island", + "tr": "Dynamic Island Bildirimleri", + "zh-Hans": "灵动岛通知", + "zh-Hant": "靈動島通知" + } + } + ] + }, + "presentation": { + "documentationURL": "https://github.com/ggbond268/MacTools#plugins-and-settings", + "examples": [ + { + "id": "primary-use", + "text": { + "ar": "عرض الإشعارات عند الكاميرا مع الاحتفاظ بسجل مركز الإشعارات.", + "de": "Mitteilungen an der Kamera-Insel anzeigen und im Mitteilungszentrum behalten.", + "en": "Show notifications at the camera island while preserving Notification Centre history.", + "es": "Muestra notificaciones junto a la cámara y conserva el historial del Centro de notificaciones.", + "fr": "Affiche les notifications près de la caméra et conserve l’historique du Centre de notifications.", + "ja": "カメラ部分に通知を表示し、通知センターの履歴を保持します。", + "ko": "카메라 영역에 알림을 표시하고 알림 센터 기록을 유지합니다.", + "pt": "Mostra notificações junto à câmara e mantém o histórico da Central de Notificações.", + "ru": "Показывает уведомления у камеры, сохраняя историю Центра уведомлений.", + "tr": "Bildirimleri kamera çevresinde gösterir ve Bildirim Merkezi geçmişini korur.", + "zh-Hans": "在灵动岛显示通知,保留通知中心历史记录。", + "zh-Hant": "在靈動島顯示通知,保留通知中心歷史記錄。" + } + } + ], + "license": "GPL-3.0-only", + "longDescription": { + "ar": "عرض الإشعارات عند الكاميرا مع الاحتفاظ بسجل مركز الإشعارات.", + "de": "Mitteilungen an der Kamera-Insel anzeigen und im Mitteilungszentrum behalten.", + "en": "Show notifications at the camera island while preserving Notification Centre history.", + "es": "Muestra notificaciones junto a la cámara y conserva el historial del Centro de notificaciones.", + "fr": "Affiche les notifications près de la caméra et conserve l’historique du Centre de notifications.", + "ja": "カメラ部分に通知を表示し、通知センターの履歴を保持します。", + "ko": "카메라 영역에 알림을 표시하고 알림 센터 기록을 유지합니다.", + "pt": "Mostra notificações junto à câmara e mantém o histórico da Central de Notificações.", + "ru": "Показывает уведомления у камеры, сохраняя историю Центра уведомлений.", + "tr": "Bildirimleri kamera çevresinde gösterir ve Bildirim Merkezi geçmişini korur.", + "zh-Hans": "在灵动岛显示通知,保留通知中心历史记录。", + "zh-Hant": "在靈動島顯示通知,保留通知中心歷史記錄。" + }, + "publisher": "MacTools", + "screenshots": [], + "supportURL": "https://github.com/ggbond268/MacTools/issues" + }, + "privacy": { + "allowsUserConfiguredDomains": false, + "dataObserved": [ + "notification-content", + "display-state" + ], + "dataPersisted": [ + "plugin-configuration" + ], + "diagnosticExportsContainUserData": false, + "networkDomains": [], + "networkUse": "none", + "processesSensitiveUserContent": true, + "retention": { + "policy": "user-controlled" + }, + "telemetry": "none" + }, + "relationships": { + "includedPackIDs": [], + "relatedPluginIDs": [], + "suggestedRecipeIDs": [], + "supersedesPluginIDs": [] + }, + "requirements": { + "applications": [], + "architectures": [ + "arm64", + "x86_64" + ], + "executables": [], + "hardware": [ + "MacBook Pro camera island" + ], + "minimumMacOSVersion": "27.0", + "permissionIDs": [ + "accessibility" + ], + "requiresRelaunch": false, + "setupComplexity": "simple" + }, + "setup": { + "optionalSurfaces": [], + "steps": [] + } + }, + "releaseChannel": null, + "releaseNotesURL": null, + "route": "/plugins/island-notifications/", + "summary": "在灵动岛显示通知,保留通知中心历史记录。", + "version": "1.0.0" + }, { "capabilities": { "panelItems": [ From 946a0961ab996efc962932b2f2bac570ec4c5fbf Mon Sep 17 00:00:00 2001 From: Niko Eltarenko <61957857+nikoelt@users.noreply.github.com> Date: Tue, 17 Nov 2026 17:09:13 +1000 Subject: [PATCH 07/29] fix(island-notifications): fit the list's panel when it opens The list measures itself only while it is on screen, so a list that grew while the panel was shut could open at its old height with the stacked cards' edges cut off. The widget now asks the host for its size again each time it becomes visible. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .../Sources/IslandNotificationsController.swift | 6 ++++++ .../Sources/IslandNotificationsPlugin.swift | 3 +++ 2 files changed, 9 insertions(+) diff --git a/Plugins/IslandNotifications/Sources/IslandNotificationsController.swift b/Plugins/IslandNotifications/Sources/IslandNotificationsController.swift index 4e514e65e..328791196 100644 --- a/Plugins/IslandNotifications/Sources/IslandNotificationsController.swift +++ b/Plugins/IslandNotifications/Sources/IslandNotificationsController.swift @@ -783,6 +783,12 @@ final class IslandNotificationsController { onStateChange?() } + /// The list only measures itself while it is on screen, so a list that changed while the panel + /// was shut asks the host again for its size as the panel shows it. + func historyBecameVisible() { + onStateChange?() + } + func openHistory(_ entry: IslandHistoryEntry) { logger.notice("list open inCentre=\(entry.centerApp != nil, privacy: .public) claude=\(entry.claudeChat != nil, privacy: .public)") history.remove(entry) diff --git a/Plugins/IslandNotifications/Sources/IslandNotificationsPlugin.swift b/Plugins/IslandNotifications/Sources/IslandNotificationsPlugin.swift index 9afdff20d..3dd8cc04b 100644 --- a/Plugins/IslandNotifications/Sources/IslandNotificationsPlugin.swift +++ b/Plugins/IslandNotifications/Sources/IslandNotificationsPlugin.swift @@ -58,6 +58,9 @@ final class IslandNotificationsPlugin: MacToolsPlugin { onContentHeight: { controller.setHistoryContentHeight($0) }) } }) + .onVisibilityChange { [controller] visible in + if visible { controller.historyBecameVisible() } + } } private var enabledRow: PluginPanelItem { From 375fe6dddd6eee964bae73985a3ebc3f723aa490 Mon Sep 17 00:00:00 2001 From: Niko Eltarenko <61957857+nikoelt@users.noreply.github.com> Date: Tue, 17 Nov 2026 17:09:13 +1000 Subject: [PATCH 08/29] feat(panel): opt-in per-panel width and smooth notch panel resizing A panel can carry its own width, used while it is showing; no existing panel has one, so nothing changes unless a panel opts in. A full-width widget alone in such a panel fills its column. The Island Notifications list gets a dedicated Notifications panel, created once when the list first appears and only while the panel limit allows, sized so its cards match Notification Centre's 344 pt column. The notch panel now glides between sizes on a spring instead of snapping, with its content clipped to the surface while it changes. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .../App/ConfiguredMenuBarPanelContent.swift | 22 +++++- Sources/App/MenuBarPanelPresenter.swift | 4 +- Sources/App/NotchMenuBarPanel.swift | 46 ++++++++++- Sources/Core/Plugins/MenuBarPanelStore.swift | 21 +++++ Sources/Core/Plugins/PanelLayoutModels.swift | 1 + Sources/PluginSupport/NotchMorphSurface.swift | 37 ++++++++- .../Resources/Localization/Plugins.xcstrings | 77 +++++++++++++++++++ .../Core/Plugins/MenuBarPanelStoreTests.swift | 22 ++++++ changes/unreleased/panel-own-width.md | 7 ++ 9 files changed, 225 insertions(+), 12 deletions(-) create mode 100644 changes/unreleased/panel-own-width.md diff --git a/Sources/App/ConfiguredMenuBarPanelContent.swift b/Sources/App/ConfiguredMenuBarPanelContent.swift index 64fe19be4..ba97a9870 100644 --- a/Sources/App/ConfiguredMenuBarPanelContent.swift +++ b/Sources/App/ConfiguredMenuBarPanelContent.swift @@ -23,11 +23,22 @@ enum ConfiguredMenuBarPanelLayout { return ComponentPanelLayout.gridContentHeight(for: ComponentGridPlacementEngine.placements(for: items)) } + /// `fillsBand`: in a panel with its own width, a full-width widget alone in a single column + /// fills the column instead of keeping its declared width. Off everywhere else. static func placement( entries: [MenuBarPanelEntry], components: [PluginPanelWidgetSnapshot], features: [PluginPanelRowSnapshot], - width: CGFloat = MenuBarPanelLayout.surfaceWidth + width: CGFloat = MenuBarPanelLayout.surfaceWidth, fillsBand: Bool = false ) -> Placement { - placement(order: entries.map { ($0.id, $0.kind) }, components: components, features: features, width: width) + var result = placement(order: entries.map { ($0.id, $0.kind) }, components: components, features: features, width: width) + guard fillsBand, MenuBarPanelWidth.columns(forSurfaceWidth: width) == 1 else { return result } + result.components = result.components.map { item in + guard item.span.width == item.span.grid.rawValue else { return item } + return ComponentGridPlacement(id: item.id, row: item.row, column: item.column, span: item.span, + yOffset: item.yOffset, gridColumns: item.gridColumns, gridSpacing: item.gridSpacing, + xOffset: 0, size: CGSize(width: width, height: item.size?.height + ?? ComponentPanelLayout.itemHeight(for: item.span))) + } + return result } static func placement(features: [PluginPanelRowSnapshot], width: CGFloat = MenuBarPanelLayout.surfaceWidth) -> Placement { @@ -154,6 +165,7 @@ private struct ConfiguredMenuBarPanelContent: View { let onPresentLaunchControlConfiguration: () -> Void @State private var scrollCoordinateSpace = UUID() + private var hasOwnWidth: Bool { pluginHost.menuBarPanels.first { $0.id == panelID }?.width != nil } @State private var retainedBodyHeight: CGFloat? @State private var isComponentDetailInline = false @State private var isFeatureDetailInline = false @@ -168,7 +180,8 @@ private struct ConfiguredMenuBarPanelContent: View { Group { if !features.isEmpty { let placement = ConfiguredMenuBarPanelLayout.placement( - entries: pluginHost.panelEntries(in: panelID), components: components, features: features, width: surfaceWidth + entries: pluginHost.panelEntries(in: panelID), components: components, features: features, width: surfaceWidth, + fillsBand: hasOwnWidth ) ScrollView(.vertical, showsIndicators: false) { ZStack(alignment: .topLeading) { @@ -197,7 +210,8 @@ private struct ConfiguredMenuBarPanelContent: View { )) } else if !components.isEmpty { let placement = ConfiguredMenuBarPanelLayout.placement( - entries: pluginHost.panelEntries(in: panelID), components: components, features: [], width: surfaceWidth + entries: pluginHost.panelEntries(in: panelID), components: components, features: [], width: surfaceWidth, + fillsBand: hasOwnWidth ) componentContent(components, height: contentBodyHeight, placements: placement.components, gridHeight: placement.height) diff --git a/Sources/App/MenuBarPanelPresenter.swift b/Sources/App/MenuBarPanelPresenter.swift index 5bdccd9f2..8acf0cc5a 100644 --- a/Sources/App/MenuBarPanelPresenter.swift +++ b/Sources/App/MenuBarPanelPresenter.swift @@ -1191,8 +1191,10 @@ final class MenuBarPanelPresenter: NSObject { screen: NSScreen? ) -> MenuBarPanelHeightResolution { let maximumWidth = MenuBarPanelWidth.maximum(visibleFrameWidth: screen?.visibleFrame.width) + // A panel with its own width (opt-in, see MenuBarPanelDefinition.width) uses it while shown. + let panelWidth = pluginHost.menuBarPanels.first { $0.id == tab.id }?.width let preferredWidth = MenuBarPanelWidth.resolved( - preferred: pluginHost.preferredMenuBarPanelWidth, maximum: maximumWidth) + preferred: panelWidth ?? pluginHost.preferredMenuBarPanelWidth, maximum: maximumWidth) // Widen only while the header sits beside the notch. Layout editing moves // it below, so editing keeps the width the user chose. let widthForNotchHeader = panelModel.isEditingLayout ? 0 : notchPanel.map { diff --git a/Sources/App/NotchMenuBarPanel.swift b/Sources/App/NotchMenuBarPanel.swift index a6e641f64..4b8f84aae 100644 --- a/Sources/App/NotchMenuBarPanel.swift +++ b/Sources/App/NotchMenuBarPanel.swift @@ -29,6 +29,8 @@ final class NotchMenuBarPanel { private var lastFrameTimestamp: CFTimeInterval? private var closeCompletion: (@MainActor () -> Void)? private var systemPanelMonitor: DispatchSourceTimer? + /// The content size the surface shows while the panel changes size; nil when settled. + private var sizeSpring: (width: NotchMorphModel.Spring, height: NotchMorphModel.Spring)? private(set) var isClosing = false init(anchor: CGRect, content: NSViewController) { @@ -80,7 +82,22 @@ final class NotchMenuBarPanel { func resize(to size: CGSize) { guard !isClosing, size != metrics.contentSize else { return } - applyContentSize(size) + let shown = sizeSpring.map { CGSize(width: $0.width.value, height: $0.height.value) } ?? metrics.contentSize + // Size changes (a list growing, a wider panel) glide on a spring from wherever the surface + // is now. Reduce Motion, or a panel still opening or closing, just applies the new size. + guard model.isSettled, model.target == 1, !NSWorkspace.shared.accessibilityDisplayShouldReduceMotion else { + applyContentSize(size) + render() + startDisplayLinkIfNeeded() + return + } + sizeSpring = (NotchMorphModel.Spring(value: Double(shown.width), velocity: sizeSpring?.width.velocity ?? 0), + NotchMorphModel.Spring(value: Double(shown.height), velocity: sizeSpring?.height.velocity ?? 0)) + metrics = NotchMorphMetrics(anchor: anchor, contentSize: size) + metrics.windowContentSize = CGSize(width: max(shown.width, size.width), height: max(shown.height, size.height)) + metrics.revealedContentSize = shown + let frame = metrics.windowFrame + if window.frame != frame { window.setFrame(frame, display: false) } render() startDisplayLinkIfNeeded() } @@ -103,6 +120,8 @@ final class NotchMenuBarPanel { } guard !isClosing else { return } isClosing = true + // A size change in progress stops where it is; the surface folds away from there. + sizeSpring = nil closeCompletion = completion window.ignoresMouseEvents = true setExpanded(false) @@ -150,6 +169,7 @@ final class NotchMenuBarPanel { // MARK: - Animation private func applyContentSize(_ size: CGSize) { + sizeSpring = nil metrics = NotchMorphMetrics(anchor: anchor, contentSize: size) let frame = metrics.windowFrame if window.frame != frame { @@ -186,13 +206,33 @@ final class NotchMenuBarPanel { let now = link.targetTimestamp let elapsed = lastFrameTimestamp.map { now - $0 } ?? (link.targetTimestamp - link.timestamp) lastFrameTimestamp = now - model.advance(by: min(max(elapsed, 0), 1.0 / 30.0)) + let dt = min(max(elapsed, 0), 1.0 / 30.0) + model.advance(by: dt) + if var springs = sizeSpring { + let target = metrics.contentSize + // The spring SwiftUI content in the panel uses, so a panel following its content keeps pace. + springs.width.step(toward: Double(target.width), response: 0.36, dampingRatio: 0.86, dt: dt) + springs.height.step(toward: Double(target.height), response: 0.36, dampingRatio: 0.86, dt: dt) + func settled(_ spring: NotchMorphModel.Spring, _ value: CGFloat) -> Bool { + abs(spring.value - Double(value)) < 0.5 && abs(spring.velocity) < 1 + } + if settled(springs.width, target.width), settled(springs.height, target.height) { + sizeSpring = nil + metrics.revealedContentSize = nil + metrics.windowContentSize = nil + let frame = metrics.windowFrame + if window.frame != frame { window.setFrame(frame, display: false) } + } else { + sizeSpring = springs + metrics.revealedContentSize = CGSize(width: springs.width.value, height: springs.height.value) + } + } render() finishIfSettled() } private func finishIfSettled() { - guard model.isSettled else { return } + guard model.isSettled, sizeSpring == nil else { return } model.snapToTarget() render() stopDisplayLink() diff --git a/Sources/Core/Plugins/MenuBarPanelStore.swift b/Sources/Core/Plugins/MenuBarPanelStore.swift index 521873afd..c4738486c 100644 --- a/Sources/Core/Plugins/MenuBarPanelStore.swift +++ b/Sources/Core/Plugins/MenuBarPanelStore.swift @@ -4,6 +4,7 @@ import MacToolsPluginKit struct MenuBarPanelDefinition: Codable, Equatable, Identifiable, Sendable { static let componentsID = "components" static let featuresID = "features" + static let notificationsID = "notifications" static let maximumCount = 5 static let maximumNameLength = 24 @@ -11,6 +12,9 @@ struct MenuBarPanelDefinition: Codable, Equatable, Identifiable, Sendable { var name: String var systemImage: String var isHidden = false + /// Opt-in: this panel's own width while it is showing. nil (every panel unless a dedicated + /// panel below sets it) uses the shared width, and a full-width widget keeps its declared size. + var width: Double? var isDefault: Bool { id == Self.componentsID || id == Self.featuresID } @@ -21,6 +25,8 @@ struct MenuBarPanelDefinition: Codable, Equatable, Identifiable, Sendable { AppL10n.plugins("plugin.panel.components", defaultValue: "组件面板") case Self.featuresID: AppL10n.plugins("plugin.panel.features", defaultValue: "功能面板") + case Self.notificationsID: + AppL10n.plugins("plugin.panel.notifications", defaultValue: "通知") default: FeatureL10n.string("新面板") } @@ -32,6 +38,14 @@ struct MenuBarPanelDefinition: Codable, Equatable, Identifiable, Sendable { return FeatureL10n.format("面板 %lld", number) } + /// Widgets that get a panel of their own the first time they appear. The Island Notifications + /// list reads like Notification Centre, whose column is 344 pt wide: its panel is sized for that + /// (344 plus the list's 8 pt margins and the panel's 6 pt padding on each side). + static let dedicatedPanels: [PluginPanelItemKey: Self] = [ + PluginPanelItemKey(pluginID: "island-notifications", itemID: "history"): + Self(id: notificationsID, name: "", systemImage: "bell", width: 372), + ] + static var defaults: [Self] { [ Self(id: componentsID, name: "", systemImage: "square.grid.2x2"), @@ -171,6 +185,13 @@ final class MenuBarPanelStore { next.placementsByPanelID[panelID] = existing continue } + if let panel = MenuBarPanelDefinition.dedicatedPanels[item.key], + !next.panels.contains(where: { $0.id == panel.id }), + next.panels.count < MenuBarPanelDefinition.maximumCount { + next.panels.append(panel) + next.placementsByPanelID[panel.id] = [MenuBarPanelPlacement(item: item.key)] + continue + } guard let initial = item.initialPlacement else { continue } next.placementsByPanelID[initial.panelID, default: []].append(MenuBarPanelPlacement(item: item.key)) } diff --git a/Sources/Core/Plugins/PanelLayoutModels.swift b/Sources/Core/Plugins/PanelLayoutModels.swift index 8b63e9595..afd259172 100644 --- a/Sources/Core/Plugins/PanelLayoutModels.swift +++ b/Sources/Core/Plugins/PanelLayoutModels.swift @@ -131,6 +131,7 @@ struct MenuBarPanelConfiguration: Codable, Equatable, Sendable { customCount += 1 } var panel = original + if let width = panel.width, !width.isFinite || width < Self.defaultWidth { panel.width = nil } panel.name = String(panel.name.trimmingCharacters(in: .whitespacesAndNewlines) .prefix(MenuBarPanelDefinition.maximumNameLength)) if panel.systemImage.isEmpty { panel.systemImage = "square.grid.2x2" } diff --git a/Sources/PluginSupport/NotchMorphSurface.swift b/Sources/PluginSupport/NotchMorphSurface.swift index f7e4a685b..7a4269eba 100644 --- a/Sources/PluginSupport/NotchMorphSurface.swift +++ b/Sources/PluginSupport/NotchMorphSurface.swift @@ -118,9 +118,23 @@ struct NotchMorphMetrics { ) } + /// While the host panel changes size, its window keeps the larger of the two sizes and the + /// surface shows `revealedContentSize` of the content, so the change can be one motion. + var windowContentSize: CGSize? + var revealedContentSize: CGSize? + + /// The expanded surface: all of the content, or the part being revealed. + var expandedWidth: CGFloat { + revealedContentSize.map { max($0.width, housingSize.width) } ?? expandedSize.width + } + var expandedHeight: CGFloat { + revealedContentSize.map { contentTopInset + $0.height + Self.bottomInset } ?? expandedSize.height + } + var windowFrame: CGRect { - let width = expandedSize.width + Self.margin * 2 - let height = (expandedSize.height + Self.margin).rounded() + let width = (windowContentSize.map { max($0.width, housingSize.width) } ?? expandedSize.width) + Self.margin * 2 + let contentHeight = windowContentSize.map { contentTopInset + $0.height + Self.bottomInset } ?? expandedSize.height + let height = (contentHeight + Self.margin).rounded() let top = anchor.maxY - (anchor.height - housingSize.height) + housingOffset return CGRect(x: (anchor.midX - width / 2).rounded(), y: top - height, width: width.rounded(), height: height) @@ -139,8 +153,8 @@ struct NotchMorphMetrics { func surfaceRect(widthFraction: Double, heightFraction: Double) -> CGRect { let size = windowSize - let width = max(Self.lerp(collapsedSize.width, expandedSize.width, widthFraction), 2) - let height = max(Self.lerp(collapsedSize.height, expandedSize.height, heightFraction), 2) + let width = max(Self.lerp(collapsedSize.width, expandedWidth, widthFraction), 2) + let height = max(Self.lerp(collapsedSize.height, expandedHeight, heightFraction), 2) // Rises from inside the housing to the expanded top as the surface deepens. // A surface that meets the display edge stays pinned to it. let collapsedTop = meetsDisplayTop ? 0 : housingOffset + (housingSize.height - collapsedSize.height) / 2 @@ -319,6 +333,21 @@ final class NotchMorphView: NSView { content.setFrameOrigin(origin) } content.alphaValue = CGFloat(min(max(model.contentOpacity, 0), 1)) + // While the surface is shorter than its content, the content ends where the surface does. + if metrics.revealedContentSize != nil { + content.wantsLayer = true + let mask = (content.layer?.mask as? CAShapeLayer) ?? CAShapeLayer() + mask.frame = content.bounds + // Into the content's own coordinates, which SwiftUI's hosting view flips. + var shift = content.isFlipped + ? CGAffineTransform(a: 1, b: 0, c: 0, d: -1, tx: -content.frame.minX, + ty: content.bounds.height + content.frame.minY) + : CGAffineTransform(translationX: -content.frame.minX, y: -content.frame.minY) + mask.path = path.copy(using: &shift) + content.layer?.mask = mask + } else if content.layer?.mask != nil { + content.layer?.mask = nil + } } CATransaction.commit() } diff --git a/Sources/Resources/Localization/Plugins.xcstrings b/Sources/Resources/Localization/Plugins.xcstrings index 398f48f57..185ec5fd3 100644 --- a/Sources/Resources/Localization/Plugins.xcstrings +++ b/Sources/Resources/Localization/Plugins.xcstrings @@ -14554,6 +14554,83 @@ } } }, + "plugin.panel.notifications": { + "extractionState": "manual", + "localizations": { + "ar": { + "stringUnit": { + "state": "translated", + "value": "الإشعارات" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Mitteilungen" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Notifications" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Notificaciones" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Notifications" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "通知" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "알림" + } + }, + "pt": { + "stringUnit": { + "state": "translated", + "value": "Notificações" + } + }, + "ru": { + "stringUnit": { + "state": "translated", + "value": "Уведомления" + } + }, + "tr": { + "stringUnit": { + "state": "translated", + "value": "Bildirimler" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "通知" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "通知" + } + } + } + }, "plugin.marketplace.sort.label": { "extractionState": "manual", "localizations": { diff --git a/Tests/Core/Plugins/MenuBarPanelStoreTests.swift b/Tests/Core/Plugins/MenuBarPanelStoreTests.swift index 19dd82aaf..31bbfe491 100644 --- a/Tests/Core/Plugins/MenuBarPanelStoreTests.swift +++ b/Tests/Core/Plugins/MenuBarPanelStoreTests.swift @@ -56,6 +56,28 @@ final class MenuBarPanelStoreTests: XCTestCase { XCTAssertEqual(migrated.configuration.legacySeed?.dashboardHidden, ["example"]) } + /// A panel's own width is opt-in: only a dedicated panel gets one, once, and only while the + /// panel limit allows; every other panel keeps the shared width. + func testDedicatedPanelIsCreatedOnceWithItsWidthAndOthersHaveNone() throws { + let history = PluginPanelItemKey(pluginID: "island-notifications", itemID: "history") + XCTAssertTrue(store.reconcile([(history, .dashboard)])) + let panel = try XCTUnwrap(store.configuration.panels.first { $0.id == MenuBarPanelDefinition.notificationsID }) + XCTAssertEqual(panel.width, 372) + XCTAssertEqual(store.configuration.placementsByPanelID[panel.id]?.map(\.item), [history]) + XCTAssertNil(store.configuration.placementsByPanelID[MenuBarPanelDefinition.componentsID]) + XCTAssertTrue(store.configuration.panels.filter { $0.id != panel.id }.allSatisfy { $0.width == nil }) + // Once seen, the item never creates the panel again, even if the person removes it. + let reloaded = MenuBarPanelStore(userDefaults: defaults) + XCTAssertFalse(reloaded.reconcile([(history, .dashboard)])) + XCTAssertEqual(reloaded.configuration.panels.filter { $0.id == panel.id }.count, 1) + } + + func testAPanelWidthBelowTheSharedMinimumIsDropped() { + var configuration = MenuBarPanelConfiguration() + configuration.panels.append(MenuBarPanelDefinition(id: "narrow", name: "", systemImage: "bell", width: 100)) + XCTAssertNil(configuration.normalized().panels.first { $0.id == "narrow" }?.width) + } + func testInitialPlacementIsAppliedOnceIncludingLibraryOnlyItems() throws { let row = key() let widget = key("example", "widget") diff --git a/changes/unreleased/panel-own-width.md b/changes/unreleased/panel-own-width.md new file mode 100644 index 000000000..0c3601818 --- /dev/null +++ b/changes/unreleased/panel-own-width.md @@ -0,0 +1,7 @@ +--- +release: app +type: changed +area: Menu Bar Panel +--- + +The notch panel now glides when it changes size, and a panel can have its own width. From e0695c8890efa1c003730ab9d5e98a16cb0e6172 Mon Sep 17 00:00:00 2001 From: Niko Eltarenko <61957857+nikoelt@users.noreply.github.com> Date: Tue, 17 Nov 2026 18:08:04 +1000 Subject: [PATCH 09/29] fix(island-notifications): keep the list's height when the panel opens The "No Notifications" line could report after the list had measured itself, shrinking the panel to the empty height and cutting off the notifications. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .../Sources/IslandNotificationsController.swift | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/Plugins/IslandNotifications/Sources/IslandNotificationsController.swift b/Plugins/IslandNotifications/Sources/IslandNotificationsController.swift index 328791196..5e983bf18 100644 --- a/Plugins/IslandNotifications/Sources/IslandNotificationsController.swift +++ b/Plugins/IslandNotifications/Sources/IslandNotificationsController.swift @@ -772,9 +772,16 @@ final class IslandNotificationsController { } func setHistoryContentHeight(_ height: CGFloat) { - let total = height > 0 - ? min(IslandHistoryLayout.maximumHeight, height) - : IslandHistoryLayout.emptyHeight + // The list and its "No Notifications" line can both report as the panel opens, the line + // after the list has measured itself, so what the list holds decides which one counts. + let total: CGFloat + if history.entries.isEmpty { + total = IslandHistoryLayout.emptyHeight + } else if height > 0 { + total = min(IslandHistoryLayout.maximumHeight, height) + } else { + return + } let span = PluginPanelWidgetLayoutMetrics.default.heightSpan(fittingContentHeight: total) // At once, both ways: the panel glides to the new height on the same spring the list // uses, and the list waits the panel's short update delay (see IslandHistoryLayout.motion). From 687f78f6331d377d4815aea87c518f92ae400d39 Mon Sep 17 00:00:00 2001 From: Niko Eltarenko <61957857+nikoelt@users.noreply.github.com> Date: Wed, 18 Nov 2026 12:43:01 +1000 Subject: [PATCH 10/29] fix(island-notifications): find edited Messages for replies A message edited after its banner showed no longer matched the card's text, so replying said the conversation couldn't be found. The lookup now also compares the earlier versions Messages keeps for edits. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .../Sources/IslandNotificationState.swift | 21 ++++++++++++--- .../Tests/IslandNotificationStateTests.swift | 26 +++++++++++++++++++ 2 files changed, 44 insertions(+), 3 deletions(-) diff --git a/Plugins/IslandNotifications/Sources/IslandNotificationState.swift b/Plugins/IslandNotifications/Sources/IslandNotificationState.swift index 54bbf0dc4..fe154e167 100644 --- a/Plugins/IslandNotifications/Sources/IslandNotificationState.swift +++ b/Plugins/IslandNotifications/Sources/IslandNotificationState.swift @@ -249,7 +249,7 @@ enum IslandMessagesChat { // Message dates are nanoseconds since 2001; look back five minutes. let since = Int64((Date().timeIntervalSinceReferenceDate - 300) * 1_000_000_000) let sql = """ - SELECT c.guid, m.text, m.attributedBody, c.group_id FROM message m + SELECT c.guid, m.text, m.attributedBody, c.group_id, m.message_summary_info FROM message m JOIN chat_message_join j ON j.message_id = m.ROWID JOIN chat c ON c.ROWID = j.chat_id WHERE m.is_from_me = 0 AND m.date > ?1 @@ -269,7 +269,12 @@ enum IslandMessagesChat { if text == nil, let blob = sqlite3_column_blob(statement, 2) { text = attributedBodyText(Data(bytes: blob, count: Int(sqlite3_column_bytes(statement, 2)))) } - guard let text, matches(normalized(text), candidates) else { continue } + // An edited message keeps its earlier versions; the banner shows the one that arrived. + var versions = text.map { [$0] } ?? [] + if let blob = sqlite3_column_blob(statement, 4) { + versions += editedVersions(Data(bytes: blob, count: Int(sqlite3_column_bytes(statement, 4)))) + } + guard versions.contains(where: { matches(normalized($0), candidates) }) else { continue } chats.insert(guid) if let groupID = sqlite3_column_text(statement, 3).map({ String(cString: $0) }), !groupID.isEmpty { groupIDs[guid] = groupID @@ -303,9 +308,19 @@ enum IslandMessagesChat { candidates.contains { $0 == text || ($0.count >= 12 && text.hasPrefix($0.trimmingCharacters(in: CharacterSet(charactersIn: "…")))) } } + /// `message_summary_info` holds each version of an edited message under "ec": the message's + /// part number, then a list of versions, each with its text archived like `attributedBody` ("t"). + static func editedVersions(_ data: Data) -> [String] { + guard let info = try? PropertyListSerialization.propertyList(from: data, format: nil) as? [String: Any], + let parts = info["ec"] as? [String: Any] else { return [] } + return parts.values.flatMap { part -> [String] in + ((part as? [[String: Any]]) ?? []).compactMap { ($0["t"] as? Data).flatMap(attributedBodyText) } + } + } + /// Newer macOS stores some message text only in `attributedBody` (an archived NSAttributedString): /// the string follows the "NSString" class marker as a length-prefixed UTF-8 run. - private static func attributedBodyText(_ data: Data) -> String? { + static func attributedBodyText(_ data: Data) -> String? { let bytes = [UInt8](data) guard let marker = bytes.firstRange(of: Array("NSString".utf8)) else { return nil } var index = marker.upperBound diff --git a/Plugins/IslandNotifications/Tests/IslandNotificationStateTests.swift b/Plugins/IslandNotifications/Tests/IslandNotificationStateTests.swift index b53c6d4c2..2a416a422 100644 --- a/Plugins/IslandNotifications/Tests/IslandNotificationStateTests.swift +++ b/Plugins/IslandNotifications/Tests/IslandNotificationStateTests.swift @@ -67,4 +67,30 @@ final class IslandNotificationStateTests: XCTestCase { hasUnexpectedContent: gate == 1, complete: gate != 2)) } } + + /// An archived string the way Messages stores one: the "NSString" class marker, then "+" and + /// a length-prefixed UTF-8 run (one byte, or 0x81 and two bytes). + private func archivedText(_ text: String) -> Data { + let utf8 = Array(text.utf8) + let length: [UInt8] = utf8.count < 0x80 ? [UInt8(utf8.count)] : [0x81, UInt8(utf8.count & 0xFF), UInt8(utf8.count >> 8)] + return Data([0x04, 0x0B] + Array("streamtyped".utf8) + Array("NSString".utf8) + [0x01, 0x94, 0x84, 0x01, 0x2B] + length + utf8 + [0x86]) + } + + func testEditedMessageKeepsEveryVersionForMatchingTheBanner() throws { + let original = "See you at the station" + let edited = String(repeating: "Running late, ", count: 10) + original + let info: [String: Any] = [ + "ec": ["0": [["t": archivedText(original), "d": 1.0], ["t": archivedText(edited), "d": 2.0]]], + "ust": true + ] + let data = try PropertyListSerialization.data(fromPropertyList: info, format: .binary, options: 0) + XCTAssertEqual(IslandMessagesChat.editedVersions(data), [original, edited]) + XCTAssertEqual(IslandMessagesChat.attributedBodyText(archivedText(edited)), edited) + } + + func testUneditedMessageHasNoEarlierVersions() throws { + let data = try PropertyListSerialization.data(fromPropertyList: ["amc": 0], format: .binary, options: 0) + XCTAssertEqual(IslandMessagesChat.editedVersions(data), []) + XCTAssertEqual(IslandMessagesChat.editedVersions(Data([0x00, 0x01])), []) + } } From 5501e3fecb76fb11b8165055de03d0f26bff2de2 Mon Sep 17 00:00:00 2001 From: Niko Eltarenko <61957857+nikoelt@users.noreply.github.com> Date: Wed, 18 Nov 2026 19:23:27 +1000 Subject: [PATCH 11/29] fix(island-notifications): confirm the reply target before sending Messages: the conversation is looked up among messages received around the banner's arrival, not the last five minutes before Send. A card held open can no longer come to match a later message with the same text from someone else; opening from the card or the list uses the same window. Claude: the card's chat is looked up again by its id at send time, and the window is checked again before the text goes in and before Send. Another chat with the same title, now or in the sidebar, refuses the reply, and a reply that isn't sent is taken back only if the box still holds just it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .../Sources/IslandNotificationAX.swift | 87 +++++++++++++++---- .../Sources/IslandNotificationState.swift | 19 ++-- .../IslandNotificationsController.swift | 22 +++-- .../Tests/IslandNotificationStateTests.swift | 26 ++++++ 4 files changed, 125 insertions(+), 29 deletions(-) diff --git a/Plugins/IslandNotifications/Sources/IslandNotificationAX.swift b/Plugins/IslandNotifications/Sources/IslandNotificationAX.swift index 6bedd8390..59f8fef58 100644 --- a/Plugins/IslandNotifications/Sources/IslandNotificationAX.swift +++ b/Plugins/IslandNotifications/Sources/IslandNotificationAX.swift @@ -218,6 +218,8 @@ final class IslandNotification: @unchecked Sendable { let lineCount: Int /// When MacTools received it (system uptime). let arrivedAt = ProcessInfo.processInfo.systemUptime + /// The same moment on the clock, which Messages' history dates are compared with. + let arrivalDate = Date() /// A header label from the banner, e.g. "TIME-SENSITIVE". @MainActor var label: String? @MainActor var appURL: URL? @@ -649,7 +651,13 @@ enum IslandClaudeReply { } @MainActor - static func send(_ text: String, to chat: IslandClaudeChat) async -> IslandReplyOutcome { + static func send(_ text: String, to card: IslandClaudeChat) async -> IslandReplyOutcome { + // The card's chat as Claude records it now: a chat opened or renamed since the card arrived + // may share its title, and the title is all the window shows. + let localID = card.localID + guard let chat = await Task.detached(priority: .userInitiated, operation: { + IslandClaudeTurnWatcher.desktopChat(localID: localID) + }).value else { return .failed } guard chat.isUnique else { return .ambiguousChat } guard let claude = NSRunningApplication.runningApplications(withBundleIdentifier: bundleIdentifier).first else { return .failed @@ -680,6 +688,7 @@ enum IslandClaudeReply { } logger.notice("claude page ready=\(scan.prompt != nil, privacy: .public) attempts=\(attempts, privacy: .public) showing=\(isShowing(title, in: scan.chatTitle), privacy: .public) entries=\(scan.sidebarEntries.count, privacy: .public)") guard scan.prompt != nil, !scan.chatTitle.isEmpty else { return .failed } + guard scan.sidebarEntries.count <= 1 else { logger.notice("claude sidebar has the title twice"); return .ambiguousChat } if !isShowing(title, in: scan.chatTitle) { if scan.sidebarEntries.count == 1, let entry = scan.sidebarEntries.first.map(IslandAXElement.init) { _ = await IslandAX.run { AXUIElementPerformAction(entry.value, kAXPressAction as CFString) == .success } @@ -711,6 +720,8 @@ enum IslandClaudeReply { let existing = await IslandAX.run { promptText(prompt.value) } guard let existing else { return .failed } guard existing.isEmpty else { logger.notice("claude chat has an unsent draft"); return .claudeDraft } + // Still that chat, and still the only one with its title, just before the text goes in. + guard await stillTarget(chat, pid: pid) else { return .ambiguousChat } let filled = await IslandAX.run { () -> Bool in guard AXUIElementSetAttributeValue(prompt.value, kAXValueAttribute as CFString, text as CFString) == .success else { return false } return AXUIElementSetAttributeValue(prompt.value, kAXFocusedAttribute as CFString, kCFBooleanTrue) == .success @@ -719,8 +730,15 @@ enum IslandClaudeReply { try? await Task.sleep(for: .milliseconds(150)) // Idle: press Claude's Send button (it appears once there is text). Working: Command-Return // queues the reply instead of interrupting. Both work with Claude in the background. + // The window can change chat while the text goes in; then nothing is sent and the text is taken back. + let final = await IslandAX.run { read(pid: pid, sidebarTitle: nil) } + guard isShowing(title, in: final.chatTitle) else { + logger.notice("claude chat changed before sending") + await takeBack(text, from: prompt) + return .failed + } let pressed = busy ? false : await IslandAX.run { () -> Bool in - guard let send = read(pid: pid, sidebarTitle: nil).send else { return false } + guard let send = final.send else { return false } return AXUIElementPerformAction(send, kAXPressAction as CFString) == .success } if !pressed { @@ -738,11 +756,29 @@ enum IslandClaudeReply { if await IslandAX.run({ promptText(prompt.value) })?.isEmpty == true { return .sent } } logger.notice("claude send not confirmed") - // Not sent: leave the box as it was (empty) rather than holding a stray reply. - _ = await IslandAX.run { AXUIElementSetAttributeValue(prompt.value, kAXValueAttribute as CFString, "" as CFString) } + await takeBack(text, from: prompt) return .failed } + /// Not sent: the box goes back to empty, as it was, but only while it still holds just this + /// reply, so nothing typed there meanwhile is lost. + private static func takeBack(_ text: String, from prompt: IslandAXElement) async { + _ = await IslandAX.run { () -> Bool in + guard promptText(prompt.value) == text else { return false } + return AXUIElementSetAttributeValue(prompt.value, kAXValueAttribute as CFString, "" as CFString) == .success + } + } + + /// The chat on screen is still this one, the sidebar shows its title at most once, and Claude's + /// records still give no other open chat that title. + private static func stillTarget(_ chat: IslandClaudeChat, pid: pid_t) async -> Bool { + let scan = await IslandAX.run { read(pid: pid, sidebarTitle: chat.title) } + guard isShowing(chat.title, in: scan.chatTitle), scan.sidebarEntries.count <= 1 else { return false } + let localID = chat.localID + let now = await Task.detached(priority: .userInitiated) { IslandClaudeTurnWatcher.desktopChat(localID: localID) }.value + return now?.title == chat.title && now?.isUnique == true + } + @IslandAXExecutor private static func promptText(_ prompt: AXUIElement) -> String? { (IslandAX.value(prompt, kAXValueAttribute, timeout: 0.5) as? String)?.trimmingCharacters(in: .whitespacesAndNewlines) @@ -950,29 +986,48 @@ final class IslandClaudeTurnWatcher { return false } - /// The desktop chat that runs this Claude Code session (none for terminal sessions). - nonisolated static func desktopChat(forSession sessionID: String) -> IslandClaudeChat? { + /// One open chat in Claude's records: its app-side id, title and the Claude Code sessions it ran. + struct DesktopSession: Equatable, Sendable { + let localID: String + let title: String + let cliSessionIDs: [String] + } + + nonisolated static func desktopSessions() -> [DesktopSession] { let root = FileManager.default.homeDirectoryForCurrentUser .appendingPathComponent("Library/Application Support/Claude/claude-code-sessions", isDirectory: true) - guard let enumerator = FileManager.default.enumerator(at: root, includingPropertiesForKeys: nil) else { return nil } - var match: IslandClaudeChat? - var titles: [String] = [] + guard let enumerator = FileManager.default.enumerator(at: root, includingPropertiesForKeys: nil) else { return [] } + var sessions: [DesktopSession] = [] for case let file as URL in enumerator where file.lastPathComponent.hasPrefix("local_") && file.pathExtension == "json" { guard let data = try? Data(contentsOf: file), let info = try? JSONSerialization.jsonObject(with: data) as? [String: Any], (info["isArchived"] as? Bool) != true, let localID = info["sessionId"] as? String else { continue } - let title = info["title"] as? String ?? "Claude" - titles.append(title) - if info["cliSessionId"] as? String == sessionID || info["lastAssistantCliSessionId"] as? String == sessionID { - match = IslandClaudeChat(localID: localID, title: title) - } + let cli = [info["cliSessionId"], info["lastAssistantCliSessionId"]].compactMap { $0 as? String } + sessions.append(DesktopSession(localID: localID, title: info["title"] as? String ?? "Claude", cliSessionIDs: cli)) } - guard var chat = match else { return nil } - chat.isUnique = titles.filter { $0 == chat.title }.count == 1 + return sessions + } + + /// The chat found by `matches`, unique only while no other open chat has its title: the title is + /// all Claude's window shows to tell chats apart. + nonisolated static func desktopChat(in sessions: [DesktopSession], where matches: (DesktopSession) -> Bool) -> IslandClaudeChat? { + guard let session = sessions.first(where: matches) else { return nil } + var chat = IslandClaudeChat(localID: session.localID, title: session.title) + chat.isUnique = sessions.filter { $0.title == session.title }.count == 1 return chat } + /// The desktop chat that runs this Claude Code session (none for terminal sessions). + nonisolated static func desktopChat(forSession sessionID: String) -> IslandClaudeChat? { + desktopChat(in: desktopSessions()) { $0.cliSessionIDs.contains(sessionID) } + } + + /// The same chat as it is now: its current title, and whether another chat has taken that title since. + nonisolated static func desktopChat(localID: String) -> IslandClaudeChat? { + desktopChat(in: desktopSessions()) { $0.localID == localID } + } + /// The text of the last assistant entry in a Claude Code transcript (JSON lines), read from its tail. nonisolated static func lastAssistantMessage(in path: String) -> String? { guard let handle = FileHandle(forReadingAtPath: path) else { return nil } diff --git a/Plugins/IslandNotifications/Sources/IslandNotificationState.swift b/Plugins/IslandNotifications/Sources/IslandNotificationState.swift index fe154e167..2e2322698 100644 --- a/Plugins/IslandNotifications/Sources/IslandNotificationState.swift +++ b/Plugins/IslandNotifications/Sources/IslandNotificationState.swift @@ -239,26 +239,35 @@ enum IslandMessagesChat { return db } + /// The messages a banner can be about: received up to five minutes before it arrived, or within + /// half a minute after (Messages writes its history a few seconds late). Fixed to the arrival, so + /// a card held open never comes to match a later message with the same text from someone else. + /// Message dates are nanoseconds since 2001. + static func dateWindow(around arrival: Date) -> ClosedRange<Int64> { + let seconds = arrival.timeIntervalSinceReferenceDate + return Int64((seconds - 300) * 1_000_000_000)...Int64((seconds + 30) * 1_000_000_000) + } + /// `bannerLines`: the banner's text lines after its title. A group banner (three lines) must lead /// to a group conversation and a one-to-one banner to a one-to-one conversation. - static func resolve(bannerLines: [String], isGroupBanner: Bool) -> Lookup { + static func resolve(bannerLines: [String], isGroupBanner: Bool, arrivedAt arrival: Date) -> Lookup { guard let db = open() else { return .unavailable } defer { sqlite3_close(db) } let candidates = Set(bannerLines.map(normalized).filter { !$0.isEmpty }) guard !candidates.isEmpty else { return .notFound } - // Message dates are nanoseconds since 2001; look back five minutes. - let since = Int64((Date().timeIntervalSinceReferenceDate - 300) * 1_000_000_000) + let window = dateWindow(around: arrival) let sql = """ SELECT c.guid, m.text, m.attributedBody, c.group_id, m.message_summary_info FROM message m JOIN chat_message_join j ON j.message_id = m.ROWID JOIN chat c ON c.ROWID = j.chat_id - WHERE m.is_from_me = 0 AND m.date > ?1 + WHERE m.is_from_me = 0 AND m.date >= ?1 AND m.date <= ?2 ORDER BY m.date DESC LIMIT 200 """ var statement: OpaquePointer? guard sqlite3_prepare_v2(db, sql, -1, &statement, nil) == SQLITE_OK, let statement else { return .notFound } defer { sqlite3_finalize(statement) } - sqlite3_bind_int64(statement, 1, since) + sqlite3_bind_int64(statement, 1, window.lowerBound) + sqlite3_bind_int64(statement, 2, window.upperBound) var rows = 0 var chats = Set<String>() var groupIDs: [String: String] = [:] diff --git a/Plugins/IslandNotifications/Sources/IslandNotificationsController.swift b/Plugins/IslandNotifications/Sources/IslandNotificationsController.swift index 5e983bf18..d0b80546d 100644 --- a/Plugins/IslandNotifications/Sources/IslandNotificationsController.swift +++ b/Plugins/IslandNotifications/Sources/IslandNotificationsController.swift @@ -698,22 +698,27 @@ final class IslandNotificationsController { /// The exact conversation comes from Messages' history; the message may land there a moment /// after its banner. No match (or no access) means no reply, never a guess. - private static func messagesConversation(body: String, lineCount: Int) async -> IslandMessagesChat.Lookup { + private static func messagesConversation(body: String, lineCount: Int, arrivedAt arrival: Date) async -> IslandMessagesChat.Lookup { let lines = body.components(separatedBy: "\n") + [body] let isGroup = lineCount > 2 var lookup = IslandMessagesChat.Lookup.notFound - for _ in 0..<4 { + // Messages writes its history a few seconds after the banner, so a quick reply keeps + // looking until 15 seconds after the banner arrived; a later one tries a few times. + var attempts = 0 + repeat { lookup = await Task.detached(priority: .userInitiated) { - IslandMessagesChat.resolve(bannerLines: lines, isGroupBanner: isGroup) + IslandMessagesChat.resolve(bannerLines: lines, isGroupBanner: isGroup, arrivedAt: arrival) }.value guard lookup == .notFound else { break } + attempts += 1 try? await Task.sleep(for: .milliseconds(500)) - } + } while attempts < 4 || Date().timeIntervalSince(arrival) < 15 return lookup } private static func replyInMessages(_ text: String, to notification: IslandNotification) async -> IslandReplyOutcome { - guard case .found(let chat) = await messagesConversation(body: notification.body, lineCount: notification.lineCount) else { return .noConversation } + guard case .found(let chat) = await messagesConversation(body: notification.body, lineCount: notification.lineCount, + arrivedAt: notification.arrivalDate) else { return .noConversation } return await IslandMessagesReply.send(text, toChat: chat) } @@ -742,7 +747,8 @@ final class IslandNotificationsController { // macOS removes a banner after a few seconds; a Messages card that outlives it still // opens its conversation, found the same way replies are. if !opened, notification.bundleIdentifier == "com.apple.MobileSMS", - case .found(let chat) = await Self.messagesConversation(body: notification.body, lineCount: notification.lineCount), + case .found(let chat) = await Self.messagesConversation(body: notification.body, lineCount: notification.lineCount, + arrivedAt: notification.arrivalDate), let url = chat.openURL, NSWorkspace.shared.open(url) { // Opened the exact conversation. } else if !opened, let url = notification.appURL { @@ -764,7 +770,7 @@ final class IslandNotificationsController { let centerApp = notification.claudeChat == nil ? IslandNotification.appName(fromDescription: description, title: notification.title, body: notification.body) : nil - history.add(IslandHistoryEntry(date: Date(), appName: notification.appName ?? centerApp ?? notification.title, + history.add(IslandHistoryEntry(date: notification.arrivalDate, appName: notification.appName ?? centerApp ?? notification.title, centerApp: centerApp, appURL: notification.appURL, bundleIdentifier: notification.bundleIdentifier, title: notification.title, body: notification.body, @@ -804,7 +810,7 @@ final class IslandNotificationsController { var opened = await inCenter(.open, entry) // Gone from Notification Centre (the app withdrew it, or it was cleared there). if !opened, entry.bundleIdentifier == "com.apple.MobileSMS", - case .found(let chat) = await Self.messagesConversation(body: entry.body, lineCount: entry.lineCount), + case .found(let chat) = await Self.messagesConversation(body: entry.body, lineCount: entry.lineCount, arrivedAt: entry.date), let url = chat.openURL { opened = NSWorkspace.shared.open(url) } diff --git a/Plugins/IslandNotifications/Tests/IslandNotificationStateTests.swift b/Plugins/IslandNotifications/Tests/IslandNotificationStateTests.swift index 2a416a422..737fad2d4 100644 --- a/Plugins/IslandNotifications/Tests/IslandNotificationStateTests.swift +++ b/Plugins/IslandNotifications/Tests/IslandNotificationStateTests.swift @@ -93,4 +93,30 @@ final class IslandNotificationStateTests: XCTestCase { XCTAssertEqual(IslandMessagesChat.editedVersions(data), []) XCTAssertEqual(IslandMessagesChat.editedVersions(Data([0x00, 0x01])), []) } + + func testMessagesLookupWindowStaysFixedToTheBannersArrival() { + let arrival = Date(timeIntervalSinceReferenceDate: 800_000_000) + let window = IslandMessagesChat.dateWindow(around: arrival) + let nanoseconds = { (offset: TimeInterval) in Int64((arrival.timeIntervalSinceReferenceDate + offset) * 1_000_000_000) } + XCTAssertTrue(window.contains(nanoseconds(-299))) + XCTAssertTrue(window.contains(nanoseconds(25))) + // A message from someone else ten minutes later never matches a card that is still open. + XCTAssertFalse(window.contains(nanoseconds(600))) + XCTAssertFalse(window.contains(nanoseconds(-301))) + } + + func testClaudeChatIsUniqueOnlyWhileNoOtherChatHasItsTitle() { + typealias Session = IslandClaudeTurnWatcher.DesktopSession + let card = Session(localID: "local_a", title: "Fix the build", cliSessionIDs: ["cli-a"]) + let other = Session(localID: "local_b", title: "Notes", cliSessionIDs: ["cli-b"]) + let unique = IslandClaudeTurnWatcher.desktopChat(in: [card, other]) { $0.localID == "local_a" } + XCTAssertEqual(unique?.title, "Fix the build") + XCTAssertEqual(unique?.isUnique, true) + // A chat opened later with the same title makes the card's chat ambiguous at send time. + let later = Session(localID: "local_c", title: "Fix the build", cliSessionIDs: ["cli-c"]) + XCTAssertEqual(IslandClaudeTurnWatcher.desktopChat(in: [card, other, later]) { $0.localID == "local_a" }?.isUnique, false) + // The session found by its Claude Code id, and a chat that has gone. + XCTAssertEqual(IslandClaudeTurnWatcher.desktopChat(in: [card, other]) { $0.cliSessionIDs.contains("cli-b") }?.localID, "local_b") + XCTAssertNil(IslandClaudeTurnWatcher.desktopChat(in: [other]) { $0.localID == "local_a" }) + } } From 688b92cf518bcf0f701c25addbed50dadfb3b9ec Mon Sep 17 00:00:00 2001 From: Niko Eltarenko <61957857+nikoelt@users.noreply.github.com> Date: Wed, 18 Nov 2026 19:30:11 +1000 Subject: [PATCH 12/29] fix(island-notifications): stop the Claude log watcher without waiting Stopping waited for any queued transcript read, up to a megabyte, on the main thread. The queue now keeps the reader alive until its queued work has run, and a turn read just before the stop is not shown after it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .../Sources/IslandNotificationAX.swift | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/Plugins/IslandNotifications/Sources/IslandNotificationAX.swift b/Plugins/IslandNotifications/Sources/IslandNotificationAX.swift index 59f8fef58..67971e531 100644 --- a/Plugins/IslandNotifications/Sources/IslandNotificationAX.swift +++ b/Plugins/IslandNotifications/Sources/IslandNotificationAX.swift @@ -892,15 +892,21 @@ final class IslandClaudeTurnWatcher { private var stream: FSEventStreamRef? private var reader: IslandClaudeTranscriptReader? private let queue = DispatchQueue(label: "MacTools.IslandNotifications.ClaudeLogs", qos: .utility) + /// Bumped by every stop, so a turn read just before it is not shown after it. + private var generation = 0 func start() { guard stream == nil else { return } try? FileManager.default.removeItem(at: Self.legacyDirectory) let roots = Self.logRoots guard !roots.isEmpty else { return } + let generation = generation let reader = IslandClaudeTranscriptReader(roots: roots) { [weak self] turn in DispatchQueue.main.async { [weak self] in - MainActor.assumeIsolated { self?.onTurn?(turn) } + MainActor.assumeIsolated { + guard let self, self.generation == generation else { return } + self.onTurn?(turn) + } } } guard let stream = Self.makeStream(paths: roots.map(\.path), reader: reader, queue: queue) else { return } @@ -933,10 +939,12 @@ final class IslandClaudeTurnWatcher { } func stop() { + generation += 1 if let stream { FSEventStreamStop(stream); FSEventStreamInvalidate(stream); FSEventStreamRelease(stream) - // Let any callback already queued finish before the reader goes. - queue.sync {} + // FSEvents holds the reader unretained. A callback already queued may still run, so the + // queue keeps the reader until it has; the main thread never waits for a log read. + if let reader { queue.async { withExtendedLifetime(reader) {} } } } stream = nil; reader = nil } From 6ee4a49a560f63d97d85b4814e707fb7cca38fd0 Mon Sep 17 00:00:00 2001 From: Niko Eltarenko <61957857+nikoelt@users.noreply.github.com> Date: Wed, 18 Nov 2026 19:32:46 +1000 Subject: [PATCH 13/29] fix(island-notifications): open or clear only the exact list row MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A row in Notification Centre now matches only with all of the notification's text, not its first 40 characters; text shortened with "…" on either side must still agree for 12 characters, and a notification with no text matches only a row with none. When two rows read the same, neither is opened or cleared: opening falls back to the app. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .../Sources/IslandCenterPress.swift | 9 ++++---- .../Sources/IslandNotificationHistory.swift | 22 ++++++++++++++----- .../IslandNotificationHistoryTests.swift | 18 +++++++++++++++ 3 files changed, 40 insertions(+), 9 deletions(-) diff --git a/Plugins/IslandNotifications/Sources/IslandCenterPress.swift b/Plugins/IslandNotifications/Sources/IslandCenterPress.swift index 23747610b..3641d09dd 100644 --- a/Plugins/IslandNotifications/Sources/IslandCenterPress.swift +++ b/Plugins/IslandNotifications/Sources/IslandCenterPress.swift @@ -115,10 +115,11 @@ enum IslandCenterPress { let deadline = ProcessInfo.processInfo.systemUptime + 1.5 while ProcessInfo.processInfo.systemUptime < deadline { let rows = rows(application) - if let row = rows.first(where: { $0.single && IslandCenterMatch.row($0.description, matchesApp: target.app, - title: target.title, body: target.body) }) { - return row.element - } + let matches = rows.filter { $0.single && IslandCenterMatch.row($0.description, matchesApp: target.app, + title: target.title, body: target.body) } + // Two rows that read the same can't be told apart: neither is opened or cleared. + if matches.count > 1 { logger.notice("center rows ambiguous count=\(matches.count, privacy: .public)"); return nil } + if let row = matches.first { return row.element } if let before { // The stack opened and the notification isn't in it. if rows.count != before { return nil } diff --git a/Plugins/IslandNotifications/Sources/IslandNotificationHistory.swift b/Plugins/IslandNotifications/Sources/IslandNotificationHistory.swift index a8b42437e..945684b53 100644 --- a/Plugins/IslandNotifications/Sources/IslandNotificationHistory.swift +++ b/Plugins/IslandNotifications/Sources/IslandNotificationHistory.swift @@ -75,8 +75,9 @@ enum IslandCenterMatch { .split(whereSeparator: { $0.isWhitespace || $0.isNewline }).joined(separator: " ") } - /// The row is this notification: it starts with the app, then has the title and the start of - /// its text. The marks between the parts depend on the language (", " "、" "," "،"). + /// The row is this notification: it starts with the app, then has the title and then all of its + /// text. The marks between the parts depend on the language (", " "、" "," "،"). Text either + /// side shortened with "…" may stop early, but must agree for at least 12 characters. static func row(_ description: String, matchesApp app: String, title: String, body: String) -> Bool { let row = normalized(description) let title = normalized(title) @@ -84,9 +85,20 @@ enum IslandCenterMatch { guard let rest = afterApp(row, app: app), rest.hasPrefix(title) else { return false } let afterTitle = rest.dropFirst(title.count) guard afterTitle.isEmpty || isMark(afterTitle) else { return false } - let text = normalized(body).trimmingCharacters(in: CharacterSet(charactersIn: "…")) - guard !text.isEmpty else { return true } - return afterTitle.contains(String(text.prefix(40))) + let wanted = normalized(body), shown = String(afterTitle) + let want = compact(wanted), have = compact(shown) + if want == have { return true } + if wanted.hasSuffix("…"), want.count >= 12, have.hasPrefix(want) { return true } + if shown.hasSuffix("…"), have.count >= 12, want.hasPrefix(have) { return true } + return false + } + + /// The text alone: without spaces, line breaks, the list marks between parts (a subtitle is its + /// own part in a row but its own line on a banner) and a closing "…". + private static func compact(_ text: String) -> String { + String(text.unicodeScalars.filter { + !CharacterSet.whitespacesAndNewlines.contains($0) && !IslandNotification.descriptionSeparators.contains($0) + }.map(Character.init)).trimmingCharacters(in: CharacterSet(charactersIn: "…")) } /// A collapsed stack of this app's notifications; only its newest shows in the description. diff --git a/Plugins/IslandNotifications/Tests/IslandNotificationHistoryTests.swift b/Plugins/IslandNotifications/Tests/IslandNotificationHistoryTests.swift index 0badd7f7e..64ecf0357 100644 --- a/Plugins/IslandNotifications/Tests/IslandNotificationHistoryTests.swift +++ b/Plugins/IslandNotifications/Tests/IslandNotificationHistoryTests.swift @@ -17,6 +17,24 @@ final class IslandNotificationHistoryTests: XCTestCase { body: "Confirmed on Viator.")) XCTAssertFalse(IslandCenterMatch.row(row, matchesApp: "Spark Desktop", title: "💬 Yannis › Please Respond: New Booking", body: "Cancelled.")) + // The same start is not the same notification: all of the text must match. + let longer = "Spark Desktop, 💬 Yannis › Please Respond: New Booking, Confirmed on Viator. Pick-up moved to 9 am." + XCTAssertFalse(IslandCenterMatch.row(longer, matchesApp: "Spark Desktop", title: "💬 Yannis › Please Respond: New Booking", + body: "Confirmed on Viator.")) + XCTAssertFalse(IslandCenterMatch.row(row, matchesApp: "Spark Desktop", title: "💬 Yannis › Please Respond: New Booking", + body: "Confirmed on Viator. Pick-up moved to 9 am.")) + // A row Notification Centre shortened matches the banner's full text, and a short cut does not. + let shortened = "Spark Desktop, 💬 Yannis › Please Respond: New Booking, Confirmed on Viator. Pick-up…" + XCTAssertTrue(IslandCenterMatch.row(shortened, matchesApp: "Spark Desktop", title: "💬 Yannis › Please Respond: New Booking", + body: "Confirmed on Viator. Pick-up moved to 9 am.")) + XCTAssertFalse(IslandCenterMatch.row("Spark Desktop, 💬 Yannis › Please Respond: New Booking, Conf…", matchesApp: "Spark Desktop", + title: "💬 Yannis › Please Respond: New Booking", body: "Confirmed on Viator.")) + // A notification with no text matches only a row with none. + XCTAssertTrue(IslandCenterMatch.row("Reminders, Bins", matchesApp: "Reminders", title: "Bins", body: "")) + XCTAssertFalse(IslandCenterMatch.row("Reminders, Bins, Recycling too", matchesApp: "Reminders", title: "Bins", body: "")) + // A group's subtitle is its own line on the banner and its own part in the row. + XCTAssertTrue(IslandCenterMatch.row("Messages, Alex, Family, See you soon", matchesApp: "Messages", title: "Alex", + body: "Family\nSee you soon")) XCTAssertTrue(IslandCenterMatch.stack(row, isApp: "Spark Desktop")) XCTAssertFalse(IslandCenterMatch.stack(row, isApp: "Spark")) } From 39b084574e13a9006ff75989284bda3e00ff595d Mon Sep 17 00:00:00 2001 From: Niko Eltarenko <61957857+nikoelt@users.noreply.github.com> Date: Wed, 18 Nov 2026 19:38:27 +1000 Subject: [PATCH 14/29] fix(island-notifications): require the host with the panel and hover changes The plugin relies on host changes in this branch (a panel's own width and the hover panel staying shut over a card), which no released host has yet; the minimum host is now the next one, 2.2.4. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- Plugins/IslandNotifications/plugin.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Plugins/IslandNotifications/plugin.json b/Plugins/IslandNotifications/plugin.json index 2b32f3afd..958e9a658 100644 --- a/Plugins/IslandNotifications/plugin.json +++ b/Plugins/IslandNotifications/plugin.json @@ -85,7 +85,7 @@ } }, "version": "1.0.0", - "minHostVersion": "2.2.0", + "minHostVersion": "2.2.4", "pluginKitVersion": 7, "bundleRelativePath": "IslandNotifications.bundle", "factoryClass": "IslandNotificationsPlugin.IslandNotificationsPluginFactory", From cffdd6e6008d2910663b0c4f5e6078838fc0724c Mon Sep 17 00:00:00 2001 From: Niko Eltarenko <61957857+nikoelt@users.noreply.github.com> Date: Wed, 18 Nov 2026 19:43:55 +1000 Subject: [PATCH 15/29] feat(island-notifications): Claude chat cards as their own opt-in, through a notice Claude chat cards were shown straight from Claude Code's session logs whenever the plugin was on, outside Focus and preview privacy. They are now a separate switch, off by default, and the logs are read only while it is on. A finished turn is posted as MacTools' own notification, and its banner becomes the card: MacTools' notification settings, Focus and hidden previews apply as for any app, the notice stays in Notification Centre's history, and nothing shows when macOS would show nothing. The guide now says how both reply targets are confirmed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .../Resources/Localizable.xcstrings | 154 ++++++++++++++++++ .../Sources/IslandClaudeNotice.swift | 33 ++++ .../Sources/IslandNotificationState.swift | 39 +++++ .../IslandNotificationsController.swift | 55 +++++-- .../Sources/IslandNotificationsPlugin.swift | 5 + .../Tests/IslandNotificationStateTests.swift | 20 +++ docs/plugins/island-notifications.md | 5 +- 7 files changed, 291 insertions(+), 20 deletions(-) create mode 100644 Plugins/IslandNotifications/Sources/IslandClaudeNotice.swift diff --git a/Plugins/IslandNotifications/Resources/Localizable.xcstrings b/Plugins/IslandNotifications/Resources/Localizable.xcstrings index 1b303fd37..162ea7a0b 100644 --- a/Plugins/IslandNotifications/Resources/Localizable.xcstrings +++ b/Plugins/IslandNotifications/Resources/Localizable.xcstrings @@ -232,6 +232,160 @@ } } }, + "settings.claudeCards": { + "extractionState": "manual", + "localizations": { + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "Claude 对话卡片" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Claude chat cards" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "Claude 對話卡片" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Claude-Chat-Karten" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Tarjetas de chats de Claude" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Cartes des conversations Claude" + } + }, + "pt": { + "stringUnit": { + "state": "translated", + "value": "Cartões de conversas do Claude" + } + }, + "ru": { + "stringUnit": { + "state": "translated", + "value": "Карточки чатов Claude" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "Claude チャットのカード" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "Claude 채팅 카드" + } + }, + "ar": { + "stringUnit": { + "state": "translated", + "value": "بطاقات محادثات Claude" + } + }, + "tr": { + "stringUnit": { + "state": "translated", + "value": "Claude sohbet kartları" + } + } + } + }, + "settings.claudeCards.description": { + "extractionState": "manual", + "localizations": { + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "Claude Code 对话在后台完成一轮时,MacTools 会发送一条通知,并显示为带回复栏的卡片。适用 MacTools 的通知设置、专注模式和预览设置。会读取这台 Mac 上 Claude Code 的会话记录。" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "When a Claude Code chat finishes a turn in the background, MacTools posts a notification and shows it as a card with a reply field. MacTools' notification settings, Focus and previews apply. Reads Claude Code's session logs on this Mac." + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "Claude Code 對話在背景完成一輪時,MacTools 會傳送一則通知,並顯示為帶回覆欄的卡片。適用 MacTools 的通知設定、專注模式和預覽設定。會讀取這台 Mac 上 Claude Code 的工作階段記錄。" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Beendet ein Claude Code-Chat eine Runde im Hintergrund, sendet MacTools eine Mitteilung und zeigt sie als Karte mit Antwortfeld. Es gelten die Mitteilungseinstellungen von MacTools, Fokus und Vorschauen. Liest die Sitzungsprotokolle von Claude Code auf diesem Mac." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Cuando un chat de Claude Code termina un turno en segundo plano, MacTools publica una notificación y la muestra como una tarjeta con campo de respuesta. Se aplican los ajustes de notificaciones de MacTools, Concentración y las previsualizaciones. Lee los registros de sesión de Claude Code en este Mac." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Lorsqu’une conversation Claude Code termine un tour en arrière-plan, MacTools envoie une notification et l’affiche sous forme de carte avec un champ de réponse. Les réglages de notification de MacTools, les modes de concentration et les aperçus s’appliquent. Lit les journaux de session de Claude Code sur ce Mac." + } + }, + "pt": { + "stringUnit": { + "state": "translated", + "value": "Quando uma conversa do Claude Code termina uma resposta em segundo plano, o MacTools publica uma notificação e mostra-a como um cartão com campo de resposta. Aplicam-se as definições de notificações do MacTools, o Foco e as pré-visualizações. Lê os registos de sessão do Claude Code neste Mac." + } + }, + "ru": { + "stringUnit": { + "state": "translated", + "value": "Когда чат Claude Code завершает ход в фоне, MacTools отправляет уведомление и показывает его карточкой с полем ответа. Действуют настройки уведомлений MacTools, режимы фокусирования и предпросмотр. Читает журналы сеансов Claude Code на этом Mac." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "Claude Code のチャットがバックグラウンドでターンを終えると、MacTools が通知を送信し、返信欄付きのカードとして表示します。MacTools の通知設定、集中モード、プレビューが適用されます。この Mac 上の Claude Code のセッションログを読み取ります。" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "Claude Code 채팅이 백그라운드에서 차례를 마치면 MacTools가 알림을 보내고 답장 필드가 있는 카드로 표시합니다. MacTools의 알림 설정, 집중 모드 및 미리보기가 적용됩니다. 이 Mac에 있는 Claude Code의 세션 기록을 읽습니다." + } + }, + "ar": { + "stringUnit": { + "state": "translated", + "value": "عندما تُنهي محادثة Claude Code دورًا في الخلفية، يرسل MacTools إشعارًا ويعرضه كبطاقة بها حقل للرد. تنطبق إعدادات إشعارات MacTools ووضع التركيز والمعاينات. يقرأ سجلات جلسات Claude Code على هذا الـ Mac." + } + }, + "tr": { + "stringUnit": { + "state": "translated", + "value": "Bir Claude Code sohbeti arka planda bir turu bitirdiğinde MacTools bir bildirim gönderir ve bunu yanıt alanı olan bir kart olarak gösterir. MacTools'un bildirim ayarları, Odak ve önizlemeler geçerlidir. Bu Mac'teki Claude Code oturum kayıtlarını okur." + } + } + } + }, "settings.previewLines": { "extractionState": "manual", "localizations": { diff --git a/Plugins/IslandNotifications/Sources/IslandClaudeNotice.swift b/Plugins/IslandNotifications/Sources/IslandClaudeNotice.swift new file mode 100644 index 000000000..82883c4c0 --- /dev/null +++ b/Plugins/IslandNotifications/Sources/IslandClaudeNotice.swift @@ -0,0 +1,33 @@ +import Foundation +import UserNotifications + +/// MacTools' own notice of a finished Claude turn. Claude's notices arrive without a banner, so +/// this one is what the island shows; posting it puts the turn under MacTools' notification +/// settings, Focus and preview privacy, and in Notification Centre's history, like any app's. +enum IslandClaudeNotice { + static func requestAuthorization() { + UNUserNotificationCenter.current().getNotificationSettings { settings in + guard settings.authorizationStatus == .notDetermined else { return } + UNUserNotificationCenter.current().requestAuthorization(options: [.alert]) { _, _ in } + } + } + + static func post(_ turn: IslandClaudeTurnWatcher.Turn) { + let title = turn.chat.title + // Banners carry at most 1,024 characters; the card shows the whole reply. + let body = String(turn.message.prefix(1_000)) + let thread = "claude." + turn.chat.localID + UNUserNotificationCenter.current().getNotificationSettings { settings in + switch settings.authorizationStatus { + case .authorized, .provisional, .ephemeral: break + default: return + } + let content = UNMutableNotificationContent() + content.title = title + content.body = body + content.threadIdentifier = thread + UNUserNotificationCenter.current().add(UNNotificationRequest(identifier: UUID().uuidString, + content: content, trigger: nil)) + } + } +} diff --git a/Plugins/IslandNotifications/Sources/IslandNotificationState.swift b/Plugins/IslandNotifications/Sources/IslandNotificationState.swift index 2e2322698..076888483 100644 --- a/Plugins/IslandNotifications/Sources/IslandNotificationState.swift +++ b/Plugins/IslandNotifications/Sources/IslandNotificationState.swift @@ -347,3 +347,42 @@ enum IslandMessagesChat { return String(bytes: bytes[index..<(index + length)], encoding: .utf8) } } + +/// Claude turns posted as MacTools notifications, each waiting for its banner. Only a banner that +/// shows the chat's title and the start of the reply becomes a Claude card: Focus can keep the +/// banner from showing at all, and hidden previews show neither, so both are honoured as for any app. +struct IslandClaudePosts { + struct Post: Equatable { + let chat: IslandClaudeChat + let message: String + let postedAt: TimeInterval + } + + /// How long a post waits for its banner (system uptime seconds). + static let wait: TimeInterval = 30 + private(set) var posts: [Post] = [] + + mutating func add(_ chat: IslandClaudeChat, message: String, at now: TimeInterval) { + prune(now) + posts.append(Post(chat: chat, message: message, postedAt: now)) + if posts.count > 8 { posts.removeFirst(posts.count - 8) } + } + + /// The post this banner shows, taken so no other banner can claim it. + mutating func take(title: String, body: String, at now: TimeInterval) -> Post? { + prune(now) + let shown = Self.normalized(body).trimmingCharacters(in: CharacterSet(charactersIn: "…")) + guard !shown.isEmpty, let index = posts.firstIndex(where: { + $0.chat.title == title && Self.normalized($0.message).hasPrefix(shown) + }) else { return nil } + return posts.remove(at: index) + } + + private mutating func prune(_ now: TimeInterval) { + posts.removeAll { now - $0.postedAt > Self.wait } + } + + private static func normalized(_ text: String) -> String { + text.split(whereSeparator: { $0.isWhitespace || $0.isNewline }).joined(separator: " ") + } +} diff --git a/Plugins/IslandNotifications/Sources/IslandNotificationsController.swift b/Plugins/IslandNotifications/Sources/IslandNotificationsController.swift index d0b80546d..08045481a 100644 --- a/Plugins/IslandNotifications/Sources/IslandNotificationsController.swift +++ b/Plugins/IslandNotifications/Sources/IslandNotificationsController.swift @@ -69,6 +69,7 @@ final class IslandNotificationsController { self.storage = storage self.localization = localization enabled = storage.bool(forKey: "enabled") + claudeCards = storage.bool(forKey: "claudeCards") presenter = IslandNotificationPresenter(localization: localization) let lines = storage.integer(forKey: "previewLines") if IslandNotificationPresenter.previewLineRange.contains(lines) { presenter.previewLines = lines } @@ -122,6 +123,16 @@ final class IslandNotificationsController { onStateChange?() } + /// Off by default: reading Claude Code's session logs is its own choice. + private(set) var claudeCards = false + private var claudePosts = IslandClaudePosts() + + func setClaudeCards(_ value: Bool) { + claudeCards = value; storage.set(value, forKey: "claudeCards") + if value { IslandClaudeNotice.requestAuthorization() } + refresh(); onStateChange?() + } + func setEnabled(_ value: Bool) { enabled = value; storage.set(value, forKey: "enabled") refresh(); onStateChange?() @@ -137,7 +148,8 @@ final class IslandNotificationsController { } updateTimer() guard trusted, anchor != nil else { stop(); onStateChange?(); return } - claudeTurns.start() + // Claude's session logs are read only while Claude chat cards are on. + if claudeCards { claudeTurns.start() } else { claudeTurns.stop() } if !loggedHistoryAccess { loggedHistoryAccess = true let logger = logger @@ -259,19 +271,30 @@ final class IslandNotificationsController { updateTimer() } - /// A Claude chat finished a turn while the user is elsewhere: show Claude's reply as a card. + /// A Claude chat finished a turn while the user is elsewhere. Claude posts its own notices without + /// a banner, so MacTools posts one and its banner becomes the card: MacTools' notification + /// settings, Focus and hidden previews then apply as for any app. private func receive(_ turn: IslandClaudeTurnWatcher.Turn) { - guard active, enabled, trusted, anchor != nil, !fallingBack, !centerOpen, + guard active, enabled, claudeCards, trusted, anchor != nil, NSWorkspace.shared.frontmostApplication?.bundleIdentifier != IslandClaudeReply.bundleIdentifier else { return } - // There is no system banner behind this card; the system-wide element is only a placeholder. - let placeholder = AXUIElementCreateSystemWide() - let notification = IslandNotification(element: placeholder, window: placeholder, originalPosition: .zero, - style: .temporary, title: turn.chat.title, body: turn.message, - identityHints: [IslandClaudeReply.bundleIdentifier]) - notification.claudeChat = turn.chat - notification.resolveIdentity() - record(notification) - enqueue([notification]) + claudePosts.add(turn.chat, message: turn.message, at: ProcessInfo.processInfo.systemUptime) + IslandClaudeNotice.post(turn) + } + + /// A banner, or MacTools' own notice of a Claude turn: then the card is that chat's, with the + /// whole reply (the banner showed its preview) and a reply field. + private func makeNotification(_ group: IslandAXWindowSnapshot.Group, window: AXUIElement, + original: CGPoint) -> IslandNotification { + if let post = claudePosts.take(title: group.title, body: group.body, at: ProcessInfo.processInfo.systemUptime) { + let notification = IslandNotification(element: group.element, window: window, originalPosition: original, + style: group.style, title: post.chat.title, body: post.message, + identityHints: [IslandClaudeReply.bundleIdentifier] + group.hints) + notification.claudeChat = post.chat + return notification + } + return IslandNotification(element: group.element, window: window, originalPosition: original, + style: group.style, title: group.title, body: group.body, + identityHints: group.hints, lineCount: group.lines) } private func receive(_ window: IslandAXElement) { @@ -362,9 +385,7 @@ final class IslandNotificationsController { ?? seen.last(where: { CFEqual($0.element, group.element) }), old.title != group.title || old.body != group.body else { continue } let original = movedIndex(window.value).map { moved[$0].original } ?? old.originalPosition - let notification = IslandNotification(element: group.element, window: window.value, originalPosition: original, - style: group.style, title: group.title, body: group.body, - identityHints: group.hints, lineCount: group.lines) + let notification = makeNotification(group, window: window.value, original: original) notification.label = group.label notification.resolveIdentity() hidden.removeAll { $0 === old } @@ -423,9 +444,7 @@ final class IslandNotificationsController { remember(window.value, original: original, taken: true) var arrivals: [IslandNotification] = [] for group in fresh { - let notification = IslandNotification(element: group.element, window: window.value, originalPosition: original, - style: group.style, title: group.title, body: group.body, - identityHints: group.hints, lineCount: group.lines) + let notification = makeNotification(group, window: window.value, original: original) notification.label = group.label hidden.append(notification) seen.append(notification) diff --git a/Plugins/IslandNotifications/Sources/IslandNotificationsPlugin.swift b/Plugins/IslandNotifications/Sources/IslandNotificationsPlugin.swift index 3dd8cc04b..5757937bb 100644 --- a/Plugins/IslandNotifications/Sources/IslandNotificationsPlugin.swift +++ b/Plugins/IslandNotifications/Sources/IslandNotificationsPlugin.swift @@ -82,6 +82,10 @@ final class IslandNotificationsPlugin: MacToolsPlugin { PluginSettingsSection(id: "notifications", title: localization.string("metadata.title", defaultValue: "灵动岛通知"), systemImage: "bell.badge.fill", rows: [ PluginSettingsRow(id: "enabled", title: localization.string("settings.enabled", defaultValue: "启用灵动岛通知"), description: status, systemImage: "bell.badge.fill", control: .toggle(isOn: controller.enabled)), + PluginSettingsRow(id: "claudeCards", title: localization.string("settings.claudeCards", defaultValue: "Claude 对话卡片"), + description: localization.string("settings.claudeCards.description", + defaultValue: "Claude Code 对话在后台完成一轮时,MacTools 会发送一条通知,并显示为带回复栏的卡片。适用 MacTools 的通知设置、专注模式和预览设置。会读取这台 Mac 上 Claude Code 的会话记录。"), + systemImage: "bubble.left.and.text.bubble.right", control: .toggle(isOn: controller.claudeCards)), PluginSettingsRow(id: "previewLines", title: localization.string("settings.previewLines", defaultValue: "预览行数"), description: localization.string("settings.previewLines.description", defaultValue: "展开前显示的消息行数。向下滚动卡片可查看全文。"), systemImage: "text.alignleft", @@ -118,6 +122,7 @@ final class IslandNotificationsPlugin: MacToolsPlugin { func handleSettingsAction(_ action: PluginSettingsAction) { switch action { case let .setBoolean(id, value) where id == "enabled": setEnabled(value) + case let .setBoolean(id, value) where id == "claudeCards": controller.setClaudeCards(value) case let .setSelection(id, option) where id == "previewLines": Int(option).map(controller.setPreviewLines) default: break } diff --git a/Plugins/IslandNotifications/Tests/IslandNotificationStateTests.swift b/Plugins/IslandNotifications/Tests/IslandNotificationStateTests.swift index 737fad2d4..4585348d3 100644 --- a/Plugins/IslandNotifications/Tests/IslandNotificationStateTests.swift +++ b/Plugins/IslandNotifications/Tests/IslandNotificationStateTests.swift @@ -119,4 +119,24 @@ final class IslandNotificationStateTests: XCTestCase { XCTAssertEqual(IslandClaudeTurnWatcher.desktopChat(in: [card, other]) { $0.cliSessionIDs.contains("cli-b") }?.localID, "local_b") XCTAssertNil(IslandClaudeTurnWatcher.desktopChat(in: [other]) { $0.localID == "local_a" }) } + + func testOnlyTheBannerShowingAClaudeTurnBecomesItsCard() { + var posts = IslandClaudePosts() + let chat = IslandClaudeChat(localID: "local_a", title: "Fix the build") + posts.add(chat, message: "Done. The build passes:\n\nall 42 tests green.", at: 100) + // A banner with its preview hidden shows neither the chat's title nor the reply. + XCTAssertNil(posts.take(title: "MacTools", body: "Notification", at: 101)) + // Another app's banner with the same title is not this turn. + XCTAssertNil(posts.take(title: "Fix the build", body: "Something else entirely", at: 101)) + // The banner shortens and rewraps the reply; it still names the turn, once. + XCTAssertEqual(posts.take(title: "Fix the build", body: "Done. The build passes: all 42…", at: 102)?.chat, chat) + XCTAssertNil(posts.take(title: "Fix the build", body: "Done. The build passes: all 42…", at: 102)) + } + + func testAClaudeTurnWhoseBannerNeverCameExpires() { + var posts = IslandClaudePosts() + posts.add(IslandClaudeChat(localID: "local_a", title: "Notes"), message: "Saved.", at: 0) + // Focus kept the banner from showing; a later banner with the same text is not this turn. + XCTAssertNil(posts.take(title: "Notes", body: "Saved.", at: IslandClaudePosts.wait + 1)) + } } diff --git a/docs/plugins/island-notifications.md b/docs/plugins/island-notifications.md index 722a71e44..2b2d4ace8 100644 --- a/docs/plugins/island-notifications.md +++ b/docs/plugins/island-notifications.md @@ -12,14 +12,15 @@ Shows macOS notifications as cards that grow out of the camera island on the Mac The plugin watches Notification Centre's banner windows through Accessibility. When a banner appears, its window is moved off screen before it draws, and the plugin shows its own non-activating card in its place. -Notification Centre stays the record. Every notification still goes into its history, and Focus, notification styles and preview privacy apply before a banner exists. The plugin never changes notification settings and never reads Notification Centre's database. +Notification Centre stays the record. Every notification still goes into its history, and Focus, notification styles and preview privacy apply before a banner exists, so the island shows only what macOS would show. The plugin never changes notification settings and never reads Notification Centre's database. Cards: - **Lifetime:** a temporary card stays for five seconds, paused while it is hovered, held open, being replied to, or under the MacTools hover panel. A persistent alert waits until it is dismissed. - **Several notifications:** one card shows at a time. A newer temporary notification replaces an idle card after one second; a held or busy card is never interrupted. - **Gestures:** swipe up to dismiss. Pull down to open the full message, or to hold a card that has nothing more to show. A click opens the exact item through the banner's own action, and Esc closes the card. -- **Replies:** Messages cards reply to the conversation found in Messages' history, never to one matched by name. Claude cards follow Claude Code's session logs and type the reply into that chat, without bringing Claude forward. +- **Replies:** Messages cards reply to the conversation found in Messages' history among messages received around the banner, never to one matched by name. Claude cards type the reply into their chat without bringing Claude forward; the chat is checked again by its id and on screen just before sending, and another chat with the same title refuses the reply. +- **Claude chat cards** (off by default): Claude posts its own notices without a banner, so with this on the plugin reads Claude Code's session logs and, when a chat finishes a turn while Claude is in the background, MacTools posts a notification of its own. Its banner becomes the card. MacTools' notification settings, Focus and preview privacy apply to it, it stays in Notification Centre's history, and nothing shows when macOS would show nothing. - **Live Activities:** with a compact system Live Activity showing, the card splits below it. With an expanded or unreadable activity, banners stay native. Notification text never leaves the Mac and is never written to disk. The logs record steps only. From 695dce15525fbe74dac7e959443e8eb03ff9f28f Mon Sep 17 00:00:00 2001 From: Niko Eltarenko <61957857+nikoelt@users.noreply.github.com> Date: Wed, 18 Nov 2026 19:56:09 +1000 Subject: [PATCH 16/29] feat(island-notifications): finish the reply's send and close Pressing Send lifts the text out of the field, as a sent message leaves the Messages field, and the button turns to a spinner; the field keeps its height, so the card doesn't move. Sent shows a green check, then the card folds straight back into the island: its content shrinks toward the island and blurs while it fades, and stays inside the surface, which it used to spill past. A send that fails brings the text back. The keyboard now returns to the app once the card has gone, instead of the card blinking out and back as it closed, and the error line gets its own room instead of covering the message. The shared morph view gains an opt-in, off by default, that keeps its content inside the surface at every size. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .../Sources/IslandNotificationPresenter.swift | 138 ++++++++++++++++-- .../IslandNotificationsController.swift | 7 +- Sources/PluginSupport/NotchMorphSurface.swift | 6 +- 3 files changed, 139 insertions(+), 12 deletions(-) diff --git a/Plugins/IslandNotifications/Sources/IslandNotificationPresenter.swift b/Plugins/IslandNotifications/Sources/IslandNotificationPresenter.swift index 29f340033..94b1f1028 100644 --- a/Plugins/IslandNotifications/Sources/IslandNotificationPresenter.swift +++ b/Plugins/IslandNotifications/Sources/IslandNotificationPresenter.swift @@ -105,7 +105,8 @@ final class IslandNotificationPresenter { updateGeometry(height: compactSize.height) // Room for the reply field to grow to its line limit without resizing the window. windowSizeFrame = frame(height: replyable - ? max(fullSize.height, min(naturalFullHeight + Layout.replyMaxExtra, maxCardHeight)) : fullSize.height) + ? max(fullSize.height, min(naturalFullHeight + Layout.replyMaxExtra + Layout.replyStatusHeight + 4, maxCardHeight)) + : fullSize.height) let card = IslandNotificationCard(notification: notification, localization: localization, previewLines: previewLines, replyable: replyable, islandCenter: islandCenter, islandBottom: islandBottom, @@ -134,6 +135,8 @@ final class IslandNotificationPresenter { root.addSubview(split) } else { let surface = NotchMorphView(content: card) + // The card's text never shows past the surface as it folds back into the island. + surface.clipsContentToSurface = true self.surface = surface root.addSubview(surface) } @@ -252,6 +255,8 @@ final class IslandNotificationPresenter { func setReplySending() { card?.setReplySending() } func showReplySent() { card?.showReplySent() } + /// Typing stops in a card that is about to go; the keyboard returns to the app as it closes. + func stopEditing() { card?.endEditing() } func showReplyError(_ message: String) { card?.showReplyError(message) } /// Hands typing back to the app the user was in. MacTools never became active, so @@ -374,6 +379,10 @@ final class IslandNotificationPresenter { let height = NotchMorphMetrics.lerp(compactSize.height, fullSize.height, max(size.value, 0)) if metrics?.contentSize.height != height { updateGeometry(height: height) } card?.expansion = CGFloat(min(max(size.value, 0), 1)) + // Going back into the island, the content shrinks toward it and blurs as it fades, the way + // the Dynamic Island folds its content away; opening, it is left exactly as laid out. + let folding = model.target < 0.5 && completion != nil && !reduceMotion + card?.setFolding(folding ? CGFloat(1 - min(max(model.height.value, 0), 1)) : 0) guard let metrics else { return } let current = frame(height: height).offsetBy(dx: -windowSizeFrame.minX, dy: -windowSizeFrame.minY) let morph: NSView? = splitSurface ?? surface @@ -659,8 +668,8 @@ private final class IslandNotificationCard: NSView { reply.router = self reply.onCancel = { [weak self] in self?.onCancelReply?() } reply.onHeightChange = { [weak self] height in - self?.onReplyHeightChange?(height - Layout.replyHeight) - self?.needsLayout = true + self?.replyFieldExtra = height - Layout.replyHeight + self?.reportReplyHeight() } reply.isHidden = true addSubview(reply, positioned: .below, relativeTo: close) @@ -793,18 +802,57 @@ private final class IslandNotificationCard: NSView { func endEditing() { reply?.endEditing() } func focusReply() { reply?.focus() } + + private var folding: CGFloat = 0 + + /// 0 while the card is shown; toward 1 as it folds into the island: it shrinks toward the + /// island at its top and blurs, while the surface fades it. + func setFolding(_ progress: CGFloat) { + let progress = min(max(progress, 0), 1) + guard progress != folding, let layer else { return } + folding = progress + CATransaction.begin() + CATransaction.setDisableActions(true) + let scale = 1 - 0.12 * progress + // About the top centre, where the island is; the card's layer has its origin at the top left. + var transform = CATransform3DMakeTranslation(bounds.midX, 0, 0) + transform = CATransform3DScale(transform, scale, scale, 1) + layer.sublayerTransform = CATransform3DTranslate(transform, -bounds.midX, 0, 0) + if progress > 0 { + if layer.filters == nil { + layerUsesCoreImageFilters = true + let blur = CIFilter(name: "CIGaussianBlur") + blur?.name = "fold" + layer.filters = blur.map { [$0] } + } + layer.setValue(10 * progress, forKeyPath: "filters.fold.inputRadius") + } else { + layer.filters = nil + } + CATransaction.commit() + } + /// What the reply area adds to the card: the field's extra lines, and the status line while + /// it shows, so the status never sits on the message. + private var replyFieldExtra: CGFloat = 0 + private func reportReplyHeight() { + let status = replyStatus.isHidden ? 0 : Layout.replyStatusHeight + 4 + onReplyHeightChange?(replyFieldExtra + status) + needsLayout = true + } + func setReplySending() { replyStatus.isHidden = true reply?.setSending(true) - needsLayout = true + reportReplyHeight() } func showReplySent() { reply?.showSent(localization.string("reply.sent", defaultValue: "已发送")) } + func showReplyError(_ message: String) { reply?.setSending(false) replyStatus.stringValue = message replyStatus.toolTip = message replyStatus.isHidden = false - needsLayout = true + reportReplyHeight() } func updateCount(_ waiting: Int) { @@ -969,6 +1017,7 @@ private final class IslandReplyBar: NSView, NSTextViewDelegate { private let textView = TextView() private let placeholder = NSTextField(labelWithString: "") private let send = NSButton() + private let spinner = NSProgressIndicator() private var isSending = false private(set) var preferredHeight = IslandNotificationCard.Layout.replyHeight var onSend: ((String) -> Void)? @@ -1027,7 +1076,12 @@ private final class IslandReplyBar: NSView, NSTextViewDelegate { send.action = #selector(sendTapped) send.toolTip = sendLabel send.setAccessibilityLabel(sendLabel) - for view in [scroll, placeholder, send] as [NSView] { addSubview(view) } + spinner.style = .spinning + spinner.controlSize = .small + spinner.isDisplayedWhenStopped = false + spinner.appearance = NSAppearance(named: .darkAqua) + spinner.wantsLayer = true + for view in [scroll, placeholder, send, spinner] as [NSView] { addSubview(view) } updateSend() } @@ -1043,6 +1097,7 @@ private final class IslandReplyBar: NSView, NSTextViewDelegate { // The send button stays at the bottom right, beside the last line (iOS). send.frame = CGRect(x: bounds.width - 4 - button, y: h - 4 - button, width: button, height: button) send.layer?.cornerRadius = button / 2 + spinner.frame = send.frame.insetBy(dx: 4, dy: 4) let textFrame = CGRect(x: 14, y: Self.verticalPadding, width: send.frame.minX - 20, height: max(0, h - Self.verticalPadding * 2)) if scroll.frame != textFrame { @@ -1069,25 +1124,90 @@ private final class IslandReplyBar: NSView, NSTextViewDelegate { if window?.firstResponder === textView { window?.makeFirstResponder(nil) } } + /// Sending: the text lifts out of the field the moment Send is pressed, as a sent message + /// leaves the Messages field, and the button turns to a spinner. The field keeps its height, + /// so the card doesn't move. A send that fails brings the text back as it was. func setSending(_ sending: Bool) { + guard sending != isSending else { return } isSending = sending textView.isEditable = !sending - textView.textColor = sending ? NSColor.white.withAlphaComponent(0.5) : .white + if sending { + liftText() + textView.alphaValue = 0 + crossfade(send, to: 0) + spinner.alphaValue = 1 + spinner.startAnimation(nil) + } else { + spinner.stopAnimation(nil) + crossfade(send, to: 1) + textView.alphaValue = 0 + NSAnimationContext.runAnimationGroup { context in + context.duration = 0.22 + textView.animator().alphaValue = 1 + } + } updateSend() } + /// The text as drawn, rising and fading out of the field. + private func liftText() { + guard let layer, !trimmed.isEmpty, !NSWorkspace.shared.accessibilityDisplayShouldReduceMotion, + let image = bitmap(of: scroll) else { return } + let lifted = CALayer() + lifted.contents = image + lifted.contentsScale = window?.backingScaleFactor ?? 2 + lifted.frame = scroll.frame + layer.addSublayer(lifted) + let duration = 0.34 + let curve = CAMediaTimingFunction(controlPoints: 0.2, 0.8, 0.2, 1) + let rise = CABasicAnimation(keyPath: "position.y") + // The bar is flipped: up is toward a smaller y. + rise.byValue = -14 + let fade = CABasicAnimation(keyPath: "opacity") + fade.fromValue = 1; fade.toValue = 0 + let group = CAAnimationGroup() + group.animations = [rise, fade] + group.duration = duration + group.timingFunction = curve + lifted.opacity = 0 + CATransaction.begin() + CATransaction.setCompletionBlock { lifted.removeFromSuperlayer() } + lifted.add(group, forKey: "lift") + CATransaction.commit() + } + + private func bitmap(of view: NSView) -> CGImage? { + guard view.bounds.width > 0, view.bounds.height > 0, + let rep = view.bitmapImageRepForCachingDisplay(in: view.bounds) else { return nil } + view.cacheDisplay(in: view.bounds, to: rep) + return rep.cgImage + } + + private func crossfade(_ view: NSView, to alpha: CGFloat) { + NSAnimationContext.runAnimationGroup { context in + context.duration = 0.18 + view.animator().alphaValue = alpha + } + } + + /// Sent: the spinner becomes a green check and "Sent" settles into the empty field, in place. func showSent(_ label: String) { isSending = true textView.isEditable = false - textView.string = "" + spinner.stopAnimation(nil) placeholder.stringValue = label placeholder.font = NSFont.systemFont(ofSize: 14, weight: .medium) placeholder.textColor = NSColor.white.withAlphaComponent(0.75) + placeholder.alphaValue = 0 placeholder.isHidden = false send.image = NSImage(systemSymbolName: "checkmark", accessibilityDescription: label) send.layer?.backgroundColor = NSColor.systemGreen.cgColor send.isEnabled = false - updateHeight() + NSAnimationContext.runAnimationGroup { context in + context.duration = 0.2 + send.animator().alphaValue = 1 + placeholder.animator().alphaValue = 1 + } NSAccessibility.post(element: self, notification: .announcementRequested, userInfo: [.announcement: label, .priority: NSAccessibilityPriorityLevel.high.rawValue]) } diff --git a/Plugins/IslandNotifications/Sources/IslandNotificationsController.swift b/Plugins/IslandNotifications/Sources/IslandNotificationsController.swift index 08045481a..76928aabb 100644 --- a/Plugins/IslandNotifications/Sources/IslandNotificationsController.swift +++ b/Plugins/IslandNotifications/Sources/IslandNotificationsController.swift @@ -695,10 +695,13 @@ final class IslandNotificationsController { logger.notice("reply outcome=\(String(describing: outcome), privacy: .public)") switch outcome { case .sent: + // The check shows for a moment, then the card folds straight back into the island. + // Typing stops now; the keyboard returns to the app once the card has gone, so the + // card never blinks out and back while it closes. presenter.showReplySent() - try? await Task.sleep(for: .milliseconds(900)) + presenter.stopEditing() + try? await Task.sleep(for: .milliseconds(450)) guard self.generation == generation, queue.current === notification else { return } - presenter.returnKeyboard() finishCurrent(dismissNative: true, reason: "replied") case .noConversation: presenter.showReplyError(localization.string("reply.error.conversation", defaultValue: "找不到这个对话。点按卡片以打开“信息”。")) diff --git a/Sources/PluginSupport/NotchMorphSurface.swift b/Sources/PluginSupport/NotchMorphSurface.swift index 7a4269eba..8c4f73986 100644 --- a/Sources/PluginSupport/NotchMorphSurface.swift +++ b/Sources/PluginSupport/NotchMorphSurface.swift @@ -258,6 +258,10 @@ final class NotchMorphView: NSView { private let surfaceMask = CAShapeLayer() private weak var content: NSView? private var surfacePath: CGPath? + /// Keeps the content inside the surface at every size, so nothing shows beyond its edge while + /// the surface folds back over content still fading. Off by default: the surface then clips + /// only while it reveals part of its content. + var clipsContentToSurface = false init(content: NSView) { self.content = content @@ -334,7 +338,7 @@ final class NotchMorphView: NSView { } content.alphaValue = CGFloat(min(max(model.contentOpacity, 0), 1)) // While the surface is shorter than its content, the content ends where the surface does. - if metrics.revealedContentSize != nil { + if metrics.revealedContentSize != nil || clipsContentToSurface { content.wantsLayer = true let mask = (content.layer?.mask as? CAShapeLayer) ?? CAShapeLayer() mask.frame = content.bounds From 5112db548b9375fbf5cd2737692903afe06f91e4 Mon Sep 17 00:00:00 2001 From: Niko Eltarenko <61957857+nikoelt@users.noreply.github.com> Date: Wed, 18 Nov 2026 20:20:23 +1000 Subject: [PATCH 17/29] fix(island-notifications): send multi-line replies cleanly A reply of several lines left a tall empty field behind it, with "Sent" at the top and the check stranded at the bottom. Now the reply rises and fades inside the field, then the field shrinks back to one line as the Messages field does, and the card shrinks with it on the same spring, so "Sent" and the check share a one-line field. Growing a line while typing follows the same spring. A send that fails brings the field back to its text's height. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .../Sources/IslandNotificationPresenter.swift | 60 ++++++++++++++----- 1 file changed, 46 insertions(+), 14 deletions(-) diff --git a/Plugins/IslandNotifications/Sources/IslandNotificationPresenter.swift b/Plugins/IslandNotifications/Sources/IslandNotificationPresenter.swift index 94b1f1028..f9a600b88 100644 --- a/Plugins/IslandNotifications/Sources/IslandNotificationPresenter.swift +++ b/Plugins/IslandNotifications/Sources/IslandNotificationPresenter.swift @@ -95,6 +95,7 @@ final class IslandNotificationPresenter { naturalFullHeight = pill && !replyable ? compactSize.height : Layout.expandedHeight(islandBottom: islandBottom, body: notification.displayBody, maxHeight: .greatestFiniteMagnitude, reply: replyable) replyExtra = 0 + shownReplyExtra = NotchMorphModel.Spring() fullSize = CGSize(width: Layout.width, height: fullHeight) self.anchor = anchor self.activity = activity @@ -194,16 +195,23 @@ final class IslandNotificationPresenter { private var maxCardHeight: CGFloat = 0 /// Extra height of a reply field grown past one line. private var replyExtra: CGFloat = 0 + /// The reply area's extra height as drawn, in points: it springs to `replyExtra`, so the field + /// and the card grow and shrink together, as the Messages field does. + private var shownReplyExtra = NotchMorphModel.Spring() private var fullHeight: CGFloat { - max(compactSize.height, min(naturalFullHeight + replyExtra, max(maxCardHeight, compactSize.height))) + max(compactSize.height, min(naturalFullHeight + CGFloat(shownReplyExtra.value), max(maxCardHeight, compactSize.height))) } - /// The reply field grew or shrank by a line: the card follows, its top staying put. + /// The reply field grew or shrank by a line, or emptied as a reply left it: the card follows, + /// its top staying put. private func replyHeightChanged(_ extra: CGFloat) { guard extra != replyExtra else { return } replyExtra = extra - fullSize.height = fullHeight - render() + if reduceMotion || window == nil { + shownReplyExtra = NotchMorphModel.Spring(value: Double(extra)) + fullSize.height = fullHeight + render() + } else { startLink() } } private func frame(height: CGFloat) -> CGRect { @@ -369,8 +377,10 @@ final class IslandNotificationPresenter { while remaining > 0 { let slice = min(remaining, 1.0 / 480.0) size.step(toward: sizeTarget, response: 0.42, dampingRatio: 0.84, dt: slice) + shownReplyExtra.step(toward: Double(replyExtra), response: 0.34, dampingRatio: 0.9, dt: slice) remaining -= slice } + fullSize.height = fullHeight render(); finish() } @@ -379,6 +389,7 @@ final class IslandNotificationPresenter { let height = NotchMorphMetrics.lerp(compactSize.height, fullSize.height, max(size.value, 0)) if metrics?.contentSize.height != height { updateGeometry(height: height) } card?.expansion = CGFloat(min(max(size.value, 0), 1)) + card?.shownReplyExtra = CGFloat(shownReplyExtra.value) // Going back into the island, the content shrinks toward it and blurs as it fades, the way // the Dynamic Island folds its content away; opening, it is left exactly as laid out. let folding = model.target < 0.5 && completion != nil && !reduceMotion @@ -393,7 +404,10 @@ final class IslandNotificationPresenter { } private func finish() { - guard model.isSettled, size.isSettled(at: sizeTarget) else { return } + guard model.isSettled, size.isSettled(at: sizeTarget), + abs(shownReplyExtra.value - Double(replyExtra)) < 0.25, abs(shownReplyExtra.velocity) < 1 else { return } + shownReplyExtra = NotchMorphModel.Spring(value: Double(replyExtra)) + fullSize.height = fullHeight model.snapToTarget() size = NotchMorphModel.Spring(value: sizeTarget) if sizeTarget == 0 { card?.setExpandedMode(false) } @@ -740,7 +754,9 @@ private final class IslandNotificationCard: NSView { // The reply field sits at the bottom of the expanded card and fades in as it opens. var bottomLimit = bounds.height - Layout.bottomPadding if let reply { - let replyHeight = reply.preferredHeight + // The field as drawn, following the card's spring rather than jumping to its new height. + let status = replyStatus.isHidden ? 0 : Layout.replyStatusHeight + 4 + let replyHeight = Layout.replyHeight + max(0, shownReplyExtra - status) let replyRect = CGRect(x: 20, y: bounds.height - Layout.replyBottom - replyHeight, width: bounds.width - 40, height: replyHeight) reply.frame = replyRect @@ -834,6 +850,10 @@ private final class IslandNotificationCard: NSView { /// What the reply area adds to the card: the field's extra lines, and the status line while /// it shows, so the status never sits on the message. private var replyFieldExtra: CGFloat = 0 + /// The reply area's extra height as the presenter draws it this frame. + var shownReplyExtra: CGFloat = 0 { + didSet { if oldValue != shownReplyExtra { needsLayout = true } } + } private func reportReplyHeight() { let status = replyStatus.isHidden ? 0 : Layout.replyStatusHeight + 4 onReplyHeightChange?(replyFieldExtra + status) @@ -1034,6 +1054,8 @@ private final class IslandReplyBar: NSView, NSTextViewDelegate { init(placeholder text: String, sendLabel: String) { super.init(frame: .zero) wantsLayer = true + // A reply lifting out of the field stays inside it. + layer?.masksToBounds = true layer?.backgroundColor = NSColor.white.withAlphaComponent(0.12).cgColor layer?.cornerCurve = .continuous layer?.borderWidth = 0.5 @@ -1132,7 +1154,9 @@ private final class IslandReplyBar: NSView, NSTextViewDelegate { isSending = sending textView.isEditable = !sending if sending { - liftText() + // The reply leaves the field first; then the field empties back to one line. The text + // stays in it unseen, so a send that fails can bring it back. + liftText { [weak self] in self?.collapseWhileSending() } textView.alphaValue = 0 crossfade(send, to: 0) spinner.alphaValue = 1 @@ -1140,6 +1164,7 @@ private final class IslandReplyBar: NSView, NSTextViewDelegate { } else { spinner.stopAnimation(nil) crossfade(send, to: 1) + updateHeight() textView.alphaValue = 0 NSAnimationContext.runAnimationGroup { context in context.duration = 0.22 @@ -1149,20 +1174,26 @@ private final class IslandReplyBar: NSView, NSTextViewDelegate { updateSend() } - /// The text as drawn, rising and fading out of the field. - private func liftText() { + private func collapseWhileSending() { + guard isSending, preferredHeight != IslandNotificationCard.Layout.replyHeight else { return } + preferredHeight = IslandNotificationCard.Layout.replyHeight + onHeightChange?(preferredHeight) + } + + /// The text as drawn, rising and fading out of the field, then `done`. + private func liftText(then done: @escaping () -> Void) { guard let layer, !trimmed.isEmpty, !NSWorkspace.shared.accessibilityDisplayShouldReduceMotion, - let image = bitmap(of: scroll) else { return } + let image = bitmap(of: scroll) else { done(); return } let lifted = CALayer() lifted.contents = image lifted.contentsScale = window?.backingScaleFactor ?? 2 lifted.frame = scroll.frame layer.addSublayer(lifted) - let duration = 0.34 + let duration = 0.26 let curve = CAMediaTimingFunction(controlPoints: 0.2, 0.8, 0.2, 1) let rise = CABasicAnimation(keyPath: "position.y") // The bar is flipped: up is toward a smaller y. - rise.byValue = -14 + rise.byValue = -12 let fade = CABasicAnimation(keyPath: "opacity") fade.fromValue = 1; fade.toValue = 0 let group = CAAnimationGroup() @@ -1171,7 +1202,7 @@ private final class IslandReplyBar: NSView, NSTextViewDelegate { group.timingFunction = curve lifted.opacity = 0 CATransaction.begin() - CATransaction.setCompletionBlock { lifted.removeFromSuperlayer() } + CATransaction.setCompletionBlock { lifted.removeFromSuperlayer(); done() } lifted.add(group, forKey: "lift") CATransaction.commit() } @@ -1224,7 +1255,8 @@ private final class IslandReplyBar: NSView, NSTextViewDelegate { /// One line up to `replyMaxLines`; past that the field keeps its height and scrolls. private func updateHeight() { - guard let container = textView.textContainer, let manager = textView.layoutManager else { return } + // A reply on its way has left the field, which stays at one line until it comes back. + guard !isSending, let container = textView.textContainer, let manager = textView.layoutManager else { return } manager.ensureLayout(for: container) let line = IslandNotificationCard.Layout.replyLineHeight let content = max(line, ceil(manager.usedRect(for: container).height)) From 3246120eb28e73c7b54cf7bff6ec16c6b0e318c9 Mon Sep 17 00:00:00 2001 From: Niko Eltarenko <61957857+nikoelt@users.noreply.github.com> Date: Wed, 18 Nov 2026 20:23:04 +1000 Subject: [PATCH 18/29] fix(island-notifications): resize the reply field at once while typing Each new line made the field and card spring to their new height while the text kept the cursor in view, so the text bounced up and down. Lines added or removed while typing take effect at once again, as in Messages; only the field emptying back to one line after Send is animated. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .../Sources/IslandNotificationPresenter.swift | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/Plugins/IslandNotifications/Sources/IslandNotificationPresenter.swift b/Plugins/IslandNotifications/Sources/IslandNotificationPresenter.swift index f9a600b88..e84a4c38d 100644 --- a/Plugins/IslandNotifications/Sources/IslandNotificationPresenter.swift +++ b/Plugins/IslandNotifications/Sources/IslandNotificationPresenter.swift @@ -203,11 +203,13 @@ final class IslandNotificationPresenter { } /// The reply field grew or shrank by a line, or emptied as a reply left it: the card follows, - /// its top staying put. + /// its top staying put. Lines added or removed while typing take effect at once, as in Messages, + /// so the text never moves under the cursor; only the field emptying after Send is animated. private func replyHeightChanged(_ extra: CGFloat) { guard extra != replyExtra else { return } replyExtra = extra - if reduceMotion || window == nil { + let emptying = card?.isSendingReply == true && Double(extra) < shownReplyExtra.value + if reduceMotion || window == nil || !emptying { shownReplyExtra = NotchMorphModel.Spring(value: Double(extra)) fullSize.height = fullHeight render() From 5cb6a5fc11075180e21f2c136fd1ee31d208fe82 Mon Sep 17 00:00:00 2001 From: Niko Eltarenko <61957857+nikoelt@users.noreply.github.com> Date: Wed, 18 Nov 2026 20:32:20 +1000 Subject: [PATCH 19/29] fix(island-notifications): stop re-registering Live Activity observers Every read of MenuBarAgent removed and re-added all of its Accessibility subscriptions, and re-registering made MenuBarAgent report changes that started another read. Subscriptions now change only for elements that appeared or went, changes are coalesced to at most two reads a second, a hidden card checks its place at most twice a second, and MenuBarAgent is found once instead of scanning every running app on each read. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .../Sources/IslandLiveActivityObserver.swift | 35 +++++++++++++------ .../IslandNotificationsController.swift | 8 ++++- 2 files changed, 31 insertions(+), 12 deletions(-) diff --git a/Plugins/IslandNotifications/Sources/IslandLiveActivityObserver.swift b/Plugins/IslandNotifications/Sources/IslandLiveActivityObserver.swift index 9c256c0fc..b6cd909e4 100644 --- a/Plugins/IslandNotifications/Sources/IslandLiveActivityObserver.swift +++ b/Plugins/IslandNotifications/Sources/IslandLiveActivityObserver.swift @@ -21,6 +21,12 @@ final class IslandLiveActivityObserver { private var generation = 0 private var reading: Task<IslandLiveActivityPlacement, Never>? private var change: DispatchWorkItem? + /// MenuBarAgent, found once and kept while it runs: finding it checks every running app's path. + private var agent: NSRunningApplication? + /// When the last change was handed on (system uptime). Changes arriving faster are coalesced, so + /// a Live Activity that redraws constantly costs at most two reads a second. + private var lastChange: TimeInterval = 0 + private static let minimumChangeInterval: TimeInterval = 0.5 nonisolated private static let logger = Logger(subsystem: "MacTools.IslandNotifications", category: "liveactivity") nonisolated private static let messagingTimeout: Float = 0.2 @@ -30,7 +36,10 @@ final class IslandLiveActivityObserver { } func refresh(anchor: CGRect) async -> IslandLiveActivityPlacement { - guard let app = NSWorkspace.shared.runningApplications.first(where: Self.isMenuBarAgent) else { + if agent?.isTerminated != false { + agent = NSWorkspace.shared.runningApplications.first(where: Self.isMenuBarAgent) + } + guard let app = agent else { Self.logger.debug("appFound=false decision=native reason=menubaragent-not-found") return .native } @@ -66,14 +75,10 @@ final class IslandLiveActivityObserver { _ = AXObserverCreate(pid, islandActivityCallback, &observer) active = IslandActivitySession(pid: pid, application: application, observer: observer) } - // Replace element subscriptions rather than retaining stale AX handles. - if let observer = active.observer { - for element in active.observed { - for name in Self.notifications { - AXObserverRemoveNotification(observer, element, name as CFString) - } - } - } + // Subscriptions change only where the elements did. Registering again for elements already + // watched makes MenuBarAgent report changes that start another read, so a read never + // re-registers what it already watches. + let previous = active.observed active.observed = [active.application] var frames: [CGRect?] = [] var complete = true @@ -144,7 +149,11 @@ final class IslandLiveActivityObserver { } Self.logger.debug("activities=\(frames.count, privacy: .public) nodes=\(250 - budget, privacy: .public) complete=\(complete, privacy: .public)") if let observer = active.observer { - for element in active.observed { + let contains = { (list: [AXUIElement], element: AXUIElement) in list.contains { CFEqual($0, element) } } + for element in previous where !contains(active.observed, element) { + for name in Self.notifications { AXObserverRemoveNotification(observer, element, name as CFString) } + } + for element in active.observed where !contains(previous, element) { for name in Self.notifications { _ = AXObserverAddNotification(observer, element, name as CFString, UnsafeMutableRawPointer(bitPattern: context)) @@ -187,10 +196,13 @@ final class IslandLiveActivityObserver { let work = DispatchWorkItem { [weak self] in guard let self else { return } self.change = nil + self.lastChange = ProcessInfo.processInfo.systemUptime self.onChange?() } change = work - DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(20), execute: work) + let sinceLast = ProcessInfo.processInfo.systemUptime - lastChange + let delay = max(0.02, Self.minimumChangeInterval - sinceLast) + DispatchQueue.main.asyncAfter(deadline: .now() + delay, execute: work) } private static func remove(_ session: IslandActivitySession) async { @@ -204,6 +216,7 @@ final class IslandLiveActivityObserver { func stop() { generation += 1 + agent = nil reading?.cancel(); reading = nil change?.cancel(); change = nil if let session { diff --git a/Plugins/IslandNotifications/Sources/IslandNotificationsController.swift b/Plugins/IslandNotifications/Sources/IslandNotificationsController.swift index 76928aabb..8d0c7a418 100644 --- a/Plugins/IslandNotifications/Sources/IslandNotificationsController.swift +++ b/Plugins/IslandNotifications/Sources/IslandNotificationsController.swift @@ -884,6 +884,8 @@ final class IslandNotificationsController { } } + private var lastActivityCheck: TimeInterval = 0 + private func tick() { guard active else { return } guard enabled, trusted, let anchor else { return } @@ -903,7 +905,11 @@ final class IslandNotificationsController { logger.notice("card hidden under a hover panel") presenter.hide() } - else if !blocked, presenter.window == nil { activityChanged() } + else if !blocked, presenter.window == nil, now - lastActivityCheck >= 0.5 { + // A hidden card waits for its place to come back; looking twice a second is enough. + lastActivityCheck = now + activityChanged() + } if blocked != wasBlocked { updateLifetime() } } else { presentNext(checkBlocking: false) } } From 678090fc803a72220f7bbc14dff8f333a9025c29 Mon Sep 17 00:00:00 2001 From: Niko Eltarenko <61957857+nikoelt@users.noreply.github.com> Date: Wed, 18 Nov 2026 20:49:52 +1000 Subject: [PATCH 20/29] fix(notch-hover-panel): keep dismissals closed and sizes set while closing Escape, a click elsewhere or a system panel could be undone by moving the pointer on the island while the panel closed, because any hover reopened it. The panel now records why it closes: only a close because the pointer left is reversed by hovering back, while a click or shortcut still claims it. After a dismissal the hover owner opens the panel again only once the pointer has left the trigger and come back. A size requested while the panel was closing was dropped, so a panel that reopened kept its old bounds and could clip its content. The latest size is now kept and applied when it reopens. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .../Sources/NotchHoverPanelController.swift | 26 ++++++++-- .../NotchHoverPanelControllerTests.swift | 49 +++++++++++++++++++ Sources/App/MenuBarPanelPresenter.swift | 14 ++++-- Sources/App/NotchMenuBarPanel.swift | 29 +++++++++-- Tests/App/NotchMenuBarPanelTests.swift | 35 +++++++++++++ 5 files changed, 141 insertions(+), 12 deletions(-) diff --git a/Plugins/NotchHoverPanel/Sources/NotchHoverPanelController.swift b/Plugins/NotchHoverPanel/Sources/NotchHoverPanelController.swift index 83a9a9d9e..4ae0fc173 100644 --- a/Plugins/NotchHoverPanel/Sources/NotchHoverPanelController.swift +++ b/Plugins/NotchHoverPanel/Sources/NotchHoverPanelController.swift @@ -87,6 +87,11 @@ final class NotchHoverPanelController: NotchHoverPanelControlling { private var displays: [NotchHoverDisplay] = [] private var activeDisplay: NotchHoverDisplay? private var ownsPanelPresentation = false + /// Set while this controller is animating its own panel closed because the pointer left. + private var dismissingForPointer = false + /// After the panel was closed some other way (Escape, a click elsewhere), hovering opens it again + /// only once the pointer has left the trigger and come back. + private var waitsForTriggerExit = false private var showWorkItem: DispatchWorkItem? private var hideWorkItem: DispatchWorkItem? private var localMouseMonitor: Any? @@ -345,6 +350,7 @@ final class NotchHoverPanelController: NotchHoverPanelControlling { let panelFrame = presentedMenuBarPanelScreenFrame?() let isInsideTrigger = triggerDisplay != nil + if waitsForTriggerExit, !isInsideTrigger { waitsForTriggerExit = false } let isInsideActiveArea = pointerIsActive( point, triggerDisplay: triggerDisplay, @@ -353,7 +359,7 @@ final class NotchHoverPanelController: NotchHoverPanelControlling { if isInsideActiveArea { cancelScheduledHide() - if isInsideTrigger, !ownsPanelPresentation, isPresentedMenuBarPanelVisible?() != true { + if isInsideTrigger, !waitsForTriggerExit, !ownsPanelPresentation, isPresentedMenuBarPanelVisible?() != true { scheduleShow() } else { cancelScheduledShow() @@ -361,10 +367,13 @@ final class NotchHoverPanelController: NotchHoverPanelControlling { if ownsPanelPresentation, let activeDisplay, isPresentedMenuBarPanelVisible?() == true { - // Cancel any in-flight hide animation when the pointer returns. - _ = requestMenuBarPanelPresentation?( + // Cancel any in-flight hide animation when the pointer returns. The host declines + // when the panel is closing because it was dismissed rather than left. + if requestMenuBarPanelPresentation?( PluginMenuBarPanelPresentationRequest(anchorRect: activeDisplay.notchFrame) - ) + ) == true { + dismissingForPointer = false + } } } else { cancelScheduledShow() @@ -467,6 +476,7 @@ final class NotchHoverPanelController: NotchHoverPanelControlling { } ownsPanelPresentation = true + dismissingForPointer = false onStateChange?() } @@ -499,7 +509,10 @@ final class NotchHoverPanelController: NotchHoverPanelControlling { guard accepted else { return } // Keep ownership while the host animates closed so a pointer moving // back onto the island can reverse the transition. - if animated, isEnabled, isPresentedMenuBarPanelVisible?() == true { return } + if animated, isEnabled, isPresentedMenuBarPanelVisible?() == true { + dismissingForPointer = true + return + } ownsPanelPresentation = false activeDisplay = nil @@ -508,6 +521,9 @@ final class NotchHoverPanelController: NotchHoverPanelControlling { private func syncOwnedPanelVisibility() { guard ownsPanelPresentation, isPresentedMenuBarPanelVisible?() == false else { return } + // Closed by something other than this controller's own pointer-left dismissal. + waitsForTriggerExit = !dismissingForPointer + dismissingForPointer = false ownsPanelPresentation = false activeDisplay = nil cancelScheduledInteractions() diff --git a/Plugins/NotchHoverPanel/Tests/NotchHoverPanelControllerTests.swift b/Plugins/NotchHoverPanel/Tests/NotchHoverPanelControllerTests.swift index 06ecf09ed..49385810e 100644 --- a/Plugins/NotchHoverPanel/Tests/NotchHoverPanelControllerTests.swift +++ b/Plugins/NotchHoverPanel/Tests/NotchHoverPanelControllerTests.swift @@ -313,6 +313,55 @@ final class NotchHoverPanelControllerTests: XCTestCase { XCTAssertTrue(controller.snapshot.isPanelVisible) } + func testDismissedPanelStaysClosedUntilThePointerLeavesAndReturns() { + let mouse = TestState(Self.triggerPoint) + let controller = NotchHoverPanelController( + storage: NotchHoverMemoryStorage(), + screensProvider: { [Self.notchScreenSnapshot()] }, + mouseLocationProvider: { mouse.value } + ) + controller.setShowDelay(0) + controller.setHideDelay(0.05) + + var isPanelVisible = false + var isClosingByDismissal = false + var presentations = 0 + controller.isPresentedMenuBarPanelVisible = { isPanelVisible } + controller.requestMenuBarPanelPresentation = { _ in + // The host declines to reverse a close that was a dismissal. + guard !isClosingByDismissal else { return false } + presentations += 1 + isPanelVisible = true + return true + } + controller.requestMenuBarPanelDismissal = { _ in true } + + controller.handlePointerLocation(mouse.value) + waitForScheduledWork() + XCTAssertEqual(presentations, 1) + + // Escape: the host closes the panel; moving within the trigger must not bring it back. + isClosingByDismissal = true + controller.handlePointerLocation(NSPoint(x: Self.triggerPoint.x + 2, y: Self.triggerPoint.y)) + XCTAssertEqual(presentations, 1) + isPanelVisible = false + isClosingByDismissal = false + controller.handlePointerLocation(NSPoint(x: Self.triggerPoint.x + 4, y: Self.triggerPoint.y)) + waitForScheduledWork() + controller.handlePointerLocation(NSPoint(x: Self.triggerPoint.x + 6, y: Self.triggerPoint.y)) + waitForScheduledWork() + XCTAssertEqual(presentations, 1, "A dismissed panel stays closed while the pointer stays on the island.") + XCTAssertFalse(controller.snapshot.isPanelVisible) + + // Leaving and coming back opens it again. + mouse.value = NSPoint(x: 40, y: 40) + controller.handlePointerLocation(mouse.value) + mouse.value = Self.triggerPoint + controller.handlePointerLocation(mouse.value) + waitForScheduledWork() + XCTAssertEqual(presentations, 2) + } + private func makeController(storage: NotchHoverMemoryStorage) -> NotchHoverPanelController { NotchHoverPanelController( storage: storage, diff --git a/Sources/App/MenuBarPanelPresenter.swift b/Sources/App/MenuBarPanelPresenter.swift index 5bdccd9f2..36db092c0 100644 --- a/Sources/App/MenuBarPanelPresenter.swift +++ b/Sources/App/MenuBarPanelPresenter.swift @@ -507,7 +507,11 @@ final class MenuBarPanelPresenter: NSObject { if let notchPanel { guard !isHoverPanelClaimed else { return false } - notchPanel.reopen() + // Hovering back reverses only a close the pointer caused by leaving. + if notchPanel.isClosing { + guard notchPanel.canReopenOnHover else { return false } + notchPanel.reopen() + } return true } if popover.isShown { @@ -563,12 +567,14 @@ final class MenuBarPanelPresenter: NSObject { dismissClassicHoverPopover(animated: animated) return true } - closeNotchPanel(notchPanel, animated: animated) + // The hover owner closes the panel only because the pointer left it. + closeNotchPanel(notchPanel, animated: animated, reason: .pointerLeft) return true } - private func closeNotchPanel(_ panel: NotchMenuBarPanel, animated: Bool) { - panel.dismiss(animated: animated) { [weak self, weak panel] in + private func closeNotchPanel(_ panel: NotchMenuBarPanel, animated: Bool, + reason: NotchMenuBarPanel.CloseReason = .dismissed) { + panel.dismiss(animated: animated, reason: reason) { [weak self, weak panel] in guard let self, let panel, self.notchPanel === panel else { return } self.finishNotchPanelDismissal(panel) } diff --git a/Sources/App/NotchMenuBarPanel.swift b/Sources/App/NotchMenuBarPanel.swift index 065595466..ded89f495 100644 --- a/Sources/App/NotchMenuBarPanel.swift +++ b/Sources/App/NotchMenuBarPanel.swift @@ -30,6 +30,15 @@ final class NotchMenuBarPanel { private var closeCompletion: (@MainActor () -> Void)? private var systemPanelMonitor: DispatchSourceTimer? private(set) var isClosing = false + /// Why the panel is closing. Only a close because the pointer left can be undone by the pointer + /// coming back; Escape, a click elsewhere or a system panel closes it for good. + enum CloseReason { case pointerLeft, dismissed } + private(set) var closeReason: CloseReason? + /// The latest size asked for while closing, applied if the panel reopens. + private var pendingSize: CGSize? + + var canReopenOnHover: Bool { isClosing && closeReason == .pointerLeft } + var contentSize: CGSize { metrics.contentSize } init(anchor: CGRect, content: NSViewController) { self.anchor = anchor @@ -79,7 +88,9 @@ final class NotchMenuBarPanel { } func resize(to size: CGSize) { - guard !isClosing, size != metrics.contentSize else { return } + guard size != metrics.contentSize else { pendingSize = nil; return } + // While closing the shape keeps the size it is folding from; the new one waits for a reopen. + guard !isClosing else { pendingSize = size; return } applyContentSize(size) render() startDisplayLinkIfNeeded() @@ -88,21 +99,33 @@ final class NotchMenuBarPanel { func reopen() { guard isClosing else { return } isClosing = false + closeReason = nil closeCompletion = nil + if let pendingSize { + self.pendingSize = nil + applyContentSize(pendingSize) + render() + } window.ignoresMouseEvents = false setExpanded(true) } - func dismiss(animated: Bool, completion: @escaping @MainActor () -> Void) { + func dismiss(animated: Bool, reason: CloseReason = .dismissed, completion: @escaping @MainActor () -> Void) { guard animated else { stopDisplayLink() isClosing = true + closeReason = reason closeCompletion = nil completion() return } - guard !isClosing else { return } + guard !isClosing else { + // A close that becomes explicit stays explicit. + if reason == .dismissed { closeReason = .dismissed } + return + } isClosing = true + closeReason = reason closeCompletion = completion window.ignoresMouseEvents = true setExpanded(false) diff --git a/Tests/App/NotchMenuBarPanelTests.swift b/Tests/App/NotchMenuBarPanelTests.swift index c58097370..73d876e46 100644 --- a/Tests/App/NotchMenuBarPanelTests.swift +++ b/Tests/App/NotchMenuBarPanelTests.swift @@ -1,3 +1,4 @@ +import AppKit import CoreGraphics import XCTest @testable import MacTools @@ -68,4 +69,38 @@ final class NotchMenuBarPanelTests: XCTestCase { XCTAssertLessThan(expandedSurface.maxY, anchor.maxY) } + + private func makePanel() -> NotchMenuBarPanel { + let content = NSViewController() + content.view = NSView(frame: CGRect(x: 0, y: 0, width: 349, height: 120)) + return NotchMenuBarPanel(anchor: CGRect(x: 663.5, y: 950, width: 185, height: 32), content: content) + } + + func testOnlyAPointerLeftCloseCanBeReversedByHover() { + let left = makePanel() + left.present(size: CGSize(width: 349, height: 120)) + left.dismiss(animated: true, reason: .pointerLeft) {} + XCTAssertTrue(left.canReopenOnHover) + + let dismissed = makePanel() + dismissed.present(size: CGSize(width: 349, height: 120)) + dismissed.dismiss(animated: true, reason: .dismissed) {} + XCTAssertFalse(dismissed.canReopenOnHover, "Escape or a click elsewhere is not undone by hovering.") + + // A hover close that becomes an explicit one stays explicit. + left.dismiss(animated: true, reason: .dismissed) {} + XCTAssertFalse(left.canReopenOnHover) + left.detachContent(); dismissed.detachContent() + } + + func testSizeChangedWhileClosingIsUsedWhenThePanelReopens() { + let panel = makePanel() + panel.present(size: CGSize(width: 349, height: 120)) + panel.dismiss(animated: true, reason: .pointerLeft) {} + panel.resize(to: CGSize(width: 349, height: 260)) + XCTAssertEqual(panel.contentSize.height, 120, "The closing shape keeps the size it folds from.") + panel.reopen() + XCTAssertEqual(panel.contentSize.height, 260) + panel.detachContent() + } } From c2ff1bbd82b05b8b761dae14ec66bb2feb223c08 Mon Sep 17 00:00:00 2001 From: Niko Eltarenko <61957857+nikoelt@users.noreply.github.com> Date: Thu, 19 Nov 2026 09:47:20 +1000 Subject: [PATCH 21/29] fix(island-notifications): verify Claude banners and adopted Messages alerts A Claude card now takes a waiting turn only from MacTools' own banner that shows the posted text, when exactly one turn fits and macOS lists that request as delivered. Notices are posted only with permission and dropped if macOS refuses them. Any other banner keeps its own content. Banners found already on screen (at start, or while a read was skipped) are adopted with an unknown arrival time: no Messages reply field, and opening falls back to Messages itself. Lookups only count messages from around the arrival until the history has settled (15 s), and a card keeps the conversation it found. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .../Sources/IslandClaudeNotice.swift | 52 +++++--- .../Sources/IslandNotificationAX.swift | 20 +++- .../Sources/IslandNotificationHistory.swift | 2 + .../Sources/IslandNotificationState.swift | 64 +++++++--- .../IslandNotificationsController.swift | 112 +++++++++++++----- .../Tests/IslandNotificationStateTests.swift | 74 ++++++++++-- docs/plugins/island-notifications.md | 6 +- 7 files changed, 250 insertions(+), 80 deletions(-) diff --git a/Plugins/IslandNotifications/Sources/IslandClaudeNotice.swift b/Plugins/IslandNotifications/Sources/IslandClaudeNotice.swift index 82883c4c0..789173a61 100644 --- a/Plugins/IslandNotifications/Sources/IslandClaudeNotice.swift +++ b/Plugins/IslandNotifications/Sources/IslandClaudeNotice.swift @@ -1,4 +1,4 @@ -import Foundation +import AppKit import UserNotifications /// MacTools' own notice of a finished Claude turn. Claude's notices arrive without a banner, so @@ -12,22 +12,40 @@ enum IslandClaudeNotice { } } - static func post(_ turn: IslandClaudeTurnWatcher.Turn) { - let title = turn.chat.title - // Banners carry at most 1,024 characters; the card shows the whole reply. - let body = String(turn.message.prefix(1_000)) - let thread = "claude." + turn.chat.localID - UNUserNotificationCenter.current().getNotificationSettings { settings in - switch settings.authorizationStatus { - case .authorized, .provisional, .ephemeral: break - default: return - } - let content = UNMutableNotificationContent() - content.title = title - content.body = body - content.threadIdentifier = thread - UNUserNotificationCenter.current().add(UNNotificationRequest(identifier: UUID().uuidString, - content: content, trigger: nil)) + /// What the notification carries: banners hold at most 1,024 characters; the card shows the whole reply. + static func postedText(_ turn: IslandClaudeTurnWatcher.Turn) -> String { + String(turn.message.prefix(1_000)) + } + + /// Posts the notice; true once macOS accepted the request. Without permission nothing is posted. + static func post(_ turn: IslandClaudeTurnWatcher.Turn, requestID: String) async -> Bool { + let center = UNUserNotificationCenter.current() + switch await center.notificationSettings().authorizationStatus { + case .authorized, .provisional, .ephemeral: break + default: return false + } + let content = UNMutableNotificationContent() + content.title = turn.chat.title + content.body = postedText(turn) + content.threadIdentifier = "claude." + turn.chat.localID + do { + try await center.add(UNNotificationRequest(identifier: requestID, content: content, trigger: nil)) + return true + } catch { + return false } } + + /// True while Notification Centre holds this request: macOS delivered it. + static func isDelivered(_ requestID: String) async -> Bool { + await UNUserNotificationCenter.current().deliveredNotifications().contains { $0.request.identifier == requestID } + } + + /// MacTools' names as a banner shows them: the bundle's display name, falling back to its name. + static var ownNames: Set<String> { + let info = Bundle.main.localizedInfoDictionary ?? [:] + let plain = Bundle.main.infoDictionary ?? [:] + let names = ["CFBundleDisplayName", "CFBundleName"].flatMap { [info[$0], plain[$0]] }.compactMap { $0 as? String } + return Set((names + [NSRunningApplication.current.localizedName].compactMap { $0 }).filter { !$0.isEmpty }) + } } diff --git a/Plugins/IslandNotifications/Sources/IslandNotificationAX.swift b/Plugins/IslandNotifications/Sources/IslandNotificationAX.swift index 67971e531..c41b9a6ac 100644 --- a/Plugins/IslandNotifications/Sources/IslandNotificationAX.swift +++ b/Plugins/IslandNotifications/Sources/IslandNotificationAX.swift @@ -220,6 +220,13 @@ final class IslandNotification: @unchecked Sendable { let arrivedAt = ProcessInfo.processInfo.systemUptime /// The same moment on the clock, which Messages' history dates are compared with. let arrivalDate = Date() + /// False for a banner that was already on screen when the island first read it (at start, or + /// after a read it missed): when it really arrived is unknown, so Messages' history can't be + /// matched to it. Such a card has no reply field and opens Messages itself. + @MainActor var arrivalConfirmed = true + /// The Messages conversation this card's message was found in, once found: replies and opening + /// keep to it. + @MainActor var messagesChat: IslandMessagesChat.Conversation? /// A header label from the banner, e.g. "TIME-SENSITIVE". @MainActor var label: String? @MainActor var appURL: URL? @@ -229,9 +236,10 @@ final class IslandNotification: @unchecked Sendable { /// Set for a card made from a finished Claude chat turn (no system banner behind it). @MainActor var claudeChat: IslandClaudeChat? /// Claude chat cards and Messages banners get the inline reply field. Messages replies go only - /// to the exact conversation id from Messages' history, so they need that history to be readable. + /// to the exact conversation id from Messages' history, so they need that history to be readable + /// and a confirmed arrival to match it against. @MainActor var canReply: Bool { - claudeChat != nil || (bundleIdentifier == "com.apple.MobileSMS" && IslandMessagesChat.isAvailable) + claudeChat != nil || (bundleIdentifier == "com.apple.MobileSMS" && arrivalConfirmed && IslandMessagesChat.isAvailable) } /// A banner with a third line has a subtitle between the title and the message: for a group @@ -333,6 +341,8 @@ struct IslandAXWindowSnapshot: @unchecked Sendable { var lines = 2 /// A small all-caps header above the title, e.g. "TIME-SENSITIVE". var label: String? + /// The sending app as the banner names it, when its description gives one. + var app: String? let element: AXUIElement let style: IslandNotificationStyle let title: String @@ -367,10 +377,10 @@ struct IslandAXWindowSnapshot: @unchecked Sendable { let title = text.first ?? "" let body = text.dropFirst().joined(separator: "\n") // macOS 27 describes a banner as "<App>, <title>, <body>"; the app comes first. - if let app = IslandNotification.appName(fromDescription: hints.first ?? "", title: title, body: body) { - hints.insert(app, at: 0) - } + let app = IslandNotification.appName(fromDescription: hints.first ?? "", title: title, body: body) + if let app { hints.insert(app, at: 0) } var group = Group(element: element, style: style, title: title, body: body, hints: hints) + group.app = app group.lines = text.count group.label = label groups.append(group) diff --git a/Plugins/IslandNotifications/Sources/IslandNotificationHistory.swift b/Plugins/IslandNotifications/Sources/IslandNotificationHistory.swift index 945684b53..b9bcb98c2 100644 --- a/Plugins/IslandNotifications/Sources/IslandNotificationHistory.swift +++ b/Plugins/IslandNotifications/Sources/IslandNotificationHistory.swift @@ -18,6 +18,8 @@ struct IslandHistoryEntry: Identifiable, Equatable { let claudeChat: IslandClaudeChat? /// Banner text lines, for finding a Messages conversation if Notification Centre no longer has it. let lineCount: Int + /// MacTools saw the banner arrive; without that its Messages conversation isn't looked up. + var arrivalConfirmed = true var groupKey: String { bundleIdentifier ?? appName } diff --git a/Plugins/IslandNotifications/Sources/IslandNotificationState.swift b/Plugins/IslandNotifications/Sources/IslandNotificationState.swift index 076888483..93ed86efa 100644 --- a/Plugins/IslandNotifications/Sources/IslandNotificationState.swift +++ b/Plugins/IslandNotifications/Sources/IslandNotificationState.swift @@ -242,20 +242,27 @@ enum IslandMessagesChat { /// The messages a banner can be about: received up to five minutes before it arrived, or within /// half a minute after (Messages writes its history a few seconds late). Fixed to the arrival, so /// a card held open never comes to match a later message with the same text from someone else. + /// `recentOnly`: only messages from the half minute around the arrival. Until the banner's own + /// message has had time to reach the history, an older one with the same text from someone else + /// could be the only match, so only these count then (see `settledAfter`). /// Message dates are nanoseconds since 2001. - static func dateWindow(around arrival: Date) -> ClosedRange<Int64> { + static func dateWindow(around arrival: Date, recentOnly: Bool = false) -> ClosedRange<Int64> { let seconds = arrival.timeIntervalSinceReferenceDate - return Int64((seconds - 300) * 1_000_000_000)...Int64((seconds + 30) * 1_000_000_000) + return Int64((seconds - (recentOnly ? 30 : 300)) * 1_000_000_000)...Int64((seconds + 30) * 1_000_000_000) } + /// Seconds after the banner by which Messages has written its message to the history: from then + /// the whole window is searched, and a single matching conversation is the banner's. + static let settledAfter: TimeInterval = 15 + /// `bannerLines`: the banner's text lines after its title. A group banner (three lines) must lead /// to a group conversation and a one-to-one banner to a one-to-one conversation. - static func resolve(bannerLines: [String], isGroupBanner: Bool, arrivedAt arrival: Date) -> Lookup { + static func resolve(bannerLines: [String], isGroupBanner: Bool, arrivedAt arrival: Date, recentOnly: Bool = false) -> Lookup { guard let db = open() else { return .unavailable } defer { sqlite3_close(db) } let candidates = Set(bannerLines.map(normalized).filter { !$0.isEmpty }) guard !candidates.isEmpty else { return .notFound } - let window = dateWindow(around: arrival) + let window = dateWindow(around: arrival, recentOnly: recentOnly) let sql = """ SELECT c.guid, m.text, m.attributedBody, c.group_id, m.message_summary_info FROM message m JOIN chat_message_join j ON j.message_id = m.ROWID @@ -348,34 +355,59 @@ enum IslandMessagesChat { } } -/// Claude turns posted as MacTools notifications, each waiting for its banner. Only a banner that -/// shows the chat's title and the start of the reply becomes a Claude card: Focus can keep the -/// banner from showing at all, and hidden previews show neither, so both are honoured as for any app. +/// Claude turns posted as MacTools notifications, each waiting for its banner. A banner becomes a +/// Claude card only when MacTools itself posted it (its app is MacTools), it shows the chat's title +/// and the text that was posted, and exactly one waiting turn fits; the controller then confirms +/// macOS delivered that very request. Anything else keeps the banner's own content. Focus can keep +/// the banner from showing at all, and hidden previews show neither, so both are honoured as for +/// any app. struct IslandClaudePosts { struct Post: Equatable { let chat: IslandClaudeChat + /// The whole reply, which the card shows. let message: String + /// What the notification carried: the start of the reply. + let posted: String + /// The notification request's identifier, checked against Notification Centre's delivered list. + let requestID: String let postedAt: TimeInterval } /// How long a post waits for its banner (system uptime seconds). static let wait: TimeInterval = 30 + /// A shortened banner ("…") must still show at least this much of the posted text. + static let minimumShortenedMatch = 12 private(set) var posts: [Post] = [] - mutating func add(_ chat: IslandClaudeChat, message: String, at now: TimeInterval) { + mutating func add(_ chat: IslandClaudeChat, message: String, posted: String, requestID: String, at now: TimeInterval) { prune(now) - posts.append(Post(chat: chat, message: message, postedAt: now)) + posts.append(Post(chat: chat, message: message, posted: posted, requestID: requestID, postedAt: now)) if posts.count > 8 { posts.removeFirst(posts.count - 8) } } - /// The post this banner shows, taken so no other banner can claim it. - mutating func take(title: String, body: String, at now: TimeInterval) -> Post? { + /// A request macOS refused (no permission, or an error) has no banner to wait for. + mutating func remove(requestID: String) { + posts.removeAll { $0.requestID == requestID } + } + + /// The post this banner shows, taken so no other banner can claim it. `fromMacTools`: the + /// banner's app is MacTools itself. None when no post, or more than one, fits. + mutating func take(title: String, body: String, fromMacTools: Bool, at now: TimeInterval) -> Post? { prune(now) - let shown = Self.normalized(body).trimmingCharacters(in: CharacterSet(charactersIn: "…")) - guard !shown.isEmpty, let index = posts.firstIndex(where: { - $0.chat.title == title && Self.normalized($0.message).hasPrefix(shown) - }) else { return nil } - return posts.remove(at: index) + guard fromMacTools else { return nil } + let shown = Self.normalized(body) + let matching = posts.indices.filter { posts[$0].chat.title == title && Self.shows(shown, Self.normalized(posts[$0].posted)) } + guard matching.count == 1 else { return nil } + return posts.remove(at: matching[0]) + } + + /// The banner shows the posted text whole, or shortened with "…" after a long enough start. + private static func shows(_ shown: String, _ posted: String) -> Bool { + guard !shown.isEmpty else { return false } + if shown == posted { return true } + guard shown.hasSuffix("…") else { return false } + let start = shown.trimmingCharacters(in: CharacterSet(charactersIn: "…").union(.whitespaces)) + return start.count >= minimumShortenedMatch && posted.hasPrefix(start) } private mutating func prune(_ now: TimeInterval) { diff --git a/Plugins/IslandNotifications/Sources/IslandNotificationsController.swift b/Plugins/IslandNotifications/Sources/IslandNotificationsController.swift index 8d0c7a418..8aabf606b 100644 --- a/Plugins/IslandNotifications/Sources/IslandNotificationsController.swift +++ b/Plugins/IslandNotifications/Sources/IslandNotificationsController.swift @@ -51,6 +51,9 @@ final class IslandNotificationsController { private static let prehideGrace: TimeInterval = 0.5 private var ignored: [IslandAXElement] = [] private var receiving: [IslandAXElement] = [] + /// Windows whose next read adopts what it finds: banners already there when MacTools started, + /// or that came while a read was skipped. Their arrival time is unknown. + private var adopting: [IslandAXElement] = [] private var pending: [IslandAXElement] = [] private var generation = 0 private var ready = false @@ -189,7 +192,7 @@ final class IslandNotificationsController { ready = true // Notifications already on screen when MacTools starts become cards too. macOS keeps them // in one window with any that arrive later, so skipping them would leave those native. - for window in windows { receive(window) } + for window in windows { receive(window, adopting: true) } } } @@ -252,7 +255,7 @@ final class IslandNotificationsController { isolated deinit { deactivate() } private func stop() { - generation += 1; ready = false; receiving.removeAll(); pending.removeAll() + generation += 1; ready = false; receiving.removeAll(); pending.removeAll(); adopting.removeAll() replaceWork?.cancel(); replaceWork = nil observer.stop() claudeTurns.stop() @@ -277,28 +280,48 @@ final class IslandNotificationsController { private func receive(_ turn: IslandClaudeTurnWatcher.Turn) { guard active, enabled, claudeCards, trusted, anchor != nil, NSWorkspace.shared.frontmostApplication?.bundleIdentifier != IslandClaudeReply.bundleIdentifier else { return } - claudePosts.add(turn.chat, message: turn.message, at: ProcessInfo.processInfo.systemUptime) - IslandClaudeNotice.post(turn) + let requestID = UUID().uuidString + // Waiting before the request goes out, so a quick banner finds it; claiming it also needs + // macOS to have delivered this request (see makeNotification). + claudePosts.add(turn.chat, message: turn.message, posted: IslandClaudeNotice.postedText(turn), + requestID: requestID, at: ProcessInfo.processInfo.systemUptime) + Task { + if await !IslandClaudeNotice.post(turn, requestID: requestID) { claudePosts.remove(requestID: requestID) } + } } /// A banner, or MacTools' own notice of a Claude turn: then the card is that chat's, with the - /// whole reply (the banner showed its preview) and a reply field. + /// whole reply (the banner showed its preview) and a reply field. Only MacTools' own banner, + /// showing the posted text, for one waiting turn whose request macOS delivered, counts; any + /// other banner keeps its own content. private func makeNotification(_ group: IslandAXWindowSnapshot.Group, window: AXUIElement, - original: CGPoint) -> IslandNotification { - if let post = claudePosts.take(title: group.title, body: group.body, at: ProcessInfo.processInfo.systemUptime) { + original: CGPoint, adopted: Bool) async -> IslandNotification { + let fromMacTools = group.app.map { IslandClaudeNotice.ownNames.contains($0) } ?? false + if let post = claudePosts.take(title: group.title, body: group.body, fromMacTools: fromMacTools, + at: ProcessInfo.processInfo.systemUptime), + await IslandClaudeNotice.isDelivered(post.requestID) { let notification = IslandNotification(element: group.element, window: window, originalPosition: original, style: group.style, title: post.chat.title, body: post.message, identityHints: [IslandClaudeReply.bundleIdentifier] + group.hints) notification.claudeChat = post.chat return notification } - return IslandNotification(element: group.element, window: window, originalPosition: original, - style: group.style, title: group.title, body: group.body, - identityHints: group.hints, lineCount: group.lines) + let notification = IslandNotification(element: group.element, window: window, originalPosition: original, + style: group.style, title: group.title, body: group.body, + identityHints: group.hints, lineCount: group.lines) + notification.arrivalConfirmed = !adopted + return notification } - private func receive(_ window: IslandAXElement) { - guard active, ready, !fallingBack, !centerPressing else { return } + /// `adopting`: this window may hold banners that came while the island wasn't reading it. + private func receive(_ window: IslandAXElement, adopting adopt: Bool = false) { + if adopt, !adopting.contains(where: { CFEqual($0.value, window.value) }) { adopting.append(window) } + guard active, ready, !fallingBack else { return } + guard !centerPressing else { + // Banners arriving now are read later, when their arrival time is no longer known. + if !adopting.contains(where: { CFEqual($0.value, window.value) }) { adopting.append(window) } + return + } if receiving.contains(where: { CFEqual($0.value, window.value) }) { if !pending.contains(where: { CFEqual($0.value, window.value) }) { pending.append(window) } return @@ -319,8 +342,12 @@ final class IslandNotificationsController { // A failed query is unknown, never "closed". let focus = await observer.centerFocus() guard self.generation == generation, active else { return } - if focus == true { await centerOpened(); return } - guard focus == false else { return } + guard focus == false else { + // Not read now: what this window holds is read later, its arrival time unknown. + if !adopting.contains(where: { CFEqual($0.value, window.value) }) { adopting.append(window) } + if focus == true { await centerOpened() } + return + } centerOpen = false // Hide a new banner window at once, before reading it, so the banner never draws its first // frames natively. A window the island doesn't take comes back (see settleUntaken). @@ -374,6 +401,7 @@ final class IslandNotificationsController { await settleUntaken(window, definitive: snapshot.unexpected || ignoredHit || !enabled) return } + let adopted = adopting.contains { CFEqual($0.value, window.value) } let fresh = snapshot.groups.filter { group in !hidden.contains { CFEqual($0.element, group.element) } && !seen.contains { CFEqual($0.element, group.element) } } @@ -385,7 +413,8 @@ final class IslandNotificationsController { ?? seen.last(where: { CFEqual($0.element, group.element) }), old.title != group.title || old.body != group.body else { continue } let original = movedIndex(window.value).map { moved[$0].original } ?? old.originalPosition - let notification = makeNotification(group, window: window.value, original: original) + let notification = await makeNotification(group, window: window.value, original: original, adopted: adopted) + guard self.generation == generation, !centerOpen else { return } notification.label = group.label notification.resolveIdentity() hidden.removeAll { $0 === old } @@ -400,6 +429,8 @@ final class IslandNotificationsController { if let index = movedIndex(window.value) { moved[index].taken = true } enqueue(replacements) } + // Read in full: later banners in this window are seen as they come. + if snapshot.complete, !snapshot.unexpected, fresh.isEmpty { adopting.removeAll { CFEqual($0.value, window.value) } } guard !fresh.isEmpty else { // Nothing new for the island in a window moved on arrival: it goes straight back. if replacements.isEmpty { await settleUntaken(window, definitive: true) } @@ -441,10 +472,19 @@ final class IslandNotificationsController { _ = await IslandAX.run { IslandAX.restore(window.value, to: original) } return } + var made: [(IslandAXWindowSnapshot.Group, IslandNotification)] = [] + for group in fresh { + made.append((group, await makeNotification(group, window: window.value, original: original, adopted: adopted))) + } + // Confirming a Claude notice's delivery is a short wait; anything can have changed. + guard self.generation == generation, !fallingBack, !centerOpen else { + _ = await IslandAX.run { IslandAX.restore(window.value, to: original) } + return + } remember(window.value, original: original, taken: true) var arrivals: [IslandNotification] = [] - for group in fresh { - let notification = makeNotification(group, window: window.value, original: original) + adopting.removeAll { CFEqual($0.value, window.value) } + for (group, notification) in made { notification.label = group.label hidden.append(notification) seen.append(notification) @@ -719,28 +759,40 @@ final class IslandNotificationsController { } /// The exact conversation comes from Messages' history; the message may land there a moment - /// after its banner. No match (or no access) means no reply, never a guess. + /// after its banner. No match (or no access) means no reply, never a guess. Until the banner's + /// own message has surely been written (`settledAfter`), only messages from around its arrival + /// count; after that the whole window, where a second conversation with the same text makes the + /// match ambiguous. Only a banner whose arrival MacTools saw is looked up at all. private static func messagesConversation(body: String, lineCount: Int, arrivedAt arrival: Date) async -> IslandMessagesChat.Lookup { let lines = body.components(separatedBy: "\n") + [body] let isGroup = lineCount > 2 var lookup = IslandMessagesChat.Lookup.notFound - // Messages writes its history a few seconds after the banner, so a quick reply keeps - // looking until 15 seconds after the banner arrived; a later one tries a few times. var attempts = 0 repeat { + let settled = Date().timeIntervalSince(arrival) >= IslandMessagesChat.settledAfter lookup = await Task.detached(priority: .userInitiated) { - IslandMessagesChat.resolve(bannerLines: lines, isGroupBanner: isGroup, arrivedAt: arrival) + IslandMessagesChat.resolve(bannerLines: lines, isGroupBanner: isGroup, arrivedAt: arrival, recentOnly: !settled) }.value guard lookup == .notFound else { break } + if settled, attempts >= 3 { break } attempts += 1 try? await Task.sleep(for: .milliseconds(500)) - } while attempts < 4 || Date().timeIntervalSince(arrival) < 15 + } while true + return lookup + } + + /// The card's conversation: found once, then kept, so a reply and an open go to the same one. + private static func conversation(for notification: IslandNotification) async -> IslandMessagesChat.Lookup { + guard notification.arrivalConfirmed else { return .notFound } + if let chat = notification.messagesChat { return .found(chat) } + let lookup = await messagesConversation(body: notification.body, lineCount: notification.lineCount, + arrivedAt: notification.arrivalDate) + if case .found(let chat) = lookup { notification.messagesChat = chat } return lookup } private static func replyInMessages(_ text: String, to notification: IslandNotification) async -> IslandReplyOutcome { - guard case .found(let chat) = await messagesConversation(body: notification.body, lineCount: notification.lineCount, - arrivedAt: notification.arrivalDate) else { return .noConversation } + guard case .found(let chat) = await conversation(for: notification) else { return .noConversation } return await IslandMessagesReply.send(text, toChat: chat) } @@ -767,10 +819,10 @@ final class IslandNotificationsController { logger.notice("card open banner=\(opened, privacy: .public)") guard self.generation == generation else { return } // macOS removes a banner after a few seconds; a Messages card that outlives it still - // opens its conversation, found the same way replies are. + // opens its conversation, found the same way replies are (one adopted from before + // MacTools saw it opens Messages itself). if !opened, notification.bundleIdentifier == "com.apple.MobileSMS", - case .found(let chat) = await Self.messagesConversation(body: notification.body, lineCount: notification.lineCount, - arrivedAt: notification.arrivalDate), + case .found(let chat) = await Self.conversation(for: notification), let url = chat.openURL, NSWorkspace.shared.open(url) { // Opened the exact conversation. } else if !opened, let url = notification.appURL { @@ -796,7 +848,8 @@ final class IslandNotificationsController { centerApp: centerApp, appURL: notification.appURL, bundleIdentifier: notification.bundleIdentifier, title: notification.title, body: notification.body, - claudeChat: notification.claudeChat, lineCount: notification.lineCount)) + claudeChat: notification.claudeChat, lineCount: notification.lineCount, + arrivalConfirmed: notification.arrivalConfirmed)) } func setHistoryContentHeight(_ height: CGFloat) { @@ -831,7 +884,8 @@ final class IslandNotificationsController { Task { var opened = await inCenter(.open, entry) // Gone from Notification Centre (the app withdrew it, or it was cleared there). - if !opened, entry.bundleIdentifier == "com.apple.MobileSMS", + // An entry adopted from before MacTools saw it opens Messages itself. + if !opened, entry.bundleIdentifier == "com.apple.MobileSMS", entry.arrivalConfirmed, case .found(let chat) = await Self.messagesConversation(body: entry.body, lineCount: entry.lineCount, arrivedAt: entry.date), let url = chat.openURL { opened = NSWorkspace.shared.open(url) diff --git a/Plugins/IslandNotifications/Tests/IslandNotificationStateTests.swift b/Plugins/IslandNotifications/Tests/IslandNotificationStateTests.swift index 4585348d3..fe6685104 100644 --- a/Plugins/IslandNotifications/Tests/IslandNotificationStateTests.swift +++ b/Plugins/IslandNotifications/Tests/IslandNotificationStateTests.swift @@ -1,4 +1,5 @@ import XCTest +import ApplicationServices @testable import IslandNotificationsPlugin final class IslandNotificationStateTests: XCTestCase { @@ -120,23 +121,76 @@ final class IslandNotificationStateTests: XCTestCase { XCTAssertNil(IslandClaudeTurnWatcher.desktopChat(in: [other]) { $0.localID == "local_a" }) } - func testOnlyTheBannerShowingAClaudeTurnBecomesItsCard() { + func testOnlyMacToolsOwnBannerShowingAClaudeTurnBecomesItsCard() { var posts = IslandClaudePosts() let chat = IslandClaudeChat(localID: "local_a", title: "Fix the build") - posts.add(chat, message: "Done. The build passes:\n\nall 42 tests green.", at: 100) + let reply = "Done. The build passes:\n\nall 42 tests green." + posts.add(chat, message: reply, posted: reply, requestID: "r1", at: 100) // A banner with its preview hidden shows neither the chat's title nor the reply. - XCTAssertNil(posts.take(title: "MacTools", body: "Notification", at: 101)) - // Another app's banner with the same title is not this turn. - XCTAssertNil(posts.take(title: "Fix the build", body: "Something else entirely", at: 101)) + XCTAssertNil(posts.take(title: "MacTools", body: "Notification", fromMacTools: true, at: 101)) + // Another app's banner with the same title and text is not this turn. + XCTAssertNil(posts.take(title: "Fix the build", body: "Done. The build passes: all 42 tests green.", fromMacTools: false, at: 101)) + // MacTools' own banner with other text is not this turn. + XCTAssertNil(posts.take(title: "Fix the build", body: "Something else entirely", fromMacTools: true, at: 101)) // The banner shortens and rewraps the reply; it still names the turn, once. - XCTAssertEqual(posts.take(title: "Fix the build", body: "Done. The build passes: all 42…", at: 102)?.chat, chat) - XCTAssertNil(posts.take(title: "Fix the build", body: "Done. The build passes: all 42…", at: 102)) + XCTAssertEqual(posts.take(title: "Fix the build", body: "Done. The build passes: all 42…", fromMacTools: true, at: 102)?.chat, chat) + XCTAssertNil(posts.take(title: "Fix the build", body: "Done. The build passes: all 42…", fromMacTools: true, at: 102)) } - func testAClaudeTurnWhoseBannerNeverCameExpires() { + func testAShortBannerMustShowTheWholePostedText() { var posts = IslandClaudePosts() - posts.add(IslandClaudeChat(localID: "local_a", title: "Notes"), message: "Saved.", at: 0) + let chat = IslandClaudeChat(localID: "local_a", title: "Notes") + posts.add(chat, message: "Done. I saved the notes and the summary.", posted: "Done. I saved the notes and the summary.", + requestID: "r1", at: 0) + // "Notes / Done." from anywhere, even MacTools, is not this turn: it shows only the start. + XCTAssertNil(posts.take(title: "Notes", body: "Done.", fromMacTools: true, at: 1)) + XCTAssertNil(posts.take(title: "Notes", body: "Done.…", fromMacTools: true, at: 1)) + XCTAssertEqual(posts.take(title: "Notes", body: "Done. I saved the notes and the summary.", fromMacTools: true, at: 1)?.chat, chat) + } + + func testTwoWaitingTurnsABannerCouldBeAreNeitherTaken() { + var posts = IslandClaudePosts() + let first = IslandClaudeChat(localID: "local_a", title: "Notes") + let second = IslandClaudeChat(localID: "local_b", title: "Notes") + posts.add(first, message: "Done. The first summary is ready.", posted: "Done. The first summary is ready.", requestID: "r1", at: 0) + posts.add(second, message: "Done. The first draft is ready.", posted: "Done. The first draft is ready.", requestID: "r2", at: 0) + // Shortened to a start both share: no card takes either reply. + XCTAssertNil(posts.take(title: "Notes", body: "Done. The first…", fromMacTools: true, at: 1)) + XCTAssertEqual(posts.posts.count, 2) + // The whole text tells them apart. + XCTAssertEqual(posts.take(title: "Notes", body: "Done. The first draft is ready.", fromMacTools: true, at: 1)?.chat, second) + } + + func testAClaudeTurnMacOSRefusedOrThatNeverShowedIsNotTaken() { + var posts = IslandClaudePosts() + posts.add(IslandClaudeChat(localID: "local_a", title: "Notes"), message: "Saved the file.", posted: "Saved the file.", + requestID: "r1", at: 0) + posts.remove(requestID: "r1") + XCTAssertNil(posts.take(title: "Notes", body: "Saved the file.", fromMacTools: true, at: 1)) + posts.add(IslandClaudeChat(localID: "local_a", title: "Notes"), message: "Saved the file.", posted: "Saved the file.", + requestID: "r2", at: 0) // Focus kept the banner from showing; a later banner with the same text is not this turn. - XCTAssertNil(posts.take(title: "Notes", body: "Saved.", at: IslandClaudePosts.wait + 1)) + XCTAssertNil(posts.take(title: "Notes", body: "Saved the file.", fromMacTools: true, at: IslandClaudePosts.wait + 1)) + } + + func testUntilTheHistoryHasSettledOnlyMessagesFromAroundTheArrivalCount() { + let arrival = Date(timeIntervalSinceReferenceDate: 800_000_000) + let window = IslandMessagesChat.dateWindow(around: arrival, recentOnly: true) + let nanoseconds = { (offset: TimeInterval) in Int64((arrival.timeIntervalSinceReferenceDate + offset) * 1_000_000_000) } + XCTAssertTrue(window.contains(nanoseconds(-20))) + XCTAssertTrue(window.contains(nanoseconds(25))) + // Someone else's identical message from three minutes earlier is not this banner's. + XCTAssertFalse(window.contains(nanoseconds(-180))) + } + + @MainActor + func testAnAlertAdoptedFromBeforeMacToolsSawItHasNoMessagesReply() { + let element = AXUIElementCreateApplication(getpid()) + let notification = IslandNotification(element: element, window: element, originalPosition: .zero, style: .persistent, + title: "Alice", body: "See you there", identityHints: []) + notification.appURL = URL(fileURLWithPath: "/System/Applications/Messages.app") + XCTAssertEqual(notification.canReply, IslandMessagesChat.isAvailable) + notification.arrivalConfirmed = false + XCTAssertFalse(notification.canReply) } } diff --git a/docs/plugins/island-notifications.md b/docs/plugins/island-notifications.md index 2b2d4ace8..8ba6201e8 100644 --- a/docs/plugins/island-notifications.md +++ b/docs/plugins/island-notifications.md @@ -19,8 +19,8 @@ Cards: - **Lifetime:** a temporary card stays for five seconds, paused while it is hovered, held open, being replied to, or under the MacTools hover panel. A persistent alert waits until it is dismissed. - **Several notifications:** one card shows at a time. A newer temporary notification replaces an idle card after one second; a held or busy card is never interrupted. - **Gestures:** swipe up to dismiss. Pull down to open the full message, or to hold a card that has nothing more to show. A click opens the exact item through the banner's own action, and Esc closes the card. -- **Replies:** Messages cards reply to the conversation found in Messages' history among messages received around the banner, never to one matched by name. Claude cards type the reply into their chat without bringing Claude forward; the chat is checked again by its id and on screen just before sending, and another chat with the same title refuses the reply. -- **Claude chat cards** (off by default): Claude posts its own notices without a banner, so with this on the plugin reads Claude Code's session logs and, when a chat finishes a turn while Claude is in the background, MacTools posts a notification of its own. Its banner becomes the card. MacTools' notification settings, Focus and preview privacy apply to it, it stays in Notification Centre's history, and nothing shows when macOS would show nothing. +- **Replies:** Messages cards reply to the conversation found in Messages' history among messages received around the banner, never to one matched by name. Until the banner's own message has had time to reach the history (15 seconds), only messages from the half minute around it count. A banner that was already on screen when the plugin first read it (at start, or one that came while Notification Centre was open) has no known arrival time, so its card has no reply field and opens Messages itself. Claude cards type the reply into their chat without bringing Claude forward; the chat is checked again by its id and on screen just before sending, and another chat with the same title refuses the reply. +- **Claude chat cards** (off by default): Claude posts its own notices without a banner, so with this on the plugin reads Claude Code's session logs and, when a chat finishes a turn while Claude is in the background, MacTools posts a notification of its own. Its banner becomes the card only when the banner is MacTools' own, shows the posted text, fits exactly one waiting turn, and macOS reports that notice delivered; any other banner keeps its own content. MacTools' notification settings, Focus and preview privacy apply to it, it stays in Notification Centre's history, and nothing shows when macOS would show nothing. - **Live Activities:** with a compact system Live Activity showing, the card splits below it. With an expanded or unreadable activity, banners stay native. Notification text never leaves the Mac and is never written to disk. The logs record steps only. @@ -31,7 +31,7 @@ The list in the panel shows the notifications the island has shown since MacTool Opening or clearing an entry acts on its row in Notification Centre, so the app opens the exact item. Notification Centre is opened through its own accessibility action on a short-lived background thread, its window is moved off screen as it appears, and the row is pressed. Notification Centre applies that move only after drawing its first frame, so on rare occasions a sliver of it shows at the screen edge for a few tens of milliseconds. -If the row is gone, because the app withdrew it or it was cleared, Messages and Claude entries open their conversation or chat directly. Every other entry opens its app. +If the row is gone, because the app withdrew it or it was cleared, Messages and Claude entries open their conversation or chat directly (a Messages entry adopted from before the plugin saw it opens Messages itself). Every other entry opens its app. ## Recovery From 1d4a0bbfb46fd858731fe2364f05173f5910d22b Mon Sep 17 00:00:00 2001 From: Niko Eltarenko <61957857+nikoelt@users.noreply.github.com> Date: Thu, 19 Nov 2026 10:16:11 +1000 Subject: [PATCH 22/29] chore(island-notifications): log which Claude banner check passed Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .../Sources/IslandNotificationsController.swift | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/Plugins/IslandNotifications/Sources/IslandNotificationsController.swift b/Plugins/IslandNotifications/Sources/IslandNotificationsController.swift index 8aabf606b..c78d96c14 100644 --- a/Plugins/IslandNotifications/Sources/IslandNotificationsController.swift +++ b/Plugins/IslandNotifications/Sources/IslandNotificationsController.swift @@ -297,9 +297,14 @@ final class IslandNotificationsController { private func makeNotification(_ group: IslandAXWindowSnapshot.Group, window: AXUIElement, original: CGPoint, adopted: Bool) async -> IslandNotification { let fromMacTools = group.app.map { IslandClaudeNotice.ownNames.contains($0) } ?? false - if let post = claudePosts.take(title: group.title, body: group.body, fromMacTools: fromMacTools, - at: ProcessInfo.processInfo.systemUptime), - await IslandClaudeNotice.isDelivered(post.requestID) { + let waiting = !claudePosts.posts.isEmpty + let post = claudePosts.take(title: group.title, body: group.body, fromMacTools: fromMacTools, + at: ProcessInfo.processInfo.systemUptime) + let delivered = if let post { await IslandClaudeNotice.isDelivered(post.requestID) } else { false } + if waiting { + logger.notice("claude banner fromMacTools=\(fromMacTools, privacy: .public) matched=\(post != nil, privacy: .public) delivered=\(delivered, privacy: .public)") + } + if let post, delivered { let notification = IslandNotification(element: group.element, window: window, originalPosition: original, style: group.style, title: post.chat.title, body: post.message, identityHints: [IslandClaudeReply.bundleIdentifier] + group.hints) From b8cab65ad52a3628079d75e3230e1194aaee91b3 Mon Sep 17 00:00:00 2001 From: Niko Eltarenko <61957857+nikoelt@users.noreply.github.com> Date: Thu, 19 Nov 2026 10:29:16 +1000 Subject: [PATCH 23/29] fix(island-notifications): clear a replied notification; animate opened list entries A reply sent from a card now removes its notification, as replying from the notification itself does: from the panel's list, and from Notification Centre (a banner still alive is closed off screen; one already filed there has its row cleared, as the list's Clear does; MacTools' own Claude notice is removed directly). Opening an entry from the list removes it on the list's spring, as Clear does, so the cards below move up with the panel instead of leaving a gap. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .../Sources/IslandNotificationAX.swift | 4 ++ .../IslandNotificationHistoryView.swift | 4 +- .../IslandNotificationsController.swift | 44 ++++++++++++++++++- 3 files changed, 49 insertions(+), 3 deletions(-) diff --git a/Plugins/IslandNotifications/Sources/IslandNotificationAX.swift b/Plugins/IslandNotifications/Sources/IslandNotificationAX.swift index c41b9a6ac..839bb6601 100644 --- a/Plugins/IslandNotifications/Sources/IslandNotificationAX.swift +++ b/Plugins/IslandNotifications/Sources/IslandNotificationAX.swift @@ -227,6 +227,10 @@ final class IslandNotification: @unchecked Sendable { /// The Messages conversation this card's message was found in, once found: replies and opening /// keep to it. @MainActor var messagesChat: IslandMessagesChat.Conversation? + /// Its entry in the panel's list. + @MainActor var historyID: UUID? + /// For a Claude card: MacTools' own notice behind it. + @MainActor var claudeRequestID: String? /// A header label from the banner, e.g. "TIME-SENSITIVE". @MainActor var label: String? @MainActor var appURL: URL? diff --git a/Plugins/IslandNotifications/Sources/IslandNotificationHistoryView.swift b/Plugins/IslandNotifications/Sources/IslandNotificationHistoryView.swift index 51a347fa6..b8b3cdb65 100644 --- a/Plugins/IslandNotifications/Sources/IslandNotificationHistoryView.swift +++ b/Plugins/IslandNotifications/Sources/IslandNotificationHistoryView.swift @@ -111,7 +111,9 @@ struct IslandNotificationHistoryView: View { folded: level, onClick: { if top, !open, more > 0 { withAnimation(animation) { expanded = group.id } } - else { onOpen(entry) } + // Opening takes the notification off the list, as Clear does: the + // cards below move up on the panel's spring instead of leaving a gap. + else { withAnimation(animation) { onOpen(entry) } } }, onClose: { withAnimation(animation) { onClear(top && !open ? group.entries : [entry]) } }) .padding(.horizontal, CGFloat(min(level, 2)) * 12) diff --git a/Plugins/IslandNotifications/Sources/IslandNotificationsController.swift b/Plugins/IslandNotifications/Sources/IslandNotificationsController.swift index c78d96c14..b67cf1c5b 100644 --- a/Plugins/IslandNotifications/Sources/IslandNotificationsController.swift +++ b/Plugins/IslandNotifications/Sources/IslandNotificationsController.swift @@ -3,6 +3,8 @@ import Combine import ApplicationServices import MacToolsPluginKit import OSLog +import SwiftUI +import UserNotifications /// A NotificationCenter window MacTools moved off screen. `taken`: the island shows its banner. struct IslandMovedWindow: @unchecked Sendable { @@ -309,6 +311,7 @@ final class IslandNotificationsController { style: group.style, title: post.chat.title, body: post.message, identityHints: [IslandClaudeReply.bundleIdentifier] + group.hints) notification.claudeChat = post.chat + notification.claudeRequestID = post.requestID return notification } let notification = IslandNotification(element: group.element, window: window, originalPosition: original, @@ -748,6 +751,7 @@ final class IslandNotificationsController { try? await Task.sleep(for: .milliseconds(450)) guard self.generation == generation, queue.current === notification else { return } finishCurrent(dismissNative: true, reason: "replied") + clearReplied(notification) case .noConversation: presenter.showReplyError(localization.string("reply.error.conversation", defaultValue: "找不到这个对话。点按卡片以打开“信息”。")) case .notAuthorized: @@ -838,6 +842,40 @@ final class IslandNotificationsController { } } + /// Replying from a notification itself marks the chat read, and its notification goes: a reply + /// sent from a card removes it from the list and from Notification Centre the same way. + private func clearReplied(_ notification: IslandNotification) { + let entry = history.entries.first { $0.id == notification.historyID } + if let entry { + // On the list's spring, in case the panel is open. + let motion = NSWorkspace.shared.accessibilityDisplayShouldReduceMotion ? nil : IslandHistoryLayout.motion + withAnimation(motion) { history.remove(entry) } + } + if let requestID = notification.claudeRequestID { + UNUserNotificationCenter.current().removeDeliveredNotifications(withIdentifiers: [requestID]) + return + } + // An alert is closed with the card (finishCurrent), which takes it out of Notification Centre. + guard notification.style == .temporary else { return } + let desktopMinX = Self.desktopMinX + let generation = generation + Task { + // Still a banner, off screen: closing it there takes it out of Notification Centre too. + let closed = await IslandAX.run { () -> Bool in + guard let position = IslandAX.position(notification.window), position.x < desktopMinX - 5000 else { return false } + return IslandAX.perform(anyOf: IslandAX.centerAction("Close"), on: notification.element) + } + logger.notice("replied notification closed banner=\(closed, privacy: .public)") + guard !closed, let entry, entry.centerApp != nil else { return } + // Filed in Notification Centre by now: its row is cleared there, as the list's Clear does, + // once the card has folded away. + try? await Task.sleep(for: .seconds(1)) + guard self.generation == generation else { return } + let cleared = await inCenter(.clear, entry) + logger.notice("replied notification cleared inCentre=\(cleared, privacy: .public)") + } + } + // MARK: The panel's Notifications list // // Opening or clearing an entry acts on its row in Notification Centre, out of sight, as a click @@ -849,12 +887,14 @@ final class IslandNotificationsController { let centerApp = notification.claudeChat == nil ? IslandNotification.appName(fromDescription: description, title: notification.title, body: notification.body) : nil - history.add(IslandHistoryEntry(date: notification.arrivalDate, appName: notification.appName ?? centerApp ?? notification.title, + let entry = IslandHistoryEntry(date: notification.arrivalDate, appName: notification.appName ?? centerApp ?? notification.title, centerApp: centerApp, appURL: notification.appURL, bundleIdentifier: notification.bundleIdentifier, title: notification.title, body: notification.body, claudeChat: notification.claudeChat, lineCount: notification.lineCount, - arrivalConfirmed: notification.arrivalConfirmed)) + arrivalConfirmed: notification.arrivalConfirmed) + notification.historyID = entry.id + history.add(entry) } func setHistoryContentHeight(_ height: CGFloat) { From 91dc7031858532a6989d32da3c31f995747fcd9f Mon Sep 17 00:00:00 2001 From: Niko Eltarenko <61957857+nikoelt@users.noreply.github.com> Date: Thu, 19 Nov 2026 11:04:30 +1000 Subject: [PATCH 24/29] fix(island-notifications): keep an all-caps sender as the title, not a label A short all-caps first line was always read as a header label such as TIME-SENSITIVE and dropped. An email from an all-caps sender then lost its sender, and the app was read as "Spark Desktop, SENDER", so the card and list entry had no icon or app. A line that the banner's description lists as its own part, right before the next line, is now kept as the title. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .../Sources/IslandNotificationAX.swift | 13 ++++++++++++- .../Tests/IslandNotificationHistoryTests.swift | 9 +++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/Plugins/IslandNotifications/Sources/IslandNotificationAX.swift b/Plugins/IslandNotifications/Sources/IslandNotificationAX.swift index 839bb6601..089c5914a 100644 --- a/Plugins/IslandNotifications/Sources/IslandNotificationAX.swift +++ b/Plugins/IslandNotifications/Sources/IslandNotificationAX.swift @@ -303,6 +303,16 @@ final class IslandNotification: @unchecked Sendable { return first.isEmpty || first == title ? nil : first } + /// An all-caps first line can be a header label ("TIME-SENSITIVE") or simply the title: an email + /// from "SERPROBOT". The description lists the banner's text after the app; a line listed there as + /// its own part, right before the next line, is the title, not a label. + nonisolated static func isLabel(_ line: String, beforeTitle title: String, description: String) -> Bool { + guard let app = appName(fromDescription: description, title: title, body: "") else { return true } + let parts = app.split(whereSeparator: { $0.unicodeScalars.allSatisfy { ",、,،".unicodeScalars.contains($0) } }) + .map { String($0).trimmingCharacters(in: descriptionSeparators) } + return !(parts.count > 1 && parts.last == line.trimmingCharacters(in: descriptionSeparators)) + } + @MainActor func resolveIdentity() { guard identityHints.contains(where: { !$0.isEmpty }) else { return } let runningApplications = NSWorkspace.shared.runningApplications @@ -374,7 +384,8 @@ struct IslandAXWindowSnapshot: @unchecked Sendable { // Time Sensitive (and similar) banners put a short all-caps label above the title. var label: String? if text.count >= 3, let first = text.first, first.count <= 24, - first.rangeOfCharacter(from: .letters) != nil, first.rangeOfCharacter(from: .lowercaseLetters) == nil { + first.rangeOfCharacter(from: .letters) != nil, first.rangeOfCharacter(from: .lowercaseLetters) == nil, + IslandNotification.isLabel(first, beforeTitle: text[1], description: hints.first ?? "") { label = first text.removeFirst() } diff --git a/Plugins/IslandNotifications/Tests/IslandNotificationHistoryTests.swift b/Plugins/IslandNotifications/Tests/IslandNotificationHistoryTests.swift index 64ecf0357..d0ceaf9a0 100644 --- a/Plugins/IslandNotifications/Tests/IslandNotificationHistoryTests.swift +++ b/Plugins/IslandNotifications/Tests/IslandNotificationHistoryTests.swift @@ -55,6 +55,15 @@ final class IslandNotificationHistoryTests: XCTestCase { "Spark Desktop") } + /// A sender written in capitals is the title; a header label is not part of the description's text. + func testAnAllCapsSenderIsTheTitleNotAHeaderLabel() { + let email = "Spark Desktop, SERPROBOT, Weekly report, Here is your automatic report" + XCTAssertFalse(IslandNotification.isLabel("SERPROBOT", beforeTitle: "Weekly report", description: email)) + XCTAssertTrue(IslandNotification.isLabel("TIME-SENSITIVE", beforeTitle: "Standup", description: "Calendar, Standup, In 5 minutes")) + // No description to go by: as before, a short all-caps first line is a label. + XCTAssertTrue(IslandNotification.isLabel("TIME-SENSITIVE", beforeTitle: "Standup", description: "")) + } + @MainActor func testListGroupsByAppNewestFirstAndKeepsALimit() { let history = IslandNotificationHistory() From 2ed3756403feff3690d1aecfc76a2b03b8e51419 Mon Sep 17 00:00:00 2001 From: Niko Eltarenko <61957857+nikoelt@users.noreply.github.com> Date: Thu, 19 Nov 2026 11:22:04 +1000 Subject: [PATCH 25/29] chore(island-notifications): log why a MacTools banner matched no Claude reply Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .../Sources/IslandNotificationState.swift | 14 ++++++++++++++ .../Sources/IslandNotificationsController.swift | 2 ++ 2 files changed, 16 insertions(+) diff --git a/Plugins/IslandNotifications/Sources/IslandNotificationState.swift b/Plugins/IslandNotifications/Sources/IslandNotificationState.swift index 93ed86efa..5d87770f0 100644 --- a/Plugins/IslandNotifications/Sources/IslandNotificationState.swift +++ b/Plugins/IslandNotifications/Sources/IslandNotificationState.swift @@ -401,6 +401,20 @@ struct IslandClaudePosts { return posts.remove(at: matching[0]) } + /// Why no post fits a banner, in counts and lengths only (no text), for the log. + func mismatch(title: String, body: String) -> String { + let shown = Self.normalized(body) + let sameTitle = posts.filter { $0.chat.title == title } + let fits = sameTitle.filter { Self.shows(shown, Self.normalized($0.posted)) }.count + let lengths = sameTitle.map { post -> String in + let posted = Self.normalized(post.posted) + let common = zip(shown, posted).prefix { $0 == $1 }.count + return "\(posted.count)/common\(common)" + } + let titleLengths = posts.map { "\($0.chat.title.count)" }.joined(separator: ",") + return "posts=\(posts.count) titleLengths=[\(titleLengths)] bannerTitle=\(title.count) sameTitle=\(sameTitle.count) fits=\(fits) shown=\(shown.count) ellipsis=\(shown.hasSuffix("…")) posted=[\(lengths.joined(separator: ","))]" + } + /// The banner shows the posted text whole, or shortened with "…" after a long enough start. private static func shows(_ shown: String, _ posted: String) -> Bool { guard !shown.isEmpty else { return false } diff --git a/Plugins/IslandNotifications/Sources/IslandNotificationsController.swift b/Plugins/IslandNotifications/Sources/IslandNotificationsController.swift index b67cf1c5b..7bff5b6f7 100644 --- a/Plugins/IslandNotifications/Sources/IslandNotificationsController.swift +++ b/Plugins/IslandNotifications/Sources/IslandNotificationsController.swift @@ -300,11 +300,13 @@ final class IslandNotificationsController { original: CGPoint, adopted: Bool) async -> IslandNotification { let fromMacTools = group.app.map { IslandClaudeNotice.ownNames.contains($0) } ?? false let waiting = !claudePosts.posts.isEmpty + let mismatch = fromMacTools ? claudePosts.mismatch(title: group.title, body: group.body) : "" let post = claudePosts.take(title: group.title, body: group.body, fromMacTools: fromMacTools, at: ProcessInfo.processInfo.systemUptime) let delivered = if let post { await IslandClaudeNotice.isDelivered(post.requestID) } else { false } if waiting { logger.notice("claude banner fromMacTools=\(fromMacTools, privacy: .public) matched=\(post != nil, privacy: .public) delivered=\(delivered, privacy: .public)") + if fromMacTools, post == nil { logger.notice("claude banner unmatched \(mismatch, privacy: .public)") } } if let post, delivered { let notification = IslandNotification(element: group.element, window: window, originalPosition: original, From 31acc5b88df179c81d373997ac9c78e102c1600e Mon Sep 17 00:00:00 2001 From: Niko Eltarenko <61957857+nikoelt@users.noreply.github.com> Date: Thu, 19 Nov 2026 11:25:52 +1000 Subject: [PATCH 26/29] fix(island-notifications): report a Claude reply with thinking once Claude writes a reply that has thinking as two lines that both end the turn: the thinking, then the text, under one message id. The watcher reported both, the thinking line falling back to the last reply in the log, so the same reply was posted twice and the card's single-match check refused both, leaving two plain MacTools notifications. A thinking-only line is no longer a reply, each message id is reported once per session, a reply already waiting is not posted again, and copies of one chat's same reply count as one turn when matching. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .../Sources/IslandNotificationAX.swift | 22 +++++++++++++---- .../Sources/IslandNotificationState.swift | 14 +++++++++-- .../IslandNotificationsController.swift | 3 ++- .../Tests/IslandNotificationStateTests.swift | 24 +++++++++++++++++++ 4 files changed, 56 insertions(+), 7 deletions(-) diff --git a/Plugins/IslandNotifications/Sources/IslandNotificationAX.swift b/Plugins/IslandNotifications/Sources/IslandNotificationAX.swift index 089c5914a..8f9421a7d 100644 --- a/Plugins/IslandNotifications/Sources/IslandNotificationAX.swift +++ b/Plugins/IslandNotifications/Sources/IslandNotificationAX.swift @@ -1114,6 +1114,9 @@ final class IslandClaudeTranscriptReader: @unchecked Sendable { private let deliver: @Sendable (IslandClaudeTurnWatcher.Turn) -> Void private let started = Date() private var files: [String: LogFile] = [:] + /// The last reply reported for each session, by its message id: Claude writes one reply as + /// several lines (its thinking, then its text), each marked as ending the turn. + private var reported: [String: String] = [:] private let timestampFormatter: ISO8601DateFormatter = { let formatter = ISO8601DateFormatter() formatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds] @@ -1158,6 +1161,16 @@ final class IslandClaudeTranscriptReader: @unchecked Sendable { for line in lines { apply(line, path: path, fallbackSession: fallbackSession, notBefore: file.notBefore) } } + /// The text a turn-ending line reports. A line holding only the reply's thinking is not the reply: + /// its text follows on the next line, under the same message id. A turn that ends with no text + /// of its own (after tools) reports the last reply in the log. + static func replyText(_ blocks: [[String: Any]], lastMessage: () -> String?) -> String? { + let text = blocks.filter { $0["type"] as? String == "text" }.compactMap { $0["text"] as? String }.joined(separator: "\n") + guard text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { return text } + let thinking = blocks.contains { ["thinking", "redacted_thinking"].contains($0["type"] as? String ?? "") } + return thinking ? nil : lastMessage() + } + private static func firstSight(_ path: String, size: UInt64, started: Date) -> LogFile { let created = (try? FileManager.default.attributesOfItem(atPath: path)[.creationDate] as? Date) ?? .distantPast // A log created while watching is read whole; an older one only from near its end, and only @@ -1181,14 +1194,15 @@ final class IslandClaudeTranscriptReader: @unchecked Sendable { guard time >= notBefore else { return } } let session = entry["sessionId"] as? String ?? fallbackSession + let messageID = message["id"] as? String + // Each reply once, however many lines it is written as. + if let messageID, reported[session] == messageID { return } let blocks = message["content"] as? [[String: Any]] ?? [] - var text = blocks.filter { $0["type"] as? String == "text" }.compactMap { $0["text"] as? String }.joined(separator: "\n") - if text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { - text = IslandClaudeTurnWatcher.lastAssistantMessage(in: path) ?? "" - } + guard let text = Self.replyText(blocks, lastMessage: { IslandClaudeTurnWatcher.lastAssistantMessage(in: path) }) else { return } let cleaned = IslandClaudeTurnWatcher.cleaned(text) // Only desktop chats get a card: a reply goes into the chat in the Claude app. guard !cleaned.isEmpty, let chat = IslandClaudeTurnWatcher.desktopChat(forSession: session) else { return } + if let messageID { reported[session] = messageID } deliver(IslandClaudeTurnWatcher.Turn(chat: chat, message: cleaned)) } } diff --git a/Plugins/IslandNotifications/Sources/IslandNotificationState.swift b/Plugins/IslandNotifications/Sources/IslandNotificationState.swift index 5d87770f0..ef90f70e6 100644 --- a/Plugins/IslandNotifications/Sources/IslandNotificationState.swift +++ b/Plugins/IslandNotifications/Sources/IslandNotificationState.swift @@ -385,6 +385,11 @@ struct IslandClaudePosts { if posts.count > 8 { posts.removeFirst(posts.count - 8) } } + /// The same reply of the same chat already waits: it is not posted twice. + func isWaiting(_ chat: IslandClaudeChat, message: String) -> Bool { + posts.contains { $0.chat.localID == chat.localID && $0.message == message } + } + /// A request macOS refused (no permission, or an error) has no banner to wait for. mutating func remove(requestID: String) { posts.removeAll { $0.requestID == requestID } @@ -397,8 +402,13 @@ struct IslandClaudePosts { guard fromMacTools else { return nil } let shown = Self.normalized(body) let matching = posts.indices.filter { posts[$0].chat.title == title && Self.shows(shown, Self.normalized(posts[$0].posted)) } - guard matching.count == 1 else { return nil } - return posts.remove(at: matching[0]) + // Copies of one chat's same reply are one turn; replies of different chats, or different + // replies, that the banner could each be are not told apart. + let turns = Set(matching.map { posts[$0].chat.localID + "\u{0}" + posts[$0].posted }) + guard turns.count == 1, let newest = matching.last else { return nil } + let post = posts[newest] + for index in matching.reversed() { posts.remove(at: index) } + return post } /// Why no post fits a banner, in counts and lengths only (no text), for the log. diff --git a/Plugins/IslandNotifications/Sources/IslandNotificationsController.swift b/Plugins/IslandNotifications/Sources/IslandNotificationsController.swift index 7bff5b6f7..c1104161c 100644 --- a/Plugins/IslandNotifications/Sources/IslandNotificationsController.swift +++ b/Plugins/IslandNotifications/Sources/IslandNotificationsController.swift @@ -281,7 +281,8 @@ final class IslandNotificationsController { /// settings, Focus and hidden previews then apply as for any app. private func receive(_ turn: IslandClaudeTurnWatcher.Turn) { guard active, enabled, claudeCards, trusted, anchor != nil, - NSWorkspace.shared.frontmostApplication?.bundleIdentifier != IslandClaudeReply.bundleIdentifier else { return } + NSWorkspace.shared.frontmostApplication?.bundleIdentifier != IslandClaudeReply.bundleIdentifier, + !claudePosts.isWaiting(turn.chat, message: turn.message) else { return } let requestID = UUID().uuidString // Waiting before the request goes out, so a quick banner finds it; claiming it also needs // macOS to have delivered this request (see makeNotification). diff --git a/Plugins/IslandNotifications/Tests/IslandNotificationStateTests.swift b/Plugins/IslandNotifications/Tests/IslandNotificationStateTests.swift index fe6685104..03f15f62c 100644 --- a/Plugins/IslandNotifications/Tests/IslandNotificationStateTests.swift +++ b/Plugins/IslandNotifications/Tests/IslandNotificationStateTests.swift @@ -161,6 +161,30 @@ final class IslandNotificationStateTests: XCTestCase { XCTAssertEqual(posts.take(title: "Notes", body: "Done. The first draft is ready.", fromMacTools: true, at: 1)?.chat, second) } + func testAReplysThinkingLineIsNotTheReply() { + // Claude writes a reply with thinking as two turn-ending lines: the thinking, then the text. + XCTAssertNil(IslandClaudeTranscriptReader.replyText([["type": "thinking", "thinking": "…"]], lastMessage: { "Earlier reply" })) + XCTAssertEqual(IslandClaudeTranscriptReader.replyText([["type": "text", "text": "The reply"]], lastMessage: { nil }), "The reply") + // A turn that ends after tools, with no text of its own, reports the last reply. + XCTAssertEqual(IslandClaudeTranscriptReader.replyText([], lastMessage: { "Last reply" }), "Last reply") + } + + func testCopiesOfOneChatsReplyAreOneTurn() { + var posts = IslandClaudePosts() + let chat = IslandClaudeChat(localID: "local_a", title: "Notes") + let reply = "You're right, the threshold was too high." + posts.add(chat, message: reply, posted: reply, requestID: "r1", at: 0) + XCTAssertTrue(posts.isWaiting(chat, message: reply)) + XCTAssertFalse(posts.isWaiting(IslandClaudeChat(localID: "local_b", title: "Notes"), message: reply)) + posts.add(chat, message: reply, posted: reply, requestID: "r2", at: 0) + XCTAssertEqual(posts.take(title: "Notes", body: reply, fromMacTools: true, at: 1)?.requestID, "r2") + XCTAssertTrue(posts.posts.isEmpty) + // The same reply from two different chats with one title stays ambiguous. + posts.add(chat, message: reply, posted: reply, requestID: "r3", at: 2) + posts.add(IslandClaudeChat(localID: "local_b", title: "Notes"), message: reply, posted: reply, requestID: "r4", at: 2) + XCTAssertNil(posts.take(title: "Notes", body: reply, fromMacTools: true, at: 3)) + } + func testAClaudeTurnMacOSRefusedOrThatNeverShowedIsNotTaken() { var posts = IslandClaudePosts() posts.add(IslandClaudeChat(localID: "local_a", title: "Notes"), message: "Saved the file.", posted: "Saved the file.", From d51e1d2da5e3b05e85c4e99d4fb1b30e3aa25598 Mon Sep 17 00:00:00 2001 From: Niko Eltarenko <61957857+nikoelt@users.noreply.github.com> Date: Thu, 19 Nov 2026 11:54:55 +1000 Subject: [PATCH 27/29] fix(island-notifications): simpler Claude reply targeting, stricter Messages prefix MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Claude replies: - A sidebar entry is a button whose first text equals the chat's title, however deeply Claude nests it (a selected or hovered row has more groups). The exact first-child layout rejected the real row, so replies failed with "chat not in the sidebar". - Only "<title> - Claude Code" counts as the chat showing. - The claude:// link is no longer opened to reply (it always brings Claude forward); without a sidebar entry the reply fails and the card opens the chat. - A banner takes a waiting reply only when exactly one matches; the merging of copies and the mismatch log are gone (each reply is reported once by the log reader). Messages: a banner matches only the start of a longer message when macOS shortened it ("…" or the 1,024-character cut), so "See you tomorrow" no longer matches someone else's "See you tomorrow at noon". A group banner also matches its message without the group's name, and attachment placeholders are ignored. Reviewed with Fable 5.2 and GPT 6.2 Astra. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .../Sources/IslandNotificationAX.swift | 41 ++++++------ .../Sources/IslandNotificationState.swift | 66 ++++++++++--------- .../IslandNotificationsController.swift | 5 +- .../Tests/IslandNotificationStateTests.swift | 30 +++++++-- 4 files changed, 84 insertions(+), 58 deletions(-) diff --git a/Plugins/IslandNotifications/Sources/IslandNotificationAX.swift b/Plugins/IslandNotifications/Sources/IslandNotificationAX.swift index 8f9421a7d..cd36f0635 100644 --- a/Plugins/IslandNotifications/Sources/IslandNotificationAX.swift +++ b/Plugins/IslandNotifications/Sources/IslandNotificationAX.swift @@ -659,8 +659,8 @@ private func islandAXObserverCallback(_ observer: AXObserver, _ element: AXUIEle /// scripting interface, so this drives its accessibility interface: when another chat is open, that /// chat's sidebar entry is pressed in the background; nothing is typed until the window shows exactly /// the expected chat; an unsent draft in Claude is never overwritten, and a failed send leaves the -/// box as it was. Claude is never brought forward: its own chat link (which always activates it) is -/// used only while Claude is already in front. +/// box as it was. Claude is never brought forward: its own chat link always activates it, so it is +/// only for opening the chat from the card. enum IslandClaudeReply { static let bundleIdentifier = "com.anthropic.claudefordesktop" /// Steps only, never message text. @@ -696,7 +696,7 @@ enum IslandClaudeReply { /// The page title is exactly "<chat title> - Claude Code" (so "Foo" never matches "Foo bar"). nonisolated static func isShowing(_ title: String, in pageTitle: String) -> Bool { - pageTitle == title + " - Claude Code" || pageTitle == title + " - Claude" + pageTitle == title + " - Claude Code" } @MainActor @@ -715,17 +715,13 @@ enum IslandClaudeReply { guard scan.prompt != nil, !scan.chatTitle.isEmpty else { return .failed } guard scan.sidebarEntries.count <= 1 else { logger.notice("claude sidebar has the title twice"); return .ambiguousChat } if !isShowing(title, in: scan.chatTitle) { - if scan.sidebarEntries.count == 1, let entry = scan.sidebarEntries.first.map(IslandAXElement.init) { - _ = await IslandAX.run { AXUIElementPerformAction(entry.value, kAXPressAction as CFString) == .success } - } else if NSWorkspace.shared.frontmostApplication?.processIdentifier == pid, let link = chat.link { - // Claude's link always brings Claude forward, so it is used only when Claude is - // already in front. Otherwise the reply fails and the card offers to open the chat: - // Claude never flashes up behind a reply. - _ = try? await NSWorkspace.shared.open(link) - } else { + // Claude's own link always brings Claude forward, so only its sidebar entry is pressed. Without + // one the reply fails and the card offers to open the chat: Claude never flashes up. + guard scan.sidebarEntries.count == 1, let entry = scan.sidebarEntries.first.map(IslandAXElement.init) else { logger.notice("claude chat not in the sidebar") return .failed } + _ = await IslandAX.run { AXUIElementPerformAction(entry.value, kAXPressAction as CFString) == .success } // Wait until the chat has opened and stayed open for two checks in a row. var matches = 0 for _ in 0..<20 where matches < 2 { @@ -863,16 +859,23 @@ enum IslandClaudeReply { return scan } - /// A sidebar entry is a button around a label whose first text is the chat's title; status text - /// such as "Running" or "Forked from …" follows it. Links to a chat inside a transcript have no - /// such label, so they never count as its entry. + /// A sidebar entry is a button whose first text is the chat's title; status text such as + /// "Running" or "Forked from …" follows it, and how deeply Claude nests it varies (a selected or + /// hovered row has more groups). A fork's first text is "<title> (fork)". Links to a chat inside + /// a transcript have no text of their own, so they never count as its entry. @IslandAXExecutor private static func entryTitle(_ button: AXUIElement) -> String? { - guard let label = IslandAX.children(button, timeout: 0.5)?.first, - IslandAX.value(label, kAXRoleAttribute, timeout: 0.5) as? String == kAXGroupRole, - let text = IslandAX.children(label, timeout: 0.5)?.first, - IslandAX.value(text, kAXRoleAttribute, timeout: 0.5) as? String == kAXStaticTextRole else { return nil } - return IslandAX.value(text, kAXValueAttribute, timeout: 0.5) as? String + func firstText(_ element: AXUIElement, depth: Int) -> String?? { + guard depth <= 4 else { return nil } + for child in IslandAX.children(element, timeout: 0.5) ?? [] { + if IslandAX.value(child, kAXRoleAttribute, timeout: 0.5) as? String == kAXStaticTextRole { + return .some(IslandAX.value(child, kAXValueAttribute, timeout: 0.5) as? String) + } + if let found = firstText(child, depth: depth + 1) { return found } + } + return nil + } + return firstText(button, depth: 1) ?? nil } } diff --git a/Plugins/IslandNotifications/Sources/IslandNotificationState.swift b/Plugins/IslandNotifications/Sources/IslandNotificationState.swift index ef90f70e6..744da54bd 100644 --- a/Plugins/IslandNotifications/Sources/IslandNotificationState.swift +++ b/Plugins/IslandNotifications/Sources/IslandNotificationState.swift @@ -257,11 +257,11 @@ enum IslandMessagesChat { /// `bannerLines`: the banner's text lines after its title. A group banner (three lines) must lead /// to a group conversation and a one-to-one banner to a one-to-one conversation. - static func resolve(bannerLines: [String], isGroupBanner: Bool, arrivedAt arrival: Date, recentOnly: Bool = false) -> Lookup { + static func resolve(body: String, isGroupBanner: Bool, arrivedAt arrival: Date, recentOnly: Bool = false) -> Lookup { guard let db = open() else { return .unavailable } defer { sqlite3_close(db) } - let candidates = Set(bannerLines.map(normalized).filter { !$0.isEmpty }) - guard !candidates.isEmpty else { return .notFound } + let banner = BannerText(body: body, isGroup: isGroupBanner) + guard !banner.whole.isEmpty else { return .notFound } let window = dateWindow(around: arrival, recentOnly: recentOnly) let sql = """ SELECT c.guid, m.text, m.attributedBody, c.group_id, m.message_summary_info FROM message m @@ -290,7 +290,7 @@ enum IslandMessagesChat { if let blob = sqlite3_column_blob(statement, 4) { versions += editedVersions(Data(bytes: blob, count: Int(sqlite3_column_bytes(statement, 4)))) } - guard versions.contains(where: { matches(normalized($0), candidates) }) else { continue } + guard versions.contains(where: { banner.matches($0) }) else { continue } chats.insert(guid) if let groupID = sqlite3_column_text(statement, 3).map({ String(cString: $0) }), !groupID.isEmpty { groupIDs[guid] = groupID @@ -315,13 +315,38 @@ enum IslandMessagesChat { return Conversation(identifier: String(parts[2]), isGroup: parts[1] == "+") } - private static func normalized(_ text: String) -> String { - text.split(whereSeparator: { $0.isWhitespace || $0.isNewline }).joined(separator: " ") + /// Attachment placeholders (U+FFFC) aside, the words with their spacing evened out. + static func normalized(_ text: String) -> String { + text.replacingOccurrences(of: "\u{FFFC}", with: " ") + .split(whereSeparator: { $0.isWhitespace || $0.isNewline }).joined(separator: " ") } - /// Banners can shorten long messages, so a long enough banner line may be a prefix. - private static func matches(_ text: String, _ candidates: Set<String>) -> Bool { - candidates.contains { $0 == text || ($0.count >= 12 && text.hasPrefix($0.trimmingCharacters(in: CharacterSet(charactersIn: "…")))) } + /// What a banner shows, to match a message against. A message matches a line exactly, or the + /// whole text (for a group, the text under the group's name). Only a banner macOS shortened, + /// ending in "…" or cut at its 1,024-character limit, may show just the start of the message, so + /// only then does a long enough start count: "See you tomorrow" is not "See you tomorrow at noon". + struct BannerText { + let lines: Set<String> + let whole: Set<String> + let shortened: Bool + + init(body: String, isGroup: Bool) { + let parts = body.components(separatedBy: "\n") + lines = Set(parts.map(IslandMessagesChat.normalized).filter { !$0.isEmpty }) + let texts = [body] + (isGroup && parts.count > 1 ? [parts.dropFirst().joined(separator: "\n")] : []) + whole = Set(texts.map(IslandMessagesChat.normalized).filter { !$0.isEmpty }) + shortened = body.hasSuffix("…") || body.count == 1024 + } + + func matches(_ message: String) -> Bool { + let text = IslandMessagesChat.normalized(message) + if lines.contains(text) || whole.contains(text) { return true } + guard shortened else { return false } + return whole.contains { candidate in + let start = candidate.trimmingCharacters(in: CharacterSet(charactersIn: "…").union(.whitespaces)) + return start.count >= 12 && text.hasPrefix(start) + } + } } /// `message_summary_info` holds each version of an edited message under "ec": the message's @@ -402,27 +427,8 @@ struct IslandClaudePosts { guard fromMacTools else { return nil } let shown = Self.normalized(body) let matching = posts.indices.filter { posts[$0].chat.title == title && Self.shows(shown, Self.normalized(posts[$0].posted)) } - // Copies of one chat's same reply are one turn; replies of different chats, or different - // replies, that the banner could each be are not told apart. - let turns = Set(matching.map { posts[$0].chat.localID + "\u{0}" + posts[$0].posted }) - guard turns.count == 1, let newest = matching.last else { return nil } - let post = posts[newest] - for index in matching.reversed() { posts.remove(at: index) } - return post - } - - /// Why no post fits a banner, in counts and lengths only (no text), for the log. - func mismatch(title: String, body: String) -> String { - let shown = Self.normalized(body) - let sameTitle = posts.filter { $0.chat.title == title } - let fits = sameTitle.filter { Self.shows(shown, Self.normalized($0.posted)) }.count - let lengths = sameTitle.map { post -> String in - let posted = Self.normalized(post.posted) - let common = zip(shown, posted).prefix { $0 == $1 }.count - return "\(posted.count)/common\(common)" - } - let titleLengths = posts.map { "\($0.chat.title.count)" }.joined(separator: ",") - return "posts=\(posts.count) titleLengths=[\(titleLengths)] bannerTitle=\(title.count) sameTitle=\(sameTitle.count) fits=\(fits) shown=\(shown.count) ellipsis=\(shown.hasSuffix("…")) posted=[\(lengths.joined(separator: ","))]" + guard matching.count == 1 else { return nil } + return posts.remove(at: matching[0]) } /// The banner shows the posted text whole, or shortened with "…" after a long enough start. diff --git a/Plugins/IslandNotifications/Sources/IslandNotificationsController.swift b/Plugins/IslandNotifications/Sources/IslandNotificationsController.swift index c1104161c..042939f92 100644 --- a/Plugins/IslandNotifications/Sources/IslandNotificationsController.swift +++ b/Plugins/IslandNotifications/Sources/IslandNotificationsController.swift @@ -301,13 +301,11 @@ final class IslandNotificationsController { original: CGPoint, adopted: Bool) async -> IslandNotification { let fromMacTools = group.app.map { IslandClaudeNotice.ownNames.contains($0) } ?? false let waiting = !claudePosts.posts.isEmpty - let mismatch = fromMacTools ? claudePosts.mismatch(title: group.title, body: group.body) : "" let post = claudePosts.take(title: group.title, body: group.body, fromMacTools: fromMacTools, at: ProcessInfo.processInfo.systemUptime) let delivered = if let post { await IslandClaudeNotice.isDelivered(post.requestID) } else { false } if waiting { logger.notice("claude banner fromMacTools=\(fromMacTools, privacy: .public) matched=\(post != nil, privacy: .public) delivered=\(delivered, privacy: .public)") - if fromMacTools, post == nil { logger.notice("claude banner unmatched \(mismatch, privacy: .public)") } } if let post, delivered { let notification = IslandNotification(element: group.element, window: window, originalPosition: original, @@ -776,14 +774,13 @@ final class IslandNotificationsController { /// count; after that the whole window, where a second conversation with the same text makes the /// match ambiguous. Only a banner whose arrival MacTools saw is looked up at all. private static func messagesConversation(body: String, lineCount: Int, arrivedAt arrival: Date) async -> IslandMessagesChat.Lookup { - let lines = body.components(separatedBy: "\n") + [body] let isGroup = lineCount > 2 var lookup = IslandMessagesChat.Lookup.notFound var attempts = 0 repeat { let settled = Date().timeIntervalSince(arrival) >= IslandMessagesChat.settledAfter lookup = await Task.detached(priority: .userInitiated) { - IslandMessagesChat.resolve(bannerLines: lines, isGroupBanner: isGroup, arrivedAt: arrival, recentOnly: !settled) + IslandMessagesChat.resolve(body: body, isGroupBanner: isGroup, arrivedAt: arrival, recentOnly: !settled) }.value guard lookup == .notFound else { break } if settled, attempts >= 3 { break } diff --git a/Plugins/IslandNotifications/Tests/IslandNotificationStateTests.swift b/Plugins/IslandNotifications/Tests/IslandNotificationStateTests.swift index 03f15f62c..3c57e810d 100644 --- a/Plugins/IslandNotifications/Tests/IslandNotificationStateTests.swift +++ b/Plugins/IslandNotifications/Tests/IslandNotificationStateTests.swift @@ -169,17 +169,16 @@ final class IslandNotificationStateTests: XCTestCase { XCTAssertEqual(IslandClaudeTranscriptReader.replyText([], lastMessage: { "Last reply" }), "Last reply") } - func testCopiesOfOneChatsReplyAreOneTurn() { + func testAReplyAlreadyWaitingIsNotPostedAgainAndTwoChatsAreNotGuessed() { var posts = IslandClaudePosts() let chat = IslandClaudeChat(localID: "local_a", title: "Notes") let reply = "You're right, the threshold was too high." posts.add(chat, message: reply, posted: reply, requestID: "r1", at: 0) + // The controller doesn't post a reply that already waits, so it shows once. XCTAssertTrue(posts.isWaiting(chat, message: reply)) XCTAssertFalse(posts.isWaiting(IslandClaudeChat(localID: "local_b", title: "Notes"), message: reply)) - posts.add(chat, message: reply, posted: reply, requestID: "r2", at: 0) - XCTAssertEqual(posts.take(title: "Notes", body: reply, fromMacTools: true, at: 1)?.requestID, "r2") - XCTAssertTrue(posts.posts.isEmpty) - // The same reply from two different chats with one title stays ambiguous. + XCTAssertEqual(posts.take(title: "Notes", body: reply, fromMacTools: true, at: 1)?.requestID, "r1") + // The same reply from two different chats with one title: neither is taken. posts.add(chat, message: reply, posted: reply, requestID: "r3", at: 2) posts.add(IslandClaudeChat(localID: "local_b", title: "Notes"), message: reply, posted: reply, requestID: "r4", at: 2) XCTAssertNil(posts.take(title: "Notes", body: reply, fromMacTools: true, at: 3)) @@ -197,6 +196,27 @@ final class IslandNotificationStateTests: XCTestCase { XCTAssertNil(posts.take(title: "Notes", body: "Saved the file.", fromMacTools: true, at: IslandClaudePosts.wait + 1)) } + func testABannerMatchesOnlyTheStartOfAMessageWhenMacOSShortenedIt() { + typealias Banner = IslandMessagesChat.BannerText + // A whole banner is not the start of someone else's longer message. + let full = Banner(body: "See you tomorrow", isGroup: false) + XCTAssertTrue(full.matches("See you tomorrow")) + XCTAssertFalse(full.matches("See you tomorrow at noon")) + // Shortened with "…", or cut at the 1,024-character limit, a long enough start counts. + XCTAssertTrue(Banner(body: "See you tomorrow at the…", isGroup: false).matches("See you tomorrow at the station")) + let long = String(repeating: "word ", count: 300) + XCTAssertTrue(Banner(body: String(long.prefix(1024)), isGroup: false).matches(long)) + XCTAssertFalse(Banner(body: "Hi…", isGroup: false).matches("Hi there, how are you?")) + } + + func testAGroupBannersMessageMatchesWithoutTheGroupsName() { + let banner = IslandMessagesChat.BannerText(body: "The team\nFirst line\nsecond line", isGroup: true) + XCTAssertTrue(banner.matches("First line\nsecond line")) + XCTAssertFalse(banner.matches("First line and more")) + // A photo's placeholder in the message is not text the banner shows. + XCTAssertTrue(IslandMessagesChat.BannerText(body: "Look at this", isGroup: false).matches("\u{FFFC}Look at this")) + } + func testUntilTheHistoryHasSettledOnlyMessagesFromAroundTheArrivalCount() { let arrival = Date(timeIntervalSinceReferenceDate: 800_000_000) let window = IslandMessagesChat.dateWindow(around: arrival, recentOnly: true) From 12801b3214031ab8e2814e7e9e74afef9d7a7833 Mon Sep 17 00:00:00 2001 From: Niko Eltarenko <61957857+nikoelt@users.noreply.github.com> Date: Thu, 19 Nov 2026 13:17:54 +1000 Subject: [PATCH 28/29] fix(island-notifications): don't turn a Claude card's banner into a second card A Claude card shows the whole reply while its banner shows the start. Any later read of that notification window compared the banner with the card's text, saw a difference, took the banner for a newer notification and made a second, plain MacTools card from it, which then appeared in the list beside the Claude entry. Each card now keeps the banner's own text, and only a change to that counts. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .../Sources/IslandNotificationAX.swift | 14 +++++++++++++- .../Sources/IslandNotificationsController.swift | 5 +++-- .../Tests/IslandNotificationStateTests.swift | 10 ++++++++++ 3 files changed, 26 insertions(+), 3 deletions(-) diff --git a/Plugins/IslandNotifications/Sources/IslandNotificationAX.swift b/Plugins/IslandNotifications/Sources/IslandNotificationAX.swift index cd36f0635..5fc0e0901 100644 --- a/Plugins/IslandNotifications/Sources/IslandNotificationAX.swift +++ b/Plugins/IslandNotifications/Sources/IslandNotificationAX.swift @@ -214,6 +214,10 @@ final class IslandNotification: @unchecked Sendable { let title: String let body: String let identityHints: [String] + /// What the banner itself shows. A Claude card shows the whole reply instead, so a re-read of + /// its window compares the banner with this, never with the card's text. + let bannerTitle: String + let bannerBody: String /// Text lines in the banner. A third line is a subtitle, which group conversations use. let lineCount: Int /// When MacTools received it (system uptime). @@ -265,7 +269,8 @@ final class IslandNotification: @unchecked Sendable { } init(element: AXUIElement, window: AXUIElement, originalPosition: CGPoint, - style: IslandNotificationStyle, title: String, body: String, identityHints: [String], lineCount: Int = 2) { + style: IslandNotificationStyle, title: String, body: String, identityHints: [String], lineCount: Int = 2, + bannerTitle: String? = nil, bannerBody: String? = nil) { self.element = element self.window = window self.originalPosition = originalPosition @@ -274,6 +279,13 @@ final class IslandNotification: @unchecked Sendable { self.body = body self.identityHints = identityHints self.lineCount = lineCount + self.bannerTitle = bannerTitle ?? title + self.bannerBody = bannerBody ?? body + } + + /// macOS swapped a newer notification into this banner when its text is no longer what it was. + func bannerChanged(title: String, body: String) -> Bool { + bannerTitle != title || bannerBody != body } /// The marks Notification Centre puts between the parts of a description, in every language it diff --git a/Plugins/IslandNotifications/Sources/IslandNotificationsController.swift b/Plugins/IslandNotifications/Sources/IslandNotificationsController.swift index 042939f92..e67718d98 100644 --- a/Plugins/IslandNotifications/Sources/IslandNotificationsController.swift +++ b/Plugins/IslandNotifications/Sources/IslandNotificationsController.swift @@ -310,7 +310,8 @@ final class IslandNotificationsController { if let post, delivered { let notification = IslandNotification(element: group.element, window: window, originalPosition: original, style: group.style, title: post.chat.title, body: post.message, - identityHints: [IslandClaudeReply.bundleIdentifier] + group.hints) + identityHints: [IslandClaudeReply.bundleIdentifier] + group.hints, + bannerTitle: group.title, bannerBody: group.body) notification.claudeChat = post.chat notification.claudeRequestID = post.requestID return notification @@ -420,7 +421,7 @@ final class IslandNotificationsController { for group in snapshot.groups { guard let old = hidden.first(where: { CFEqual($0.element, group.element) }) ?? seen.last(where: { CFEqual($0.element, group.element) }), - old.title != group.title || old.body != group.body else { continue } + old.bannerChanged(title: group.title, body: group.body) else { continue } let original = movedIndex(window.value).map { moved[$0].original } ?? old.originalPosition let notification = await makeNotification(group, window: window.value, original: original, adopted: adopted) guard self.generation == generation, !centerOpen else { return } diff --git a/Plugins/IslandNotifications/Tests/IslandNotificationStateTests.swift b/Plugins/IslandNotifications/Tests/IslandNotificationStateTests.swift index 3c57e810d..62db3e904 100644 --- a/Plugins/IslandNotifications/Tests/IslandNotificationStateTests.swift +++ b/Plugins/IslandNotifications/Tests/IslandNotificationStateTests.swift @@ -227,6 +227,16 @@ final class IslandNotificationStateTests: XCTestCase { XCTAssertFalse(window.contains(nanoseconds(-180))) } + func testAClaudeCardsBannerIsNotTakenForANewerNotification() { + let element = AXUIElementCreateApplication(getpid()) + // The card shows the whole reply; its banner showed the start. + let card = IslandNotification(element: element, window: element, originalPosition: .zero, style: .temporary, + title: "Notes", body: "Done. The whole reply, with every paragraph.", + identityHints: [], bannerTitle: "Notes", bannerBody: "Done. The whole…") + XCTAssertFalse(card.bannerChanged(title: "Notes", body: "Done. The whole…")) + XCTAssertTrue(card.bannerChanged(title: "Notes", body: "Something newer")) + } + @MainActor func testAnAlertAdoptedFromBeforeMacToolsSawItHasNoMessagesReply() { let element = AXUIElementCreateApplication(getpid()) From bc9af383914512bd6dd4d914706be3f9f808c9d2 Mon Sep 17 00:00:00 2001 From: Niko Eltarenko <61957857+nikoelt@users.noreply.github.com> Date: Thu, 19 Nov 2026 13:41:13 +1000 Subject: [PATCH 29/29] fix(island-notifications): track a Claude card's banner like any other A Claude card now has MacTools' own banner behind it, but three places still treated it as a card with no banner: - The shown card's banner is re-read twice a second for Claude cards too, so a second Claude turn macOS swaps into that banner becomes its card instead of being missed. - A window handed back to native closes its Claude card as well, so the card and the native banner never show together. - Opening or clearing a Claude card or list entry removes MacTools' notice from Notification Centre, as replying already did. Found in review by Fable 5.2. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .../Sources/IslandNotificationAX.swift | 3 +- .../Sources/IslandNotificationHistory.swift | 4 ++- .../IslandNotificationsController.swift | 31 ++++++++++++++----- 3 files changed, 28 insertions(+), 10 deletions(-) diff --git a/Plugins/IslandNotifications/Sources/IslandNotificationAX.swift b/Plugins/IslandNotifications/Sources/IslandNotificationAX.swift index 5fc0e0901..15ac02d83 100644 --- a/Plugins/IslandNotifications/Sources/IslandNotificationAX.swift +++ b/Plugins/IslandNotifications/Sources/IslandNotificationAX.swift @@ -241,7 +241,8 @@ final class IslandNotification: @unchecked Sendable { @MainActor var appName: String? @MainActor var appIcon: NSImage? @MainActor var bundleIdentifier: String? { appURL.flatMap { Bundle(url: $0)?.bundleIdentifier } } - /// Set for a card made from a finished Claude chat turn (no system banner behind it). + /// Set for a card made from a finished Claude chat turn. Behind it is MacTools' own banner, which + /// is tracked like any other; only what the card shows and where a reply goes differ. @MainActor var claudeChat: IslandClaudeChat? /// Claude chat cards and Messages banners get the inline reply field. Messages replies go only /// to the exact conversation id from Messages' history, so they need that history to be readable diff --git a/Plugins/IslandNotifications/Sources/IslandNotificationHistory.swift b/Plugins/IslandNotifications/Sources/IslandNotificationHistory.swift index b9bcb98c2..700479d02 100644 --- a/Plugins/IslandNotifications/Sources/IslandNotificationHistory.swift +++ b/Plugins/IslandNotifications/Sources/IslandNotificationHistory.swift @@ -14,12 +14,14 @@ struct IslandHistoryEntry: Identifiable, Equatable { let bundleIdentifier: String? let title: String let body: String - /// A Claude chat turn: there is no Notification Centre row behind it, only the chat. + /// A Claude chat turn: its row in Notification Centre is MacTools' notice (see `claudeRequestID`). let claudeChat: IslandClaudeChat? /// Banner text lines, for finding a Messages conversation if Notification Centre no longer has it. let lineCount: Int /// MacTools saw the banner arrive; without that its Messages conversation isn't looked up. var arrivalConfirmed = true + /// A Claude entry: MacTools' own notice behind it, removed when the entry is opened or cleared. + var claudeRequestID: String? var groupKey: String { bundleIdentifier ?? appName } diff --git a/Plugins/IslandNotifications/Sources/IslandNotificationsController.swift b/Plugins/IslandNotifications/Sources/IslandNotificationsController.swift index e67718d98..0c01479a3 100644 --- a/Plugins/IslandNotifications/Sources/IslandNotificationsController.swift +++ b/Plugins/IslandNotifications/Sources/IslandNotificationsController.swift @@ -535,7 +535,7 @@ final class IslandNotificationsController { if !restored { logger.error("Could not put back a notification window") } dropWaiting { CFEqual($0.window, window) } hidden.removeAll { CFEqual($0.window, window) } - if let current = queue.current, current.claudeChat == nil, CFEqual(current.window, window) { + if let current = queue.current, CFEqual(current.window, window) { finishCurrent(dismissNative: false, reason: "banner back to native") } } @@ -812,8 +812,10 @@ final class IslandNotificationsController { lifetimeTimer?.invalidate(); lifetimeTimer = nil let generation = generation if let link = notification.claudeChat?.link { - // A Claude chat card opens its chat with Claude's own link. + // A Claude chat card opens its chat with Claude's own link; its notice goes, as a + // clicked notification does. NSWorkspace.shared.open(link) + Self.removeClaudeNotice(notification.claudeRequestID) closing = false finishCurrent(dismissNative: false, reason: "opened") return @@ -852,8 +854,8 @@ final class IslandNotificationsController { let motion = NSWorkspace.shared.accessibilityDisplayShouldReduceMotion ? nil : IslandHistoryLayout.motion withAnimation(motion) { history.remove(entry) } } - if let requestID = notification.claudeRequestID { - UNUserNotificationCenter.current().removeDeliveredNotifications(withIdentifiers: [requestID]) + if notification.claudeRequestID != nil { + Self.removeClaudeNotice(notification.claudeRequestID) return } // An alert is closed with the card (finishCurrent), which takes it out of Notification Centre. @@ -877,6 +879,12 @@ final class IslandNotificationsController { } } + /// MacTools' own notice behind a Claude card, taken out of Notification Centre. + private static func removeClaudeNotice(_ requestID: String?) { + guard let requestID else { return } + UNUserNotificationCenter.current().removeDeliveredNotifications(withIdentifiers: [requestID]) + } + // MARK: The panel's Notifications list // // Opening or clearing an entry acts on its row in Notification Centre, out of sight, as a click @@ -893,7 +901,8 @@ final class IslandNotificationsController { bundleIdentifier: notification.bundleIdentifier, title: notification.title, body: notification.body, claudeChat: notification.claudeChat, lineCount: notification.lineCount, - arrivalConfirmed: notification.arrivalConfirmed) + arrivalConfirmed: notification.arrivalConfirmed, + claudeRequestID: notification.claudeRequestID) notification.historyID = entry.id history.add(entry) } @@ -926,7 +935,11 @@ final class IslandNotificationsController { func openHistory(_ entry: IslandHistoryEntry) { logger.notice("list open inCentre=\(entry.centerApp != nil, privacy: .public) claude=\(entry.claudeChat != nil, privacy: .public)") history.remove(entry) - if let link = entry.claudeChat?.link { NSWorkspace.shared.open(link); return } + if let link = entry.claudeChat?.link { + NSWorkspace.shared.open(link) + Self.removeClaudeNotice(entry.claudeRequestID) + return + } Task { var opened = await inCenter(.open, entry) // Gone from Notification Centre (the app withdrew it, or it was cleared there). @@ -944,8 +957,10 @@ final class IslandNotificationsController { func clearHistory(_ entries: [IslandHistoryEntry]) { for entry in entries { history.remove(entry) } + // A Claude entry's row is MacTools' own notice, removed directly. + for entry in entries { Self.removeClaudeNotice(entry.claudeRequestID) } Task { - for entry in entries { _ = await inCenter(.clear, entry) } + for entry in entries where entry.claudeRequestID == nil { _ = await inCenter(.clear, entry) } } } @@ -992,7 +1007,7 @@ final class IslandNotificationsController { // macOS swaps a newer notification from the same app into its existing banner without any // creation event, so re-read the shown card's hidden banner window twice a second. let now = ProcessInfo.processInfo.systemUptime - if now - lastRescan >= 0.5, let current = queue.current, current.claudeChat == nil, !closing { + if now - lastRescan >= 0.5, let current = queue.current, !closing { lastRescan = now receive(IslandAXElement(value: current.window)) }