Jotley / app / macOS / Views / RecordingWidgetPanel.swift
| 1 | import AppKit |
| 2 | import SwiftUI |
| 3 | |
| 4 | final class RecordingWidgetPanel: NSPanel, NSWindowDelegate { |
| 5 | private static let positionXKey = "recordingWidgetPositionX" |
| 6 | private static let positionYKey = "recordingWidgetPositionY" |
| 7 | |
| 8 | private let windowSize = CGSize(width: 220, height: 52) |
| 9 | |
| 10 | init(viewModel: RecordingWidgetViewModel, onWidgetTapped: (() -> Void)? = nil) { |
| 11 | |
| 12 | let frame = NSRect(origin: RecordingWidgetPanel.initialOrigin(windowSize: windowSize), size: windowSize) |
| 13 | super.init( |
| 14 | contentRect: frame, |
| 15 | styleMask: [.borderless, .nonactivatingPanel], |
| 16 | backing: .buffered, |
| 17 | defer: false |
| 18 | ) |
| 19 | |
| 20 | level = .floating |
| 21 | collectionBehavior = [.canJoinAllSpaces, .fullScreenAuxiliary] |
| 22 | hidesOnDeactivate = false |
| 23 | isMovableByWindowBackground = true |
| 24 | isMovable = true |
| 25 | backgroundColor = .clear |
| 26 | isOpaque = false |
| 27 | hasShadow = false |
| 28 | animationBehavior = .none |
| 29 | delegate = self |
| 30 | |
| 31 | let widgetView = RecordingWidgetView(viewModel: viewModel, onWidgetTapped: onWidgetTapped) |
| 32 | let hostingView = NSHostingView(rootView: widgetView) |
| 33 | hostingView.frame = NSRect(origin: .zero, size: windowSize) |
| 34 | hostingView.wantsLayer = true |
| 35 | hostingView.layer?.backgroundColor = NSColor.clear.cgColor |
| 36 | hostingView.layer?.masksToBounds = false |
| 37 | contentView = hostingView |
| 38 | } |
| 39 | |
| 40 | func windowDidMove(_ notification: Notification) { |
| 41 | savePosition() |
| 42 | } |
| 43 | |
| 44 | private func savePosition() { |
| 45 | let origin = frame.origin |
| 46 | UserDefaults.standard.set(origin.x, forKey: Self.positionXKey) |
| 47 | UserDefaults.standard.set(origin.y, forKey: Self.positionYKey) |
| 48 | } |
| 49 | |
| 50 | private static func initialOrigin(windowSize: CGSize) -> CGPoint { |
| 51 | let defaults = UserDefaults.standard |
| 52 | let savedX = defaults.object(forKey: positionXKey) as? Double |
| 53 | let savedY = defaults.object(forKey: positionYKey) as? Double |
| 54 | |
| 55 | if let savedX, let savedY { |
| 56 | return CGPoint(x: savedX, y: savedY) |
| 57 | } |
| 58 | |
| 59 | guard let screen = NSScreen.main else { |
| 60 | return CGPoint(x: 20, y: 20) |
| 61 | } |
| 62 | |
| 63 | let frame = screen.visibleFrame |
| 64 | let x = frame.maxX - windowSize.width - 24 |
| 65 | let y = frame.minY + 24 |
| 66 | return CGPoint(x: x, y: y) |
| 67 | } |
| 68 | } |