Skip to content

Commit ed433d5

Browse files
author
Mirror Bot
committed
Mirror from private (10d157c1)
1 parent 47d4a71 commit ed433d5

2 files changed

Lines changed: 130 additions & 59 deletions

File tree

‎Sources/WhatCable/App/App.swift‎

Lines changed: 124 additions & 59 deletions
Original file line numberDiff line numberDiff line change
@@ -414,61 +414,66 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSPopoverDelegate, NSW
414414
/// Point size every menu-bar glyph is rendered at.
415415
private static let menuBarIconPointSize: CGFloat = 16
416416

417-
/// The fixed canvas size every menu-bar glyph is composited into, so the
418-
/// button image is the same width no matter which symbol is chosen. Computed
419-
/// once as the largest rendered glyph across all offered icons (so none is
420-
/// clipped). A constant image width means swapping the icon never changes the
421-
/// button width, so the popover never has to close and reopen to re-centre
422-
/// its arrow. A plain SymbolConfiguration does NOT achieve this: it pins the
423-
/// point size, but glyphs still have different intrinsic widths (e.g.
424-
/// `cable.connector.horizontal` is wider than `bolt.fill`), which shifted the
425-
/// anchor and forced the reseat blink (issue #313).
426-
private static let menuBarIconCanvasSize: NSSize = {
427-
let config = NSImage.SymbolConfiguration(pointSize: menuBarIconPointSize, weight: .regular)
428-
var size = NSSize(width: menuBarIconPointSize, height: menuBarIconPointSize)
429-
for name in AppSettings.menuBarIconChoices {
430-
guard let image = NSImage(systemSymbolName: name, accessibilityDescription: nil)?
431-
.withSymbolConfiguration(config) else { continue }
432-
size.width = max(size.width, image.size.width)
433-
size.height = max(size.height, image.size.height)
434-
}
435-
return NSSize(width: ceil(size.width), height: ceil(size.height))
436-
}()
437-
438-
/// Composite an SF Symbol, centred, into the fixed canvas so every glyph
439-
/// occupies the same width. Returns a template image so the menu bar tints it.
417+
/// The box every menu-bar glyph is drawn into. One size for all of them, so
418+
/// swapping icons never changes the button width and so never moves the
419+
/// popover: the status item is right-aligned in the menu bar, so a width
420+
/// change slides its left edge, and the popover correctly follows the icon.
421+
///
422+
/// The size is chosen, not measured off the widest icon. Sizing the box to
423+
/// the widest glyph is what made the item 42pt wide when a typical menu bar
424+
/// extra is 22-26pt (issue #411): the default `cable.connector` is only 10pt
425+
/// wide and was being padded out to 24pt to match `powerplug.fill`. Glyphs
426+
/// wider or taller than this box are scaled down to fit instead, keeping
427+
/// their aspect ratio, so every icon gets the same 18x18 footprint without
428+
/// inheriting the widest one's. Note that is a constant footprint, not a
429+
/// constant painted glyph: a symbol already smaller than the box keeps its
430+
/// natural size and simply sits centred in it.
431+
private static let menuBarIconBoxSize = NSSize(width: 18, height: 18)
432+
433+
/// The uniform-size glyph for a symbol name, or nil if the symbol is
434+
/// unavailable on this macOS. Returns a template image so the menu bar tints it.
435+
///
436+
/// Aspect-fit into `menuBarIconBoxSize` and centred, so every icon occupies
437+
/// exactly the same space. A plain SymbolConfiguration does NOT achieve this:
438+
/// it pins the point size, but glyphs still have different intrinsic widths
439+
/// (`cable.connector.horizontal` is 24pt against `cable.connector`'s 10pt),
440+
/// which shifts the button and moves the popover with it (issue #313).
440441
///
441442
/// Uses the drawing-handler initialiser rather than lockFocus so the glyph
442443
/// rasterises at each display's backing scale (crisp on Retina) instead of a
443444
/// single baked-in scale.
444-
private static func centeredMenuBarIcon(_ symbol: NSImage) -> NSImage {
445-
let size = menuBarIconCanvasSize
446-
let symbolSize = symbol.size
447-
let canvas = NSImage(size: size, flipped: false) { _ in
445+
private static func glyphImage(_ symbolName: String) -> NSImage? {
446+
let config = NSImage.SymbolConfiguration(pointSize: menuBarIconPointSize, weight: .regular)
447+
guard let symbol = NSImage(systemSymbolName: symbolName, accessibilityDescription: AppInfo.name)?
448+
.withSymbolConfiguration(config) else { return nil }
449+
450+
let box = menuBarIconBoxSize
451+
let natural = symbol.size
452+
// Only ever scale down: a glyph already inside the box keeps its own size
453+
// rather than being blown up to fill it.
454+
let scale = min(1, min(box.width / natural.width, box.height / natural.height))
455+
let drawn = NSSize(width: natural.width * scale, height: natural.height * scale)
456+
457+
let canvas = NSImage(size: box, flipped: false) { _ in
448458
let origin = NSPoint(
449-
x: ((size.width - symbolSize.width) / 2).rounded(),
450-
y: ((size.height - symbolSize.height) / 2).rounded()
459+
x: ((box.width - drawn.width) / 2).rounded(),
460+
y: ((box.height - drawn.height) / 2).rounded()
461+
)
462+
symbol.draw(
463+
in: NSRect(origin: origin, size: drawn),
464+
from: .zero,
465+
operation: .sourceOver,
466+
fraction: 1.0
451467
)
452-
symbol.draw(at: origin, from: .zero, operation: .sourceOver, fraction: 1.0)
453468
return true
454469
}
455470
canvas.isTemplate = true
456471
return canvas
457472
}
458473

459-
/// The centred, constant-width glyph for a symbol name, or nil if the symbol
460-
/// is unavailable on this macOS.
461-
private static func glyphImage(_ symbolName: String) -> NSImage? {
462-
let config = NSImage.SymbolConfiguration(pointSize: menuBarIconPointSize, weight: .regular)
463-
guard let symbol = NSImage(systemSymbolName: symbolName, accessibilityDescription: AppInfo.name)?
464-
.withSymbolConfiguration(config) else { return nil }
465-
return centeredMenuBarIcon(symbol)
466-
}
467-
468474
/// Set the status-item button to the plain glyph (no readout). Falls back to
469475
/// a short text label if the SF Symbol is unavailable (keeps the menu bar
470-
/// usable). The glyph is a fixed-width canvas so the button width is identical
471-
/// for every icon, keeping the popover anchor stable across an icon swap.
476+
/// usable).
472477
private func applyGlyph(to button: NSStatusBarButton, symbolName: String) {
473478
if let image = Self.glyphImage(symbolName) {
474479
button.image = image
@@ -482,19 +487,70 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSPopoverDelegate, NSW
482487
}
483488
}
484489

485-
/// Re-anchor the popover after the status-item button changed width, so its
486-
/// arrow stays centred on the button. This works by closing and reopening,
487-
/// so it must never run while the popover is pinned (`keepOpen`): that close
488-
/// would dismiss a popover the user deliberately kept open. With the live
489-
/// watts label on, the label changes width as the number changes (e.g.
490-
/// 9W -> 10W), so without this guard a pinned popover snapped shut whenever
491-
/// the wattage ticked over. When pinned we accept a slightly off-centre
492-
/// arrow rather than shutting the window.
493-
private func reseatPopoverAfterWidthChange(button: NSStatusBarButton, widthBefore: CGFloat) {
494-
guard !Self.refreshSignal.keepOpen else { return }
495-
guard button.frame.width != widthBefore, let popover, popover.isShown else { return }
496-
popover.performClose(nil)
497-
togglePopover(from: button)
490+
/// Re-anchor an open popover after the status-item button changed width, so
491+
/// its arrow stays centred on the button.
492+
///
493+
/// AppKit's header says popovers "are automatically moved when the location
494+
/// or size of the positioning view changes", but that does not hold for an
495+
/// `NSStatusBarButton`: issue #313 is a reproduction, with a screenshot, of
496+
/// the arrow going misaligned on an icon swap and only correcting on the
497+
/// next reopen. So the re-anchor has to be explicit.
498+
///
499+
/// It is done by calling `show` again, which the header documents as a
500+
/// re-anchor rather than a reopen: "If the popover is already being shown,
501+
/// this method will update to be associated with the new view and
502+
/// positioningRect passed."
503+
///
504+
/// Assigning `positioningRect` instead does NOT work here, which was tried
505+
/// first and rejected on evidence: the arrow was left sitting well to the
506+
/// left of the icon after an icon swap. The reason is that `positioningRect`
507+
/// is a rectangle *within* the positioning view, and a status-item button's
508+
/// `bounds` always has a zero origin, so only its size ever changes. When a
509+
/// menu bar item changes width what actually moves is the item's window, and
510+
/// assigning a same-origin rect never tells AppKit to recompute against it.
511+
/// `show` re-reads the view's position, so it does.
512+
///
513+
/// Animation is suppressed for the re-anchor so this reads as the arrow
514+
/// staying put, not the panel re-presenting itself.
515+
///
516+
/// The previous implementation called `performClose` and reopened, which is
517+
/// why it needed a `keepOpen` guard: that close dismissed popovers the user
518+
/// had pinned (issue #346). Nothing closes here, so no guard is needed and
519+
/// pinned popovers get their arrow re-centred too.
520+
/// There is deliberately no "did the width actually change?" test. A status
521+
/// item's button frame is not guaranteed to report a new width synchronously
522+
/// (the status bar reflows a `variableLength` item on its own schedule), so
523+
/// such a test can read stale and skip the re-anchor entirely. The caller
524+
/// already returns early unless the rendered content changed, so this only
525+
/// runs when the geometry plausibly moved.
526+
private func reanchorPopoverAfterWidthChange() {
527+
// Deferred a runloop turn on purpose. An NSStatusItem with
528+
// `variableLength` reflows to fit its contents on the status bar's own
529+
// schedule, not synchronously inside the layout call above, so
530+
// re-anchoring immediately reads the button at its OLD width. The item
531+
// then grows and leaves the arrow off-centre, which is what turning the
532+
// watts readout on did: the label adds ~29pt, and the arrow stayed put
533+
// while the item widened underneath it. By the next turn the status bar
534+
// has settled and `bounds` is the real rect.
535+
// The button is deliberately re-read here rather than captured. Between
536+
// scheduling and the next turn the menu bar can be torn down and rebuilt
537+
// (`tearDownMenuBarMode` then `setUpMenuBarMode`, e.g. a display-mode
538+
// switch), which leaves the captured button belonging to a status item
539+
// that has been removed. Showing a popover relative to a view that is no
540+
// longer in a window raises NSInvalidArgumentException, so the stale
541+
// button has to be dropped, not merely null-checked.
542+
DispatchQueue.main.async { [weak self] in
543+
guard let self,
544+
let button = self.statusItem?.button,
545+
button.window != nil,
546+
let popover = self.popover,
547+
popover.isShown
548+
else { return }
549+
let animated = popover.animates
550+
popover.animates = false
551+
popover.show(relativeTo: button.bounds, of: button, preferredEdge: .minY)
552+
popover.animates = animated
553+
}
498554
}
499555

500556
/// Single entry point that paints the status item for the current state: the
@@ -532,7 +588,6 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSPopoverDelegate, NSW
532588
guard content != lastMenuBarContent else { return }
533589
lastMenuBarContent = content
534590

535-
let widthBefore = button.frame.width
536591
switch content {
537592
case .glyphOnly(let symbol):
538593
applyGlyph(to: button, symbolName: symbol)
@@ -548,14 +603,22 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSPopoverDelegate, NSW
548603
button.needsLayout = true
549604
button.needsDisplay = true
550605
button.layoutSubtreeIfNeeded()
551-
reseatPopoverAfterWidthChange(button: button, widthBefore: widthBefore)
606+
reanchorPopoverAfterWidthChange()
552607
}
553608

554609
/// The figure-space-padded "NNW" title for the menu bar watts label. The
555610
/// padding keeps the width constant across 9 -> 10: U+2007 (FIGURE SPACE) is
556611
/// exactly one digit wide in a monospaced-digit font, so a padded single
557-
/// digit lines up with a double digit and the anchor doesn't drift as the
558-
/// value ticks.
612+
/// digit lines up with a double digit (issue #346).
613+
///
614+
/// This padding is kept deliberately, even though the popover is now
615+
/// re-anchored on a width change rather than closed and reopened. The
616+
/// re-anchor keeps the arrow centred, but it cannot stop the item itself
617+
/// changing width, and a live wattage ticking across 9 -> 10 would then
618+
/// shuffle the whole popover sideways every few seconds while the user is
619+
/// reading it. Costing 8pt of menu bar, only while charging below 10W, is
620+
/// the cheaper side of that trade. The icon padding was a different case
621+
/// and was removed: see `glyphImage`.
559622
private static func wattsAttributedTitle(_ watts: Int) -> NSAttributedString {
560623
let digits = String(watts)
561624
let padded = digits.count < 2
@@ -598,7 +661,9 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSPopoverDelegate, NSW
598661
/// alpha, so both tint to the menu bar colour at their drawn opacity).
599662
private static func menuBarBarImage(symbolName: String, fillStep: Int) -> NSImage {
600663
let glyph = glyphImage(symbolName)
601-
let glyphSize = menuBarIconCanvasSize
664+
// Every glyph is drawn into the same box, so the composite is a constant
665+
// width whether or not the symbol resolved.
666+
let glyphSize = menuBarIconBoxSize
602667
let totalWidth = glyphSize.width + powerBarGap + powerBarWidth
603668
let height = max(glyphSize.height, powerBarHeight)
604669
let fraction = Double(fillStep) / Double(powerBarSteps)

‎Sources/WhatCable/Views/SettingsView.swift‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -221,6 +221,12 @@ struct MenuBarIconPicker: View {
221221
Image(systemName: name)
222222
.scaledFont(.body)
223223
.frame(width: 28 * fontScale, height: 24 * fontScale)
224+
// Without this the button only responds where the glyph
225+
// actually paints: `.plain` hit-tests the rendered
226+
// content, and the box below is drawn as decoration, so
227+
// the empty space inside it was dead. Makes the whole
228+
// swatch the target, which is what it looks like.
229+
.contentShape(RoundedRectangle(cornerRadius: 6))
224230
.background(
225231
RoundedRectangle(cornerRadius: 6)
226232
.fill(selection == name ? Color.accentColor.opacity(0.25) : Color.clear)

0 commit comments

Comments
 (0)