diff --git a/Sources/StableBar/BarStore.swift b/Sources/StableBar/BarStore.swift index 31aac75d..bbfbcd63 100644 --- a/Sources/StableBar/BarStore.swift +++ b/Sources/StableBar/BarStore.swift @@ -763,6 +763,8 @@ final class BarStore: NSObject { var environment = next.environment environment["NAME"] = name environment["CONFIG_DIR"] = configurationURL.deletingLastPathComponent().path + environment["STABLEBAR"] = Bundle.main.executablePath + environment["STABLEBAR_CONFIG"] = sharedConfigurationURL.path if let events = registry[provider.type]?.events, !events.isEmpty { script.onOutputChange = { [weak self, weak script] previous, output in for event in events { @@ -1176,6 +1178,8 @@ final class BarStore: NSObject { var environment = configuration.environment.merging(widget.environment) { _, widget in widget } environment["NAME"] = widget.id environment["CONFIG_DIR"] = configurationURL.deletingLastPathComponent().path + environment["STABLEBAR"] = Bundle.main.executablePath + environment["STABLEBAR_CONFIG"] = sharedConfigurationURL.path return environment } diff --git a/Sources/StableBar/LaunchCommand.swift b/Sources/StableBar/LaunchCommand.swift index 97dcbb68..ed7a3368 100644 --- a/Sources/StableBar/LaunchCommand.swift +++ b/Sources/StableBar/LaunchCommand.swift @@ -48,7 +48,7 @@ enum LaunchCommand { init(arguments: [String]) throws { var arguments = arguments - var url = Self.configurationURL + var url = ProcessInfo.processInfo.environment["STABLEBAR_CONFIG"].map { URL(filePath: $0) } ?? Self.configurationURL let targeted = arguments.first == "--config" if arguments.first == "--config" { guard arguments.count >= 2 else { throw CommandFailure(message: Self.usage) } diff --git a/Sources/StableBar/ScriptWidget.swift b/Sources/StableBar/ScriptWidget.swift index 4fb0f601..a7fcf68b 100644 --- a/Sources/StableBar/ScriptWidget.swift +++ b/Sources/StableBar/ScriptWidget.swift @@ -17,6 +17,8 @@ struct ScriptEvent: Sendable { var variables = resolved.merging(environment) { _, event in event } variables["NAME"] = configured["NAME"] variables["CONFIG_DIR"] = configured["CONFIG_DIR"] + variables["STABLEBAR"] = configured["STABLEBAR"] + variables["STABLEBAR_CONFIG"] = configured["STABLEBAR_CONFIG"] variables["SENDER"] = sender return variables } @@ -144,6 +146,8 @@ final class ScriptWidget { var variables = environment.merging(provider.environment) { _, value in value } variables["NAME"] = environment["NAME"] variables["CONFIG_DIR"] = environment["CONFIG_DIR"] + variables["STABLEBAR"] = environment["STABLEBAR"] + variables["STABLEBAR_CONFIG"] = environment["STABLEBAR_CONFIG"] guard let type = registry[provider.type] else { stop() error = "Unknown data source type: \(provider.type)." diff --git a/Tests/StableBarTests/ScriptEventTests.swift b/Tests/StableBarTests/ScriptEventTests.swift index 15a24565..9d45fcb5 100644 --- a/Tests/StableBarTests/ScriptEventTests.swift +++ b/Tests/StableBarTests/ScriptEventTests.swift @@ -215,12 +215,13 @@ import Testing try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) let url = directory.appending(path: "config.json") let configuration: [String: Any] = [ - "environment": ["ROOT_ONLY": "root", "SHARED": "root", "NAME": "incorrect", "CONFIG_DIR": "incorrect"], + "environment": ["ROOT_ONLY": "root", "SHARED": "root", "NAME": "incorrect", "CONFIG_DIR": "incorrect", "STABLEBAR": "incorrect"], "widgets": [[ "id": "environment", "type": "script", "position": "right", "interval": NSNull(), "events": ["custom"], - "environment": ["SHARED": "widget", "NAME": "also incorrect", "CONFIG_DIR": "also incorrect", "INFO": "initial"], - "command": "printf '%s|%s|%s|%s|%s|%s' \"$ROOT_ONLY\" \"$SHARED\" \"$NAME\" \"$CONFIG_DIR\" \"$SENDER\" \"$INFO\"" + "environment": ["SHARED": "widget", "NAME": "also incorrect", "CONFIG_DIR": "also incorrect", + "STABLEBAR_CONFIG": "also incorrect", "INFO": "initial"], + "command": "printf '%s|%s|%s|%s|%s|%s|%s|%s' \"$ROOT_ONLY\" \"$SHARED\" \"$NAME\" \"$CONFIG_DIR\" \"$STABLEBAR\" \"$STABLEBAR_CONFIG\" \"$SENDER\" \"$INFO\"" ]] ] try JSONSerialization.data(withJSONObject: configuration).write(to: url, options: .atomic) @@ -231,16 +232,18 @@ import Testing } store.reloadConfiguration() let script = try #require(store.scripts["environment"]) - let startup = "root|widget|environment|\(directory.path)|startup|initial" + let bar = "\(try #require(Bundle.main.executablePath))|\(url.path)" + let startup = "root|widget|environment|\(directory.path)|\(bar)|startup|initial" for _ in 0..<100 { if script.output.text == startup { break } try await Task.sleep(for: .milliseconds(20)) } #expect(script.output.text == startup) store.refreshScripts(for: "custom", environment: [ - "SHARED": "event", "NAME": "incorrect", "CONFIG_DIR": "incorrect", "SENDER": "incorrect", "INFO": "quoted ' = value" + "SHARED": "event", "NAME": "incorrect", "CONFIG_DIR": "incorrect", "STABLEBAR": "incorrect", "STABLEBAR_CONFIG": "incorrect", + "SENDER": "incorrect", "INFO": "quoted ' = value" ]) - let refreshed = "root|event|environment|\(directory.path)|custom|quoted ' = value" + let refreshed = "root|event|environment|\(directory.path)|\(bar)|custom|quoted ' = value" for _ in 0..<100 { if script.output.text == refreshed { break } try await Task.sleep(for: .milliseconds(20)) diff --git a/docs/command-line.md b/docs/command-line.md index 374e16e1..78d719a8 100644 --- a/docs/command-line.md +++ b/docs/command-line.md @@ -1,6 +1,6 @@ # Command-line controls -The executable is `StableBar.app/Contents/MacOS/StableBar`; [install the command](#install-the-command) to run it as `stablebar`. Prefix commands with `--config PATH` to address a specific running configuration; otherwise live commands target the default configuration. Replies are JSON, and errors exit with status 1. Each configuration has one local control endpoint per user. +The executable is `StableBar.app/Contents/MacOS/StableBar`; [install the command](#install-the-command) to run it as `stablebar`. Prefix commands with `--config PATH` to address a specific running configuration; otherwise live commands target the configuration in `STABLEBAR_CONFIG`, which [widget commands](create-a-widget.md) get from the bar that runs them, or the default configuration. Replies are JSON, and errors exit with status 1. Each configuration has one local control endpoint per user. ```sh StableBar --query @@ -37,7 +37,7 @@ Without `id`, `unset` can also address widget definitions by their ID and profil - `--popup ID`: open the popup or menu of a widget, or close it when it's open. It opens on the active display, as `"display": "active"` defines it; a widget in **More widgets** opens its popup under the More widgets button on its side. Key bindings can call it, for example in `aerospace.toml`: `alt-c = 'exec-and-forget /Applications/StableBar.app/Contents/MacOS/StableBar --popup agenda'`. - `--popup ID --open [--duration SECONDS]`, `--popup ID --close`, `--popup --close`: for scripts, which need the popup in a known state. `--open` opens the popup and leaves it as it is when it's already open. `--duration` closes it after that many seconds, at most a day, unless the pointer has moved into it or it's pinned by then. `--close` closes the widget's popup, pinned or not, and does nothing when it's closed; without an ID, it closes every popup, pinned ones too. Their reply, like `--query` without an ID, includes `popup`: the ID of the widget whose popup is open under the bar, or `null`; pinned popups aren't listed. For example, `StableBar --popup agenda --open --duration 30` shows the agenda for 30 seconds. - `--focus`: give the keyboard to the bar on the active display, as Control-F2 does for the macOS menu bar. The arrow keys move between its widgets, Return or Space clicks one, and Escape gives the keyboard back; see [Keyboard and VoiceOver](widgets.md#keyboard-and-voiceover). Bind it to a key in Shortcuts, Raycast, skhd or your window manager, for example in `aerospace.toml`: `alt-b = 'exec-and-forget /Applications/StableBar.app/Contents/MacOS/StableBar --focus'`. -- `--trigger EVENT [KEY=VALUE ...]`: send an event. Without `--config`, this broadcasts to all subscribed bars for compatibility; with `--config`, it targets that configuration. +- `--trigger EVENT [KEY=VALUE ...]`: send an event. Without `--config`, this broadcasts to all subscribed bars for compatibility, also from a widget's command; with `--config`, it targets that configuration, such as `--config "$STABLEBAR_CONFIG"` for the bar that runs the widget. - `--reload`: reload configuration; without `--config`, notify all running bars. - `--packages`, `--inspect-package PATH`, `--install-package PATH|ID [--source SOURCE]`, `--enable-package ID VERSION [--persist]`, `--uninstall-package ID VERSION`: review and manage packages. `--packages` lists installed packages; `source` names the source that installed each one (`stablebar`, a private source's `id`, or `local` for a folder) and is absent for packages installed before StableBar recorded sources. `--install-package` installs a folder, or a package from the [store](packages.md#store) or a [private source](packages.md#private-sources) in the configuration file when its argument is not a folder. When more than one source lists the ID, it names them; add `--source` with a source's `id`. It refuses a package that another source installed. Installation does not enable commands. Uninstall requires the bar to be running and always saves configuration edits before removing that version. Package selections belong in the root file or its includes; use profile widget overrides to hide package widgets contextually. - `--build-source PACKAGES OUT [--previous FILE] [--url URL --name NAME]`: build a [private package source](packages.md#publishing-a-source) from a folder of packages. It writes an archive for each package version that isn't published yet, and `index.json`, into `OUT`, then prints what to upload. `--previous` is the index you published last time; its versions that are still in `PACKAGES` keep their entries and no archive is written for them, and a package whose folder is gone leaves the index. With `--url` (the index's `https` address) and `--name`, it also prints a join link. It checks each package like `--inspect-package`, needs StableBar 0.6.0 or later, and doesn't use a configuration file or a running bar. diff --git a/docs/create-a-widget.md b/docs/create-a-widget.md index b1171c5d..189ebb99 100644 --- a/docs/create-a-widget.md +++ b/docs/create-a-widget.md @@ -87,12 +87,20 @@ External hooks can trigger an event without launching another bar: Use that event name in the widget's `events`. A trigger posts a distributed notification with that name, so trigger names share one space with the names macOS and your apps send. Extra `KEY=VALUE` arguments become environment variables, preserving spaces, quotes and equals signs as data. Trigger arguments and distributed-notification data cannot replace variables exported by your login shell, such as `PATH` or `HOME`. Events finish the currently running update and coalesce pending refreshes to the latest event and payload. A widget never runs overlapping update commands. This queue is intended for refreshing current state, not recording every event. +A widget's own commands can run the StableBar that started them as `"$STABLEBAR"`. Its live commands, such as `--refresh` and `--popup`, then address that bar instead of the default configuration: + +```json +"onClick": "\"$STABLEBAR\" --refresh weather" +``` + Commands inherit your login shell's environment, then top-level `environment`, then the widget's `environment`, then event data. Values must be strings. StableBar supplies these variables: | Variable | Value | | --- | --- | | `NAME` | Widget ID; event data cannot replace it | | `CONFIG_DIR` | Directory containing the main configuration; event data cannot replace it | +| `STABLEBAR` | Path of the running StableBar executable; event data cannot replace it | +| `STABLEBAR_CONFIG` | Path of the configuration file the bar was started with, which the [command line](command-line.md) uses when `--config` isn't given; event data cannot replace it | | `SENDER` | `startup`, `routine`, the subscribed event name, `action` after an action completes, or a mouse event below | | `INFO` | For StableBar's events, as the table above lists; for a trigger, its `INFO` value; otherwise the distributed notification's JSON payload when available, with dates as ISO 8601 strings and without values JSON can't hold, such as data | | `SID` | Display number for pointer actions and workspace events | diff --git a/docs/providers.md b/docs/providers.md index 7d240dcb..a7d37a84 100644 --- a/docs/providers.md +++ b/docs/providers.md @@ -33,7 +33,7 @@ Provider `type` is `command`, `stream`, `system`, `network`, `wifi`, `battery`, A widget with `type` set to `system`, `network`, `wifi`, `battery`, `bluetooth`, `audio`, `inputSource`, `microphone`, `privacy`, `calendar` or `disk` uses the provider of that name. Without a definition in `providers`, it is a native provider of that type with default settings, shared by every widget that names it. An implicit `system` provider uses a 2-second interval and lists 5 apps when a consumer enables Essentials details. Define a provider with the same name to change its interval or other settings. `{ "id": "power", "type": "battery", "position": "right" }` is enough for a battery widget. -Provider `environment` overlays the top-level environment. `NAME` is the provider name and `CONFIG_DIR` remains the main configuration directory. The environment of a consuming widget applies to that widget's actions, not the shared update process. Add `events` to a provider or consuming widget to request updates; one event refreshes a shared provider once. An explicit refresh restarts a stream's process with the new event payload, and restarts the listener of a push source such as `battery`, which then reads its current state again. +Provider `environment` overlays the top-level environment. `NAME` is the provider name, `CONFIG_DIR` remains the main configuration directory, and `STABLEBAR` and `STABLEBAR_CONFIG` remain the running bar's. The environment of a consuming widget applies to that widget's actions, not the shared update process. Add `events` to a provider or consuming widget to request updates; one event refreshes a shared provider once. An explicit refresh restarts a stream's process with the new event payload, and restarts the listener of a push source such as `battery`, which then reads its current state again. A stream writes one complete JSON object per line, including `text`, and flushes stdout after each update. Empty lines are ignored; the final line may omit its newline. Streaming output represents current state: when updates arrive faster than the UI consumes them, only the newest pending update is retained. Each line is limited to 1 MiB; stderr retains its latest 16 KiB. Malformed output stops the process and retains the last good value. Clean exits and failures reconnect with exponential backoff, capped at five minutes or the configured interval if longer. Ten seconds of successful streaming resets the failure streak.