Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 18 additions & 3 deletions App/AppModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -43,10 +43,19 @@ final class AppModel {
"com.apphousekitchen.aldente": "AlDente",
]

private(set) var battery: BatterySnapshot?
private(set) var battery: BatterySnapshot? {
didSet { updateMenuBarItem() }
}
private(set) var batteryError: String?
private(set) var status: DaemonStatus?
private(set) var service = ServiceState.checking
private(set) var status: DaemonStatus? {
didSet { updateMenuBarItem() }
}
private(set) var service = ServiceState.checking {
didSet { updateMenuBarItem() }
}
/// What the menu bar item shows. It changes far less often than the readings it comes from,
/// and the item redraws only when it does.
private(set) var menuBarItem = MenuBarItem()
private(set) var history: [HistorySample] = []
private(set) var logs: [LogEntry] = []
/// One point a day, for the long-term health chart.
Expand Down Expand Up @@ -112,10 +121,16 @@ final class AppModel {
self.macOSLimit = macOSLimit
smoothedCurrent = battery?.current
isPreview = true
updateMenuBarItem()
}
#endif

var settings: ChargeSettings? { status?.settings }

private func updateMenuBarItem() {
let item = MenuBarItem(model: self)
if item != menuBarItem { menuBarItem = item }
}
var isControllable: Bool { service == .running && status?.adapterKey != nil }

