import AppKit @MainActor final class HoverControlsView: OverlayChromeView { private(set) var buttons: [HoverActionButton] = [] let tabsView = HoverTabsView() private var presentations: [HoverControlPresentation] = [] var actionTopInset: CGFloat = 0 { didSet { needsLayout = true } } var invoke: ((HoverControlID, Bool) -> Void)? var alwaysFloat: (() -> Void)? var dismiss: (() -> Void)? override var isFlipped: Bool { true } override init(frame: CGRect, paletteSource: OverlayPaletteSource = .shared) { super.init(frame: frame, paletteSource: paletteSource) withoutImplicitAnimations { layer?.cornerRadius = 12 layer?.cornerCurve = .continuous } setAccessibilityElement(true) setAccessibilityRole(.group) setAccessibilityLabel(UIStrings.text("Window controls")) setAccessibilityIdentifier("hover.controls") tabsView.isHidden = true addSubview(tabsView) for id in HoverControlID.allCases { let button = HoverActionButton(id: id) button.invoke = { [weak self] option in self?.invoke?(id, option) } button.navigate = { [weak self] forward in self?.focusNext(after: id, forward: forward) } button.tabNavigate = { [weak self, weak button] forward in guard let button else { return } self?.focusAdjacent(to: button, forward: forward) } button.dismiss = { [weak self] in self?.dismiss?() } button.bezelStyle = .rounded button.isBordered = false button.focusRingType = .exterior button.setAccessibilityIdentifier("hover.\(id)") addSubview(button) buttons.append(button) } setAccessibilityChildren(buttons) buttons[HoverControlID.floating.rawValue].setAccessibilityCustomActions([ NSAccessibilityCustomAction( name: UIStrings.text("Always float"), handler: { [weak self] in guard let action = self?.alwaysFloat else { return false } action() return true }) ]) } required init?(coder: NSCoder) { fatalError("init(coder:) is unavailable") } override func layout() { super.layout() let visible = buttons.filter { !$0.isHidden } for button in buttons where button.isHidden { button.frame = .zero } let inset = min(max(0, actionTopInset), bounds.height) tabsView.frame = CGRect(x: bounds.minX, y: bounds.minY, width: bounds.width, height: inset) let actions = CGRect(x: bounds.minX, y: bounds.minY + inset, width: bounds.width, height: bounds.height - inset) for (button, frame) in zip(visible, HoverBarModel.controlFrames(in: actions, count: visible.count)) { button.frame = frame } } func configureTabs(_ tabs: [HoverWindowTab]) { tabsView.configure(tabs) actionTopInset = tabs.count > 1 ? 38 : 0 refreshAccessibilityAndKeyboardOrder() } func configure(_ presentations: [HoverControlPresentation]) { guard self.presentations != presentations else { return } self.presentations = presentations for (button, presentation) in zip(buttons, presentations) { button.isEnabled = presentation.enabled button.isHidden = !presentation.visible let title = NSMutableAttributedString( string: presentation.title, attributes: [.font: NSFont.systemFont(ofSize: 12, weight: .medium)]) if !presentation.shortcut.isEmpty { title.append( NSAttributedString( string: "\n" + presentation.shortcut, attributes: [ .font: NSFont.systemFont(ofSize: 10), .foregroundColor: NSColor.secondaryLabelColor, ])) } let style = NSMutableParagraphStyle() style.alignment = .center style.lineBreakMode = .byTruncatingTail title.addAttribute(.paragraphStyle, value: style, range: NSRange(location: 0, length: title.length)) button.icon = presentation.icon button.attributedTitle = title button.setAccessibilityLabel(presentation.title) button.setAccessibilityHelp(presentation.help) button.toolTip = presentation.toolTip } refreshAccessibilityAndKeyboardOrder() refreshPalette() needsLayout = true } func focusFirst() { if let button = buttons.first(where: { $0.isEnabled && !$0.isHidden }) { window?.makeFirstResponder(button) } } private var keyboardButtons: [NSButton] { let tabs = tabsView.isHidden ? [] : (tabsView.accessibilityChildren() ?? []).compactMap { $0 as? NSButton } return (tabs + buttons).filter { $0.isEnabled && !$0.isHidden } } private func refreshAccessibilityAndKeyboardOrder() { let actions: [NSView] = buttons.filter { !$0.isHidden } setAccessibilityChildren((tabsView.isHidden ? [] : [tabsView]) + actions) let ordered = keyboardButtons for (index, button) in ordered.enumerated() { button.nextKeyView = ordered[(index + 1) % ordered.count] } } private func focusAdjacent(to button: NSButton, forward: Bool) { let ordered = keyboardButtons guard !ordered.isEmpty, let index = ordered.firstIndex(where: { $0 === button }) else { return } let next = (index + (forward ? 1 : ordered.count - 1)) % ordered.count window?.makeFirstResponder(ordered[next]) } private func focusNext(after id: HoverControlID, forward: Bool) { for offset in 1...buttons.count { let index = (id.rawValue + (forward ? offset : buttons.count - offset)) % buttons.count if buttons[index].isEnabled && !buttons[index].isHidden { window?.makeFirstResponder(buttons[index]) return } } } } enum HoverControlIcon: Equatable { case symbol(String) case layout(MenuIcon) } struct HoverControlPresentation: Equatable { let icon: HoverControlIcon let title: String let shortcut: String let enabled: Bool let visible: Bool let help: String let toolTip: String init( title: String, shortcut: String, enabled: Bool, help: String, toolTip: String? = nil, visible: Bool = true, icon: HoverControlIcon = .symbol("rectangle") ) { self.icon = icon self.title = title self.shortcut = shortcut self.enabled = enabled self.visible = visible self.help = help self.toolTip = toolTip ?? help } } @MainActor final class HoverActionButton: NSButton { let id: HoverControlID private let actionCell = HoverActionButtonCell(textCell: "") var icon: HoverControlIcon { get { actionCell.icon } set { actionCell.icon = newValue; needsDisplay = true } } var invoke: ((Bool) -> Void)? var navigate: ((Bool) -> Void)? var tabNavigate: ((Bool) -> Void)? var dismiss: (() -> Void)? var optionHeld = false init(id: HoverControlID) { self.id = id super.init(frame: .zero) cell = actionCell target = self action = #selector(pressed) } required init?(coder: NSCoder) { fatalError("init(coder:) is unavailable") } override var needsPanelToBecomeKey: Bool { false } override var acceptsFirstResponder: Bool { isEnabled && !isHidden } override func acceptsFirstMouse(for event: NSEvent?) -> Bool { true } @objc private func pressed() { invoke?(optionHeld || NSApplication.shared.currentEvent?.modifierFlags.contains(.option) == true) } override func keyDown(with event: NSEvent) { switch event.charactersIgnoringModifiers { case "\t": (tabNavigate ?? navigate)?(!event.modifierFlags.contains(.shift)) case "\u{19}": (tabNavigate ?? navigate)?(false) case "\u{F702}": navigate?(false) case "\u{F703}": navigate?(true) case "\u{F700}", "\u{F701}": if id == .display { invoke?(false) } else { super.keyDown(with: event) } case "\r", " ": invoke?(event.modifierFlags.contains(.option)) case "\u{1B}": dismiss?() default: super.keyDown(with: event) } } } @MainActor private final class HoverActionButtonCell: NSButtonCell { var icon: HoverControlIcon = .symbol("rectangle") override func drawInterior(withFrame cellFrame: NSRect, in controlView: NSView) { if isHighlighted { NSColor.selectedControlColor.withAlphaComponent(0.25).setFill() NSBezierPath(roundedRect: cellFrame.insetBy(dx: 2, dy: 2), xRadius: 6, yRadius: 6).fill() } _ = drawTitle(attributedTitle, withFrame: cellFrame, in: controlView) } override func drawTitle(_ title: NSAttributedString, withFrame frame: NSRect, in controlView: NSView) -> NSRect { let lines = title.string.components(separatedBy: "\n") guard let first = lines.first else { return frame } let color = isEnabled ? (controlView as? NSButton)?.contentTintColor ?? .labelColor : .disabledControlTextColor let label = NSAttributedString( string: first, attributes: [ .font: NSFont.systemFont(ofSize: 12, weight: .medium), .foregroundColor: color, ]) let hint = NSAttributedString( string: lines.dropFirst().joined(separator: " "), attributes: [ .font: NSFont.systemFont(ofSize: 10), .foregroundColor: isEnabled ? NSColor.secondaryLabelColor : NSColor.disabledControlTextColor, ]) let iconSize: CGFloat = 16 let spacing: CGFloat = 5 let rowHeight = max(iconSize, ceil(label.size().height)) let hintHeight = hint.length == 0 ? 0 : ceil(hint.size().height) let gap: CGFloat = hintHeight == 0 ? 0 : 4 let contentHeight = rowHeight + gap + hintHeight let top = controlView.isFlipped ? frame.midY - contentHeight / 2 : frame.midY + contentHeight / 2 - rowHeight let labelWidth = min(ceil(label.size().width), max(0, frame.width - iconSize - spacing - 8)) let rowWidth = iconSize + spacing + labelWidth let iconFrame = CGRect( x: frame.midX - rowWidth / 2, y: top + (rowHeight - iconSize) / 2, width: iconSize, height: iconSize) drawIcon(in: iconFrame, color: color, flipped: controlView.isFlipped) label.draw( in: CGRect( x: iconFrame.maxX + spacing, y: top + (rowHeight - label.size().height) / 2, width: labelWidth, height: rowHeight)) if hintHeight > 0 { let y = controlView.isFlipped ? top + rowHeight + gap : top - gap - hintHeight let width = min(ceil(hint.size().width), max(0, frame.width - 8)) hint.draw(in: CGRect(x: frame.midX - width / 2, y: y, width: width, height: hintHeight)) } return frame } private func drawIcon(in frame: CGRect, color: NSColor, flipped: Bool) { switch icon { case .symbol(let name): let image = NSImage(systemSymbolName: name, accessibilityDescription: nil)? .withSymbolConfiguration(.init(pointSize: 14, weight: .medium)) let tinted = image?.withSymbolConfiguration(.init(paletteColors: [color])) tinted?.draw(in: frame, from: .zero, operation: .sourceOver, fraction: 1, respectFlipped: true, hints: nil) case .layout(.tiles(let tiles)): color.set() for tile in tiles { let rect = CGRect( x: frame.minX + tile.frame.minX / 18 * frame.width, y: frame.minY + (flipped ? tile.frame.minY : 18 - tile.frame.maxY) / 18 * frame.height, width: tile.frame.width / 18 * frame.width, height: tile.frame.height / 18 * frame.height) let path = NSBezierPath(roundedRect: rect, xRadius: 0.7, yRadius: 0.7) if tile.isFocused { path.fill() } else { path.lineWidth = 1; path.stroke() } } case .layout(.logo): break } } }