Skip to content

RediWM is a Wayland compositor written in Zig (OpenGL ES) that includes everything in one process

battery indicator updates

oxydizer245b2742d7b5
diff --git a/assets/icons/divide.svg b/assets/icons/divide.svg
new file mode 100644
index 0000000..40e9200
--- /dev/null
+++ b/assets/icons/divide.svg
@@ -0,0 +1,4 @@
+<svg width="24" height="24" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
+<path d="M6 12H18" fill="none" stroke="#000000" stroke-width="2" stroke-linecap="round"/>
+<circle cx="12" cy="6" r="1.5"/><circle cx="12" cy="18" r="1.5"/>
+</svg>
diff --git a/build/support.zig b/build/support.zig
index 39a6169..7b0a211 100644
--- a/build/support.zig
+++ b/build/support.zig
@@ -103,7 +103,7 @@ pub fn addShellUi(b: *std.Build, module: *std.Build.Module) void {
pub fn addShellIcons(b: *std.Build, module: *std.Build.Module) void {
module.addAnonymousImport("redi-logo", .{ .root_source_file = b.path("assets/redi-logo.svg") });
module.addAnonymousImport("rediwm-settings-icon", .{ .root_source_file = b.path("assets/icons/rediwm-settings.png") });
- inline for (.{ "git-branch", "home", "folder", "terminal", "settings", "keyboard", "edit", "mouse", "display", "music", "headphones", "wifi", "ethernet", "globe", "bluetooth", "battery", "notification-bell", "speaker", "speaker-xmark", "power-button", "clock", "lock", "logout", "restart", "eye", "eye-off", "refresh", "cut", "copy", "paste", "trash-outline", "trash", "view-grid", "view-list", "sort", "filter", "zoom-in", "zoom-out", "rotate", "crop", "undo", "save", "fit", "print", "open", "usb-stick", "drive", "eject", "users", "squares" }) |name| {
+ inline for (.{ "git-branch", "home", "folder", "terminal", "settings", "keyboard", "edit", "mouse", "display", "music", "headphones", "wifi", "ethernet", "globe", "bluetooth", "battery", "notification-bell", "speaker", "speaker-xmark", "power-button", "clock", "lock", "logout", "restart", "eye", "eye-off", "refresh", "cut", "copy", "paste", "trash-outline", "trash", "view-grid", "view-list", "sort", "filter", "zoom-in", "zoom-out", "rotate", "crop", "undo", "save", "fit", "print", "open", "usb-stick", "drive", "eject", "users", "squares", "divide" }) |name| {
module.addAnonymousImport("shell-icon-" ++ name, .{ .root_source_file = b.path("assets/icons/" ++ name ++ ".svg") });
}
}
diff --git a/docs/plans/calendar.md b/docs/plans/calendar.md
new file mode 100644
index 0000000..e0ef570
--- /dev/null
+++ b/docs/plans/calendar.md
@@ -0,0 +1,344 @@
+# Calendar integration plan
+
+Status: draft, 2026-10-25. The first release must support **Google Calendar
+and Outlook/Microsoft 365 together**, including personal Microsoft accounts
+and work or school accounts. CalDAV follows after those providers.
+
+Build a native Calendar application, an agenda in the taskbar clock popup,
+and a separate service for storage, synchronization and reminders. Use
+[KOrganizer](https://apps.kde.org/korganizer/) as the feature reference:
+multiple calendars, event editing, recurrence, reminders, invitations,
+tasks and calendar-file interoperability. Deliver this in increments with
+explicit completion criteria.
+
+## Current foundation
+
+[`src/calendar.zig`](../../src/calendar.zig) currently provides a month grid,
+today highlighting, month navigation, locale/week-start handling and taskbar
+placement. It has no event model, selected-day agenda, storage, accounts,
+editing or reminders. Preserve its existing behavior and
+[`tests/calendar_popup.py`](../../tests/calendar_popup.py) coverage.
+
+RediWM already has native Wayland app patterns, shared widgets, notification
+actions and session helper management. Its Accounts/Users code manages local
+Linux users; online accounts need a separate unprivileged subsystem. OAuth,
+calendar storage and a desktop keyring client are new infrastructure.
+
+## Product scope
+
+| Area | First release | Full calendar follow-up |
+| --- | --- | --- |
+| Accounts | Multiple Google, personal Outlook and Microsoft 365 work/school accounts; connect, reconnect and remove | CalDAV, qualified Nextcloud/iCloud configurations and subscribed calendars |
+| Calendars | Local calendar plus multiple provider calendars, visibility toggles, colors and default destination; enforce permissions | Create/manage remote calendars, shared/delegated calendars and sharing controls |
+| Clock popup | Select a date, event indicators, selected-day/upcoming agenda, Open Calendar and New Event | Optional next-event clock label and richer quick actions |
+| Application | Month, week, day and agenda views; Today, date navigation, search over cached data, keyboard operation | Drag to reschedule/resize, work-week options, print and undo where reversible |
+| Events | Create/edit/delete, all-day and timed events, location, description, time zone and existing meeting links | Attachments, categories, richer availability and conference creation |
+| Recurrence | Common repeat rules, read existing exceptions, edit one occurrence or whole series; preserve unsupported rules | This and following occurrences, advanced recurrence editor and cross-provider moves |
+| Reliability | Offline viewing/editing within cached coverage, visible pending changes/conflicts, restart recovery | Expanded offline coverage and provider-specific advanced operations |
+| Reminders | Reminders with the app closed, Open/Snooze/Dismiss, missed-reminder list, lock and DND behavior | More alarm options and qualified provider reminder-state synchronization |
+| Interoperability | Preview/import/export `.ics`, opening calendar files, display invitees and response status | Send invitations, RSVP/cancellation workflows, free/busy, tasks and birthdays |
+
+First-release shared/delegated calendars are supported only where explicitly
+qualified; do not label Microsoft 365 groups, shared mailboxes or on-premises
+Exchange as supported merely because a user's own calendar works. Report
+unsupported operations clearly and offer the provider's event page.
+
+“Gmail integration” initially means calendars associated with a Google
+account, including events Google has already generated from Gmail. These are
+available through the Calendar API, with restrictions on what can be edited.
+Inbox scanning, parsing arbitrary mail and sending mail are separate later
+features. [Google event types](https://developers.google.com/workspace/calendar/api/guides/event-types)
+
+## Architecture and backend choice
+
+Keep the UI and provider work in separate processes:
+
+```mermaid
+flowchart LR
+ Popup[Clock popup agenda] <--> Service[Calendar service]
+ App[Native Calendar app] <--> Service
+ Settings[Settings Online Accounts] <--> Service
+ Service <--> Store[Calendar store and pending changes]
+ Service <--> Keyring[Desktop keyring]
+ Service <--> Google[Google Calendar]
+ Service <--> Microsoft[Microsoft Graph]
+ Service --> Notifications[RediWM notifications]
+```
+
+The compositor receives bounded snapshots and change notifications. HTTP,
+authentication, disk transactions and recurrence expansion stay outside its
+input/render thread. The app also uses asynchronous requests and never writes
+the service's database directly.
+
+Start with a short backend prototype before committing to a custom sync
+engine:
+
+| Choice | Benefit | Decision |
+| --- | --- | --- |
+| Evolution Data Server with its provider modules | Existing calendar service, asynchronous C API and change subscriptions; a Microsoft Graph calendar backend exists in evolution-ews | Preferred reuse candidate, subject to the Phase 0 gates below |
+| Native service using SQLite and libical | Direct control over lifecycle and dependencies; established iCalendar/recurrence primitives | Fallback if reuse fails; RediWM then owns OAuth, sync, conflict handling and provider maintenance |
+| Akonadi | KDE PIM store and resource interoperability | Consider only if sharing KDE's data infrastructure becomes a requirement; introduces a broader Qt/KDE dependency set |
+
+References: [EDS client API](https://gnome.pages.gitlab.gnome.org/evolution-data-server/libecal/class.Client.html),
+[Microsoft Graph calendar backend](https://gitlab.gnome.org/GNOME/evolution-ews/-/blob/master/src/Microsoft365/calendar/e-cal-backend-m365.c),
+[libical](https://github.com/libical/libical),
+[Akonadi architecture](https://community.kde.org/KDE_PIM/Akonadi/Architecture).
+
+Accept EDS only if the packaged versions can support calendar-only browser
+sign-in, both Microsoft account types, offline writes, recurrence exceptions,
+controlled service lifetime and an acceptable idle footprint without an
+Evolution window or toolkit-owned account dialogs. Its current Google OAuth
+implementation requests mail, contacts and tasks as well as calendars, so a
+narrower credential integration must be proved. Qualify the Microsoft
+**Graph** backend and its actual distribution availability.
+[EDS Google OAuth implementation](https://raw.githubusercontent.com/GNOME/evolution-data-server/master/src/libedataserver/e-oauth2-service-google.c)
+
+Choose one backend after the prototype. With EDS, its store is authoritative;
+any RediWM sidecar stores only app-specific state the backend cannot own.
+With the native implementation, use one private SQLite store. Do not build
+two independently editable copies of calendar data. Isolate any GLib bridge
+behind a small C ABI, respecting the repository's translate-c restrictions.
+
+## Accounts and provider contracts
+
+Add **Settings → Online Accounts**, reachable from Calendar. Show provider,
+account identity, enabled calendars, last successful sync, pending work and
+actionable states such as Offline, Sign in again or Organization approval
+required. Disconnect stops new work and offers preservation/export of unsent
+changes before local removal; it must not delete remote calendars.
+
+Use external-browser OAuth authorization code flow with PKCE and a validated
+loopback callback, with cancellation, expiry and state validation. Register
+desktop/public clients and never rely on a shipped client secret being
+confidential. Request calendar permissions plus only the identity/session
+scopes needed for sign-in. Browser-based authorization keeps MFA with the
+provider. [Google desktop OAuth](https://developers.google.com/identity/protocols/oauth2/native-app),
+[Microsoft authorization code flow](https://learn.microsoft.com/en-us/entra/identity-platform/v2-oauth2-auth-code-flow)
+
+Google's initial scope set should cover calendar-list discovery and event
+read/write access; request calendar-management/sharing permissions only when
+those features arrive. Complete the applicable production consent and
+verification work. An external app left in Google's Testing state generally
+gets seven-day refresh tokens for calendar access, which is not a usable
+release configuration. [Google scopes](https://developers.google.com/workspace/calendar/api/auth),
+[refresh-token expiry](https://developers.google.com/identity/protocols/oauth2#expiration)
+
+For Microsoft, register support for organizational and personal accounts and
+use Graph v1.0 with delegated `Calendars.ReadWrite` and the required sign-in
+and refresh scopes. Qualify tenant consent, MFA, conditional-access failures
+and token renewal. Shared-calendar permissions are a later explicit addition;
+the desktop client does not need tenant-wide application permissions.
+[Calendar API overview](https://learn.microsoft.com/en-us/graph/outlook-calendar-concept-overview),
+[Microsoft permissions](https://learn.microsoft.com/en-us/graph/permissions-reference#calendarsreadwrite)
+
+Store refresh tokens and CalDAV credentials in a qualified desktop keyring
+through Secret Service or a supported adapter. Existing PAM keyring hooks
+do not supply the client API or guarantee unlocking during automatic login.
+A locked/missing keyring leaves local/cached calendars usable and pauses
+authentication; never silently store tokens as plaintext. Keep secrets out
+of config files, logs, argv, UI arenas and ordinary IPC snapshots.
+[Secret Service API](https://specifications.freedesktop.org/secret-service/latest/)
+
+| Provider | Required synchronization behavior |
+| --- | --- |
+| Google | Paginated initial sync, per-calendar sync tokens, deletions and permission changes; recover invalid tokens with a new remote snapshot while preserving unsent local changes |
+| Microsoft | Fixed-range `calendarView/delta` where supported; qualify secondary calendars and use bounded calendar-view snapshot/diff otherwise; extend/rebuild coverage as the range advances |
+| Both | Durable pending writes, retry/backoff, authentication recovery, conflict handling, idempotent creation and accurate account/calendar capabilities |
+
+Google incremental queries have parameter restrictions and invalid tokens
+return `410`; rebuilding the remote cache must not wipe the local outbox.
+Microsoft's stable calendar-view delta API is tied to a calendar and time
+range, so one moving date filter cannot reuse the same delta state forever.
+[Google sync](https://developers.google.com/workspace/calendar/api/guides/sync),
+[Microsoft delta sync](https://learn.microsoft.com/en-us/graph/delta-query-events)
+
+Qualify primary and secondary owned Microsoft calendars separately. The v1.0
+delta method reference documents the primary-calendar routes; do not assume
+all per-calendar delta routes are available. A snapshot fallback must finish
+all pages before identifying removals, and removal from a cached time range
+must not be treated as proof that the underlying event was deleted.
+[Microsoft delta method](https://learn.microsoft.com/en-us/graph/api/event-delta?view=graph-rest-1.0)
+
+Use Google conditional writes with ETags and qualify Graph's corresponding
+version/conflict behavior. Persist Graph immutable event IDs where supported
+and use `transactionId` when creating events; keep provider IDs separate from
+the app's stable local IDs. Lost responses must not duplicate an event or
+invitation on retry. [Google conditional writes](https://developers.google.com/workspace/calendar/api/guides/version-resources),
+[Microsoft immutable IDs](https://learn.microsoft.com/en-us/graph/outlook-immutable-id),
+[Microsoft event properties](https://learn.microsoft.com/en-us/graph/api/resources/event?view=graph-rest-1.0)
+
+## Calendar data and synchronization rules
+
+Model accounts, calendars, event masters, occurrence exceptions, attendees,
+alarms, provider revisions, pending mutations and synchronization coverage.
+Represent date-only all-day events separately from instants. Preserve original
+time zones, floating times from imported files, exclusive end dates and
+provider metadata. Use tested IANA/Windows time-zone mapping for Microsoft
+interoperability and bound recurrence expansion to requested ranges.
+
+Each occurrence needs stable identity based on its series and original
+occurrence, even when rescheduled. Support removed and moved instances and
+daylight-saving transitions. Preserve recurrence rules and fields the editor
+cannot represent; disable unsupported edits instead of rewriting them into
+something simpler. Provider-specific recurrence formats must round-trip.
+[Google recurrence behavior](https://developers.google.com/workspace/calendar/api/guides/recurringevents)
+
+For Graph, fetch series masters needed for whole-series editing and retain
+their links to occurrences/exceptions returned by calendar views. Qualify a
+moved occurrence crossing the cache boundary, and preserve pending changes
+when an occurrence leaves that range.
+
+Commit fetched pages and sync checkpoints consistently. Reconcile local
+mutations against the last remote version and present meaningful conflicts;
+do not silently overwrite another device's edit. Preserve unresolved writes
+through token expiry, service crashes and resync. Database migrations need
+backup/recovery behavior, and account removal must cancel stale completions.
+
+Define a documented offline horizon in Phase 0 and fetch extra ranges on
+demand. Distinguish an empty calendar from a range never downloaded. Search
+must state when results cover cached data only. A remote series edit or event
+move must invalidate affected occurrence caches and reminder schedules.
+
+Only enable invite-affecting operations once their delivery behavior is
+qualified. In the first release, existing meetings can be viewed; unsupported
+organizer/attendee edits open the provider. The later meeting workflow must
+show recipients and whether saving sends invitations, updates or cancellation
+messages. Importing an `.ics` file must not send mail as a side effect.
+
+## Reminders and service lifecycle
+
+Run one service owner for the primary user session, independent of Calendar
+window lifetime. Define startup, restart, logout and nested-session isolation
+explicitly; use a single database writer and reminder delivery target. The
+greeter must never activate the service, keyring, account setup or cache.
+
+If EDS is selected, RediWM owns its wrapper and subscriptions. Logout must
+release those without terminating shared EDS or keyring processes used by
+other applications. Coordinate reminder ownership so an existing backend
+alarm service does not deliver a second copy.
+
+Persist snoozed/dismissed alarms and a delivery ledger keyed by event
+occurrence and alarm. Recalculate deadlines after edits, deletions, resume,
+time-zone changes and wall-clock adjustments. Use notification replacement
+and durable delivery state to avoid repeated alarms after reconnect/restart.
+Keep a missed-reminder list because notification toast lifetime is not a
+durable record. Local snoozes need not change other devices' reminders.
+
+Use normal notification urgency, existing DND behavior and lock suppression;
+event details must not leak through new shell inspection or automation
+endpoints while locked. Account dialogs must not appear over the lock screen.
+Cached calendar data uses private XDG storage; keyring protection of tokens
+does not encrypt the calendar database itself.
+
+Use one-shot deadlines for the next reminder, retry or scheduled provider
+refresh, plus network/resume/change signals. Sync on account connection,
+relevant app opening, manual refresh and network recovery; coalesce a
+configurable background refresh deadline for changes made on other devices.
+Keep the existing clock tick independent. With no enabled calendar work,
+there should be no additional wakeups or repainting.
+
+Neither provider's webhook service is a direct push connection to an ordinary
+offline-capable desktop: it requires a publicly reachable HTTPS receiver.
+The first release uses scheduled incremental sync and exposes freshness.
+A hosted push relay would be a separate product/operations decision.
+[Google push](https://developers.google.com/workspace/calendar/api/guides/push),
+[Microsoft webhooks](https://learn.microsoft.com/en-us/graph/change-notifications-delivery-webhooks)
+
+## Repository integration
+
+| Location | Planned work |
+| --- | --- |
+| `src/calendar_main.zig`, `src/calendar_app/` | New native Wayland app using shared Cairo/widgets, theme loading, Compose, fractional scale and ordinary app-scope launch/activation |
+| `src/calendar_service/` | Service entry point, backend adapter, bounded asynchronous API, lifetime, reminders and recovery; native store/provider modules only if selected in Phase 0 |
+| `src/calendar_model/` | Provider-independent types, occurrence identities, date ranges and capabilities without compositor imports |
+| `src/online_accounts/` | Provider account configuration, OAuth/keyring interface and credential lifecycle; never the privileged accounts helper |
+| `src/calendar.zig` and new sibling concern files | Selected date, event indicators, agenda, widgets and service subscription; split paint/input/client responsibilities as needed |
+| `src/output/panels.zig`, `src/input/`, `src/keyboard/` | Preserve popup anchoring/dismissal; add deliberate scroll, focus, navigation and key-repeat behavior |
+| `src/control_center/panel.zig`, `sections/online_accounts.zig`, `search_index.zig` | Online Accounts navigation, page lifecycle, controls and searchable entries |
+| `src/server/session.zig`, `src/session/services.zig` | Primary-session service ownership, greeter exclusion, bounded teardown and restart policy |
+| `src/notifications/manager.zig` | Reuse existing D-Bus notification actions and lock/DND behavior; add changes only where required |
+| `build.zig`, `build/apps.zig`, `build/tests.zig`, `build/data.zig`, `data/`, `scripts/` | Modules, executables, dependencies, test roots, desktop entry/icon, `text/calendar` handling and installer/release lists |
+
+A private nonblocking Unix socket is a reasonable app/popup/service transport,
+following the transfers helper precedent. Version and bound messages, check
+peer identity, copy snapshots into their owner's memory, cancel by request
+generation and resubscribe after reconnect. Missing service/account data must
+not block opening the clock popup. Freeze the transport choice in Phase 0.
+
+The existing `dbus.Connection` uses a Wayland server event loop and lacks
+automatic reconnect/activation fallback. Budget event-loop integration for
+keyring/notifications or the selected backend; it is not a drop-in module for
+the standalone app's poll loop. Read the relevant area `AGENTS.md` files and
+rendering notes before implementation.
+
+## Delivery phases and completion criteria
+
+1. **Phase 0 — Backend and account prototype.** Compare EDS and native dependencies,
+ qualify Google plus both Microsoft account types, calendar-only consent,
+ keyring access and provider round-trips. Exercise one recurring event,
+ offline edit and concurrent modification per provider, including primary
+ and secondary owned calendars and Graph series-master loading. Record process
+ footprint, idle wakes, package versions, license notices, registration
+ ownership, cache horizon and transport choice. Completion means one chosen
+ backend with demonstrated behavior; mock data alone does not pass this gate.
+2. **Phase 1 — Local calendar foundation.** Add service/model, durable local calendar,
+ native month/agenda views, editor, common recurrence and `.ics` preview,
+ import/export. Completion means local events survive restarts and the app
+ stays responsive; unsupported input round-trips or is clearly rejected.
+3. **Phase 2 — Google and Microsoft synchronization.** Add Online Accounts and implement
+ both providers through the same contract, initially read-only then writes.
+ Complete calendar selection, offline outbox, expiry/reconnect, conflicts,
+ deletion and range coverage. Completion means an event created/edited on
+ either side appears correctly on the other, for all three account classes,
+ including restart and offline recovery. No Google-only release gate.
+4. **Phase 3 — Integrated first release.** Finish day/week views and search, agenda
+ popup, app activation and reminders with the app closed. Qualify DND/lock,
+ suspend/resume, locales, multiple accounts, account removal and packaging.
+ Complete production OAuth readiness. Completion means the entire first
+ release column above works with both providers.
+5. **Phase 4 — Meetings and desktop parity.** Add provider-native invite/RSVP/cancel,
+ shared/delegated calendars, free/busy, conferencing, drag rescheduling,
+ advanced recurrence, calendar management, print and qualified undo.
+ Completion requires explicit capability tests and no duplicate invitations
+ on retries. Sharing and attendee permissions must be enforced by the service.
+6. **Phase 5 — Additional providers and personal information.** Add CalDAV discovery,
+ conditional writes and collection sync, then qualify named servers. Add
+ read-only webcal/holiday feeds, contact birthdays, tasks and attachments.
+ Treat Google Tasks/Microsoft To Do and contacts as separate adapters/scopes;
+ a calendar account does not imply support. Calendar-file import and feed
+ subscription remain distinct operations.
+
+CalDAV implementations should use the standard protocol and synchronization
+extension where supported, with explicit fallback/capability detection.
+[CalDAV](https://www.rfc-editor.org/rfc/rfc4791),
+[WebDAV collection synchronization](https://www.rfc-editor.org/rfc/rfc6578)
+
+## Validation
+
+Extend existing popup coverage and add focused model/service tests. Keep
+tests beside their concern and import test roots explicitly. Automated tests
+use private XDG directories, private buses, fixture keyrings and fake provider
+servers; they never contact personal accounts or change host services.
+Manual provider qualification uses dedicated test calendars/accounts.
+
+Required cases include DST gaps/overlaps, all-day dates, leap days, floating
+times, recurring exceptions, Windows/IANA zones, malformed/bounded imports,
+remote deletion, lost responses, pagination, invalid sync state, advancing
+Graph coverage, rate limits, token revocation, locked keyring, permission
+changes, conflicting edits, crash recovery and unsent edits on disconnect.
+
+Exercise popup/app updates while requests are pending, service restarts,
+close/reopen, stable selection, keyboard navigation, themes and scales 1/1.5.
+Test reminder cancellation, duplicate prevention, snooze, clock changes,
+resume, DND, lock and multiple/nested sessions. Measure per-thread wakeups
+with no accounts, idle local calendars and scheduled remote sync separately.
+
+Implementation gates follow [`TESTING.md`](../../TESTING.md): Debug and
+ReleaseSafe builds, `zig build test`, calendar app/service fixtures and
+`tests/calendar_popup.py`. When touching integration, also run the relevant
+notification, lock/greeter, session lifecycle, activation and i18n suites.
+Compare failures with a clean HEAD worktree before calling them regressions.
+
+The next implementation step is Phase 0. Its backend decision and real Google,
+personal Outlook and Microsoft 365 results determine the work estimate for
+the remaining phases.
diff --git a/po/rediwm.pot b/po/rediwm.pot
index a5dee5d..0694a04 100644
--- a/po/rediwm.pot
+++ b/po/rediwm.pot
@@ -571,6 +571,10 @@ msgstr ""
msgid "Bass boost"
msgstr ""
+#: src/server/wakeups.zig
+msgid "Battery is at {percent}%. Plug in your charger."
+msgstr ""
+
#: src/printing/options.zig
msgid "Black and white"
msgstr ""
@@ -903,6 +907,10 @@ msgstr ""
msgid "Capture the current display."
msgstr ""
+#: src/control_center/sections/appearance_sections.zig
+msgid "Center"
+msgstr ""
+
#: src/control_center/sections/sound.zig
msgid "Centre"
msgstr ""
@@ -3251,6 +3259,10 @@ msgstr ""
msgid "Lost contact with login service. Try again."
msgstr ""
+#: src/server/wakeups.zig
+msgid "Low battery"
+msgstr ""
+
#: src/control_center/sections/network.zig
msgid "MAC address"
msgstr ""
@@ -4239,6 +4251,10 @@ msgstr ""
msgid "Please wait for the file operation to finish."
msgstr ""
+#: src/server/wakeups.zig
+msgid "Plug in your charger."
+msgstr ""
+
#: src/taskbar/battery.zig
msgid "Plugged In"
msgstr ""
@@ -5691,6 +5707,10 @@ msgstr ""
msgid "Taskbar"
msgstr ""
+#: src/control_center/search_index.zig
+msgid "Taskbar alignment"
+msgstr ""
+
#: src/control_center/sections/region.zig
msgid "Taskbar clock. The date uses your regional format."
msgstr ""
@@ -7023,6 +7043,10 @@ msgstr ""
msgid "panel height"
msgstr ""
+#: src/control_center/search_index.zig
+msgid "panel left center right"
+msgstr ""
+
#: src/control_center/search_index.zig
msgid "panel margin"
msgstr ""
@@ -7315,6 +7339,10 @@ msgid_plural "{count}{more} items"
msgstr[0] ""
msgstr[1] ""
+#: src/taskbar/battery.zig
+msgid "{hours}h {minutes}min"
+msgstr ""
+
#: src/desktop/app_paint.zig
msgid "{kind} · {bytes} bytes"
msgstr ""
@@ -7327,6 +7355,10 @@ msgstr ""
msgid "{locale} · RediWM stays in English"
msgstr ""
+#: src/taskbar/battery.zig
+msgid "{minutes}min"
+msgstr ""
+
#: src/images/app_thumbs.zig
msgid "{modified}{name} — Images ({position}/{count})"
msgstr ""
@@ -7435,6 +7467,10 @@ msgstr ""
msgid "{value}% · ↓ {rate} KiB/s · ↑ {rate3} KiB/s"
msgstr ""
+#: src/taskbar/battery.zig
+msgid "~{time} left"
+msgstr ""
+
#: src/files/app_torrent_rows.zig
msgid "↓ {rate} KiB/s ↑ {rate2} KiB/s"
msgstr ""
diff --git a/src/Server.zig b/src/Server.zig
index a2acd87..e87862a 100644
--- a/src/Server.zig
+++ b/src/Server.zig
@@ -164,6 +164,8 @@ audio_wake_source: ?*wl.EventSource = null,
// taskbar still picks up plug changes on its minute tick.
battery_uevent_fd: ?std.posix.fd_t = null,
battery_uevent_source: ?*wl.EventSource = null,
+battery_warning: battery_mod.Warning = .{},
+battery_warning_id: ?u32 = null,
// Optional for the same reason `audio` is: a spawn/eventfd failure just
// means every consumer's `server.iconLookup(...)` reports `.missing`
@@ -1049,6 +1051,7 @@ pub const IconNameCache = struct {
pub const createAudioWakeFd = server_wakeups.createAudioWakeFd;
pub const handleAudioWake = server_wakeups.handleAudioWake;
pub const handleBatteryUevent = server_wakeups.handleBatteryUevent;
+pub const updateBatteryWarning = server_wakeups.updateBatteryWarning;
pub const ensureGpuTimer = server_wakeups.ensureGpuTimer;
pub const observingStats = server_wakeups.observingStats;
pub const expireGpuTimer = server_wakeups.expireGpuTimer;
diff --git a/src/Taskbar.zig b/src/Taskbar.zig
index 2065424..352d97f 100644
--- a/src/Taskbar.zig
+++ b/src/Taskbar.zig
@@ -316,6 +316,7 @@ pub fn destroy(bar: *Taskbar) void {
/// Takes a fresh `battery.read` snapshot; only a change requests a frame.
pub fn applyBattery(bar: *Taskbar, next: battery.State) void {
+ bar.server.updateBatteryWarning(next);
if (std.meta.eql(next, bar.battery_state)) return;
const layout_changed = (next.percent == null) != (bar.battery_state.percent == null);
bar.battery_shimmer.update(bar.battery_state, next, nowMs());
diff --git a/src/battery_popup.zig b/src/battery_popup.zig
index c9a880b..1d964a9 100644
--- a/src/battery_popup.zig
+++ b/src/battery_popup.zig
@@ -97,7 +97,10 @@ pub const Popup = struct {
var pct: [16]u8 = undefined;
const percent = if (state.percent) |p| std.fmt.bufPrint(&pct, "{d}%", .{p}) catch "" else "—";
label(&r, 24, 16, 100, 38, percent, 27, t.window_fg, true);
- label(&r, 125, 18, 220, 36, state.status(), 16, t.window_dim, false);
+ var estimate_buf: [192]u8 = undefined;
+ const estimate = state.estimate(&estimate_buf);
+ label(&r, 125, if (estimate != null) 14 else 18, 220, if (estimate != null) 24 else 36, state.status(), 16, t.window_dim, false);
+ if (estimate) |value| label(&r, 125, 38, 220, 20, value, 12, t.window_dim, false);
r.fillRect(20, 66, 328, 1, .{ .color = t.border });
ring(&r, state.percent orelse 0);
centered(&r, 136, 52, percent, 36, t.window_fg, true);
diff --git a/src/calculator/app.zig b/src/calculator/app.zig
index 1f8f002..2f441c7 100644
--- a/src/calculator/app.zig
+++ b/src/calculator/app.zig
@@ -11,6 +11,12 @@ fn entrySize() f32 {
return ui.widgets.button.metrics(.lg, theme.global).font_size * 2;
}
+fn keypadTheme() theme.Theme {
+ var palette = theme.shellPalette();
+ palette.button_font_size *= 1.5;
+ return palette;
+}
+
const labels = [_][]const u8{
"AC", "(", ")",
"⌫", // Clear and editing.
@@ -73,6 +79,7 @@ pub const App = struct {
for (&self.buttons, labels, 0..) |*button, label, id| {
button.* = .{ .kind = .{ .button = .{
.label = label,
+ .icon = if (id == 6) .divide else null,
.size = .lg,
.variant = if (id == 19) .primary else .secondary,
.owner = self,
@@ -92,6 +99,7 @@ pub const App = struct {
const cell_w = (width - 32 - gap * 3) / 4;
const top: f32 = @max(112, entrySize() + cairo.statusSize() + 56);
const cell_h = @max(24, (height - top - 16 - gap * 5) / 6);
+ const icon_size = ui.widgets.button.metrics(.lg, keypadTheme()).font_size;
self.root.computed_width = width;
self.root.computed_height = height;
for (&self.buttons, 0..) |*button, id| {
@@ -113,6 +121,8 @@ pub const App = struct {
y = top + 5 * (cell_h + gap);
}
ui.arrange.arrange(button, x, y, w, h);
+ // Keep the operator icon at the label size when the keypad resizes.
+ if (button.kind.button.icon != null) button.kind.button.icon_scale = icon_size / @min(w, h);
}
}
pub fn resize(self: *App, width: i32, height: i32) void {
@@ -217,9 +227,7 @@ pub const App = struct {
defer ui.input.active_dispatcher = null;
if (cairo.Layer.begin(cr, .{ .x = 0, .y = 0, .w = @floatFromInt(self.w), .h = @floatFromInt(self.h) })) |value| {
var layer = value;
- var keypad_theme = theme.shellPalette();
- keypad_theme.button_font_size *= 1.5;
- layer.renderer.palette = keypad_theme;
+ layer.renderer.palette = keypadTheme();
ui.paint.paint(&self.root, &layer.renderer);
layer.finish();
}
diff --git a/src/config/default.zig b/src/config/default.zig
index c76796d..f17c49b 100644
--- a/src/config/default.zig
+++ b/src/config/default.zig
@@ -33,7 +33,7 @@ pub const source =
\\selection_alpha = 0.35 # highlight opacity when it follows the accent
\\taskbar_size = 44.0 # taskbar height in pixels (36.0 to 84.0)
\\# taskbar_edge_gap = 0 # floating taskbar: px between it and the screen edge (0–64)
- \\# taskbar_length = 100 # percent of the screen edge it spans, centred (20–100)
+ \\# taskbar_length = 100 # percent of the screen edge it spans (20–100)
\\# taskbar_radius = 0 # corner radius in px; a pill at half the taskbar size
\\# taskbar_outline_width = 1 # the bar's outline, px (0–8); colour: taskbar_outline
\\# taskbar_outline = "rgba(255,255,255,0.06)" # unset follows border_soft
@@ -136,6 +136,7 @@ pub const source =
\\dock_pinned_apps = [] # desktop entry IDs pinned by dragging them from the start menu
\\# Taskbar sections, ordered within each section; prefix with - to hide an item.
\\taskbar_position = "bottom" # top or bottom
+ \\taskbar_alignment = "center" # left, center or right; visible below 100% length
\\taskbar_items = ["left:start", "left:windows", "right:capture", "right:tray", "right:battery", "~right:wifi", "~right:wired", "right:volume", "right:clock", "-right:power"]
\\# A ~ prefix (~right:wifi, ~right:wired) shows the item only while a wireless adapter
\\# exists, or a cable is connected; a plain or - entry always shows or hides it.
diff --git a/src/config/loader.zig b/src/config/loader.zig
index 52ebde4..8489060 100644
--- a/src/config/loader.zig
+++ b/src/config/loader.zig
@@ -194,6 +194,7 @@ pub const CompositorConfig = struct {
dock_pinned_apps: []const []const u8 = &.{},
taskbar_items: TaskbarItems = .{},
taskbar_position: types.TaskbarPosition = .bottom,
+ taskbar_alignment: types.TaskbarAlignment = .center,
/// App identities opted into compositor tabs. Only + launches join a group.
window_tab_apps: []const []const u8 = &.{},
focus_follows_mouse: bool = false,
diff --git a/src/config/loader_fields.zig b/src/config/loader_fields.zig
index 854151e..4f3a492 100644
--- a/src/config/loader_fields.zig
+++ b/src/config/loader_fields.zig
@@ -110,6 +110,7 @@ pub const compositor_rules: std.enums.EnumFieldStruct(std.meta.FieldEnum(Composi
.dock_pinned_apps = .json_string_list,
.taskbar_items = .taskbar_items,
.taskbar_position = .enumeration,
+ .taskbar_alignment = .enumeration,
.icon_theme = .string,
.window_tab_apps = .json_string_list,
.default_file_manager = .string,
diff --git a/src/config/loader_fields_tests.zig b/src/config/loader_fields_tests.zig
index a100fe3..4a16fb3 100644
--- a/src/config/loader_fields_tests.zig
+++ b/src/config/loader_fields_tests.zig
@@ -87,6 +87,12 @@ test "config field parsing preserves ranges and derived zoom state" {
}
var c = CompositorConfig{};
+ try std.testing.expectEqual(types.TaskbarAlignment.center, c.taskbar_alignment);
+ inline for (.{ "left", "center", "right" }) |value| {
+ try applyCompositorKey(&c, a, "taskbar_alignment", "\"" ++ value ++ "\"");
+ try std.testing.expectEqualStrings(value, @tagName(c.taskbar_alignment));
+ }
+ try std.testing.expectError(error.InvalidValue, applyCompositorKey(&c, a, "taskbar_alignment", "top"));
try std.testing.expectEqual(types.DockPosition.bottom, c.dock_position);
inline for (.{ "top", "bottom", "left", "right" }) |value| {
try applyCompositorKey(&c, a, "dock_position", value);
diff --git a/src/config/theme_pack.zig b/src/config/theme_pack.zig
index 63e9820..1cbafff 100644
--- a/src/config/theme_pack.zig
+++ b/src/config/theme_pack.zig
@@ -11,6 +11,7 @@ const TaskbarItems = @import("taskbar_items.zig").Config;
/// remain in [compositor]; packs cannot inject other compositor settings.
pub const Layout = struct {
taskbar_position: ?@import("types.zig").TaskbarPosition = null,
+ taskbar_alignment: ?@import("types.zig").TaskbarAlignment = null,
/// Which section (left, centre or right) each taskbar item sits in, in
/// what order and whether it shows: the `[compositor]` list's own syntax.
taskbar_items: ?TaskbarItems = null,
@@ -19,7 +20,7 @@ pub const Layout = struct {
dock_height: ?u32 = null,
dock_hover_zoom: ?f32 = null,
- pub const keys = .{ "taskbar_position", "taskbar_items", "dock_enabled", "dock_position", "dock_height", "dock_hover_zoom" };
+ pub const keys = .{ "taskbar_position", "taskbar_alignment", "taskbar_items", "dock_enabled", "dock_position", "dock_height", "dock_hover_zoom" };
pub fn apply(self: Layout, compositor: anytype) void {
inline for (keys) |key| if (@field(self, key)) |value| {
@@ -30,6 +31,8 @@ pub const Layout = struct {
fn parseKey(self: *Layout, key: []const u8, value: []const u8) !void {
if (std.mem.eql(u8, key, "taskbar_position")) {
self.taskbar_position = std.meta.stringToEnum(@import("types.zig").TaskbarPosition, try theme.unquote(value)) orelse return error.InvalidLayout;
+ } else if (std.mem.eql(u8, key, "taskbar_alignment")) {
+ self.taskbar_alignment = std.meta.stringToEnum(@import("types.zig").TaskbarAlignment, try theme.unquote(value)) orelse return error.InvalidLayout;
} else if (std.mem.eql(u8, key, "taskbar_items")) {
self.taskbar_items = TaskbarItems.parse(value) catch return error.InvalidLayout;
} else if (std.mem.eql(u8, key, "dock_enabled")) {
@@ -50,8 +53,8 @@ pub const Layout = struct {
pub fn write(a: A, bytes: *std.ArrayList(u8), compositor: anytype) !void {
const items = try compositor.taskbar_items.serialize(a);
defer a.free(items);
- const text = try std.fmt.allocPrint(a, "[layout]\ntaskbar_position = \"{s}\"\ntaskbar_items = {s}\ndock_enabled = {}\ndock_position = \"{s}\"\ndock_height = {d}\ndock_hover_zoom = {d}\n", .{
- @tagName(compositor.taskbar_position), items, compositor.dock_enabled, @tagName(compositor.dock_position), compositor.dock_height, compositor.dock_hover_zoom,
+ const text = try std.fmt.allocPrint(a, "[layout]\ntaskbar_position = \"{s}\"\ntaskbar_alignment = \"{s}\"\ntaskbar_items = {s}\ndock_enabled = {}\ndock_position = \"{s}\"\ndock_height = {d}\ndock_hover_zoom = {d}\n", .{
+ @tagName(compositor.taskbar_position), @tagName(compositor.taskbar_alignment), items, compositor.dock_enabled, @tagName(compositor.dock_position), compositor.dock_height, compositor.dock_hover_zoom,
});
defer a.free(text);
try bytes.appendSlice(a, text);
@@ -263,6 +266,16 @@ test "pack metadata, future tokens and unsafe paths" {
const exported = try parse(a, bytes.items, "test", "");
try std.testing.expectEqual(pack.layout.dock_position, exported.layout.dock_position);
}
+ inline for (.{ "left", "center", "right" }) |alignment| {
+ const pack = try parse(a, "[layout]\ntaskbar_alignment = \"" ++ alignment ++ "\"\n", "test", "");
+ var compositor = @import("loader.zig").CompositorConfig{};
+ pack.layout.apply(&compositor);
+ try std.testing.expectEqualStrings(alignment, @tagName(compositor.taskbar_alignment));
+ var bytes: std.ArrayList(u8) = .empty;
+ try Layout.write(a, &bytes, compositor);
+ const exported = try parse(a, bytes.items, "test", "");
+ try std.testing.expectEqual(pack.layout.taskbar_alignment, exported.layout.taskbar_alignment);
+ }
{
// A pack arranges the taskbar's items, and an export carries them.
const pack = try parse(a, "[layout]\ntaskbar_items = [\"left:start\", \"left:windows\", \"-center:tray\", \"right:battery\", \"right:network\", \"right:volume\", \"center:clock\"]\n", "test", "");
diff --git a/src/config/types.zig b/src/config/types.zig
index a328a3e..0f43418 100644
--- a/src/config/types.zig
+++ b/src/config/types.zig
@@ -1,6 +1,7 @@
const std = @import("std");
pub const PanModifier = enum { super, super_alt };
pub const TaskbarPosition = enum { top, bottom };
+pub const TaskbarAlignment = enum { left, center, right };
pub const DockPosition = enum {
top,
bottom,
diff --git a/src/config_runtime/apply.zig b/src/config_runtime/apply.zig
index 7f2a868..2fe3041 100644
--- a/src/config_runtime/apply.zig
+++ b/src/config_runtime/apply.zig
@@ -212,7 +212,9 @@ pub fn applyDiff(server: *Server, old: Config, new: Config) void {
server.refreshTaskbars();
}
- if (!std.meta.eql(old.compositor.taskbar_items, new.compositor.taskbar_items)) {
+ if (!std.meta.eql(old.compositor.taskbar_items, new.compositor.taskbar_items) or
+ old.compositor.taskbar_alignment != new.compositor.taskbar_alignment)
+ {
if (!theme_changed) server.refreshTaskbarsGeometry();
if (server.input.open_control_center) |cc| cc.refresh();
}
diff --git a/src/control_center/search_index.zig b/src/control_center/search_index.zig
index 464a8ee..d400276 100644
--- a/src/control_center/search_index.zig
+++ b/src/control_center/search_index.zig
@@ -82,6 +82,7 @@ const source_entries = [_]SourceEntry{
.{ .page = .appearance, .title = i18n.msg("Inactive window opacity"), .target = "inactive_opacity", .keywords = i18n.msg("transparency unfocused") },
.{ .page = .appearance, .title = i18n.msg("Terminal opacity"), .target = "terminal_opacity", .keywords = i18n.msg("transparency") },
.{ .page = .appearance, .title = i18n.msg("Taskbar position"), .target = "taskbar_position", .keywords = i18n.msg("panel top bottom") },
+ .{ .page = .appearance, .title = i18n.msg("Taskbar alignment"), .target = "taskbar_alignment", .keywords = i18n.msg("panel left center right") },
.{ .page = .appearance, .title = i18n.msg("Taskbar edge gap"), .target = "taskbar_edge_gap", .keywords = i18n.msg("panel margin") },
.{ .page = .appearance, .title = i18n.msg("Taskbar length"), .target = "taskbar_length", .keywords = i18n.msg("panel width") },
.{ .page = .appearance, .title = i18n.msg("Taskbar corner radius"), .target = "taskbar_radius", .keywords = i18n.msg("panel rounded") },
diff --git a/src/control_center/sections/appearance.zig b/src/control_center/sections/appearance.zig
index b8f0d1f..3860be4 100644
--- a/src/control_center/sections/appearance.zig
+++ b/src/control_center/sections/appearance.zig
@@ -98,6 +98,7 @@ pub const onTerminalOpacityChanged = appearance_chrome.onTerminalOpacityChanged;
pub const max_window_gap = appearance_chrome.max_window_gap;
pub const onWindowGapChanged = appearance_chrome.onWindowGapChanged;
pub const onTaskbarPositionChanged = appearance_chrome.onTaskbarPositionChanged;
+pub const onTaskbarAlignmentChanged = appearance_chrome.onTaskbarAlignmentChanged;
pub const onFocusZoomChanged = appearance_chrome.onFocusZoomChanged;
pub const onDragFeedbackChanged = appearance_chrome.onDragFeedbackChanged;
pub const onDragScaleChanged = appearance_chrome.onDragScaleChanged;
@@ -291,8 +292,9 @@ pub const Section = struct {
terminal_opacity_group_children: [2]Widget = undefined,
terminal_opacity_value_buf: [16]u8 = undefined,
px: [22]PxControl = undefined,
- taskbar_section_children: [13]Widget = undefined,
+ taskbar_section_children: [14]Widget = undefined,
taskbar_position_children: [2]Widget = undefined,
+ taskbar_alignment_children: [2]Widget = undefined,
clock_bold_children: [2]Widget = undefined,
clock_italic_children: [2]Widget = undefined,
items_children: [6]Widget = undefined,
diff --git a/src/control_center/sections/appearance_chrome.zig b/src/control_center/sections/appearance_chrome.zig
index 32ba8f2..3647eaa 100644
--- a/src/control_center/sections/appearance_chrome.zig
+++ b/src/control_center/sections/appearance_chrome.zig
@@ -183,6 +183,22 @@ pub fn onTaskbarPositionChanged(owner: ?*anyopaque, _: usize, index: usize) void
server.applyTaskbarPosition();
}
+pub fn onTaskbarAlignmentChanged(owner: ?*anyopaque, _: usize, index: usize) void {
+ if (index > 2) return;
+ const s = section(owner);
+ const server = s.cc.server;
+ const alignment: @TypeOf(server.config.compositor.taskbar_alignment) = @enumFromInt(index);
+ if (alignment == server.config.compositor.taskbar_alignment) return;
+ setting_save.saveCompositor(main.gpa, server.io, server.config.path, "taskbar_alignment", alignment) catch |err| {
+ std.log.warn("could not save taskbar alignment: {}", .{err});
+ s.taskbar_alignment_children[1].kind.segmented.selected = @intFromEnum(server.config.compositor.taskbar_alignment);
+ s.taskbar_alignment_children[1].markDirty();
+ return;
+ };
+ server.config.compositor.taskbar_alignment = alignment;
+ server.refreshTaskbarsGeometry();
+}
+
pub fn onFocusZoomChanged(owner: ?*anyopaque, _: usize, index: usize) void {
if (index >= focus_zoom_labels.len) return;
const s = section(owner);
diff --git a/src/control_center/sections/appearance_sections.zig b/src/control_center/sections/appearance_sections.zig
index 5108dc8..e1d9666 100644
--- a/src/control_center/sections/appearance_sections.zig
+++ b/src/control_center/sections/appearance_sections.zig
@@ -87,6 +87,11 @@ pub fn buildTaskbarSection(out: *Section, t: theme.Theme, pal: theme.Theme) Widg
.{ .name = "taskbar_position", .kind = .{ .segmented = .{ .labels = panel.translatedLabels(&.{ i18n.msg("Top"), i18n.msg("Bottom") }), .selected = @intFromEnum(out.cc.server.config.compositor.taskbar_position), .owner = out, .on_change = &onTaskbarPositionChanged } }, .width = .{ .fixed = segmented_width } },
};
const position_row: Widget = .{ .kind = .container, .direction = .row, .justify = .space_between, .@"align" = .center, .children = &out.taskbar_position_children };
+ out.taskbar_alignment_children = .{
+ labelWidget(i18n.tr("Taskbar alignment")),
+ .{ .name = "taskbar_alignment", .kind = .{ .segmented = .{ .labels = panel.translatedLabels(&.{ i18n.msg("Left"), i18n.msg("Center"), i18n.msg("Right") }), .selected = @intFromEnum(out.cc.server.config.compositor.taskbar_alignment), .owner = out, .on_change = &appearance_chrome.onTaskbarAlignmentChanged } }, .width = .{ .fixed = segmented_width } },
+ };
+ const alignment_row: Widget = .{ .kind = .container, .direction = .row, .justify = .space_between, .@"align" = .center, .children = &out.taskbar_alignment_children };
const taskbar_min: f32 = @floatFromInt(Taskbar.min_bar_height);
const taskbar_row = pxGroup(out, px_taskbar_size, i18n.tr("Taskbar size"), std.math.clamp(t.taskbar_size, taskbar_min, 84.0), taskbar_min, 84, 2, &PxHandler(px_taskbar_size, "taskbar_size", true).changed);
// A floating bar: its gap from the edge, its length and its corners. At
@@ -149,7 +154,7 @@ pub fn buildTaskbarSection(out: *Section, t: theme.Theme, pal: theme.Theme) Widg
i18n.tr("Warning: Screen capture is hidden. Recording and screen sharing can continue without a visible indicator or Stop sharing button. Hiding it is not recommended."), .font_size = theme.global.settings_description_size, .color = pal.dim } } },
};
const items_group: Widget = .{ .kind = .container, .direction = .column, .gap = 8, .@"align" = .stretch, .children = &out.items_children };
- out.taskbar_section_children = .{ panel.sectionTitle(i18n.tr("Taskbar")), position_row, taskbar_row, edge_gap_row, length_row, radius_row, chip_width_row, chip_gap_row, start_gap_row, start_icon_row, clock_bold_row, clock_italic_row, items_group };
+ out.taskbar_section_children = .{ panel.sectionTitle(i18n.tr("Taskbar")), position_row, alignment_row, taskbar_row, edge_gap_row, length_row, radius_row, chip_width_row, chip_gap_row, start_gap_row, start_icon_row, clock_bold_row, clock_italic_row, items_group };
const taskbar_section: Widget = .{ .kind = .container, .direction = .column, .gap = 12, .children = &out.taskbar_section_children };
return taskbar_section;
}
diff --git a/src/editor/app_controls.zig b/src/editor/app_controls.zig
index 2557fbc..996ce7d 100644
--- a/src/editor/app_controls.zig
+++ b/src/editor/app_controls.zig
@@ -49,7 +49,7 @@ pub fn paintIcon(self: *App, cr: *c.cairo_t, box: Rect, icon: @import("ui").layo
var layer = ui.Layer.begin(cr, .{ .x = @floatCast(box.x), .y = @floatCast(box.y), .w = @floatCast(box.w), .h = @floatCast(box.h) }) orelse return;
defer layer.finish();
layer.renderer.palette = theme.shellPalette();
- button.paint(&layer.renderer, layer.local(), .{ .label = label, .icon = icon, .icon_scale = 1, .variant = .ghost, .size = .sm }, .{
+ button.paint(&layer.renderer, layer.local(), .{ .label = label, .icon = icon, .variant = .ghost, .size = .sm }, .{
.selected = selected,
.pointer = if (!self.menu_open and self.close_tab == null and box.contains(self.px, self.py)) .hover else .idle,
});
diff --git a/src/notifications_tests.zig b/src/notifications_tests.zig
index c95db7d..a8f0521 100644
--- a/src/notifications_tests.zig
+++ b/src/notifications_tests.zig
@@ -181,4 +181,37 @@ test "notifications unit: replaces_id, urgency, DND, lock suppression" {
);
try std.testing.expectEqual(@as(u32, 4), id4);
try std.testing.expect(mgr.findToast(id4) != null);
+ try batteryWarnings(&server, mgr);
+}
+
+fn batteryWarnings(server: *Server, mgr: *notif.Manager) !void {
+ server.greeter_mode = false;
+ server.notifications = mgr;
+ server.battery_warning = .{};
+ server.battery_warning_id = null;
+ const initial = mgr.history.items.len;
+ server.updateBatteryWarning(.{ .percent = 11, .discharging = true });
+ try std.testing.expectEqual(initial, mgr.history.items.len);
+ server.updateBatteryWarning(.{ .percent = 10, .discharging = true });
+ const id = server.battery_warning_id.?;
+ const toast = mgr.findToast(id).?;
+ try std.testing.expectEqualStrings("Low battery", toast.summary);
+ try std.testing.expectEqualStrings("Battery is at 10%. Plug in your charger.", toast.body);
+ try std.testing.expectEqual(@as(u8, 2), toast.urgency);
+ try std.testing.expect(toast.expire_at_ms == null); // Visible even in DND.
+ server.updateBatteryWarning(.{ .percent = 9, .discharging = true });
+ try std.testing.expectEqual(initial + 1, mgr.history.items.len);
+ mgr.closeNotification(id, 2); // Dismissing does not rearm the warning.
+ server.updateBatteryWarning(.{ .percent = 8, .discharging = true });
+ try std.testing.expectEqual(initial + 1, mgr.history.items.len);
+ server.updateBatteryWarning(.{ .percent = 8, .charging = true, .plugged = true });
+ try std.testing.expect(server.battery_warning_id == null);
+ server.updateBatteryWarning(.{ .percent = 7, .discharging = true });
+ try std.testing.expectEqual(initial + 2, mgr.history.items.len);
+ const second = mgr.findToast(server.battery_warning_id.?).?;
+ server.updateBatteryWarning(.{ .percent = 12, .discharging = true });
+ try std.testing.expect(second.closing);
+ server.greeter_mode = true;
+ server.updateBatteryWarning(.{ .percent = 1, .discharging = true });
+ try std.testing.expectEqual(initial + 2, mgr.history.items.len);
}
diff --git a/src/server/session.zig b/src/server/session.zig
index b282fa6..6621da5 100644
--- a/src/server/session.zig
+++ b/src/server/session.zig
@@ -124,6 +124,12 @@ pub fn startDesktopService(server: *Server, step: usize) bool {
log.warn("init: could not create notifications manager: {}", .{err});
break :blk null;
};
+ // Outputs already took their initial battery snapshots before the
+ // notification service started. Warn immediately when logging in low.
+ var outputs = server.outputs.iterator(.forward);
+ while (outputs.next()) |output| {
+ if (output.taskbar) |bar| server.updateBatteryWarning(bar.battery_state);
+ }
},
1 => {
server.configurePolkit(server.config.polkit);
diff --git a/src/server/wakeups.zig b/src/server/wakeups.zig
index 129f489..ae98375 100644
--- a/src/server/wakeups.zig
+++ b/src/server/wakeups.zig
@@ -1,6 +1,7 @@
//! Server wake handlers: audio, battery and the GPU timer.
const std = @import("std");
+const i18n = @import("i18n");
const Server = @import("../Server.zig");
const wl = @import("wayland").server.wl;
const battery_mod = @import("../taskbar/battery.zig");
@@ -42,6 +43,7 @@ pub fn handleBatteryUevent(fd: c_int, mask: wl.EventMask, server: *Server) c_int
_ = mask;
if (!battery_mod.drainUevents(fd)) return 0;
const state = battery_mod.read(server.io, @import("../main.zig").gpa);
+ server.updateBatteryWarning(state);
var it = server.outputs.iterator(.forward);
while (it.next()) |output| {
if (output.taskbar) |bar| bar.applyBattery(state);
@@ -49,6 +51,41 @@ pub fn handleBatteryUevent(fd: c_int, mask: wl.EventMask, server: *Server) c_int
return 0;
}
+/// Uses the same snapshots as the badge, without another timer or sysfs read.
+pub fn updateBatteryWarning(server: *Server, state: battery_mod.State) void {
+ if (server.greeter_mode) return;
+ const manager = server.notifications orelse return;
+ switch (server.battery_warning.update(state)) {
+ .none => {},
+ .clear => {
+ if (server.battery_warning_id) |id| manager.closeNotification(id, 3);
+ server.battery_warning_id = null;
+ },
+ .show => {
+ var buf: [256]u8 = undefined;
+ const body = i18n.fmt(&buf, i18n.tr("Battery is at {percent}%. Plug in your charger."), .{ .percent = state.percent.? }) catch i18n.tr("Plug in your charger.");
+ server.battery_warning_id = manager.postNotification(
+ "RediWM",
+ 0,
+ "battery-caution",
+ i18n.tr("Low battery"),
+ body,
+ &.{},
+ 2,
+ false,
+ false,
+ 0,
+ "",
+ null,
+ ) catch blk: {
+ // Retry on the next normal update if posting failed.
+ server.battery_warning.notified = false;
+ break :blk null;
+ };
+ },
+ }
+}
+
pub fn ensureGpuTimer(server: *Server) void {
server.gpu_timer_used_ns = @import("../ipc/stats.zig").nowNs();
if (server.gpu_timer_tried) return;
diff --git a/src/taskbar/battery.zig b/src/taskbar/battery.zig
index c5fbfe9..b08cc8e 100644
--- a/src/taskbar/battery.zig
+++ b/src/taskbar/battery.zig
@@ -4,8 +4,8 @@
//! adapter's `_PSR`, measured at 1-1.5 ms of kernel CPU charged to the
//! compositor.
//! Kernel power_supply uevents (plug, unplug, charge state) trigger an
-//! immediate read; capacity is re-read on the taskbar's minute tick, because
-//! many firmwares never announce percentage changes.
+//! immediate read; capacity and time estimates are re-read on the taskbar's
+//! minute tick, because many firmwares never announce percentage changes.
const i18n = @import("i18n");
const std = @import("std");
const linux = std.os.linux;
@@ -14,10 +14,22 @@ pub const State = struct {
percent: ?u8 = null,
plugged: bool = false,
charging: bool = false,
+ discharging: bool = false,
full: bool = false,
health: ?u8 = null,
full_wh: ?f64 = null,
cycles: ?u32 = null,
+ remaining_minutes: ?u32 = null,
+
+ pub fn estimate(self: State, buf: []u8) ?[]const u8 {
+ const minutes = self.remaining_minutes orelse return null;
+ var duration_buf: [96]u8 = undefined;
+ const duration = if (minutes < 60)
+ i18n.fmt(&duration_buf, i18n.tr("{minutes}min"), .{ .minutes = minutes }) catch return null
+ else
+ i18n.fmt(&duration_buf, i18n.tr("{hours}h {minutes}min"), .{ .hours = minutes / 60, .minutes = minutes % 60 }) catch return null;
+ return i18n.fmt(buf, i18n.tr("~{time} left"), .{ .time = duration }) catch null;
+ }
pub fn status(self: State) []const u8 {
if (self.charging) return i18n.tr("Charging");
@@ -27,6 +39,25 @@ pub const State = struct {
}
};
+/// One warning per low-battery episode, shared by every output. Missing
+/// snapshots do not rearm it; only a real recovery or end of discharge does.
+pub const Warning = struct {
+ notified: bool = false,
+
+ pub const Action = enum { none, show, clear };
+
+ pub fn update(self: *Warning, state: State) Action {
+ const percent = state.percent orelse return .none;
+ if (percent > 10 or !state.discharging or state.charging or state.full) {
+ self.notified = false;
+ return .clear;
+ }
+ if (self.notified) return .none;
+ self.notified = true;
+ return .show;
+ }
+};
+
fn field(contents: []const u8, key: []const u8) ?[]const u8 {
var lines = std.mem.tokenizeScalar(u8, contents, '\n');
while (lines.next()) |line| {
@@ -36,19 +67,21 @@ fn field(contents: []const u8, key: []const u8) ?[]const u8 {
return null;
}
-const Snapshot = struct {
+pub const Snapshot = struct {
sum: u32 = 0,
count: u32 = 0,
online: bool = false,
charging: bool = false,
+ discharging: bool = false,
full_count: u32 = 0,
health_sum: u32 = 0,
health_count: u32 = 0,
energy_sum: f64 = 0,
energy_count: u32 = 0,
cycles: ?u32 = null,
+ remaining_minutes: ?u32 = null,
- fn add(self: *Snapshot, contents: []const u8) void {
+ pub fn add(self: *Snapshot, contents: []const u8) void {
const kind = field(contents, "POWER_SUPPLY_TYPE") orelse return;
// Ignore peripheral batteries (mice, keyboards, etc.).
if (std.mem.eql(u8, field(contents, "POWER_SUPPLY_SCOPE") orelse "", "Device")) return;
@@ -64,7 +97,9 @@ const Snapshot = struct {
const percent = @min(raw, 100);
self.sum += percent;
self.count += 1;
+ self.remaining_minutes = estimateMinutes(contents);
if (std.mem.eql(u8, field(contents, "POWER_SUPPLY_STATUS") orelse "", "Charging")) self.charging = true;
+ if (std.mem.eql(u8, field(contents, "POWER_SUPPLY_STATUS") orelse "", "Discharging")) self.discharging = true;
if (std.mem.eql(u8, field(contents, "POWER_SUPPLY_STATUS") orelse "", "Full")) self.full_count += 1;
const energy = number(contents, "POWER_SUPPLY_ENERGY_FULL");
const charge = number(contents, "POWER_SUPPLY_CHARGE_FULL");
@@ -88,17 +123,20 @@ const Snapshot = struct {
self.cycles = std.fmt.parseInt(u32, field(contents, "POWER_SUPPLY_CYCLE_COUNT") orelse "", 10) catch null;
}
- fn state(self: Snapshot) State {
+ pub fn state(self: Snapshot) State {
return .{
// Equal-pack average when more than one system battery is present.
.percent = if (self.count == 0) null else @intCast((self.sum + self.count / 2) / self.count),
.plugged = self.online or self.charging,
.charging = self.charging,
+ .discharging = self.discharging and !self.charging,
.full = self.count > 0 and self.full_count == self.count,
.health = if (self.count > 0 and self.health_count == self.count) @intCast((self.health_sum + self.count / 2) / self.count) else null,
.full_wh = if (self.count > 0 and self.energy_count == self.count) self.energy_sum else null,
// Cycle counts belong to a pack; summing them is misleading.
.cycles = if (self.count == 1) self.cycles else null,
+ // A pack's time is not a system estimate with multiple batteries.
+ .remaining_minutes = if (self.count == 1) self.remaining_minutes else null,
};
}
};
@@ -108,6 +146,42 @@ fn number(contents: []const u8, key: []const u8) ?f64 {
return @floatFromInt(value);
}
+// Driver times are seconds; capacity/rate pairs are micro-Wh/micro-W or
+// micro-Ah/micro-A. Keep pairs in the same units, with no voltage guesswork.
+fn estimateMinutes(contents: []const u8) ?u32 {
+ const status = field(contents, "POWER_SUPPLY_STATUS") orelse return null;
+ const charging = std.mem.eql(u8, status, "Charging");
+ if (!charging and !std.mem.eql(u8, status, "Discharging")) return null;
+ const time_keys = if (charging)
+ [_][]const u8{ "POWER_SUPPLY_TIME_TO_FULL_NOW", "POWER_SUPPLY_TIME_TO_FULL_AVG" }
+ else
+ [_][]const u8{ "POWER_SUPPLY_TIME_TO_EMPTY_NOW", "POWER_SUPPLY_TIME_TO_EMPTY_AVG" };
+ for (time_keys) |key| {
+ if (number(contents, key)) |seconds| {
+ if (minutesFromHours(seconds / 3600)) |minutes| return minutes;
+ }
+ }
+ const pairs = [_][3][]const u8{
+ .{ "POWER_SUPPLY_ENERGY_NOW", "POWER_SUPPLY_ENERGY_FULL", "POWER_SUPPLY_POWER_NOW" },
+ .{ "POWER_SUPPLY_CHARGE_NOW", "POWER_SUPPLY_CHARGE_FULL", "POWER_SUPPLY_CURRENT_NOW" },
+ };
+ for (pairs) |keys| {
+ const now = number(contents, keys[0]) orelse continue;
+ const rate = number(contents, keys[2]) orelse continue;
+ if (rate <= 0) continue;
+ const remaining = if (charging) (number(contents, keys[1]) orelse continue) - now else now;
+ if (minutesFromHours(remaining / rate)) |minutes| return minutes;
+ }
+ return null;
+}
+
+fn minutesFromHours(hours: f64) ?u32 {
+ // Reject missing/invalid rates and avoid overflowing on broken firmware.
+ const minutes = @ceil(hours * 60);
+ if (!std.math.isFinite(minutes) or minutes <= 0 or minutes > std.math.maxInt(u32)) return null;
+ return @intFromFloat(minutes);
+}
+
pub fn read(io: std.Io, allocator: std.mem.Allocator) State {
var dir = std.Io.Dir.cwd().openDir(io, "/sys/class/power_supply", .{ .iterate = true }) catch return .{};
defer dir.close(io);
@@ -167,7 +241,7 @@ pub fn drainUevents(fd: std.posix.fd_t) bool {
/// Kernel uevents are `action@devpath` then NUL-separated KEY=VALUE pairs.
/// Peripheral batteries are ignored by `read`, so their events are too.
-fn isSystemPowerSupplyUevent(msg: []const u8) bool {
+pub fn isSystemPowerSupplyUevent(msg: []const u8) bool {
var fields = std.mem.splitScalar(u8, msg, 0);
if (std.mem.indexOfScalar(u8, fields.first(), '@') == null) return false;
var power_supply = false;
@@ -178,85 +252,6 @@ fn isSystemPowerSupplyUevent(msg: []const u8) bool {
return power_supply;
}
-test "battery percentage and external power are independent" {
- var s: Snapshot = .{};
- s.add("POWER_SUPPLY_TYPE=Battery\nPOWER_SUPPLY_CAPACITY=82\nPOWER_SUPPLY_STATUS=Discharging\n");
- try std.testing.expectEqual(State{ .percent = 82 }, s.state());
- s.add("POWER_SUPPLY_TYPE=Mains\nPOWER_SUPPLY_ONLINE=1\n");
- try std.testing.expectEqual(State{ .percent = 82, .plugged = true }, s.state());
- s = .{};
- s.add("POWER_SUPPLY_TYPE=Battery\nPOWER_SUPPLY_CAPACITY=100\nPOWER_SUPPLY_STATUS=Full\n");
- s.add("POWER_SUPPLY_TYPE=USB\nPOWER_SUPPLY_ONLINE=1\n");
- try std.testing.expectEqual(State{ .percent = 100, .plugged = true, .full = true }, s.state());
-}
-
-test "only system power_supply uevents trigger a read" {
- try std.testing.expect(isSystemPowerSupplyUevent("change@/devices/platform/ACPI0003:00/power_supply/AC0\x00ACTION=change\x00SUBSYSTEM=power_supply\x00POWER_SUPPLY_NAME=AC0\x00POWER_SUPPLY_ONLINE=1\x00"));
- try std.testing.expect(isSystemPowerSupplyUevent("remove@/devices/x/power_supply/BAT1\x00ACTION=remove\x00SUBSYSTEM=power_supply"));
- try std.testing.expect(!isSystemPowerSupplyUevent("change@/devices/x/power_supply/hid-mouse\x00SUBSYSTEM=power_supply\x00POWER_SUPPLY_SCOPE=Device\x00"));
- try std.testing.expect(!isSystemPowerSupplyUevent("add@/devices/pci0000:00/usb1/1-1\x00ACTION=add\x00SUBSYSTEM=usb\x00"));
- try std.testing.expect(!isSystemPowerSupplyUevent("libudev\x00SUBSYSTEM=power_supply\x00"));
-}
-
-test "draining reports a queued power_supply event once and stops at EAGAIN" {
- var fds: [2]i32 = undefined;
- try std.testing.expectEqual(linux.E.SUCCESS, linux.errno(linux.socketpair(linux.AF.UNIX, linux.SOCK.DGRAM | linux.SOCK.NONBLOCK | linux.SOCK.CLOEXEC, 0, &fds)));
- defer for (fds) |fd| {
- _ = std.posix.system.close(fd);
- };
- const usb = "add@/devices/usb1\x00SUBSYSTEM=usb\x00";
- const ac = "change@/devices/AC0/power_supply/AC0\x00SUBSYSTEM=power_supply\x00";
- try std.testing.expect(!drainUevents(fds[0]));
- _ = linux.sendto(fds[1], usb, usb.len, 0, null, 0);
- try std.testing.expect(!drainUevents(fds[0]));
- _ = linux.sendto(fds[1], ac, ac.len, 0, null, 0);
- _ = linux.sendto(fds[1], usb, usb.len, 0, null, 0);
- try std.testing.expect(drainUevents(fds[0]));
- try std.testing.expect(!drainUevents(fds[0]));
-}
-
-test "over-full capacity from a worn pack clamps to 100 instead of hiding" {
- var s: Snapshot = .{};
- s.add("POWER_SUPPLY_TYPE=Battery\nPOWER_SUPPLY_CAPACITY=101\nPOWER_SUPPLY_STATUS=Discharging\n");
- try std.testing.expectEqual(State{ .percent = 100 }, s.state());
- s = .{};
- s.add("POWER_SUPPLY_TYPE=Battery\nPOWER_SUPPLY_CAPACITY=300\n");
- try std.testing.expectEqual(@as(?u8, 100), s.state().percent);
-}
-
-test "absent peripheral and invalid batteries are hidden; charging works without AC entry" {
- var s: Snapshot = .{};
- s.add("POWER_SUPPLY_TYPE=Battery\nPOWER_SUPPLY_CAPACITY=90\nPOWER_SUPPLY_SCOPE=Device\n");
- s.add("POWER_SUPPLY_TYPE=Battery\nPOWER_SUPPLY_CAPACITY=90\nPOWER_SUPPLY_PRESENT=0\n");
- s.add("POWER_SUPPLY_TYPE=Battery\nPOWER_SUPPLY_CAPACITY=-1\n");
- try std.testing.expectEqual(@as(?u8, null), s.state().percent);
- s.add("POWER_SUPPLY_TYPE=Battery\nPOWER_SUPPLY_CAPACITY=0\nPOWER_SUPPLY_STATUS=Charging\n");
- try std.testing.expectEqual(State{ .percent = 0, .plugged = true, .charging = true }, s.state());
-}
-
-test "battery details use full versus design capacity and preserve missing readings" {
- var s: Snapshot = .{};
- s.add("POWER_SUPPLY_TYPE=Battery\nPOWER_SUPPLY_CAPACITY=100\nPOWER_SUPPLY_STATUS=Full\nPOWER_SUPPLY_ENERGY_FULL=57000000\nPOWER_SUPPLY_ENERGY_FULL_DESIGN=90000000\nPOWER_SUPPLY_CYCLE_COUNT=482\n");
- try std.testing.expectEqual(@as(?u8, 63), s.state().health);
- try std.testing.expectEqual(@as(?f64, 57), s.state().full_wh);
- try std.testing.expectEqual(@as(?u32, 482), s.state().cycles);
- try std.testing.expectEqualStrings("Fully Charged", s.state().status());
- s.add("POWER_SUPPLY_TYPE=Battery\nPOWER_SUPPLY_CAPACITY=80\n");
- try std.testing.expectEqual(@as(?u8, null), s.state().health);
- try std.testing.expectEqual(@as(?f64, null), s.state().full_wh);
- try std.testing.expectEqual(@as(?u32, null), s.state().cycles);
- try std.testing.expect(!s.state().full);
-}
-
-test "charge-only battery uses nominal voltage; invalid details stay unavailable" {
- var s: Snapshot = .{};
- s.add("POWER_SUPPLY_TYPE=Battery\nPOWER_SUPPLY_CAPACITY=50\nPOWER_SUPPLY_CHARGE_FULL=4000000\nPOWER_SUPPLY_CHARGE_FULL_DESIGN=5000000\nPOWER_SUPPLY_VOLTAGE_MIN_DESIGN=12000000\nPOWER_SUPPLY_CYCLE_COUNT=0\n");
- try std.testing.expectEqual(@as(?u8, 80), s.state().health);
- try std.testing.expectEqual(@as(?f64, 48), s.state().full_wh);
- try std.testing.expectEqual(@as(?u32, 0), s.state().cycles);
- s = .{};
- s.add("POWER_SUPPLY_TYPE=Battery\nPOWER_SUPPLY_CAPACITY=20\nPOWER_SUPPLY_ENERGY_FULL=-1\nPOWER_SUPPLY_ENERGY_FULL_DESIGN=0\nPOWER_SUPPLY_CYCLE_COUNT=-1\n");
- try std.testing.expectEqual(@as(?u8, null), s.state().health);
- try std.testing.expectEqual(@as(?f64, null), s.state().full_wh);
- try std.testing.expectEqual(@as(?u32, null), s.state().cycles);
+test {
+ _ = @import("battery_tests.zig");
}
diff --git a/src/taskbar/battery_tests.zig b/src/taskbar/battery_tests.zig
new file mode 100644
index 0000000..03eb25c
--- /dev/null
+++ b/src/taskbar/battery_tests.zig
@@ -0,0 +1,148 @@
+const std = @import("std");
+const linux = std.os.linux;
+const battery = @import("battery.zig");
+const State = battery.State;
+const Snapshot = battery.Snapshot;
+const isSystemPowerSupplyUevent = battery.isSystemPowerSupplyUevent;
+const drainUevents = battery.drainUevents;
+
+test "battery percentage and external power are independent" {
+ var s: Snapshot = .{};
+ s.add("POWER_SUPPLY_TYPE=Battery\nPOWER_SUPPLY_CAPACITY=82\nPOWER_SUPPLY_STATUS=Discharging\n");
+ try std.testing.expectEqual(State{ .percent = 82, .discharging = true }, s.state());
+ s.add("POWER_SUPPLY_TYPE=Mains\nPOWER_SUPPLY_ONLINE=1\n");
+ try std.testing.expectEqual(State{ .percent = 82, .plugged = true, .discharging = true }, s.state());
+ s = .{};
+ s.add("POWER_SUPPLY_TYPE=Battery\nPOWER_SUPPLY_CAPACITY=100\nPOWER_SUPPLY_STATUS=Full\n");
+ s.add("POWER_SUPPLY_TYPE=USB\nPOWER_SUPPLY_ONLINE=1\n");
+ try std.testing.expectEqual(State{ .percent = 100, .plugged = true, .full = true }, s.state());
+}
+
+test "only system power_supply uevents trigger a read" {
+ try std.testing.expect(isSystemPowerSupplyUevent("change@/devices/platform/ACPI0003:00/power_supply/AC0\x00ACTION=change\x00SUBSYSTEM=power_supply\x00POWER_SUPPLY_NAME=AC0\x00POWER_SUPPLY_ONLINE=1\x00"));
+ try std.testing.expect(isSystemPowerSupplyUevent("remove@/devices/x/power_supply/BAT1\x00ACTION=remove\x00SUBSYSTEM=power_supply"));
+ try std.testing.expect(!isSystemPowerSupplyUevent("change@/devices/x/power_supply/hid-mouse\x00SUBSYSTEM=power_supply\x00POWER_SUPPLY_SCOPE=Device\x00"));
+ try std.testing.expect(!isSystemPowerSupplyUevent("add@/devices/pci0000:00/usb1/1-1\x00ACTION=add\x00SUBSYSTEM=usb\x00"));
+ try std.testing.expect(!isSystemPowerSupplyUevent("libudev\x00SUBSYSTEM=power_supply\x00"));
+}
+
+test "draining reports a queued power_supply event once and stops at EAGAIN" {
+ var fds: [2]i32 = undefined;
+ try std.testing.expectEqual(linux.E.SUCCESS, linux.errno(linux.socketpair(linux.AF.UNIX, linux.SOCK.DGRAM | linux.SOCK.NONBLOCK | linux.SOCK.CLOEXEC, 0, &fds)));
+ defer for (fds) |fd| {
+ _ = std.posix.system.close(fd);
+ };
+ const usb = "add@/devices/usb1\x00SUBSYSTEM=usb\x00";
+ const ac = "change@/devices/AC0/power_supply/AC0\x00SUBSYSTEM=power_supply\x00";
+ try std.testing.expect(!drainUevents(fds[0]));
+ _ = linux.sendto(fds[1], usb, usb.len, 0, null, 0);
+ try std.testing.expect(!drainUevents(fds[0]));
+ _ = linux.sendto(fds[1], ac, ac.len, 0, null, 0);
+ _ = linux.sendto(fds[1], usb, usb.len, 0, null, 0);
+ try std.testing.expect(drainUevents(fds[0]));
+ try std.testing.expect(!drainUevents(fds[0]));
+}
+
+test "over-full capacity from a worn pack clamps to 100 instead of hiding" {
+ var s: Snapshot = .{};
+ s.add("POWER_SUPPLY_TYPE=Battery\nPOWER_SUPPLY_CAPACITY=101\nPOWER_SUPPLY_STATUS=Discharging\n");
+ try std.testing.expectEqual(State{ .percent = 100, .discharging = true }, s.state());
+ s = .{};
+ s.add("POWER_SUPPLY_TYPE=Battery\nPOWER_SUPPLY_CAPACITY=300\n");
+ try std.testing.expectEqual(@as(?u8, 100), s.state().percent);
+}
+
+test "absent peripheral and invalid batteries are hidden; charging works without AC entry" {
+ var s: Snapshot = .{};
+ s.add("POWER_SUPPLY_TYPE=Battery\nPOWER_SUPPLY_CAPACITY=90\nPOWER_SUPPLY_SCOPE=Device\n");
+ s.add("POWER_SUPPLY_TYPE=Battery\nPOWER_SUPPLY_CAPACITY=90\nPOWER_SUPPLY_PRESENT=0\n");
+ s.add("POWER_SUPPLY_TYPE=Battery\nPOWER_SUPPLY_CAPACITY=-1\n");
+ try std.testing.expectEqual(@as(?u8, null), s.state().percent);
+ s.add("POWER_SUPPLY_TYPE=Battery\nPOWER_SUPPLY_CAPACITY=0\nPOWER_SUPPLY_STATUS=Charging\n");
+ try std.testing.expectEqual(State{ .percent = 0, .plugged = true, .charging = true }, s.state());
+}
+
+test "battery details use full versus design capacity and preserve missing readings" {
+ var s: Snapshot = .{};
+ s.add("POWER_SUPPLY_TYPE=Battery\nPOWER_SUPPLY_CAPACITY=100\nPOWER_SUPPLY_STATUS=Full\nPOWER_SUPPLY_ENERGY_FULL=57000000\nPOWER_SUPPLY_ENERGY_FULL_DESIGN=90000000\nPOWER_SUPPLY_CYCLE_COUNT=482\n");
+ try std.testing.expectEqual(@as(?u8, 63), s.state().health);
+ try std.testing.expectEqual(@as(?f64, 57), s.state().full_wh);
+ try std.testing.expectEqual(@as(?u32, 482), s.state().cycles);
+ try std.testing.expectEqualStrings("Fully Charged", s.state().status());
+ s.add("POWER_SUPPLY_TYPE=Battery\nPOWER_SUPPLY_CAPACITY=80\n");
+ try std.testing.expectEqual(@as(?u8, null), s.state().health);
+ try std.testing.expectEqual(@as(?f64, null), s.state().full_wh);
+ try std.testing.expectEqual(@as(?u32, null), s.state().cycles);
+ try std.testing.expect(!s.state().full);
+}
+
+test "charge-only battery uses nominal voltage; invalid details stay unavailable" {
+ var s: Snapshot = .{};
+ s.add("POWER_SUPPLY_TYPE=Battery\nPOWER_SUPPLY_CAPACITY=50\nPOWER_SUPPLY_CHARGE_FULL=4000000\nPOWER_SUPPLY_CHARGE_FULL_DESIGN=5000000\nPOWER_SUPPLY_VOLTAGE_MIN_DESIGN=12000000\nPOWER_SUPPLY_CYCLE_COUNT=0\n");
+ try std.testing.expectEqual(@as(?u8, 80), s.state().health);
+ try std.testing.expectEqual(@as(?f64, 48), s.state().full_wh);
+ try std.testing.expectEqual(@as(?u32, 0), s.state().cycles);
+ s = .{};
+ s.add("POWER_SUPPLY_TYPE=Battery\nPOWER_SUPPLY_CAPACITY=20\nPOWER_SUPPLY_ENERGY_FULL=-1\nPOWER_SUPPLY_ENERGY_FULL_DESIGN=0\nPOWER_SUPPLY_CYCLE_COUNT=-1\n");
+ try std.testing.expectEqual(@as(?u8, null), s.state().health);
+ try std.testing.expectEqual(@as(?f64, null), s.state().full_wh);
+ try std.testing.expectEqual(@as(?u32, null), s.state().cycles);
+}
+
+test "time estimates use driver seconds then matching energy or charge rates" {
+ const cases = .{
+ .{ "Charging", "POWER_SUPPLY_TIME_TO_FULL_NOW=5100\n", @as(?u32, 85) },
+ .{ "Discharging", "POWER_SUPPLY_TIME_TO_EMPTY_NOW=0\nPOWER_SUPPLY_TIME_TO_EMPTY_AVG=3600\n", @as(?u32, 60) },
+ .{ "Charging", "POWER_SUPPLY_ENERGY_NOW=40000000\nPOWER_SUPPLY_ENERGY_FULL=57000000\nPOWER_SUPPLY_POWER_NOW=12000000\n", @as(?u32, 85) },
+ .{ "Discharging", "POWER_SUPPLY_ENERGY_NOW=40000000\nPOWER_SUPPLY_POWER_NOW=12000000\n", @as(?u32, 200) },
+ .{ "Charging", "POWER_SUPPLY_CHARGE_NOW=3000000\nPOWER_SUPPLY_CHARGE_FULL=4000000\nPOWER_SUPPLY_CURRENT_NOW=2000000\n", @as(?u32, 30) },
+ .{ "Discharging", "POWER_SUPPLY_CHARGE_NOW=3000000\nPOWER_SUPPLY_CURRENT_NOW=2000000\n", @as(?u32, 90) },
+ .{ "Discharging", "POWER_SUPPLY_TIME_TO_EMPTY_NOW=1\n", @as(?u32, 1) },
+ .{ "Discharging", "POWER_SUPPLY_ENERGY_NOW=3000000\nPOWER_SUPPLY_POWER_NOW=0\n", @as(?u32, null) },
+ .{ "Discharging", "POWER_SUPPLY_ENERGY_NOW=3000000\nPOWER_SUPPLY_CURRENT_NOW=2000000\n", @as(?u32, null) },
+ .{ "Charging", "POWER_SUPPLY_ENERGY_NOW=60000000\nPOWER_SUPPLY_ENERGY_FULL=57000000\nPOWER_SUPPLY_POWER_NOW=12000000\n", @as(?u32, null) },
+ .{ "Charging", "POWER_SUPPLY_TIME_TO_FULL_NOW=-1\n", @as(?u32, null) },
+ .{ "Discharging", "POWER_SUPPLY_TIME_TO_EMPTY_NOW=18446744073709551615\n", @as(?u32, null) },
+ .{ "Full", "POWER_SUPPLY_TIME_TO_FULL_NOW=3600\n", @as(?u32, null) },
+ .{ "Not charging", "POWER_SUPPLY_TIME_TO_FULL_NOW=3600\n", @as(?u32, null) },
+ .{ "Unknown", "POWER_SUPPLY_ENERGY_NOW=40000000\nPOWER_SUPPLY_POWER_NOW=12000000\n", @as(?u32, null) },
+ };
+ inline for (cases) |case| {
+ var snapshot: Snapshot = .{};
+ snapshot.add("POWER_SUPPLY_TYPE=Battery\nPOWER_SUPPLY_CAPACITY=72\nPOWER_SUPPLY_STATUS=" ++ case[0] ++ "\n" ++ case[1]);
+ try std.testing.expectEqual(case[2], snapshot.state().remaining_minutes);
+ }
+}
+
+test "fresh snapshots replace estimates and multiple packs do not expose one pack's time" {
+ var s: Snapshot = .{};
+ s.add("POWER_SUPPLY_TYPE=Battery\nPOWER_SUPPLY_CAPACITY=72\nPOWER_SUPPLY_STATUS=Charging\nPOWER_SUPPLY_TIME_TO_FULL_NOW=5100\n");
+ var buf: [192]u8 = undefined;
+ try std.testing.expectEqualStrings("~1h 25min left", s.state().estimate(&buf).?);
+ s = .{};
+ s.add("POWER_SUPPLY_TYPE=Battery\nPOWER_SUPPLY_CAPACITY=72\nPOWER_SUPPLY_STATUS=Discharging\nPOWER_SUPPLY_TIME_TO_EMPTY_NOW=1800\n");
+ try std.testing.expectEqualStrings("~30min left", s.state().estimate(&buf).?);
+ s.add("POWER_SUPPLY_TYPE=Battery\nPOWER_SUPPLY_CAPACITY=90\nPOWER_SUPPLY_STATUS=Discharging\nPOWER_SUPPLY_TIME_TO_EMPTY_NOW=3600\n");
+ try std.testing.expectEqual(@as(?u32, null), s.state().remaining_minutes);
+ s = .{};
+ s.add("POWER_SUPPLY_TYPE=Battery\nPOWER_SUPPLY_CAPACITY=72\nPOWER_SUPPLY_STATUS=Charging\n");
+ try std.testing.expectEqual(@as(?[]const u8, null), s.state().estimate(&buf));
+}
+
+test "low battery warns once at ten percent, rearms after recovery, and ignores missing data" {
+ var warning: battery.Warning = .{};
+ try std.testing.expectEqual(.clear, warning.update(.{ .percent = 11, .discharging = true }));
+ try std.testing.expectEqual(.show, warning.update(.{ .percent = 10, .discharging = true }));
+ // Repeated snapshots, another monitor, and further discharge do not repeat.
+ try std.testing.expectEqual(.none, warning.update(.{ .percent = 10, .discharging = true }));
+ try std.testing.expectEqual(.none, warning.update(.{}));
+ try std.testing.expectEqual(.none, warning.update(.{ .percent = 0, .discharging = true }));
+ try std.testing.expectEqual(.clear, warning.update(.{ .percent = 5, .charging = true, .plugged = true }));
+ try std.testing.expectEqual(.show, warning.update(.{ .percent = 5, .discharging = true }));
+ try std.testing.expectEqual(.clear, warning.update(.{ .percent = 12, .discharging = true }));
+ try std.testing.expectEqual(.show, warning.update(.{ .percent = 9, .discharging = true }));
+ try std.testing.expectEqual(.clear, warning.update(.{ .percent = 8, .plugged = true }));
+ try std.testing.expectEqual(.clear, warning.update(.{ .percent = 8 }));
+ // A weak adapter may still report a genuine discharge while online.
+ try std.testing.expectEqual(.show, warning.update(.{ .percent = 8, .plugged = true, .discharging = true }));
+}
diff --git a/src/taskbar/layout.zig b/src/taskbar/layout.zig
index 21fdbbd..74dcc5d 100644
--- a/src/taskbar/layout.zig
+++ b/src/taskbar/layout.zig
@@ -37,6 +37,7 @@ pub fn placement(bar: *Taskbar, output_box: wlr.Box) shape.Placement {
.height = barHeight(),
.edge_gap = edgeGap(),
.length = ui_theme.global.taskbar_length,
+ .alignment = bar.server.config.compositor.taskbar_alignment,
.radius = barRadius(),
.top = bar.server.config.compositor.taskbar_position == .top,
});
diff --git a/src/taskbar/shape.zig b/src/taskbar/shape.zig
index 55882ed..4be46fd 100644
--- a/src/taskbar/shape.zig
+++ b/src/taskbar/shape.zig
@@ -13,8 +13,9 @@ pub const Spec = struct {
height: i32,
/// Logical px between the bar and the output edge it sits on.
edge_gap: i32 = 0,
- /// Percent of the output's width; the bar is centred.
+ /// Percent of the output's width.
length: f32 = 100,
+ alignment: @import("config").types.TaskbarAlignment = .center,
radius: f32 = 0,
top: bool = false,
};
@@ -32,7 +33,11 @@ pub fn place(output: wlr.Box, spec: Spec) Placement {
const gap = std.math.clamp(spec.edge_gap, 0, @max(0, output.height - spec.height));
return .{
.box = .{
- .x = output.x + @divTrunc(output.width - width, 2),
+ .x = output.x + switch (spec.alignment) {
+ .left => @as(i32, 0),
+ .center => @divTrunc(output.width - width, 2),
+ .right => output.width - width,
+ },
.y = if (spec.top) output.y + gap else output.y + output.height - spec.height - gap,
.width = width,
.height = spec.height,
@@ -90,108 +95,6 @@ fn coverage(distance: f32, scale: f32) f32 {
return std.math.clamp(0.5 - distance * scale, 0, 1);
}
-const TestColor = struct {
- r: f32 = 0,
- g: f32 = 0,
- b: f32 = 0,
- a: f32 = 0,
-
- fn over(source: TestColor, destination: TestColor) TestColor {
- const alpha = source.a + destination.a * (1 - source.a);
- if (alpha == 0) return .{};
- return .{
- .r = (source.r * source.a + destination.r * destination.a * (1 - source.a)) / alpha,
- .g = (source.g * source.a + destination.g * destination.a * (1 - source.a)) / alpha,
- .b = (source.b * source.a + destination.b * destination.a * (1 - source.a)) / alpha,
- .a = alpha,
- };
- }
- fn scaled(color: TestColor, alpha: f32) TestColor {
- return .{ .r = color.r, .g = color.g, .b = color.b, .a = std.math.clamp(color.a * alpha, 0, 1) };
- }
-};
-
-test "the bar is centred, keeps its gap on the edge it sits on and never gets too short" {
- const output: wlr.Box = .{ .x = 100, .y = 50, .width = 1920, .height = 1080 };
- const flat = place(output, .{ .height = 44 });
- try std.testing.expectEqual(wlr.Box{ .x = 100, .y = 50 + 1080 - 44, .width = 1920, .height = 44 }, flat.box);
- try std.testing.expectEqual(@as(i32, 44), flat.reserved);
-
- const floating = place(output, .{ .height = 44, .edge_gap = 12, .length = 60 });
- try std.testing.expectEqual(wlr.Box{ .x = 100 + 384, .y = 50 + 1080 - 44 - 12, .width = 1152, .height = 44 }, floating.box);
- try std.testing.expectEqual(@as(i32, 56), floating.reserved);
-
- const top = place(output, .{ .height = 44, .edge_gap = 12, .length = 60, .top = true });
- try std.testing.expectEqual(@as(i32, 50 + 12), top.box.y);
- try std.testing.expectEqual(@as(i32, 56), top.reserved);
-
- // Shorter than the items need, or than the output is wide.
- try std.testing.expectEqual(min_width, place(output, .{ .height = 44, .length = 20 }).box.width);
- const narrow: wlr.Box = .{ .x = 0, .y = 0, .width = 300, .height = 600 };
- try std.testing.expectEqual(@as(i32, 300), place(narrow, .{ .height = 44, .length = 50 }).box.width);
- // Out-of-range asks fall back into range instead of leaving the output.
- try std.testing.expectEqual(@as(i32, 1920), place(output, .{ .height = 44, .length = 400 }).box.width);
- try std.testing.expectEqual(@as(i32, 1080), place(output, .{ .height = 44, .edge_gap = 5000 }).reserved);
-}
-
-test "only the original bar is flush" {
- const output: wlr.Box = .{ .x = 0, .y = 0, .width = 1920, .height = 1080 };
- const bottom = place(output, .{ .height = 44 }).box;
- try std.testing.expect(flush(output, bottom, 0));
- try std.testing.expect(flush(output, place(output, .{ .height = 44, .top = true }).box, 0));
- try std.testing.expect(!flush(output, bottom, 8));
- try std.testing.expect(!flush(output, place(output, .{ .height = 44, .edge_gap = 6 }).box, 0));
- try std.testing.expect(!flush(output, place(output, .{ .height = 44, .length = 80 }).box, 0));
-}
-
-test "items clear a rounded end by exactly what the curve takes" {
- try std.testing.expectEqual(@as(i32, 0), cornerInset(0, 4));
- // Margin as tall as the radius: the item's corner is past the curve.
- try std.testing.expectEqual(@as(i32, 0), cornerInset(6, 6));
- // A pill 44 high: an item 4 from the top starts about 9.4 px in.
- try std.testing.expectEqual(@as(i32, 10), cornerInset(22, 4));
- try std.testing.expectEqual(@as(f32, 22), effectiveRadius(80, 44));
- try std.testing.expectEqual(@as(f32, 0), effectiveRadius(-3, 44));
- // The reported inset really does put the item corner inside the arc.
- const r: f32 = 22;
- const inset: f32 = @floatFromInt(cornerInset(r, 4));
- try std.testing.expect((r - inset) * (r - inset) + (r - 4) * (r - 4) <= r * r);
-}
-
-test "the flush background is the original fill and hairline, on the side facing the windows" {
- const fill: TestColor = .{ .r = 0.1, .g = 0.1, .b = 0.1, .a = 0.96 };
- const line: TestColor = .{ .r = 1, .g = 1, .b = 1, .a = 0.06 };
- const bottom: Look = .{ .width = 400, .height = 44, .radius = 0, .outline = 1, .flush = true, .top = false };
- try std.testing.expectEqualDeep(line.over(fill), background(TestColor, bottom, 100, 0.5, 1, fill, line));
- try std.testing.expectEqualDeep(fill, background(TestColor, bottom, 100, 1.5, 1, fill, line));
- var top = bottom;
- top.top = true;
- try std.testing.expectEqualDeep(fill, background(TestColor, top, 100, 0.5, 1, fill, line));
- try std.testing.expectEqualDeep(line.over(fill), background(TestColor, top, 100, 43.5, 1, fill, line));
- var bare = bottom;
- bare.outline = 0;
- try std.testing.expectEqualDeep(fill, background(TestColor, bare, 100, 0.5, 1, fill, line));
-}
-
-fn expectColor(expected: TestColor, actual: TestColor) !void {
- inline for (.{ "r", "g", "b", "a" }) |channel| try std.testing.expectApproxEqAbs(@field(expected, channel), @field(actual, channel), 1e-5);
-}
-
-test "a floating background rounds its corners and wears its outline all round" {
- const fill: TestColor = .{ .r = 0.1, .g = 0.1, .b = 0.1, .a = 0.9 };
- const line: TestColor = .{ .r = 1, .g = 0, .b = 0, .a = 0.5 };
- const look: Look = .{ .width = 400, .height = 44, .radius = 22, .outline = 2, .flush = false, .top = false };
- // The corner is cut away, the middle is plain fill, the rim carries the outline.
- try std.testing.expectEqual(@as(f32, 0), background(TestColor, look, 0.5, 0.5, 1, fill, line).a);
- try expectColor(fill, background(TestColor, look, 200, 22, 1, fill, line));
- try expectColor(line.over(fill), background(TestColor, look, 200, 0.5, 1, fill, line));
- try expectColor(line.over(fill), background(TestColor, look, 200, 43.5, 1, fill, line));
- try expectColor(line.over(fill), background(TestColor, look, 0.5, 22, 1, fill, line));
- // Square but floating (only a gap or a length): the corners stay filled.
- var square = look;
- square.radius = 0;
- try std.testing.expect(background(TestColor, square, 1, 1, 1, fill, line).a > 0.9);
- // The ramp is antialiased across the curve.
- const edge = background(TestColor, look, 6.4, 6.4, 1, fill, line).a;
- try std.testing.expect(edge > 0 and edge < 1);
+test {
+ _ = @import("shape_tests.zig");
}
diff --git a/src/taskbar/shape_tests.zig b/src/taskbar/shape_tests.zig
new file mode 100644
index 0000000..5ca6cf8
--- /dev/null
+++ b/src/taskbar/shape_tests.zig
@@ -0,0 +1,127 @@
+const std = @import("std");
+const wlr = @import("wlroots");
+const shape = @import("shape.zig");
+const place = shape.place;
+const flush = shape.flush;
+const min_width = shape.min_width;
+const cornerInset = shape.cornerInset;
+const effectiveRadius = shape.effectiveRadius;
+const Look = shape.Look;
+const background = shape.background;
+
+const TestColor = struct {
+ r: f32 = 0,
+ g: f32 = 0,
+ b: f32 = 0,
+ a: f32 = 0,
+
+ pub fn over(source: TestColor, destination: TestColor) TestColor {
+ const alpha = source.a + destination.a * (1 - source.a);
+ if (alpha == 0) return .{};
+ return .{
+ .r = (source.r * source.a + destination.r * destination.a * (1 - source.a)) / alpha,
+ .g = (source.g * source.a + destination.g * destination.a * (1 - source.a)) / alpha,
+ .b = (source.b * source.a + destination.b * destination.a * (1 - source.a)) / alpha,
+ .a = alpha,
+ };
+ }
+ pub fn scaled(color: TestColor, alpha: f32) TestColor {
+ return .{ .r = color.r, .g = color.g, .b = color.b, .a = std.math.clamp(color.a * alpha, 0, 1) };
+ }
+};
+
+test "the bar is centred, keeps its gap on the edge it sits on and never gets too short" {
+ const output: wlr.Box = .{ .x = 100, .y = 50, .width = 1920, .height = 1080 };
+ const flat = place(output, .{ .height = 44 });
+ try std.testing.expectEqual(wlr.Box{ .x = 100, .y = 50 + 1080 - 44, .width = 1920, .height = 44 }, flat.box);
+ try std.testing.expectEqual(@as(i32, 44), flat.reserved);
+
+ const floating = place(output, .{ .height = 44, .edge_gap = 12, .length = 60 });
+ try std.testing.expectEqual(wlr.Box{ .x = 100 + 384, .y = 50 + 1080 - 44 - 12, .width = 1152, .height = 44 }, floating.box);
+ try std.testing.expectEqual(@as(i32, 56), floating.reserved);
+
+ const top = place(output, .{ .height = 44, .edge_gap = 12, .length = 60, .top = true });
+ try std.testing.expectEqual(@as(i32, 50 + 12), top.box.y);
+ try std.testing.expectEqual(@as(i32, 56), top.reserved);
+
+ inline for (.{ .left, .center, .right }, .{ 100, 484, 868 }) |alignment, x| {
+ for ([_]bool{ false, true }) |at_top| {
+ const aligned = place(output, .{ .height = 44, .edge_gap = 12, .length = 60, .alignment = alignment, .top = at_top });
+ try std.testing.expectEqual(@as(i32, x), aligned.box.x);
+ try std.testing.expectEqual(floating.box.width, aligned.box.width);
+ try std.testing.expectEqual(if (at_top) top.box.y else floating.box.y, aligned.box.y);
+ try std.testing.expectEqual(floating.reserved, aligned.reserved);
+ try std.testing.expectEqual(flat.box, place(output, .{ .height = 44, .alignment = alignment }).box);
+ }
+ }
+
+ // Shorter than the items need, or than the output is wide.
+ try std.testing.expectEqual(min_width, place(output, .{ .height = 44, .length = 20 }).box.width);
+ const narrow: wlr.Box = .{ .x = 0, .y = 0, .width = 300, .height = 600 };
+ try std.testing.expectEqual(@as(i32, 300), place(narrow, .{ .height = 44, .length = 50 }).box.width);
+ // Out-of-range asks fall back into range instead of leaving the output.
+ try std.testing.expectEqual(@as(i32, 1920), place(output, .{ .height = 44, .length = 400 }).box.width);
+ try std.testing.expectEqual(@as(i32, 1080), place(output, .{ .height = 44, .edge_gap = 5000 }).reserved);
+}
+
+test "only the original bar is flush" {
+ const output: wlr.Box = .{ .x = 0, .y = 0, .width = 1920, .height = 1080 };
+ const bottom = place(output, .{ .height = 44 }).box;
+ try std.testing.expect(flush(output, bottom, 0));
+ try std.testing.expect(flush(output, place(output, .{ .height = 44, .top = true }).box, 0));
+ try std.testing.expect(!flush(output, bottom, 8));
+ try std.testing.expect(!flush(output, place(output, .{ .height = 44, .edge_gap = 6 }).box, 0));
+ try std.testing.expect(!flush(output, place(output, .{ .height = 44, .length = 80 }).box, 0));
+}
+
+test "items clear a rounded end by exactly what the curve takes" {
+ try std.testing.expectEqual(@as(i32, 0), cornerInset(0, 4));
+ // Margin as tall as the radius: the item's corner is past the curve.
+ try std.testing.expectEqual(@as(i32, 0), cornerInset(6, 6));
+ // A pill 44 high: an item 4 from the top starts about 9.4 px in.
+ try std.testing.expectEqual(@as(i32, 10), cornerInset(22, 4));
+ try std.testing.expectEqual(@as(f32, 22), effectiveRadius(80, 44));
+ try std.testing.expectEqual(@as(f32, 0), effectiveRadius(-3, 44));
+ // The reported inset really does put the item corner inside the arc.
+ const r: f32 = 22;
+ const inset: f32 = @floatFromInt(cornerInset(r, 4));
+ try std.testing.expect((r - inset) * (r - inset) + (r - 4) * (r - 4) <= r * r);
+}
+
+test "the flush background is the original fill and hairline, on the side facing the windows" {
+ const fill: TestColor = .{ .r = 0.1, .g = 0.1, .b = 0.1, .a = 0.96 };
+ const line: TestColor = .{ .r = 1, .g = 1, .b = 1, .a = 0.06 };
+ const bottom: Look = .{ .width = 400, .height = 44, .radius = 0, .outline = 1, .flush = true, .top = false };
+ try std.testing.expectEqualDeep(line.over(fill), background(TestColor, bottom, 100, 0.5, 1, fill, line));
+ try std.testing.expectEqualDeep(fill, background(TestColor, bottom, 100, 1.5, 1, fill, line));
+ var top = bottom;
+ top.top = true;
+ try std.testing.expectEqualDeep(fill, background(TestColor, top, 100, 0.5, 1, fill, line));
+ try std.testing.expectEqualDeep(line.over(fill), background(TestColor, top, 100, 43.5, 1, fill, line));
+ var bare = bottom;
+ bare.outline = 0;
+ try std.testing.expectEqualDeep(fill, background(TestColor, bare, 100, 0.5, 1, fill, line));
+}
+
+fn expectColor(expected: TestColor, actual: TestColor) !void {
+ inline for (.{ "r", "g", "b", "a" }) |channel| try std.testing.expectApproxEqAbs(@field(expected, channel), @field(actual, channel), 1e-5);
+}
+
+test "a floating background rounds its corners and wears its outline all round" {
+ const fill: TestColor = .{ .r = 0.1, .g = 0.1, .b = 0.1, .a = 0.9 };
+ const line: TestColor = .{ .r = 1, .g = 0, .b = 0, .a = 0.5 };
+ const look: Look = .{ .width = 400, .height = 44, .radius = 22, .outline = 2, .flush = false, .top = false };
+ // The corner is cut away, the middle is plain fill, the rim carries the outline.
+ try std.testing.expectEqual(@as(f32, 0), background(TestColor, look, 0.5, 0.5, 1, fill, line).a);
+ try expectColor(fill, background(TestColor, look, 200, 22, 1, fill, line));
+ try expectColor(line.over(fill), background(TestColor, look, 200, 0.5, 1, fill, line));
+ try expectColor(line.over(fill), background(TestColor, look, 200, 43.5, 1, fill, line));
+ try expectColor(line.over(fill), background(TestColor, look, 0.5, 22, 1, fill, line));
+ // Square but floating (only a gap or a length): the corners stay filled.
+ var square = look;
+ square.radius = 0;
+ try std.testing.expect(background(TestColor, square, 1, 1, 1, fill, line).a > 0.9);
+ // The ramp is antialiased across the curve.
+ const edge = background(TestColor, look, 6.4, 6.4, 1, fill, line).a;
+ try std.testing.expect(edge > 0 and edge < 1);
+}
diff --git a/src/ui/layout.zig b/src/ui/layout.zig
index cfa47d2..0178c00 100644
--- a/src/ui/layout.zig
+++ b/src/ui/layout.zig
@@ -143,6 +143,7 @@ pub const IconId = enum {
more,
users,
squares,
+ divide,
};
pub const ButtonState = enum { idle, hover, press, disabled };
diff --git a/src/ui/paint_icons.zig b/src/ui/paint_icons.zig
index a5a2956..806501b 100644
--- a/src/ui/paint_icons.zig
+++ b/src/ui/paint_icons.zig
@@ -174,7 +174,7 @@ pub fn iconDistance(id: IconId, px: f32, py: f32, cx: f32, cy: f32, half: f32, t
const bar = sdSegment(px, py, cx, cy - half * 0.95, cx, cy - half * 0.05, t);
break :blk @min(@max(ring, -gap), bar);
},
- .clock => 1000, // Embedded SVG; no procedural fallback.
+ .clock, .divide => 1000, // Embedded SVG; no procedural fallback.
.power_saver, .power_balanced, .power_performance => blk: {
// Upper three quarters of a ring, open at the bottom, with a
// needle from the hub.
diff --git a/src/ui/shell_icons.zig b/src/ui/shell_icons.zig
index 2486c3a..3bcc3e0 100644
--- a/src/ui/shell_icons.zig
+++ b/src/ui/shell_icons.zig
@@ -104,6 +104,7 @@ pub fn configure(io: std.Io, root: []const u8) void {
.{ IconId.eject, "eject" },
.{ IconId.users, "users" },
.{ IconId.squares, "squares" },
+ .{ IconId.divide, "divide" },
}) |pair| {
loadOverride(io, root, pair[0], pair[1]);
}
@@ -195,6 +196,7 @@ fn builtinSource(id: IconId) ?[]const u8 {
.eject => @embedFile("shell-icon-eject"),
.users => @embedFile("shell-icon-users"),
.squares => @embedFile("shell-icon-squares"),
+ .divide => @embedFile("shell-icon-divide"),
else => null,
};
}
@@ -254,7 +256,7 @@ fn rasterize(svg: []const u8, size: i32) ?Mask {
test "bundled shell SVGs render nonempty transparent masks at fractional scales" {
defer deinit();
- for ([_]IconId{ .print, .usb_stick, .drive, .eject, .home, .settings, .mouse, .display, .music, .headphones, .wifi, .bluetooth, .battery, .notification, .volume, .volume_muted, .power, .clock, .lock, .logout, .reboot }) |id| {
+ for ([_]IconId{ .print, .usb_stick, .drive, .eject, .home, .settings, .mouse, .display, .music, .headphones, .wifi, .bluetooth, .battery, .notification, .volume, .volume_muted, .power, .clock, .lock, .logout, .reboot, .divide }) |id| {
for ([_]i32{ 24, 36, 48 }) |size| {
const mask = get(id, size) orelse return error.InvalidShellIcon;
var visible = false;
diff --git a/tests/battery_popup.py b/tests/battery_popup.py
index b3e7f4c..95afd87 100644
--- a/tests/battery_popup.py
+++ b/tests/battery_popup.py
@@ -18,19 +18,24 @@ def run(scale, gold=False, top=False):
root = Path(directory)
hook = root / "battery.so"
subprocess.run(["cc", "-shared", "-fPIC", "-Wall", "-Wextra", "-Werror", str(Path(__file__).with_name("battery_hook.c")), "-ldl", "-o", str(hook)], check=True)
- for state, percent, details in (("Full", 100, True), ("Discharging", 18, False), ("Charging", 72, True)):
+ for state, percent, details in (("Full", 100, True), ("Discharging", 10, False), ("Charging", 72, True)):
tmp = root / state
tmp.mkdir(mode=0o700)
supply = tmp / "power_supply" / "BAT0"
supply.mkdir(parents=True)
(supply / "scope").write_text("System\n")
- (supply / "uevent").write_text(f"POWER_SUPPLY_TYPE=Battery\nPOWER_SUPPLY_CAPACITY={percent}\nPOWER_SUPPLY_STATUS={state}\n" + (
- "POWER_SUPPLY_ENERGY_FULL=57000000\nPOWER_SUPPLY_ENERGY_FULL_DESIGN=90000000\nPOWER_SUPPLY_CYCLE_COUNT=482\n" if details else ""))
+ readings = f"POWER_SUPPLY_TYPE=Battery\nPOWER_SUPPLY_CAPACITY={percent}\nPOWER_SUPPLY_STATUS={state}\n" + (
+ "POWER_SUPPLY_ENERGY_FULL=57000000\nPOWER_SUPPLY_ENERGY_FULL_DESIGN=90000000\nPOWER_SUPPLY_CYCLE_COUNT=482\n" if details else "")
+ if state == "Charging":
+ readings += "POWER_SUPPLY_ENERGY_NOW=40000000\nPOWER_SUPPLY_POWER_NOW=12000000\n"
+ elif state == "Discharging":
+ readings += "POWER_SUPPLY_CHARGE_NOW=3000000\nPOWER_SUPPLY_CURRENT_NOW=2000000\n"
+ (supply / "uevent").write_text(readings)
config = '[compositor]\nxwayland = false\ntaskbar_position = "' + ('top' if top else 'bottom') + '"\n'
if gold:
config += '[theme]\nbase = "gold"\n'
fake = start_fake()
- process, log = spawn_compositor(tmp, scale=scale, renderer=os.environ.get("REDIWM_TEST_RENDERER", "gles2"), config_content=config, env_extra={
+ process, log = spawn_compositor(tmp, outputs=int(os.environ.get("REDIWM_TEST_OUTPUTS", "1")), scale=scale, renderer=os.environ.get("REDIWM_TEST_RENDERER", "gles2"), config_content=config, env_extra={
"LD_PRELOAD": str(hook), "REDIWM_TEST_BATTERY_DIR": str(supply.parent),
"DBUS_SYSTEM_BUS_ADDRESS": os.environ["DBUS_SESSION_BUS_ADDRESS"],
"DBUS_SESSION_BUS_ADDRESS": "", "XDG_CACHE_HOME": str(tmp),
@@ -39,6 +44,12 @@ def run(scale, gold=False, top=False):
with IPCClient(tmp, timeout=15) as ipc:
ipc.wait_for("wallpaper_presented", timeout_ms=10000)
wait_for(lambda: "active profile balanced" in log_text(tmp), "power profile baseline")
+ warnings = [n for n in ipc.get_notifications()["history"] if n["summary"] == "Low battery"]
+ assert len(warnings) == (1 if state == "Discharging" else 0), warnings
+ if warnings:
+ assert warnings[0]["body"] == "Battery is at 10%. Plug in your charger."
+ assert warnings[0]["urgency"] == 2
+ ipc.dismiss_notification(warnings[0]["id"])
bar = ipc.get_shell_state()["taskbars"][0]
boxes = {item["name"]: item["box"] for item in bar["right_items"]}
@@ -75,6 +86,18 @@ def run(scale, gold=False, top=False):
red, green, blue = initial.getpixel((x, y))
assert red > 190 and green > 180 and blue > 155, ("Gold detail card", (red, green, blue))
+ if state == "Charging":
+ # Rate changes with the same percentage must repaint an open
+ # popup on the existing minute tick, without input/events.
+ (supply / "uevent").write_text(readings.replace("POWER_SUPPLY_POWER_NOW=12000000", "POWER_SUPPLY_POWER_NOW=24000000"))
+ time.sleep(60 - time.time() % 60 + 0.2)
+ refreshed = capture("estimate-refreshed")
+ pixelscale = initial.width / bar["box"]["width"]
+ estimate_box = tuple(round(v * pixelscale) for v in (
+ origin[0] + 125 * factor, origin[1] + 38 * factor,
+ origin[0] + 345 * factor, origin[1] + 58 * factor))
+ assert ImageChops.difference(initial.crop(estimate_box), refreshed.crop(estimate_box)).getbbox(), "time estimate did not refresh on the minute tick"
+
# Click selection and external changes both update the check.
ipc.click_at(*row(2))
assert read_line(fake) == {"set": "performance"}
diff --git a/tests/taskbar_sections.py b/tests/taskbar_sections.py
index 93d620f..5604747 100644
--- a/tests/taskbar_sections.py
+++ b/tests/taskbar_sections.py
@@ -139,7 +139,12 @@ def run():
well = ui.find(f'taskbar_zone_{zones[zone]}')['global_box']
if well == aimed:
break
- ipc.move_cursor(round(well['x'] + well['width'] / 2), well['y'] + well['height'] - 3)
+ # The drag grab follows the pointer outside the
+ # viewport, but synthetic input must stay on-screen.
+ height = ipc.get_outputs()[0]['logical_height']
+ y = max(0, min(height - 1, well['y'] + well['height'] - 3))
+ assert well['y'] <= y < well['y'] + well['height'], well
+ ipc.move_cursor(round(well['x'] + well['width'] / 2), y)
aimed = well
ipc.pointer_button(0x110, False)
wait_for(lambda: any(entry.lstrip('-~') == f'{zones[zone]}:{name}'
diff --git a/tests/taskbar_shape.py b/tests/taskbar_shape.py
index dd9a81c..757ba4c 100644
--- a/tests/taskbar_shape.py
+++ b/tests/taskbar_shape.py
@@ -15,9 +15,10 @@ from ui_driver import UIDriver
BAR = 44
-def expected_box(output, gap, length, top=False):
+def expected_box(output, gap, length, top=False, alignment="center"):
width = max(min(420, output["w"]), min(output["w"], round(output["w"] * length / 100)))
- return {"x": (output["w"] - width) // 2, "y": gap if top else output["h"] - BAR - gap,
+ x = {"left": 0, "center": (output["w"] - width) // 2, "right": output["w"] - width}[alignment]
+ return {"x": x, "y": gap if top else output["h"] - BAR - gap,
"width": width, "height": BAR}
@@ -84,6 +85,22 @@ def run():
expected = expected_box(output, gap, length)
wait_for(lambda: bar_box() == expected, f"bar did not float: {bar_box()} != {expected}")
+ # Inline choices move the whole bar and survive a page rebuild.
+ assert ui.find("taskbar_alignment")["selected_index"] == 1
+ for alignment, index in (("left", 0), ("right", 2), ("center", 1)):
+ widget = ui.scroll_into_view("taskbar_alignment")
+ box = widget["global_box"]
+ ipc.click_at(round(box["x"] + box["width"] * (index + .5) / 3),
+ round(box["y"] + box["height"] / 2))
+ ipc.wait_for_panel_settled("control_center")
+ wait_for(lambda: bar_box() == expected_box(output, gap, length, alignment=alignment),
+ f"taskbar alignment {alignment}")
+ assert tomllib.loads(config_path.read_text())["compositor"]["taskbar_alignment"] == alignment
+ ipc.close_panel("control_center")
+ ipc.action("open_appearance")
+ ipc.wait_for_panel_settled("control_center")
+ assert ui.find("taskbar_alignment")["selected_index"] == index
+
# A maximized window gives up the gap along with the bar.
ipc.wait_for("window_geometry_settled", window_id=win_id)
floating = ipc.get_window_debug(win_id)["chrome_box"]
@@ -115,6 +132,14 @@ def run():
wait_for(lambda: (lambda b: b["y"] == BAR + 20 and b["y"] + b["height"] == output["h"])(
ipc.get_window_debug(win_id)["chrome_box"]), f"maximized window under the top bar: {ipc.get_window_debug(win_id)['chrome_box']}")
+ for alignment in ("left", "right", "center"):
+ current = tomllib.loads(config_path.read_text())["compositor"]["taskbar_alignment"]
+ config_path.write_text(config_path.read_text().replace(
+ f'taskbar_alignment = "{current}"', f'taskbar_alignment = "{alignment}"'))
+ ipc.reload_config()
+ wait_for(lambda: bar_box() == expected_box(output, 20, 50, top=True, alignment=alignment),
+ f"reloaded top taskbar alignment {alignment}")
+
# Too short a bar keeps room for its items; a bad value is refused.
config_path.write_text(config_path.read_text().replace("taskbar_length = 50", "taskbar_length = 20"))
ipc.reload_config()