Skip to the content.

Power Timer internals

How Power Timer is built and how it works: the structure of the code, the countdown, the power actions, the main window, the settings, the Windows details, testing, making changes and releasing.

Contents

Overview

Building

Power Timer is built with Lazarus 4.8 and FPC 3.2.2.

PowerTimer.lpi has two build modes:

Both are GUI programs (no console window). The manifest makes the program DPI aware per monitor (PM_V2), and Application.Scaled scales the forms.

The version is supplied at build time. The project’s own version is 0.0.0, so a build from the IDE or with lazbuild shows 0.0.0 in the About box. publish.sh build -v <version> writes the version into src/PowerTimer.lpi before it builds and puts the file back when the script ends, also when the build fails: x.y.z.0 as the file version, from the version without its - or + part, and the whole version, e.g. 1.0.1-preview.2, as the product version. AppInfo.AppVersion reads the product version from the running executable’s version resource, and the About box shows it. Nothing compares versions: Power Timer stores no version anywhere.

The “Build” workflow, .github/workflows/build.yml, builds Power Timer, runs the tests and uploads PowerTimer.exe. It runs for pushes to master that change src/, tests/, publish.sh, .gitattributes (the line ends of publish.sh on the Windows runner), the workflow itself or .github/actions/setup-lazarus/, and when run from the Actions tab (Build → Run workflow, for any branch). Changes to the docs alone don’t run it.

Both workflows pin their actions by commit hash.

Source layout

All code is in src/; each form is a .pas unit with its .lfm form file.

Area Units
Startup PowerTimer.lpr, SystemLibraries
Main window MainForm, AccessKeyLabel, TaskbarProgress
Countdown Countdown, TimerLogic, TimeFields
Actions PowerActions
Warning WarningForm
Settings AppSettings, OptionsForm
About AboutForm, AppInfo

Countdown

TCountdown in Countdown decides when the action runs. It gets the time (Now) and the tick count (GetTickCount64) passed in and runs the action through an event, so it has no UI or OS dependencies and is unit tested. The main form calls Tick from its countdown timer every 250 ms.

Two modes (TCountdownMode):

Start. Start returns False and starts nothing for 00:00:00 in Countdown mode; the main form then asks, if Warn me if countdown time is zero is on, and runs the action itself. At time always starts: a clock time always has a next occurrence. Before it starts, the main form checks whether Sleep or Hibernate can run, see Power actions.

The end time. EndTime is when the action runs, for the status bar. In At time mode it is the target. In Countdown mode it is the end computed at Start, kept as long as the time and the tick count move on together, so it doesn’t flicker when they drift by a millisecond; once the time plus the time left differs from it by more than 2 seconds, e.g. after the clock was changed, it is that instead. The seconds left are rounded up, so 00:00:00 shows only when it is time.

The warning. OnWarn fires once when at most WarnSeconds are left. The main form sets WarnSeconds to TimerLogic.WarnSeconds, 60, or to 0 when Warn 1 minute before the action is off. A countdown that isn’t longer than WarnSeconds doesn’t warn: whoever started it knows when it ends.

Adding time. Postpone moves the end later, the deadline in Countdown mode and the target in At time mode, and warns again before the new end. The entered time stays, so a stop shows the time that was entered. The minutes are AddMinutes of the settings, from MinAddMinutes (1) to MaxAddMinutes (120), DefaultAddMinutes (10) by default.

Sleep. The ticks run only while the computer is awake, but the tick count goes on while it sleeps or hibernates. A gap of more than SleepGapMs (10 seconds) between two ticks means the computer was asleep. When the end passed during such a gap, the action doesn’t run on waking: the end moves to WakeGraceSeconds (60) after waking, EndedDuringSleep is set and OnWarn fires, whatever WarnSeconds is, and the warning says that the time passed while the computer was asleep. Postpone and a new Start clear EndedDuringSleep.

