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
1 change: 1 addition & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ newly matching skills before continuing. Human contributors do not need them.
| Check the cask as the tap's CI does | `./scripts/check.sh cask` |
| Retake the README screenshots | `./scripts/screenshots.sh` (after `./scripts/build.sh Debug`; see CONTRIBUTING.md) |
| Render the dashboard pages, menu bar panel and widgets to PNG files, light and dark, with sample data | `"${TMPDIR:-/tmp}/Chargectl-DerivedData/Build/Products/Debug/Chargectl.app/Contents/MacOS/Chargectl" --render-design <folder> --only <name prefix>` after `./scripts/build.sh Debug`. It never talks to the helper; shot names are in `App/Debug/DesignRender.swift` |
| Measure the app's CPU with sample data, page by page, without taking the keyboard or mouse | `./scripts/measure-cpu.sh` (or `./scripts/measure-cpu.sh <Chargectl.app>` for another Debug build). Run it after dashboard or menu bar changes and before a release |
| Try a changed release workflow without publishing (only when the user asks) | `gh workflow run release.yml --ref <branch>` |

The build and test scripts regenerate the Xcode project from `project.yml`
Expand Down
21 changes: 21 additions & 0 deletions App/AppDelegate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,13 @@ enum Dashboard {

/// Shows the Dock icon and brings the window forward.
static func show(_ window: NSWindow? = nil) {
if Setup.staysInBackground {
if let window = window ?? Self.window {
placeOnBuiltInScreen(window)
window.orderFrontRegardless()
}
return
}
NSApp.setActivationPolicy(.regular)
NSApp.activate()
let window = window ?? Self.window
Expand All @@ -90,6 +97,20 @@ enum Dashboard {
window?.makeKeyAndOrderFront(nil)
}

/// Measuring in the background: with another display connected, the window goes in the middle
/// of the Mac's own screen, away from whatever the user is doing on the main one.
private static func placeOnBuiltInScreen(_ window: NSWindow) {
guard NSScreen.screens.count > 1,
let screen = NSScreen.screens.first(where: {
let id = $0.deviceDescription[NSDeviceDescriptionKey("NSScreenNumber")] as? CGDirectDisplayID
return id.map { CGDisplayIsBuiltin($0) != 0 } ?? false
})
else { return }
let area = screen.visibleFrame
let size = window.frame.size
window.setFrameOrigin(NSPoint(x: area.midX - size.width / 2, y: area.midY - size.height / 2))
}

/// Back to a menu bar–only app once no window of ours is open.
static func didClose() {
DispatchQueue.main.async {
Expand Down
21 changes: 21 additions & 0 deletions App/ChargectlApp.swift
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,27 @@ enum Setup {
#endif
}

/// Debug builds started with --background (scripts/measure-cpu.sh) show their windows
/// without making Chargectl the active app, and on the Mac's own screen when another display
/// is connected, so a measurement stays out of the way of whoever is using the Mac.
static var staysInBackground: Bool {
#if DEBUG
CommandLine.arguments.contains("--background")
#else
false
#endif
}

/// Debug builds started with --appear-active draw the dashboard as if Chargectl were the app in
/// front, also while it stays in the background.
static var appearsActive: Bool {
#if DEBUG
CommandLine.arguments.contains("--appear-active")
#else
false
#endif
}

static var isNeeded: Bool {
if isDemo { return false }
return !UserDefaults.standard.bool(forKey: PreferenceKey.setupComplete)
Expand Down
3 changes: 3 additions & 0 deletions App/Dashboard/DashboardView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ struct DashboardView: View {
}
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
}
.transformEnvironment(\.appearsActive) { if Setup.appearsActive { $0 = true } }
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background {
Expand All @@ -64,6 +65,8 @@ struct DashboardView: View {
.onOpenURL { url in
// chargectl://dashboard/<page>
if let target = DashboardPage(rawValue: url.lastPathComponent) { page = target }
// Measuring in the background: keep the window above whatever the user brought forward.
if Setup.staysInBackground { Dashboard.show() }
}
}

Expand Down
17 changes: 12 additions & 5 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -105,10 +105,14 @@ Changes to how charging is controlled must also be tried on a real MacBook.
Say in the pull request which Mac and macOS version you used and what you saw.

Changes to the dashboard or the menu bar panel should not raise the app's CPU
use. Run the Debug build with `--demo --live-readings`, which changes the
watts and the temperature every second as a real Mac does, and watch
Chargectl in Activity Monitor with the window open, in front and behind
another app. It should stay at a few percent.
use. `./scripts/measure-cpu.sh` builds the Debug app and measures it with
sample data whose watts and temperature change every second, as a real Mac's
do: each dashboard page in front, the window in the background, and the window
closed. It takes about two minutes and never takes the keyboard or moves the
mouse. The window comes forward without focus, on the Mac's own screen when
another display is connected; keep it uncovered while it runs. Compare the
Chargectl column with a run on `main`. The WindowServer column also counts
every other app on screen, so read it only as a rough guide.

### Screenshots

Expand Down Expand Up @@ -194,7 +198,10 @@ review says. Open an issue describing the change instead.
1. Set `MARKETING_VERSION` in [`project.yml`](project.yml) and move the
`Unreleased` entries in [`CHANGELOG.md`](CHANGELOG.md) under the new version.
Add a one-sentence summary in bold, unless the release has one entry.
2. Merge that to `main`, then tag it:
2. Run `./scripts/measure-cpu.sh` and compare it with the last release. With
the window in front, a page that uses clearly more CPU than before needs a
reason before you ship.
3. Merge that to `main`, then tag it:

```sh
git tag -a v0.2.0 -m "Chargectl 0.2.0" && git push origin v0.2.0
Expand Down
101 changes: 101 additions & 0 deletions scripts/measure-cpu.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
#!/usr/bin/env bash
# Measures how much CPU Chargectl and the window server use with the dashboard open on each page,
# in the background and closed. It runs a Debug build with --demo --live-readings: sample data
# whose watts and temperature change every second, as a real Mac's do, and no helper, so it never
# changes how the Mac charges. Run it before a release and after changing the dashboard or the
# menu bar panel.
#
# scripts/measure-cpu.sh builds the Debug app, then measures it
# scripts/measure-cpu.sh <Chargectl.app> measures another Debug build, to compare
#
# It never takes the keyboard or moves the mouse: the app stays in the background (--background)
# and its window comes forward without focus. "In front" is measured with --appear-active, which
# draws the dashboard as if Chargectl were the app in front. Keep the window uncovered while it
# runs, about two minutes. CHARGECTL_MEASURE_SECONDS sets how long each state is measured
# (default 15).
set -euo pipefail
source "$(dirname "${BASH_SOURCE[0]}")/env.sh"

seconds="${CHARGECTL_MEASURE_SECONDS:-15}"
if [[ $# -gt 0 ]]; then
app="$1"
else
"$CHARGECTL_ROOT/scripts/build.sh" Debug
app="$CHARGECTL_DERIVED_DATA/Build/Products/Debug/Chargectl.app"
fi
# The full path without doubled slashes, as the process list shows it.
app="$(cd "$app" 2>/dev/null && pwd -P || true)"
executable="$app/Contents/MacOS/Chargectl"
if [[ ! -x "$executable" ]]; then
echo "measure-cpu: no Chargectl app at ${1:-the Debug build}" >&2
exit 2
fi

now() { perl -MTime::HiRes=time -e 'printf "%.3f\n", time'; }
# CPU time a process has used so far, in seconds.
cpu_time() { ps -p "$1" -o time= | awk -F: '{ t = 0; for (i = 1; i <= NF; i++) t = t * 60 + $i; print t }'; }
# Average CPU of the app and the window server over the measuring time, as "app% server%".
measure() {
local app_before server_before start app_after server_after end
app_before=$(cpu_time "$pid") server_before=$(cpu_time "$server") start=$(now)
sleep "$seconds"
app_after=$(cpu_time "$pid") server_after=$(cpu_time "$server") end=$(now)
awk -v a="$app_before" -v b="$app_after" -v s="$server_before" -v t="$server_after" -v d="$start" -v e="$end" \
'BEGIN { printf "%.1f%% %.1f%%\n", (b - a) / (e - d) * 100, (t - s) / (e - d) * 100 }'
}
row() { printf '%-26s %10s %14s\n' "$1" "$2" "$3"; }
# Shows a dashboard page. Opening the link with this app, by path, keeps it away from an installed
# Chargectl, which handles chargectl:// links too; -g leaves the app in the background.
show() { open -g -a "$app" "chargectl://dashboard/$1"; }

pid=""
stop() { if [[ -n "$pid" ]]; then kill "$pid" 2>/dev/null || true; fi; }
trap stop EXIT
# start [argument]: runs the app in the background with sample data and sets pid.
start() {
local arguments=(--demo --live-readings --background "$@")
open -g -n -a "$app" --args "${arguments[@]}"
pid=""
for _ in $(seq 1 20); do
pid=$(pgrep -f -x "$executable ${arguments[*]}" | head -1 || true)
[[ -n "$pid" ]] && break
sleep 0.5
done
if [[ -z "$pid" ]]; then
echo "measure-cpu: Chargectl did not start" >&2
exit 1
fi
sleep 5
}

server=$(pgrep -x WindowServer | head -1)
# The window server's own load, before Chargectl starts. The app's column is this script's shell.
pid=$$
read -r _ idle_server < <(measure)
pid=""

echo "Chargectl $(defaults read "$app/Contents/Info.plist" CFBundleShortVersionString), $seconds s per state"
row "" "Chargectl" "WindowServer"
row "not running" "" "$idle_server"

start --appear-active
for page in overview control history logs settings; do
show "$page"
sleep 4
read -r app_cpu server_cpu < <(measure)
row "$page, in front" "$app_cpu" "$server_cpu"
done
stop

start
show overview
sleep 4
read -r app_cpu server_cpu < <(measure)
row "overview, in background" "$app_cpu" "$server_cpu"
# Quitting from outside only closes the dashboard; the app stays in the menu bar. AppleScript
# reports that as a cancelled quit.
osascript -e "tell application \"$app\" to quit" >/dev/null 2>&1 || true
sleep 4
read -r app_cpu server_cpu < <(measure)
row "window closed" "$app_cpu" "$server_cpu"
row "memory" "$(($(ps -p "$pid" -o rss=) / 1024)) MB" ""