Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280import AppKitimport UniformTypeIdentifiers
/// Borderless panels refuse key status by default; we need it for typing.final class LauncherPanel: NSPanel { override var canBecomeKey: Bool { true } override var canBecomeMain: Bool { false }}
/// One result line: icon, name, and an optional dimmed detail at the right; highlighted when selected.final class ResultRow: NSView { private let icon = NSImageView() private let label = NSTextField(labelWithString: "") private let detail = NSTextField(labelWithString: "") var onClick: (() -> Void)? var isSelected = false { didSet { layer?.backgroundColor = isSelected ? NSColor.controlAccentColor.cgColor : nil label.textColor = isSelected ? .white : .labelColor detail.textColor = isSelected ? NSColor.white.withAlphaComponent(0.75) : .secondaryLabelColor } }
override init(frame: NSRect) { super.init(frame: frame) wantsLayer = true layer?.cornerRadius = 7 icon.imageScaling = .scaleProportionallyUpOrDown label.font = .systemFont(ofSize: 16) label.lineBreakMode = .byTruncatingTail detail.font = .systemFont(ofSize: 12) detail.alignment = .right detail.lineBreakMode = .byTruncatingMiddle addSubview(icon) addSubview(label) addSubview(detail) }
required init?(coder: NSCoder) { fatalError("not used") }
func configure(name: String, detail text: String?, icon image: NSImage) { label.stringValue = name detail.stringValue = text ?? "" detail.isHidden = text == nil icon.image = image needsLayout = true }
override func layout() { super.layout() let h = bounds.height let detailWidth = detail.isHidden ? 0 : min(300, detail.intrinsicContentSize.width) icon.frame = NSRect(x: 10, y: (h - 26) / 2, width: 26, height: 26) label.frame = NSRect(x: 46, y: (h - 20) / 2, width: bounds.width - 56 - detailWidth - (detailWidth > 0 ? 10 : 0), height: 20) detail.frame = NSRect(x: bounds.width - 10 - detailWidth, y: (h - 16) / 2, width: detailWidth, height: 16) }
override func mouseDown(with event: NSEvent) { onClick?() }}
/// The floating search panel: a text field with a short list of matches underneath.final class LauncherController: NSObject, NSTextFieldDelegate { private static let width: CGFloat = 600 private static let fieldHeight: CGFloat = 48 private static let rowHeight: CGFloat = 40 private static let pad: CGFloat = 10 private static let cornerRadius: CGFloat = 12 private static let maxRows = 8
private let index: AppIndex private let usage: Usage private let panel: LauncherPanel private let background = NSVisualEffectView() private let field = NSTextField() private var rows: [ResultRow] = [] private var results: [AppEntry] = [] private var selected = 0 /// Screen y of the panel's top edge; the panel grows downward from here as results change. private var top: CGFloat = 0 private var iconCache: [String: NSImage] = [:]
init(index: AppIndex, usage: Usage) { self.index = index self.usage = usage panel = LauncherPanel( contentRect: NSRect(x: 0, y: 0, width: LauncherController.width, height: 100), styleMask: [.borderless, .nonactivatingPanel], backing: .buffered, defer: false ) super.init()
panel.level = .floating panel.isOpaque = false panel.backgroundColor = .clear panel.hasShadow = true panel.isMovable = false panel.hidesOnDeactivate = false panel.isReleasedWhenClosed = false panel.collectionBehavior = [.canJoinAllSpaces, .fullScreenAuxiliary, .transient]
background.material = .popover background.blendingMode = .behindWindow background.state = .active // Behind-window blur ignores layer corner radii; a mask image is what actually shapes it. background.maskImage = LauncherController.roundedMask(radius: LauncherController.cornerRadius) panel.contentView = background
field.font = .systemFont(ofSize: 24, weight: .light) field.isBordered = false field.drawsBackground = false field.focusRingType = .none field.placeholderString = "Launch…" field.delegate = self background.addSubview(field)
for i in 0..<LauncherController.maxRows { let row = ResultRow(frame: .zero) row.isHidden = true row.onClick = { [weak self] in self?.selected = i self?.launchSelected() } background.addSubview(row) rows.append(row) }
index.onChange = { [weak self] in guard let self else { return } // Every rescan drops the cached icons, so an updated app or a changed // mollusc icon shows up within a minute rather than at the next restart. self.iconCache.removeAll() if self.panel.isVisible { self.refresh() } } NotificationCenter.default.addObserver( self, selector: #selector(resignedKey), name: NSWindow.didResignKeyNotification, object: panel ) }
private static func roundedMask(radius: CGFloat) -> NSImage { let size = NSSize(width: radius * 2 + 1, height: radius * 2 + 1) let image = NSImage(size: size, flipped: false) { rect in NSColor.black.setFill() NSBezierPath(roundedRect: rect, xRadius: radius, yRadius: radius).fill() return true } image.capInsets = NSEdgeInsets(top: radius, left: radius, bottom: radius, right: radius) image.resizingMode = .stretch return image }
// MARK: Showing and hiding
func toggle() { panel.isVisible ? hide() : show() }
func show() { let mouse = NSEvent.mouseLocation let screen = NSScreen.screens.first { NSMouseInRect(mouse, $0.frame, false) } ?? NSScreen.main ?? NSScreen.screens[0] let visible = screen.visibleFrame top = visible.maxY - visible.height * 0.2 panel.setFrameOrigin(NSPoint(x: visible.midX - LauncherController.width / 2, y: top - panel.frame.height))
field.stringValue = "" refresh() panel.makeKeyAndOrderFront(nil) panel.makeFirstResponder(field) index.rescanIfStale() }
func hide() { panel.orderOut(nil) }
@objc private func resignedKey() { hide() }
// MARK: Results
private func refresh() { let query = field.stringValue.trimmingCharacters(in: .whitespaces).lowercased() results = Matcher.rank(query, in: index.entries, usage: usage) .prefix(LauncherController.maxRows) .map(\.entry) selected = 0 for (i, entry) in results.enumerated() { rows[i].configure(name: entry.name, detail: entry.detail, icon: icon(for: entry)) } updateSelection() relayout() }
private func icon(for entry: AppEntry) -> NSImage { if let cached = iconCache[entry.url.path] { return cached } let image: NSImage switch entry.kind { case .bundle: image = NSWorkspace.shared.icon(forFile: entry.url.path) case .mollusc: image = entry.iconFile.flatMap { NSImage(contentsOfFile: $0) } ?? NSWorkspace.shared.icon(for: .applicationBundle) } iconCache[entry.url.path] = image return image }
private func updateSelection() { for (i, row) in rows.enumerated() { row.isSelected = i == selected && i < results.count } }
private func relayout() { let count = results.count let pad = LauncherController.pad let height = pad * 2 + LauncherController.fieldHeight + (count > 0 ? CGFloat(count) * LauncherController.rowHeight + 6 : 0) panel.setFrame( NSRect(x: panel.frame.minX, y: top - height, width: LauncherController.width, height: height), display: true ) field.frame = NSRect( x: pad + 8, y: height - pad - LauncherController.fieldHeight + 8, width: LauncherController.width - 2 * (pad + 8), height: 32 ) for (i, row) in rows.enumerated() { row.isHidden = i >= count let y = height - pad - LauncherController.fieldHeight - 6 - CGFloat(i + 1) * LauncherController.rowHeight row.frame = NSRect(x: pad, y: y, width: LauncherController.width - 2 * pad, height: LauncherController.rowHeight) } panel.invalidateShadow() }
private func move(_ delta: Int) { guard !results.isEmpty else { return } selected = (selected + delta + results.count) % results.count updateSelection() }
private func launchSelected() { guard selected < results.count else { return } let entry = results[selected] hide() usage.record(entry) switch entry.kind { case .bundle: let configuration = NSWorkspace.OpenConfiguration() configuration.activates = true NSWorkspace.shared.openApplication(at: entry.url, configuration: configuration) { _, error in if let error { NSLog("FreeLaunch: could not open \(entry.url.path): \(error)") } } case .mollusc: MolluscApps.launch(entry) } }
// MARK: NSTextFieldDelegate
func controlTextDidChange(_ obj: Notification) { refresh() }
func control(_ control: NSControl, textView: NSTextView, doCommandBy selector: Selector) -> Bool { switch selector { case #selector(NSResponder.moveUp(_:)): move(-1) case #selector(NSResponder.moveDown(_:)): move(1) case #selector(NSResponder.insertNewline(_:)): launchSelected() case #selector(NSResponder.cancelOperation(_:)), #selector(NSResponder.complete(_:)): hide() default: return false } return true }}