The time fields. The fields take two digits each, up to 23:59:59 (MaxHour, MaxMinute, MaxSecond); TimeFields has their input rules: what a key press may type, the Up/Down steps, which wrap around, and the parsing, which clamps. The default delay of the settings (1 to 24 hours) fills them: in Countdown mode as hours (DefaultCountdown, which shows 24 hours as 23:59:59), in At time mode as the time that many hours from now (DefaultClockTime). While running, Countdown mode counts down in the fields, up to 99:59:59 (MaxFieldSeconds, SecondsToFieldParts), and At time mode shows the end time there.

The texts of the status bar, the window title and the tray menu are built in TimerLogic (CountdownStatus, CountdownTitle, TrayTimeLeft), and the warning’s message in WarningForm, with the seconds left from TimerLogic.FormatSecondsLeft. The end times use the time format of the user’s Windows settings (DefaultFormatSettings): the short time format, or the long one, with seconds, in At time mode when the entered seconds aren’t zero. Their formats are resource strings; the action names in them are the constants of PowerActionInfo, see Power actions.

Power actions

PowerActions describes each action once, in PowerActionInfo. A new action is one entry there, and the table doesn’t compile without an entry for every TPowerAction.

Action Runs through shutdown.exe arguments Can force
Shut down shutdown.exe /s /t 0 yes
Restart shutdown.exe /r /t 0 yes
Sign out ExitWindowsEx with EWX_LOGOFF   yes
Lock LockWorkStation   no
Sleep SetSuspendState in powrprof.dll   no
Hibernate shutdown.exe /h no

Main window

TfrmMain in MainForm holds the window, the tray icon and the TCountdown, and connects them.

Settings

AppSettings keeps the settings in HKEY_CURRENT_USER\Software\Power Timer (DefaultRegistryKey), one REG_DWORD value each. The value names are part of the stored format: renaming one loses that setting.

Value Field of TAppSettings Default Range
defaultAction DefaultAction 0, Shut down an ordinal of TPowerAction; others give Shut down
defaultTimeDelay DefaultDelayHours 1 1 to 24 hours
addMinutes AddMinutes 10 1 to 120 minutes
minimizeToTray MinimizeToTray 0 0 off, else on
rememberWinPos RememberWindowPos 0 0 off, else on
warnZeroTime WarnZeroTime 0 0 off, else on
warnBeforeAction WarnBeforeAction 1 0 off, else on
forceActions ForceActions 0 0 off, else on
positionX, positionY WindowLeft, WindowTop none used only when both are there (HasWindowPos)

Windows details

Tests

The unit tests are an fpcunit console program, tests/PowerTimerTests.lpi:

lazbuild tests/PowerTimerTests.lpi
tests/bin/x86_64-win64/PowerTimerTests.exe

The runner runs all tests and prints plain text; --help lists its other options, e.g. --format=xml. It is built for the platform fpc targets, so it also runs elsewhere, e.g. on Linux (tests/bin/x86_64-linux/PowerTimerTests, with the registry emulated in a file). publish.sh build builds and runs it before every build of Power Timer, so the Build and Publish workflows fail on a failing test.

Unit Covers
TimerLogicTests Seconds to hours, minutes and seconds and back, 24 hours and more, the 99:59:59 of the fields; the next occurrence of a clock time, later today, earlier or now meaning tomorrow; rounding up of the seconds left; the clamped delay and minutes; the default countdown and clock time; the texts: durations, seconds left, the end time today, tomorrow, on a later day and with seconds, the status bar idle, right away, tomorrow, running and over midnight, the window title and the tray menu
TimeFieldsTests Parsing with invalid text and clamping, two digits, Up/Down wrapping around, what may be typed, a key at the caret, over a selection, backspace and other control keys
CountdownTests Countdown and At time to the end and after it, a zero countdown, stopping, a clock set back and forward, Countdown mode ignoring the clock; the end time, also after a clock change; the warning once, not for a short countdown, never with 0, in At time mode, again after a restart; adding time in both modes; sleeping through the end in both modes, also with the warning off, waking before the end, no gap, stopping or adding time during the announcement, sleeping again
PowerActionsTests The stored order and out of range indexes, the list order, the names and kinds, the shutdown.exe arguments with and without forcing, which actions can force, the path of shutdown.exe, the availability of Sleep and Hibernate, the layout of TSystemPowerCapabilities
SystemLibrariesTests Paths in the system directory, loading a DLL from there, a missing DLL
AppSettingsTests The defaults, clamping, a missing key, saving and loading, invalid values, a position with only one coordinate; under Software\Power Timer Tests, which the tests delete again
AppInfoTests The title with and without a version, no version resource

