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
63 changes: 34 additions & 29 deletions App/Dashboard/HistoryPage.swift
Original file line number Diff line number Diff line change
Expand Up @@ -69,10 +69,9 @@ struct HistoryPage: View {
}

private func content(_ samples: [HistorySample], domain: ClosedRange<Date>) -> some View {
let shown = hovered.flatMap { date in
samples.min { abs($0.date.timeIntervalSince(date)) < abs($1.date.timeIntervalSince(date)) }
}
let reading = shown ?? samples.last
// The sample recorded nearest the pointer; nil while hovering a time nothing was recorded.
let shown = hovered.flatMap { samples.sample(near: $0) }
let reading = hovered == nil ? samples.last : shown
let since = model.history.first.map(\.date).flatMap { $0 > domain.lowerBound ? $0 : nil }
return VStack(spacing: 14) {
SpanRow(spans: [1, 1, 1, 1]) {
Expand All @@ -83,17 +82,17 @@ struct HistoryPage: View {
VStack(alignment: .leading, spacing: 14) {
PanelHeader(title: "Charge", symbol: "chart.xyaxis.line") {
HStack(alignment: .firstTextBaseline, spacing: 8) {
if let since, shown == nil {
if let since, hovered == nil {
Label(
"Recorded since \(since.formatted(.dateTime.hour().minute()))",
systemImage: "circle.fill"
)
.labelStyle(DotLabelStyle())
.padding(.trailing, 6)
}
Text(shown.map { $0.date.formatted(.dateTime.hour().minute()) } ?? "Now")
Text(hovered.map { $0.formatted(.dateTime.hour().minute()) } ?? "Now")
Text(
"\(Text("\(reading?.percent ?? 0)").font(.system(size: 24, weight: .semibold)))\(Text("%").font(.system(size: 13, weight: .medium)))"
"\(Text(reading.map { "\($0.percent)" } ?? "–").font(.system(size: 24, weight: .semibold)))\(Text("%").font(.system(size: 13, weight: .medium)))"
)
.foregroundStyle(.primary)
.monospacedDigit()
Expand Down Expand Up @@ -221,29 +220,34 @@ struct HistoryPage: View {
private func temperatureCard(
_ samples: [HistorySample], domain: ClosedRange<Date>, shown: HistorySample?, reading: HistorySample?
) -> some View {
let points = samples.compactMap { s in s.temperature.map { (s.date, unit.value($0)) } }
let points = zip(samples, samples.runs).compactMap { s, run in
s.temperature.map { (s.date, unit.value($0), run) }
}
let values = points.map(\.1)
let low = (values.min() ?? 0) - max(((values.max() ?? 0) - (values.min() ?? 0)) * 0.2, 0.6)
let high = (values.max() ?? 1) + max(((values.max() ?? 0) - (values.min() ?? 0)) * 0.2, 0.6)
return Panel {
VStack(alignment: .leading, spacing: 12) {
PanelHeader(title: "Temperature", symbol: "thermometer.medium") {
readout(shown, unit.format(reading?.temperature))
readout(unit.format(reading?.temperature))
}
Chart {
ForEach(points, id: \.0) { date, value in
ForEach(points, id: \.0) { date, value, run in
AreaMark(
x: .value("Time", date), yStart: .value("Base", low), yEnd: .value("Temperature", value)
x: .value("Time", date), yStart: .value("Base", low), yEnd: .value("Temperature", value),
series: .value("Run", run)
)
.interpolationMethod(.monotone)
.foregroundStyle(
LinearGradient(
colors: [Theme.warn.opacity(0.2), Theme.warn.opacity(0)], startPoint: .top,
endPoint: .bottom))
LineMark(x: .value("Time", date), y: .value("Temperature", value))
.interpolationMethod(.monotone)
.foregroundStyle(Theme.warn)
.lineStyle(StrokeStyle(lineWidth: 1.8, lineCap: .round))
LineMark(
x: .value("Time", date), y: .value("Temperature", value), series: .value("Run", run)
)
.interpolationMethod(.monotone)
.foregroundStyle(Theme.warn)
.lineStyle(StrokeStyle(lineWidth: 1.8, lineCap: .round))
}
if let threshold = model.settings.flatMap({ $0.heatProtection ? $0.heatThreshold : nil }),
unit.value(threshold) < high + 5
Expand All @@ -252,9 +256,9 @@ struct HistoryPage: View {
.lineStyle(StrokeStyle(lineWidth: 1, dash: [3, 4]))
.foregroundStyle(Theme.warn.opacity(0.7))
}
crosshair(shown)
if let shown, let value = shown.temperature {
PointMark(x: .value("Time", shown.date), y: .value("Temperature", unit.value(value)))
crosshair(recorded: shown != nil)
if let hovered, let value = samples.value(at: hovered, { $0.temperature }) {
PointMark(x: .value("Time", hovered), y: .value("Temperature", unit.value(value)))
.foregroundStyle(Theme.warn).symbolSize(40)
}
}
Expand Down Expand Up @@ -287,26 +291,26 @@ struct HistoryPage: View {
return Panel {
VStack(alignment: .leading, spacing: 12) {
PanelHeader(title: "Power", symbol: "bolt") {
Text(shown.map { $0.date.formatted(.dateTime.hour().minute()) } ?? "Now")
Text(hovered.map { $0.formatted(.dateTime.hour().minute()) } ?? "Now")
}
Chart {
RuleMark(y: .value("Zero", 0))
.lineStyle(StrokeStyle(lineWidth: 1, dash: [2, 3]))
.foregroundStyle(Theme.lineStrong)
ForEach(series.filter { !hiddenPower.contains($0.key) }, id: \.key) { item in
ForEach(samples, id: \.date) { sample in
ForEach(Array(zip(samples, samples.runs)), id: \.0.date) { sample, run in
if let value = item.value(sample) {
LineMark(
x: .value("Time", sample.date), y: .value(item.title, value),
series: .value("Series", item.title)
series: .value("Series", "\(item.title) \(run)")
)
.interpolationMethod(.monotone)
.foregroundStyle(item.tint)
.lineStyle(StrokeStyle(lineWidth: 1.8, lineCap: .round))
}
}
}
crosshair(shown)
crosshair(recorded: shown != nil)
}
.modifier(SharedChartStyle(domain: domain, hovered: $hovered, format: { "\(Int($0)) W" }))
.chartYScale(domain: low...high)
Expand Down Expand Up @@ -347,18 +351,19 @@ struct HistoryPage: View {
return Format.watts(value)
}

private func readout(_ shown: HistorySample?, _ value: String) -> some View {
private func readout(_ value: String) -> some View {
HStack(alignment: .firstTextBaseline, spacing: 8) {
Text(shown.map { $0.date.formatted(.dateTime.hour().minute()) } ?? "Now")
Text(hovered.map { $0.formatted(.dateTime.hour().minute()) } ?? "Now")
Text(value).font(.system(size: 15, weight: .semibold)).foregroundStyle(.primary).monospacedDigit()
}
}

@ChartContentBuilder private func crosshair(_ shown: HistorySample?) -> some ChartContent {
if let shown {
RuleMark(x: .value("Time", shown.date))
.lineStyle(StrokeStyle(lineWidth: 1))
.foregroundStyle(Color.secondary)
/// Follows the pointer; dashed where nothing was recorded.
@ChartContentBuilder private func crosshair(recorded: Bool) -> some ChartContent {
if let hovered {
RuleMark(x: .value("Time", hovered))
.lineStyle(StrokeStyle(lineWidth: 1, dash: recorded ? [] : [3, 3]))
.foregroundStyle(Color.secondary.opacity(recorded ? 1 : 0.7))
}
}
}
Expand Down
49 changes: 30 additions & 19 deletions App/Dashboard/OverviewPage.swift
Original file line number Diff line number Diff line change
Expand Up @@ -885,9 +885,9 @@ struct ChargeChart: View {
private var selection: Binding<Date?> { usesLocalHover ? $localHover : $hovered }

var body: some View {
let shown = selection.wrappedValue.flatMap { date in
samples.min { abs($0.date.timeIntervalSince(date)) < abs($1.date.timeIntervalSince(date)) }
}
let hovered = selection.wrappedValue
let shown = hovered.flatMap { samples.sample(near: $0) }
let runs = samples.runs
VStack(spacing: 10) {
Chart {
if let limit, let lowerBound, lowerBound < limit {
Expand All @@ -897,21 +897,24 @@ struct ChargeChart: View {
)
.foregroundStyle(Theme.accentSoft)
}
ForEach(samples, id: \.date) { sample in
ForEach(Array(zip(samples, runs)), id: \.0.date) { sample, run in
AreaMark(
x: .value("Time", sample.date), yStart: .value("Base", 0),
yEnd: .value("Charge", sample.percent)
yEnd: .value("Charge", sample.percent), series: .value("Run", run)
)
.interpolationMethod(.monotone)
.foregroundStyle(
LinearGradient(
colors: [Theme.accent.opacity(0.22), Theme.accent.opacity(0)], startPoint: .top,
endPoint: .bottom))
LineMark(x: .value("Time", sample.date), y: .value("Charge", sample.percent))
.interpolationMethod(.monotone)
.foregroundStyle(Theme.accent)
.lineStyle(StrokeStyle(lineWidth: 1.8, lineCap: .round, lineJoin: .round))
.shadow(color: Theme.glow.opacity(0.6), radius: 4)
LineMark(
x: .value("Time", sample.date), y: .value("Charge", sample.percent),
series: .value("Run", run)
)
.interpolationMethod(.monotone)
.foregroundStyle(Theme.accent)
.lineStyle(StrokeStyle(lineWidth: 1.8, lineCap: .round, lineJoin: .round))
.shadow(color: Theme.glow.opacity(0.6), radius: 4)
}
if let limit {
RuleMark(y: .value("Limit", limit))
Expand All @@ -923,17 +926,21 @@ struct ChargeChart: View {
.symbolSize(40)
.foregroundStyle(Theme.accent)
}
if let shown {
RuleMark(x: .value("Time", shown.date))
.lineStyle(StrokeStyle(lineWidth: 1))
.foregroundStyle(Color.secondary)
PointMark(x: .value("Time", shown.date), y: .value("Charge", shown.percent))
.symbolSize(50)
if let hovered {
// The line and the time follow the pointer; the dot slides along the charge line. Where
// nothing was recorded, the line is dashed and says so.
let y = samples.value(at: hovered) { Double($0.percent) }
RuleMark(x: .value("Time", hovered))
.lineStyle(StrokeStyle(lineWidth: 1, dash: y == nil ? [3, 3] : []))
.foregroundStyle(Color.secondary.opacity(y == nil ? 0.7 : 1))
PointMark(x: .value("Time", hovered), y: .value("Charge", y ?? 100))
.symbolSize(y == nil ? 0 : 50)
.foregroundStyle(Theme.accent)
.annotation(position: .top, spacing: 8, overflowResolution: .init(x: .fit, y: .disabled)) {
VStack(alignment: .leading, spacing: 1) {
Text("\(shown.percent)%").font(.system(size: 13, weight: .semibold))
Text(shown.date, format: .dateTime.hour().minute())
Text(shown.map { "\($0.percent)%" } ?? "Not recorded")
.font(.system(size: 13, weight: .semibold))
Text(hovered, format: .dateTime.hour().minute())
.font(.system(size: 11)).foregroundStyle(.secondary)
}
.padding(.horizontal, 10)
Expand Down Expand Up @@ -981,7 +988,11 @@ struct ChargerStrip: View {
context.fill(
Path(roundedRect: CGRect(origin: .zero, size: size), cornerRadius: 3), with: .color(Theme.track))
for (index, sample) in samples.enumerated() where (sample.wallPower ?? 0) > 0.5 {
let end = index + 1 < samples.count ? samples[index + 1].date : sample.date.addingTimeInterval(60)
// Up to the next sample, unless nothing was recorded in between.
let next = index + 1 < samples.count ? samples[index + 1].date : nil
let end =
next.flatMap { $0.timeIntervalSince(sample.date) <= HistorySample.maximumSpacing ? $0 : nil }
?? sample.date.addingTimeInterval(60)
let x0 = size.width * sample.date.timeIntervalSince(domain.lowerBound) / span
let x1 = size.width * end.timeIntervalSince(domain.lowerBound) / span
let charging = (sample.batteryPower ?? 0) > 0.5
Expand Down
12 changes: 10 additions & 2 deletions App/Debug/DesignRender.swift
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,10 @@
return AnyView(DashboardView(model: Sample.model(), initialPage: page))
})
}
shots.append(
Shot(name: "history-gap", size: dashboard) {
AnyView(DashboardView(model: Sample.model(historyGap: true), initialPage: .history))
})
shots.append(
Shot(name: "logs-warning", size: dashboard) {
AnyView(DashboardView(model: Sample.model(warning: true), initialPage: .logs))
Expand Down Expand Up @@ -424,7 +428,7 @@
static func model(
percent: Int = 61, service: ServiceState = .running, heat: Bool = false, enabled: Bool = true,
tiles: Bool = false, warning: Bool = false, mode: ChargeMode = .automatic, manyLogs: Bool = false,
limit: Int = 80, calibrateEveryMonths: Int? = nil, smartLimit: Bool = false
limit: Int = 80, calibrateEveryMonths: Int? = nil, smartLimit: Bool = false, historyGap: Bool = false
) -> AppModel {
let charging = mode == .automatic && percent < 80
let draining = mode != .automatic
Expand Down Expand Up @@ -458,7 +462,11 @@
smartLimit: SmartLimit.Status(target: 55, usual: 34, sessions: 23))
: nil
return AppModel(
preview: battery, status: status, service: service, history: history(),
preview: battery, status: status, service: service,
// Chargectl quit for three hours, so the helper recorded nothing.
history: history().filter {
!historyGap || !(-240 ... -60).contains($0.date.timeIntervalSinceNow / 60)
},
logs: manyLogs ? Self.manyLogs() : logs(warning: warning),
macOSLimit: 80, daily: daily())
}
Expand Down
9 changes: 9 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,15 @@ sees, with its pull request link. Credit outside contributors with

## [Unreleased]

### Fixed

- **History no longer draws a line across time nothing was recorded.** While
Chargectl was quit, which stops the helper, or the Mac slept, the charts
joined the last reading before to the first one after, and the hover marker
jumped between them. The charts now leave a gap there, and the marker
follows the pointer smoothly, saying "Not recorded" inside a gap.
([#117](https://github.com/tyldra/chargectl/pull/117))

### Changed

- **Chargectl moved to github.com/tyldra.** The app checks for updates there,
Expand Down
51 changes: 51 additions & 0 deletions Shared/XPC/DaemonModels.swift
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,57 @@ nonisolated struct HistorySample: Codable, Equatable, Sendable {
var batteryPower: Double?
/// The charger is connected, also while wall power is cut. Helpers before 0.3.0 leave it out.
var pluggedIn: Bool? = nil

/// Samples further apart than this have nothing recorded between them: Chargectl was quit, which
/// stops the helper, or the Mac slept without waking. The helper records once a minute while the
/// Mac is awake, and a sleeping Mac wakes to record about every 15 minutes.
static let maximumSpacing: TimeInterval = 20 * 60
}

extension [HistorySample] {
/// For each sample, in date order, the number of the unbroken run it belongs to. Charts draw each
/// run as its own line, so a gap in the recording shows as a gap, not a straight line across it.
nonisolated var runs: [Int] {
var run = 0
return indices.map { index in
if index > 0, self[index].date.timeIntervalSince(self[index - 1].date) > HistorySample.maximumSpacing {
run += 1
}
return run
}
}

/// A value at `date`, read along the line between the samples around it, so a marker can follow the
/// pointer smoothly. Nil when nothing was recorded then. Samples must be in date order.
nonisolated func value(at date: Date, _ read: (HistorySample) -> Double?) -> Double? {
guard let nearest = sample(near: date) else { return nil }
let after = firstIndex { $0.date >= date }
guard let after, after > 0 else { return read(nearest) }
let (a, b) = (self[after - 1], self[after])
let span = b.date.timeIntervalSince(a.date)
guard span > 0, span <= HistorySample.maximumSpacing, let va = read(a), let vb = read(b) else {
return read(nearest)
}
return va + (vb - va) * date.timeIntervalSince(a.date) / span
}

/// The sample recorded closest to `date`, or nil when nothing was recorded near it. Samples must be
/// in date order.
nonisolated func sample(near date: Date) -> HistorySample? {
var low = 0
var high = count
while low < high {
let middle = (low + high) / 2
if self[middle].date < date { low = middle + 1 } else { high = middle }
}
let nearest = [low - 1, low].filter { indices.contains($0) }.min {
abs(self[$0].date.timeIntervalSince(date)) < abs(self[$1].date.timeIntervalSince(date))
}
guard let nearest, abs(self[nearest].date.timeIntervalSince(date)) <= HistorySample.maximumSpacing / 2 else {
return nil
}
return self[nearest]
}
}

nonisolated struct LogEntry: Codable, Equatable, Identifiable, Sendable {
Expand Down
Loading