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
6 changes: 5 additions & 1 deletion Sources/App/App.swift
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,11 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSPopoverDelegate, NSW
/// view's own bounds instead: there, preferredContentSize re-triggers AppKit's
/// constraint pass until it gives up and crashes the app.
private func hosting(popover: Bool) -> NSViewController {
let host = NSHostingController(rootView: PanelView().environmentObject(model))
// Fit on the screen below the menu bar, leaving room for the popover's arrow
// or the window's title bar.
let screen = (popover ? item.button?.window?.screen : nil) ?? NSScreen.main
let maxHeight = (screen?.visibleFrame.height ?? 800) - 40
let host = NSHostingController(rootView: PanelView(maxHeight: maxHeight).environmentObject(model))
host.sizingOptions = popover ? .preferredContentSize : .standardBounds
return host
}
Expand Down
18 changes: 14 additions & 4 deletions Sources/App/EnergyMonitor.swift
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ final class EnergyMonitor {
private var last: [pid_t: Sample] = [:]
private var lastTime: UInt64 = 0
private var paths: [pid_t: String] = [:]
/// Display names by key: looking them up for every app took most of each sample.
private var names: [String: String] = [:]
private var smoothed: [String: (watts: Double, cpu: Double)] = [:]
private let timebase: Double = {
var tb = mach_timebase_info()
Expand Down Expand Up @@ -62,16 +64,24 @@ final class EnergyMonitor {
if v.0 > 0.005 || perApp[key] != nil { next[key] = v }
}
smoothed = next
names = names.filter { smoothed[$0.key] != nil }

return smoothed.map { key, v in
let isApp = key.hasSuffix(".app")
let name = isApp ? FileManager.default.displayName(atPath: key).replacingOccurrences(of: ".app", with: "")
: (key as NSString).lastPathComponent
return AppEnergy(id: key, name: name, bundlePath: isApp ? key : nil, watts: v.watts, cpuPercent: v.cpu)
AppEnergy(id: key, name: name(for: key), bundlePath: key.hasSuffix(".app") ? key : nil,
watts: v.watts, cpuPercent: v.cpu)
}
.sorted { $0.watts > $1.watts }
}

private func name(for key: String) -> String {
if let n = names[key] { return n }
let n = key.hasSuffix(".app")
? FileManager.default.displayName(atPath: key).replacingOccurrences(of: ".app", with: "")
: (key as NSString).lastPathComponent
names[key] = n
return n
}

private func appKey(for pid: pid_t) -> String {
if let p = paths[pid] { return p }
var buf = [CChar](repeating: 0, count: Int(MAXPATHLEN) * 4)
Expand Down
2 changes: 1 addition & 1 deletion Sources/App/Model.swift
Original file line number Diff line number Diff line change
Expand Up @@ -291,7 +291,7 @@ final class Model: ObservableObject {
return cfg.enabled ? "Will charge to \(cfg.limit)% when plugged in" : "Calculating time remaining…"
case .charging: return "Up to \(cfg.limit)%"
case .holding: return "Charging paused at \(cfg.limit)%"
case .sailing: return "Charging resumes below \(cfg.limit - cfg.sailing)%"
case .sailing: return "Charging resumes at \(cfg.limit - cfg.sailing)%"
case .heatPaused, .discharging, .calibrating, .topUp: return status?.reason ?? ""
case .noConfig: return "Run install.sh to finish setup"
}
Expand Down
68 changes: 62 additions & 6 deletions Sources/App/Views.swift
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,12 @@ import SwiftUI

struct PanelView: View {
@EnvironmentObject var model: Model
/// The screen's free height. A taller panel (say, Settings expanded) would run off
/// the bottom of the screen, so past this the tab scrolls between header and footer.
var maxHeight: CGFloat = .infinity

var body: some View {
VStack(alignment: .leading, spacing: 12) {
PanelStack(spacing: 12, maxHeight: maxHeight - 28) { // 28: the padding
if model.iconHidden {
Notice(text: "Your menu bar icon is hidden behind the notch. ⌘-drag other icons off the "
+ "menu bar to make room. Opening Dynamo again always shows this window.",
Expand All @@ -16,7 +19,7 @@ struct PanelView: View {
if let update = model.availableUpdate { UpdateBanner(release: update) }
Header()
TabBar()
Group {
let tab = Group {
switch model.tab {
case 1: HealthTab()
case 2: HistoryTab()
Expand All @@ -25,13 +28,64 @@ struct PanelView: View {
}
}
.transition(.opacity)
if maxHeight < .infinity {
ScrollView { tab }
.bounceOnlyWhenScrollable()
.layoutValue(key: Scrolls.self, value: true)
} else {
tab // uncapped (snapshots): ImageRenderer can't draw a ScrollView's content
}
Footer()
}
.padding(14)
.frame(width: 360)
}
}

/// Stacks the panel's sections like a leading VStack, each at its natural height, except
/// that the one marked `Scrolls` gives up height once the total would pass `maxHeight`.
/// A VStack would let that ScrollView shrink at will, and the window, which sizes to
/// the panel's minimum, would open squashed; here the panel's height is always exact.
struct PanelStack: Layout {
var spacing: CGFloat
var maxHeight: CGFloat

func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize {
let width = proposal.width
?? subviews.map { $0.sizeThatFits(.unspecified).width }.max() ?? 0
let heights = heights(width: width, subviews)
return CGSize(width: width, height: heights.reduce(0, +) + spacing * CGFloat(max(0, heights.count - 1)))
}

func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) {
var y = bounds.minY
for (view, height) in zip(subviews, heights(width: bounds.width, subviews)) {
view.place(at: CGPoint(x: bounds.minX, y: y), proposal: ProposedViewSize(width: bounds.width, height: height))
y += height + spacing
}
}

private func heights(width: CGFloat, _ subviews: Subviews) -> [CGFloat] {
var heights = subviews.map { $0.sizeThatFits(ProposedViewSize(width: width, height: nil)).height }
if let i = subviews.firstIndex(where: { $0[Scrolls.self] }) {
let rest = heights.reduce(0, +) - heights[i] + spacing * CGFloat(heights.count - 1)
heights[i] = max(0, min(heights[i], maxHeight - rest))
}
return heights
}
}

private struct Scrolls: LayoutValueKey {
static let defaultValue = false
}

extension View {
/// The panel usually fits, and then it shouldn't rubber-band under a two-finger swipe.
@ViewBuilder func bounceOnlyWhenScrollable() -> some View {
if #available(macOS 13.3, *) { scrollBounceBehavior(.basedOnSize) } else { self }
}
}

/// "Check for Updates" button with an inline result.
struct UpdateCheckRow: View {
@EnvironmentObject var model: Model
Expand Down Expand Up @@ -591,7 +645,7 @@ struct LimitCard: View {
VStack(alignment: .leading, spacing: 8) {
HStack(alignment: .firstTextBaseline, spacing: 8) {
Text("\(shown)%").font(.system(size: 28, weight: .bold, design: .rounded)).monospacedDigit()
Text(shown >= 100 ? "Charges fully" : "Resumes below \(shown - cfg.sailing)%")
Text(shown >= 100 ? "Charges fully" : "Resumes at \(shown - cfg.sailing)%")
.font(.callout).foregroundStyle(.secondary)
}
LimitSlider(value: model.draftLimit ?? Double(cfg.limit)) { v in
Expand Down Expand Up @@ -773,6 +827,7 @@ struct SettingsCard: View {
@AppStorage("settingsOpen") private var open = false
@AppStorage("showPercent") private var showPercent = true
@AppStorage("notifications") private var notifications = true
@AppStorage("checkUpdates") private var checkUpdates = true

var body: some View {
let cfg = model.config
Expand Down Expand Up @@ -813,10 +868,11 @@ struct SettingsCard: View {
SettingToggle(title: "Show percentage in menu bar", detail: nil, isOn: $showPercent)
SettingToggle(title: "Notify when tasks finish", detail: nil, isOn: $notifications)
SettingToggle(title: "Automatic update checks", detail: "Once a day, from GitHub",
isOn: Binding(get: { UserDefaults.standard.object(forKey: "checkUpdates") as? Bool ?? true },
isOn: Binding(get: { checkUpdates },
set: { v in
UserDefaults.standard.set(v, forKey: "checkUpdates")
if v { model.checkForUpdates(force: true) }
checkUpdates = v
// Off also drops a known update's banner, as at launch.
if v { model.checkForUpdates(force: true) } else { model.availableUpdate = nil }
}))
UpdateCheckRow()
SettingToggle(title: "Launch at login", detail: nil,
Expand Down
21 changes: 14 additions & 7 deletions Sources/Daemon/Daemon.swift
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,8 @@ final class Daemon {
asleepSince = nil
}
guard let bat = BatteryInfo.read() else {
writeStatus(mode: nil, reason: "Battery unreadable", error: "Could not read AppleSmartBattery")
writeStatus(mode: nil, reason: "Battery unreadable", error: "Could not read AppleSmartBattery",
inhibited: ChargeControl.chargingInhibited, adapterDisabled: ChargeControl.adapterDisabled)
return
}
if History.record(bat, into: &history) { History.save(history) }
Expand Down Expand Up @@ -136,15 +137,21 @@ final class Daemon {
event = (text, Date())
}

/// Each SMC key is read once per tick (a read is a kernel round trip), and again
/// only after a write, so the status reports what the SMC actually took.
private func apply(_ d: Decision) {
var error: String?
var inhibited = ChargeControl.chargingInhibited
var adapterDisabled = ChargeControl.adapterDisabled
do {
if ChargeControl.chargingInhibited != d.inhibitCharging {
if inhibited != d.inhibitCharging {
try ChargeControl.setChargingInhibited(d.inhibitCharging)
inhibited = ChargeControl.chargingInhibited
log("charging \(d.inhibitCharging ? "inhibited" : "enabled"): \(d.reason)")
}
if (ChargeControl.adapterDisabled ?? false) != d.disableAdapter {
if (adapterDisabled ?? false) != d.disableAdapter {
try ChargeControl.setAdapterDisabled(d.disableAdapter)
adapterDisabled = ChargeControl.adapterDisabled
log("adapter \(d.disableAdapter ? "disabled" : "enabled"): \(d.reason)")
}
} catch let e {
Expand All @@ -153,7 +160,7 @@ final class Daemon {
}
applyLED(green: d.greenLED)
setSleepPrevented(d.preventSleep)
writeStatus(mode: d.mode, reason: d.reason, error: error)
writeStatus(mode: d.mode, reason: d.reason, error: error, inhibited: inhibited, adapterDisabled: adapterDisabled)
}

/// Only touches the LED while overriding it, so macOS keeps control otherwise.
Expand Down Expand Up @@ -185,10 +192,10 @@ final class Daemon {
}
}

private func writeStatus(mode: ChargeMode?, reason: String, error: String?) {
private func writeStatus(mode: ChargeMode?, reason: String, error: String?, inhibited: Bool?, adapterDisabled: Bool?) {
let s = DaemonStatus(updatedAt: Date(), mode: mode,
chargingInhibited: ChargeControl.chargingInhibited ?? false,
adapterDisabled: ChargeControl.adapterDisabled ?? false,
chargingInhibited: inhibited ?? false,
adapterDisabled: adapterDisabled ?? false,
sleepPrevented: assertion != 0,
reason: reason, error: error,
calibration: state.calibration,
Expand Down
17 changes: 16 additions & 1 deletion Sources/smc.c
Original file line number Diff line number Diff line change
Expand Up @@ -64,15 +64,30 @@ void smc_close(void) {
conn = 0;
}

// A key's size and type never change, so each is looked up once. That halves the
// kernel calls per read; the daemon reads a few keys every tick. Single-threaded use.
#define INFO_CACHE_SIZE 16
static struct { uint32_t key; SMCKeyInfo info; } info_cache[INFO_CACHE_SIZE];
static int info_cached = 0;

static int key_info(const char *key, SMCKeyInfo *info) {
uint32_t k = fourcc(key);
for (int i = 0; i < info_cached; i++) {
if (info_cache[i].key == k) { *info = info_cache[i].info; return 0; }
}
SMCParam in, out;
memset(&in, 0, sizeof in);
memset(&out, 0, sizeof out);
in.key = fourcc(key);
in.key = k;
in.data8 = SMC_CMD_READ_KEYINFO;
int rc = call(&in, &out);
if (rc) return rc;
*info = out.keyInfo;
if (info_cached < INFO_CACHE_SIZE) {
info_cache[info_cached].key = k;
info_cache[info_cached].info = out.keyInfo;
info_cached++;
}
return 0;
}

Expand Down
Loading