The tests of the system directory and of shutdown.exe’s path check real paths only on Windows. The forms, the tray, the taskbar, the actions themselves and anything that needs sleeping or a change of the clock are tested by hand, see Manual tests.

Manual tests

What the unit tests don’t cover, worth checking on a real computer before a release:

Making changes

Adding a power action

  1. Append it to TPowerAction, never in the middle: the ordinals are stored.
  2. Add its entry to PowerActionInfo: its name, how it runs (a new TActionKind with its branch in ExecutePowerAction, if none fits), its shutdown.exe arguments and whether it can force.
  3. If it can be unavailable on some computers, a reason in UnavailableReason and the check in PowerActionUnavailableReason.
  4. Tests in PowerActionsTests; the README’s list of actions and the table in Power actions.

Adding a setting

  1. A field in TAppSettings, its default in DefaultSettings, and its range in NormalizeSettings if it has one.
  2. A value name constant in AppSettings, read in LoadSettings and written in SaveSettings. The name is part of the stored format.
  3. Its control in OptionsForm and OptionsForm.lfm, in ReadSettings and WriteSettings, and what changes in the main window on OK in TfrmMain.ShowOptions.
  4. Tests in AppSettingsTests; the README’s Options section and the table in Settings.

Releasing

Releases are made with the “Publish” workflow, .github/workflows/publish.yml, from the Actions tab (Publish → Run workflow). The work is done by publish.sh, which runs locally as well, in Git Bash on Windows, see ./publish.sh --help.

  1. Build (publish.sh build): runs the tests and builds PowerTimer.exe with the version, see Building.
  2. Package (publish.sh package): checks with PowerShell that PowerTimer.exe has that product version, where PowerShell is there, zips it (with zip, else 7z) as release/PowerTimer_v<version>_win-x64.zip, and writes its SHA-256 to release/checksums.txt.
  3. Release, in a second job, the only one with write access: tags the built commit v<version> and pushes the tag (publish.sh release; the tag may already be on that commit when a failed release is run again), then creates the GitHub release v<version> with the zip and checksums.txt and generated notes, as a pre-release if the version has a -. Run locally, publish.sh release asks before it tags and pushes, and creates no GitHub release.

The version (publish.sh version) is computed from the tags of one major version stream, by default the major of the latest release or preview tag (v1.2.3 or v1.2.3-preview.1), but at least FIRST_MAJOR, 1. Base Ver picks another stream, e.g. 1 for a fix of 1.x after 2.0.0. Run from master, the version is the next release, e.g. 1.0.1 after 1.0.0; from another branch, or with Preview, the next preview, e.g. 1.0.1-preview.1, then 1.0.1-preview.2. Bump Type (major, minor or patch, by default patch) picks the part that is increased. While a preview is open, ahead of the latest release, a bump it doesn’t pass continues it (a patch always does), and one that passes it starts a new version from the latest release: after 1.0.0 and 1.0.1-preview.2, patch gives 1.0.1 (or 1.0.1-preview.3 from another branch), minor gives 1.1.0 (or 1.1.0-preview.1). With no tag in the stream it is <stream>.0.0, or <stream>.0.0-preview.1 for a preview. Version sets the version directly; it must be a semantic version. An existing tag is an error.

Known limitations