/// macOS's own charge limit is running the Mac on battery while Chargectl has the charger
Expand Down
2 changes: 1 addition & 1 deletion App/ChargectlApp.swift
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ struct ChargectlApp: App {

var body: some Scene {
MenuBarExtra(isInserted: $showInMenuBar) {
MenuContent(model: model)
WindowContent(dropsContentWhenClosed: false) { MenuContent(model: model) }
} label: {
MenuBarLabel(model: model)
}
Expand Down
53 changes: 33 additions & 20 deletions App/Dashboard/DashboardView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -32,17 +32,20 @@ struct DashboardView: View {
}

var body: some View {
HStack(spacing: 0) {
Sidebar(model: model, page: $page)
VStack(alignment: .leading, spacing: 0) {
toolbar
NoticeStack(model: model, includeService: page == .overview)
content
.frame(maxWidth: .infinity, maxHeight: .infinity)
.id(page)
WindowContent {
HStack(spacing: 0) {
Sidebar(model: model, page: $page)
VStack(alignment: .leading, spacing: 0) {
toolbar
NoticeStack(model: model, includeService: page == .overview)
content
.frame(maxWidth: .infinity, maxHeight: .infinity)
.id(page)
}
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
}
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background {
ZStack {
Theme.window
Expand Down Expand Up @@ -236,27 +239,37 @@ private struct HelperFooter: View {
}
}

/// A status dot with a slow ring that pings outwards.
/// A status dot with a slow ring that pings outwards. The ring is drawn from the clock at 30
/// frames a second, and holds still while the window is off screen or another app is in front:
/// every frame redraws the whole window.
struct PulseDot: View {
var color: Color = Theme.accent
@State private var ping = false
@Environment(\.accessibilityReduceMotion) private var reduceMotion
@Environment(\.isOnScreen) private var isOnScreen
@Environment(\.appearsActive) private var appearsActive

private static let period = 2.4

var body: some View {
Circle()
.fill(color)
.frame(width: 7, height: 7)
.shadow(color: color.opacity(0.7), radius: 4)
.background {
Circle()
.stroke(color, lineWidth: 1.5)
.frame(width: 13, height: 13)
.scaleEffect(ping ? 1.6 : 0.6)
.opacity(ping ? 0 : 0.5)
}
.onAppear {
guard !reduceMotion else { return }
withAnimation(.easeOut(duration: 2.4).repeatForever(autoreverses: false)) { ping = true }
if !reduceMotion {
TimelineView(.animation(minimumInterval: 1 / 30, paused: !isOnScreen || !appearsActive)) {
context in
let time = context.date.timeIntervalSinceReferenceDate
let progress = time.truncatingRemainder(dividingBy: Self.period) / Self.period
// Ease out: fast at first, settling as it fades.
let eased = 1 - pow(1 - progress, 3)
Circle()
.stroke(color, lineWidth: 1.5)
.frame(width: 13, height: 13)
.scaleEffect(0.6 + eased)
.opacity(0.5 * (1 - eased))
}
}
}
.accessibilityHidden(true)
}
Expand Down
38 changes: 28 additions & 10 deletions App/Dashboard/OverviewPage.swift
Original file line number Diff line number Diff line change
Expand Up @@ -708,15 +708,37 @@ private struct HealthCell<Footer: View>: View {
}
}

/// Dashes travelling along a wire, drawn from the clock at 30 frames a second. They stand still
/// with Reduce Motion, while the window is off screen and while another app is in front.
private struct FlowingDashes: View {
let path: Path
let color: Color
@Environment(\.accessibilityReduceMotion) private var reduceMotion
@Environment(\.isOnScreen) private var isOnScreen
@Environment(\.appearsActive) private var appearsActive

private static let period = 1.2
/// One dash and its gap.
private static let length: CGFloat = 18

var body: some View {
TimelineView(.animation(minimumInterval: 1 / 30, paused: reduceMotion || !isOnScreen || !appearsActive)) {
context in
let time = context.date.timeIntervalSinceReferenceDate
let phase =
reduceMotion ? 0 : -Self.length * time.truncatingRemainder(dividingBy: Self.period) / Self.period
path.stroke(color, style: StrokeStyle(lineWidth: 2, lineCap: .round, dash: [6, 12], dashPhase: phase))
}
}
}

/// Charger on the left, Mac and battery on the right, with power travelling along the wires.
private struct PowerFlow: View {
let charger: Double
let mac: Double
let battery: Double
let pluggedIn: Bool
let wallCut: Bool
@State private var phase: CGFloat = 0
@Environment(\.accessibilityReduceMotion) private var reduceMotion

var body: some View {
GeometryReader { geometry in
Expand Down Expand Up @@ -747,10 +769,6 @@ private struct PowerFlow: View {
.position(x: size.width - 70, y: size.height - 30)
}
}
.onAppear {
guard !reduceMotion else { return }
withAnimation(.linear(duration: 1.2).repeatForever(autoreverses: false)) { phase = -18 }
}
}

private func wire(from: CGPoint, to: CGPoint, active: Bool, color: Color, bend: Bool = false) -> some View {
Expand All @@ -768,10 +786,10 @@ private struct PowerFlow: View {
return ZStack {
path.stroke(Theme.lineStrong, style: StrokeStyle(lineWidth: 2, lineCap: .round))
if active {
path.stroke(
color, style: StrokeStyle(lineWidth: 2, lineCap: .round, dash: [6, 12], dashPhase: phase)
)
.shadow(color: color.opacity(0.6), radius: 4)
// A soft line under the dashes for the glow: a shadow on the moving dashes would
// be blurred again on every frame.
path.stroke(color.opacity(0.18), style: StrokeStyle(lineWidth: 6, lineCap: .round))
FlowingDashes(path: path, color: color)
}
}
}
Expand Down
90 changes: 57 additions & 33 deletions App/Design/DesignSystem.swift
Original file line number Diff line number Diff line change
Expand Up @@ -43,9 +43,18 @@ extension Theme {

extension View {
/// Digits roll whenever the value changes, also when the change came from a background
/// refresh rather than an animated action.
/// refresh rather than an animated action. Not while the window is off screen.
func rollingNumber<Value: Equatable>(_ value: Value) -> some View {
contentTransition(.numericText()).animation(.smooth(duration: 0.45), value: value)
modifier(RollingNumber(value: value))
}
}

private struct RollingNumber<Value: Equatable>: ViewModifier {
let value: Value
@Environment(\.isOnScreen) private var isOnScreen

func body(content: Content) -> some View {
content.contentTransition(.numericText()).animation(isOnScreen ? .smooth(duration: 0.45) : nil, value: value)
}
}

Expand All @@ -58,7 +67,9 @@ struct Panel<Content: View>: View {
var spotlight = false
var tint: Color?
@ViewBuilder var content: Content
@State private var pointer: CGPoint?
/// Only the lights read it, so moving the pointer (or scrolling under it) redraws them and
/// not the card's content.
@State private var hover = PanelHover()
@Environment(\.colorScheme) private var scheme

var body: some View {
Expand All @@ -77,20 +88,7 @@ struct Panel<Content: View>: View {
)
.clipShape(shape)
}
if let pointer {
// A soft light centred on the pointer, inside the card's own frame so it
// has no edges.
GeometryReader { geometry in
RadialGradient(
colors: [Color.primary.opacity(scheme == .dark ? 0.035 : 0.02), .clear],
center: UnitPoint(
x: pointer.x / max(geometry.size.width, 1),
y: pointer.y / max(geometry.size.height, 1)),
startRadius: 0, endRadius: 260)
}
.clipShape(shape)
.allowsHitTesting(false)
}
PointerLight(hover: hover, shape: shape, isEdge: false)
}
}
.overlay {
Expand All @@ -100,33 +98,59 @@ struct Panel<Content: View>: View {
lineWidth: 1
)
.opacity(scheme == .dark ? 1 : 0)
if let pointer {
GeometryReader { geometry in
shape.strokeBorder(
RadialGradient(
colors: [Theme.accent.opacity(0.55), Color.primary.opacity(0.12), .clear],
center: UnitPoint(
x: pointer.x / max(geometry.size.width, 1),
y: pointer.y / max(geometry.size.height, 1)),
startRadius: 0, endRadius: 220),
lineWidth: 1)
}
.allowsHitTesting(false)
}
PointerLight(hover: hover, shape: shape, isEdge: true)
}
.shadow(
color: .black.opacity(scheme == .dark ? 0.12 : 0.05), radius: scheme == .dark ? 1 : 12,
y: scheme == .dark ? 1 : 6
)
.onContinuousHover(coordinateSpace: .local) { phase in
.onContinuousHover(coordinateSpace: .local) { [hover] phase in
switch phase {
case .active(let location): pointer = location
case .ended: withAnimation(.easeOut(duration: 0.3)) { pointer = nil }
case .active(let location): hover.pointer = location
case .ended: withAnimation(.easeOut(duration: 0.3)) { hover.pointer = nil }
}
}
}
}

/// Where the pointer is over a card, nil when it is elsewhere.
@Observable
final class PanelHover {
var pointer: CGPoint?
}

/// A soft light centred on the pointer: across the card, or along its edge.
private struct PointerLight<S: InsettableShape>: View {
let hover: PanelHover
let shape: S
let isEdge: Bool
@Environment(\.colorScheme) private var scheme

var body: some View {
if let pointer = hover.pointer {
GeometryReader { geometry in
let center = UnitPoint(
x: pointer.x / max(geometry.size.width, 1), y: pointer.y / max(geometry.size.height, 1))
if isEdge {
shape.strokeBorder(
RadialGradient(
colors: [Theme.accent.opacity(0.55), Color.primary.opacity(0.12), .clear], center: center,
startRadius: 0, endRadius: 220),
lineWidth: 1)
} else {
// Inside the card's own frame so it has no edges.
RadialGradient(
colors: [Color.primary.opacity(scheme == .dark ? 0.035 : 0.02), .clear], center: center,
startRadius: 0, endRadius: 260
)
.clipShape(shape)
}
}
.allowsHitTesting(false)
}
}
}

/// A card's caption: a small icon and a label, with optional content on the right.
struct PanelHeader<Trailing: View>: View {
let title: String
Expand Down
71 changes: 71 additions & 0 deletions App/Design/WindowContent.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import AppKit
import SwiftUI

extension EnvironmentValues {
/// False while the window is closed, minimised, on another Space or covered by other windows.
/// Looping animations and rolling numbers stop then, because they would go on drawing.
@Entry var isOnScreen = true
}

/// A window's content, built only while the window is open and told whether it is on screen.
/// SwiftUI keeps a closed window's views alive, and their animations and once-a-second updates
/// go on drawing it off screen, which kept the app at half a CPU core with no window open.
struct WindowContent<Content: View>: View {
/// Off for the menu bar panel, which sizes itself to its content and so must keep it.
var dropsContentWhenClosed = true
@ViewBuilder var content: Content
@State private var isOpen = true
@State private var isOnScreen = true

var body: some View {
ZStack {
if isOpen || !dropsContentWhenClosed {
content.environment(\.isOnScreen, isOnScreen)
}
}
.background {
WindowObserver { open, onScreen in
if open != isOpen { isOpen = open }
if onScreen != isOnScreen { isOnScreen = onScreen }
}
}
}
}

private struct WindowObserver: NSViewRepresentable {
let report: (_ isOpen: Bool, _ isOnScreen: Bool) -> Void

func makeNSView(context: Context) -> ObserverView { ObserverView() }

func updateNSView(_ view: ObserverView, context: Context) { view.report = report }

final class ObserverView: NSView {
var report: ((Bool, Bool) -> Void)?
private var observers: [NSObjectProtocol] = []
private var isOpen = true

override func viewDidMoveToWindow() {
super.viewDidMoveToWindow()
observers.forEach(NotificationCenter.default.removeObserver)
observers = []
guard let window else { return }
observers = [NSWindow.didChangeOcclusionStateNotification, NSWindow.willCloseNotification].map { name in
NotificationCenter.default.addObserver(forName: name, object: window, queue: .main) {
[weak self] _ in
MainActor.assumeIsolated { self?.windowChanged(name) }
}
}
}

private func windowChanged(_ name: Notification.Name) {
guard let window else { return }
if name == NSWindow.willCloseNotification {
isOpen = false
} else if window.isVisible {
// A closed window that is shown again comes back through its occlusion state.
isOpen = true
}
report?(isOpen, isOpen && window.occlusionState.contains(.visible))
}
}
}
Loading