### start() - handle first launch and wake from sleep
Source: https://github.com/swiftbar/swiftbar/blob/main/_autodocs/api-reference/02-executable-plugin.md
Starts the plugin, distinguishing between first launch and wake-from-sleep. For cron-scheduled plugins it refreshes metadata and enables the timer; for interval plugins it checks if a wake refresh is needed; for 'never' plugins it always refreshes on wake.
```swift
func start() {
beginTimerArmingCycle()
// Check if this is a wake from sleep event by checking if lastUpdated exists
if lastUpdated != nil {
// Handle wake from sleep differently - check if it's time to update based on schedule
if let metadata, metadata.nextDate != nil {
// For cron-scheduled plugins, calculate next date and set timer
refreshPluginMetadata()
enableTimer()
} else if updateInterval > 0, updateInterval < pluginNeverUpdateInterval {
// For interval-based plugins (excluding "never" plugins), check if the
// scheduled time has passed or the last run needs a redo
if needsWakeRefresh(at: Date()) {
refresh(reason: .WakeFromSleep)
} else {
// Not yet time to update, just re-enable the timer
enableTimer()
}
} else {
// For plugins without a specific interval ("never" plugins), always refresh on wake
refresh(reason: .WakeFromSleep)
}
} else {
// First start of the plugin
refresh(reason: .FirstLaunch)
}
}
```
--------------------------------
### Example directory structure for a packaged plugin
Source: https://github.com/swiftbar/swiftbar/blob/main/README-PACKAGED-PLUGINS.md
Shows the required layout of a .swiftbar plugin directory, including the main plugin.sh script, supporting libraries, assets, and configuration files. The main script must be executable.
```text
weather.swiftbar/
├── Contents/
│ ├── Info.plist # Bundle information (makes macOS treat it as a bundle)
│ ├── Resources/ # Bundle resources
│ │ └── plugin-icon.icns # Custom icon for the plugin (optional)
├── plugin.sh # Main entry point (REQUIRED, must be executable)
├── lib/ # Supporting library scripts
│ ├── weather_api.sh
│ └── formatting.sh
├── assets/ # Images and other assets
│ └── icons/
│ ├── sunny.png
│ └── cloudy.png
└── config.json # Configuration files
```
--------------------------------
### Install SwiftBar with Homebrew
Source: https://github.com/swiftbar/swiftbar/blob/main/README.md
Install SwiftBar via Homebrew. Requires macOS Monterey (12) or later.
```bash
brew install swiftbar
```
--------------------------------
### Swift: findMainExecutable(in:) implementation
Source: https://github.com/swiftbar/swiftbar/blob/main/_autodocs/api-reference/06-packaged-plugin.md
Searches a .swiftbar directory for a regular file whose name starts with 'plugin.' (e.g., plugin.sh, plugin.py). Prefers executable files, breaks ties alphabetically, and returns the entry point URL. Logs an error if no entry point is found.
```swift
// SwiftBar/Plugin/PackagedPlugin.swift:115-163
/// Finds the `plugin.*` entry point inside a `.swiftbar` directory.
static func findMainExecutable(in directory: URL) -> URL? {
guard directory.isSwiftBarPackage else {
return nil
}
...
var candidates = contents.filter { url in
var isDir: ObjCBool = false
guard fileManager.fileExists(atPath: url.path, isDirectory: &isDir), !isDir.boolValue else {
return false
}
return url.lastPathComponent.hasPrefix("plugin.")
}
// Prefer already-executable files, break ties alphabetically for determinism
candidates.sort {
let exec0 = fileManager.isExecutableFile(atPath: $0.path)
let exec1 = fileManager.isExecutableFile(atPath: $1.path)
if exec0 != exec1 { return exec0 && !exec1 }
return $0.lastPathComponent < $1.lastPathComponent
}
if let pluginFile = candidates.first {
// Keep the caller's package path (including a `.swiftbar` symlink)
// as the public identity of the entry point. ...
let entryPoint = directory.appendingPathComponent(pluginFile.lastPathComponent)
return entryPoint
}
os_log("No plugin.* entry point found in %{public}@", log: Log.plugin, type: .error, directory.path)
return nil
}
```
--------------------------------
### Pure parsing: parseLine and buildMenuTree
Source: https://github.com/swiftbar/swiftbar/blob/main/_autodocs/api-reference/11-menu-tree.md
Pure parsing example used by tests and by MenubarItem. Shows parseLine returning level, separator flag, and working line, and buildMenuTree constructing a tree from an array of strings with separators.
```swift
let (level, isSeparator, workingLine) = MenuItemNode.parseLine("--child item")
level // 1
isSeparator // false
workingLine // "child item"
let tree = MenuItemNode.buildMenuTree(from: [
"---",
"Root",
"--Child 1",
"---",
"--Child 2",
])
// tree[0] = "Root" with children [Child 1, (sep), Child 2]
```
--------------------------------
### ModernLaunchAtLogin.isEnabled
Source: https://github.com/swiftbar/swiftbar/blob/main/_autodocs/api-reference/19-launch-at-login.md
Property to get or set launch-at-login status.
```APIDOC
## ModernLaunchAtLogin.isEnabled
### Description
Gets or sets whether the app launches at login. The getter reports true if either the main app registration or the legacy helper is registered. The setter registers or unregisters the main app and handles legacy helper cleanup.
### Method
Property (get/set)
### Endpoint
`ModernLaunchAtLogin.isEnabled`
### Parameters
#### Setter Value
- **newValue** (Bool) - Required - The new enabled state.
### Response
#### Getter Return Value
- **Bool** - `true` if launch at login is enabled, `false` otherwise.
### Example
```swift
// Get
let enabled = ModernLaunchAtLogin.isEnabled
// Set
ModernLaunchAtLogin.isEnabled = true
```
```
--------------------------------
### Shell quotation and URL handling
Source: https://github.com/swiftbar/swiftbar/blob/main/_autodocs/api-reference/22-string-extensions.md
Examples of escaping shell strings, quoting when needed, and URL encoding/decoding.
```swift
"/Users/me/my script.sh".escaped() // "'/Users/me/my script.sh'"
"exit 0".quoteIfNeeded() // "'exit 0'"
"https://a.b/c".getURL()?.absoluteString // URL
"/tmp/a b.txt".URLEncoded // "/tmp/a%20b.txt" (slashes kept)
```
--------------------------------
### Define DirectoryObserverError for directory watch setup failure
Source: https://github.com/swiftbar/swiftbar/blob/main/_autodocs/errors.md
Defines a LocalizedError for directory watch setup failures. Triggered when open(url.path, O_EVTONLY) returns -1, indicating an unwatchable plugin folder (e.g., filesystem without evt support or permissions).
```swift
// SwiftBar/Utility/DirectoryObserver.swift:8 (compiled only when !MAC_APP_STORE)
struct DirectoryObserverError: LocalizedError {
let url: URL
let errorCode: CInt
var errorDescription: String? {
"Failed to open directory \(url.path): \(String(cString: strerror(errorCode))) (\(errorCode))"
}
}
```
--------------------------------
### Main script plugin.sh sourcing libraries and outputting weather data
Source: https://github.com/swiftbar/swiftbar/blob/main/README-PACKAGED-PLUGINS.md
Example main script that sources supporting libraries from PACKAGE_LIB_DIR and uses their functions to output weather data. The script outputs a menu with temperature, humidity, and wind. The main script must be named plugin.* and have executable permissions.
```bash
#!/bin/bash
# Source supporting libraries
source "$PACKAGE_LIB_DIR/weather_api.sh"
source "$PACKAGE_LIB_DIR/formatting.sh"
# Use functions from the libraries
get_weather_data
format_output
echo "☀️ 72°F"
echo "---"
echo "Humidity: 45%"
echo "Wind: 5 mph NW"
```
--------------------------------
### Streamable plugin example with `~~~` separator
Source: https://github.com/swiftbar/swiftbar/blob/main/README.md
Use this bash script to create a Streamable plugin that updates the menu bar item when the `~~~` separator is encountered. The script runs indefinitely, showing "Test 1" for 3 seconds, then nothing for 5 seconds, and "Test 2" indefinitely.
```bash
#!/bin/bash
#streamable
echo "Test 1"
echo "---"
echo "Test 2"
echo "Test 3"
sleep 3
echo "~~~"
sleep 5
echo "~~~"
echo "Test 2"
```
--------------------------------
### PluginManager method signatures with line references
Source: https://github.com/swiftbar/swiftbar/blob/main/_autodocs/api-reference/08-plugin-manager.md
Lists the public methods of PluginManager with their source line numbers. Use these signatures to call refresh, start, terminate, rebuild, and shortcut-plugin operations from other code.
```swift
// SwiftBar/Plugin/PluginManger.swift:693
func refreshAllPlugins(reason: PluginRefreshReason) // cancels queue, refreshes all enabled; on MAC_APP_STORE also loadPlugins()
func startAllPlugins() // line 703
func terminateAllPlugins() // line 709
func rebuildAllMenus() // line 715
func refreshPlugin(with index: Int, reason: PluginRefreshReason) // line 719 — by menu-bar index
func addShortcutPlugin(plugin: PersistentShortcutPlugin) // line 724
func removeShortcutPlugin(plugin: PersistentShortcutPlugin) // line 729
```
--------------------------------
### Author a .swiftbar package directory layout
Source: https://github.com/swiftbar/swiftbar/blob/main/_autodocs/api-reference/06-packaged-plugin.md
Shows the required layout of a .swiftbar package: the entry point must be named plugin.* (e.g., plugin.sh) and supporting files like lib.sh are allowed. SwiftBar chmod +x and executes the entry point; a name without an interval means the plugin never auto-refreshes.
```text
my-tools.swiftbar/
├── plugin.sh # entry point — SwiftBar chmod +x and executes this (no interval in name = never auto-refresh)
└── lib.sh # supporting files; findMainExecutable skips non-plugin.* files
```
--------------------------------
### PluginRepository init with debounced search subscription
Source: https://github.com/swiftbar/swiftbar/blob/main/_autodocs/api-reference/20-plugin-repository.md
Initializes the repository by refreshing data and setting up a debounced search subscription. The search query is received via the .repositoirySearchUpdate notification and debounced for 0.2 seconds on the main run loop.
```swift
init() {
refreshRepositoryData()
if #available(OSX 11.0, *) {
NotificationCenter.default.publisher(for: .repositoirySearchUpdate)
.compactMap { $0.userInfo?["query"] as? String }
.map { $0 }
.debounce(for: 0.2, scheduler: RunLoop.main)
.assign(to: &$searchString)
}
}
```
--------------------------------
### ExecutablePlugin initializer with support directory creation
Source: https://github.com/swiftbar/swiftbar/blob/main/_autodocs/api-reference/02-executable-plugin.md
Initializes the plugin from a file URL, resolving symlinks for a unique ID and parsing the filename for a refresh interval. Creates support directories when requested and triggers an initial refresh with reason `.FirstLaunch`.
```swift
// SwiftBar/Plugin/ExecutablePlugin.swift:66-79
init(fileURL: URL, createSupportDirectories: Bool = true) {
let nameComponents = fileURL.lastPathComponent.components(separatedBy: ".")
// Use resolved path as ID to ensure uniqueness even with symlinks
id = fileURL.resolvingSymlinksInPath().path
name = nameComponents.first ?? ""
file = fileURL.path
lastState = .Loading
makeScriptExecutable(file: file)
refreshPluginMetadata()
if metadata?.nextDate == nil, nameComponents.count > 2 {
updateInterval = nameComponents.dropFirst().compactMap { parseRefreshInterval(intervalStr: $0, baseUpdateinterval: updateInterval) }.reduce(updateInterval, min)
}
if createSupportDirectories {
createSupportDirs()
}
refresh(reason: .FirstLaunch)
}
```
--------------------------------
### GET //plugins.json
Source: https://github.com/swiftbar/swiftbar/blob/main/_autodocs/endpoints.md
Fetches the list of plugins for a specific category from the plugin repository. Supports cache control via the ignoreCache parameter.
```APIDOC
## [GET] //plugins.json
### Description
Fetches the list of plugins for a specific category from the plugin repository.
### Method
GET
### Endpoint
//plugins.json
### Parameters
#### Path Parameters
- **category** (string) - Required - The category name to fetch plugins for.
#### Query Parameters
- **ignoreCache** (boolean) - Optional - When true, forces a cache reload ignoring cached data.
### Response
#### Success Response (200)
- **RepositoryPlugin** (object) - The decoded repository plugin data.
#### Response Example
```json
{
"plugins": []
}
```
### Error Handling
Failures are published as `AnyPublisher<…, Error>`; subscribing code receives a decode/network `Error`. There is no retry policy; the UI shows the refresh state and lets the user re-trigger via the toolbar's Refresh button.
```
--------------------------------
### Create a packaged plugin
Source: https://github.com/swiftbar/swiftbar/blob/main/README-PACKAGED-PLUGINS.md
Commands to scaffold a SwiftBar packaged plugin directory, create the Info.plist bundle metadata, and write the main plugin script. The script sources a weather API library from the built-in environment variable and is placed in the plugin bundle.
```bash
# Create a packaged plugin
mkdir -p weather.swiftbar/lib
mkdir -p weather.swiftbar/assets
mkdir -p weather.swiftbar/Contents/Resources
# Create the Info.plist to make it display as a bundle
cat > weather.swiftbar/Contents/Info.plist << 'EOF'
CFBundleIdentifier
com.example.swiftbar.weather
CFBundleName
Weather
CFBundlePackageType
BNDL
CFBundleVersion
1.0
CFBundleShortVersionString
1.0
LSTypeIsPackage
EOF
# Create the main script
cat > weather.swiftbar/plugin.sh << 'EOF'
#!/bin/bash
# Use the built-in environment variables to source libraries
source "$PACKAGE_LIB_DIR/weather_api.sh"
# Get weather data
WEATHER=$(curl -s
```
--------------------------------
### launchAtLoginState helper function
Source: https://github.com/swiftbar/swiftbar/blob/main/_autodocs/api-reference/19-launch-at-login.md
Helper that returns true if either the main app or the legacy helper is enabled.
```swift
// SwiftBar/Utility/LaunchAtLogin.swift:58-60
static func launchAtLoginState(isMainAppEnabled: Bool, isLegacyEnabled: Bool) -> Bool {
isMainAppEnabled || isLegacyEnabled
}
```
--------------------------------
### GET /categories.json
Source: https://github.com/swiftbar/swiftbar/blob/main/_autodocs/endpoints.md
Fetches the list of plugin repository categories from the configured base URL. Supports cache control via the ignoreCache parameter.
```APIDOC
## [GET] /categories.json
### Description
Fetches the list of plugin repository categories from the configured base URL.
### Method
GET
### Endpoint
/categories.json
### Parameters
#### Query Parameters
- **ignoreCache** (boolean) - Optional - When true, forces a cache reload ignoring cached data.
### Response
#### Success Response (200)
- **RepositoryCategory** (object) - The decoded repository category data.
#### Response Example
```json
{
"categories": []
}
```
### Error Handling
Failures are published as `AnyPublisher<…, Error>`; subscribing code receives a decode/network `Error`. There is no retry policy; the UI shows the refresh state and lets the user re-trigger via the toolbar's Refresh button.
```
--------------------------------
### PluginRepository class declaration with shared singleton
Source: https://github.com/swiftbar/swiftbar/blob/main/_autodocs/api-reference/20-plugin-repository.md
Declares the PluginRepository class as an ObservableObject with a shared singleton instance. This is the starting point for the repository data model used by the plugin directory UI.
```swift
class PluginRepository: ObservableObject {
static let shared = PluginRepository()
```
--------------------------------
### ModernLaunchAtLogin.launchAtLoginState(isMainAppEnabled:isLegacyEnabled:)
Source: https://github.com/swiftbar/swiftbar/blob/main/_autodocs/api-reference/19-launch-at-login.md
Function to compute launch-at-login state from two booleans.
```APIDOC
## ModernLaunchAtLogin.launchAtLoginState(isMainAppEnabled:isLegacyEnabled:)
### Description
Determines the launch-at-login state based on whether the main app or legacy helper is enabled.
### Method
Function
### Endpoint
`ModernLaunchAtLogin.launchAtLoginState(isMainAppEnabled:isLegacyEnabled:)`
### Parameters
- **isMainAppEnabled** (Bool) - Required - Whether the main app registration is enabled.
- **isLegacyEnabled** (Bool) - Required - Whether the legacy helper is enabled.
### Response
#### Return Value
- **Bool** - `true` if either is enabled, `false` otherwise.
### Example
```swift
let state = ModernLaunchAtLogin.launchAtLoginState(isMainAppEnabled: true, isLegacyEnabled: false)
```
```
--------------------------------
### EphemeralPlugin method implementations
Source: https://github.com/swiftbar/swiftbar/blob/main/_autodocs/api-reference/05-ephemeral-plugin.md
Defines the EphemeralPlugin methods. disable(), enable(), start(), and refresh() are no-ops; terminate() removes the plugin by calling setEphemeralPlugin with empty content; invoke() always returns nil.
```swift
func disable() {}
func terminate() {
delegate.pluginManager.setEphemeralPlugin(pluginId: id, content: "")
}
func enable() {}
func start() {}
func refresh(reason _: PluginRefreshReason) {}
func invoke() -> String? {
nil
}
```
--------------------------------
### swiftbar://opensystemreport
Source: https://github.com/swiftbar/swiftbar/blob/main/_autodocs/endpoints.md
Opens the latest system report.
```APIDOC
## swiftbar://opensystemreport
### Description
Opens the latest system report.
### Method
URL Scheme
### Endpoint
swiftbar://opensystemreport
### Parameters
None
### Response
Writes and reveals `~/Library/Application Support/SwiftBar/Diagnostics/latest-system-report.txt`.
```
--------------------------------
### SwiftBar plugin file naming format
Source: https://github.com/swiftbar/swiftbar/blob/main/README.md
Required naming format for SwiftBar plugin files. The time part is optional and uses a number plus a duration modifier (ms, s, m, h, d). Example: date.1m.sh.
```text
{name}.{time}.{ext}
```
--------------------------------
### MenuLineParameters init(line:) parses plugin output line
Source: https://github.com/swiftbar/swiftbar/blob/main/_autodocs/api-reference/09-menu-line-parameters.md
Initializes from a raw plugin output line. Splits at the first '|' to separate title from parameters. If no '|' is found, the whole line becomes the title and params is empty.
```swift
// SwiftBar/MenuBar/MenuLineParameters.swift:22-31
init(line: String) {
guard let index = line.range(of: "|") else {
title = line
params = [:]
return
}
title = String(line[...index.lowerBound].dropLast())
params = MenuLineParameters.getParams(from: String(line[index.upperBound...]).trimmingCharacters(in: .whitespaces))
}
```
--------------------------------
### ModernLaunchAtLogin.migrateLegacyLoginItem()
Source: https://github.com/swiftbar/swiftbar/blob/main/_autodocs/api-reference/19-launch-at-login.md
Function to migrate the legacy login item.
```APIDOC
## ModernLaunchAtLogin.migrateLegacyLoginItem()
### Description
Migrates the legacy login item to the modern SMAppService registration. Called from `AppDelegate.applicationDidFinishLaunching`. Serialized on a service queue and nudges the observable when migration succeeds.
### Method
Function
### Endpoint
`ModernLaunchAtLogin.migrateLegacyLoginItem()`
### Parameters
None
### Response
None
### Example
```swift
ModernLaunchAtLogin.migrateLegacyLoginItem()
```
```
--------------------------------
### ModernLaunchAtLogin.isEnabled
Source: https://github.com/swiftbar/swiftbar/blob/main/_autodocs/api-reference/19-launch-at-login.md
Programmatic read/write access to the launch-at-login setting.
```APIDOC
## Property: ModernLaunchAtLogin.isEnabled
### Description
Read/write access to the launch-at-login setting. Setting this property updates the OS-level registration.
### Type
Bool
### Example
```swift
ModernLaunchAtLogin.isEnabled = true
let current = ModernLaunchAtLogin.isEnabled
```
```
--------------------------------
### Retry policy with wakeRefreshRetryDelay
Source: https://github.com/swiftbar/swiftbar/blob/main/_autodocs/api-reference/16-plugin-utilities.md
Example calls to wakeRefreshRetryDelay showing the retry delay for different reasons and failed attempt counts. The comments indicate the returned delay in seconds, and that a MenuAction reason returns nil to fail fast.
```swift
wakeRefreshRetryDelay(reason: .WakeFromSleep, failedAttempts: 1) // 2 s
wakeRefreshRetryDelay(reason: .WakeFromSleep, failedAttempts: 3) // 8 s
wakeRefreshRetryDelay(reason: .MenuAction, failedAttempts: 1) // nil — fail fast
```
--------------------------------
### Launch-at-login enums
Source: https://github.com/swiftbar/swiftbar/blob/main/_autodocs/types.md
Two enums used for launch-at-login migration and registration status. LegacyMigrationOutcome tracks migration results, while MainAppRegistration indicates whether the main app is enabled, requires approval, or is not registered.
```swift
// line 216
enum LegacyMigrationOutcome: Equatable {
case notNeeded
case migrated
case registrationFailed
case pendingApproval
case unregistrationFailed
}
// line 225
enum MainAppRegistration: Equatable {
case enabled
case requiresApproval
case notRegistered
}
```
--------------------------------
### AppDelegate instantiation in main.swift
Source: https://github.com/swiftbar/swiftbar/blob/main/_autodocs/api-reference/14-app-shared.md
Creates the AppDelegate instance and sets it as the application delegate before NSApplicationMain.
```swift
// SwiftBar/main.swift:3
let delegate = AppDelegate()
NSApplication.shared.delegate = delegate
_ = NSApplicationMain(CommandLine.argc, CommandLine.unsafeArgv)
```
--------------------------------
### Import plugin from URL with completion handler
Source: https://github.com/swiftbar/swiftbar/blob/main/_autodocs/api-reference/08-plugin-manager.md
Imports a plugin from a URL and handles the result asynchronously. The completion handler receives a Result where success sets installStatus to .Installed and failure sets it to .Failed, with the error being a PluginManager.ImportPluginError (.badURL or .importFail).
```swift
delegate.pluginManager.importPlugin(from: url) { result in
switch result {
case .success:
installStatus = .Installed
case .failure(let error):
// error is PluginManager.ImportPluginError — .badURL or .importFail
installStatus = .Failed
}
}
```
--------------------------------
### Info.plist for bundle appearance
Source: https://github.com/swiftbar/swiftbar/blob/main/README-PACKAGED-PLUGINS.md
XML property list that makes the plugin appear as a bundle in Finder with a custom icon. Place it in Contents/Info.plist. Includes keys for bundle identifier, name, type, and version.
```xml
CFBundleIdentifier
com.yourname.swiftbar.weather
CFBundleName
Weather
CFBundlePackageType
BNDL
CFBundleVersion
1.0
CFBundleShortVersionString
1.0
LSTypeIsPackage
```
--------------------------------
### Probe entry point before constructing PackagedPlugin
Source: https://github.com/swiftbar/swiftbar/blob/main/_autodocs/api-reference/06-packaged-plugin.md
Probes a package directory with PackagedPlugin.findMainExecutable(in:) before constructing a PackagedPlugin. The guard fails for non-loadable packages, and the initializer returns nil if the package is invalid.
```swift
let pkg = URL(fileURLWithPath: "/path/to/tools.swiftbar")
guard PackagedPlugin.findMainExecutable(in: pkg) != nil else {
// not a loadable packaged plugin
}
let plugin = PackagedPlugin(packageDirectory: pkg) // nil if invalid
```
--------------------------------
### PreferencesStore init() method
Source: https://github.com/swiftbar/swiftbar/blob/main/_autodocs/api-reference/12-preferences-store.md
Initializes the store by reading all preference values from UserDefaults using the PreferencesKeys enum. Sets default values for terminal, shell, and other settings when keys are missing. The shortcutsPlugins property is decoded from a PropertyListDecoder.
```swift
// SwiftBar/PreferencesStore.swift:100-140
init() {
pluginDirectoryPath = PreferencesStore.getValue(key: .PluginDirectory) as? String
shortcutsFolder = PreferencesStore.getValue(key: .ShortcutsFolder) as? String ?? ""
disabledPlugins = PreferencesStore.getValue(key: .DisabledPlugins) as? [PluginID] ?? []
terminal = .Terminal
shell = .Bash
swiftBarIconIsHidden = PreferencesStore.getValue(key: .HideSwiftBarIcon) as? Bool ?? false
includeBetaUpdates = PreferencesStore.getValue(key: .IncludeBetaUpdates) as? Bool ?? false
collectCrashReports = PreferencesStore.getValue(key: .CollectCrashReports) as? Bool ?? true
dimOnManualRefresh = PreferencesStore.getValue(key: .DimOnManualRefresh) as? Bool ?? true
stealthMode = PreferencesStore.getValue(key: .StealthMode) as? Bool ?? false
shortcutsPlugins = { ... PropertyListDecoder ... }()
// saved Terminal/Shell re-applied when parsable
}
```
--------------------------------
### Run a shortcut as a plugin
Source: https://github.com/swiftbar/swiftbar/blob/main/_autodocs/api-reference/18-shortcuts-manager.md
Runs a shortcut by name and renders its text output as plugin markup. The output is optional and may be nil if the shortcut fails.
```swift
let out = try? ShortcutsManager.shared.runShortcut(shortcut: "SwiftBar: Fake Weather")
if let out {
renderMenu(out) // shortcut text output is plugin markup
}
```
--------------------------------
### swiftbar://enableplugin
Source: https://github.com/swiftbar/swiftbar/blob/main/_autodocs/endpoints.md
Enables a plugin.
```APIDOC
## swiftbar://enableplugin
### Description
Enables a plugin.
### Method
URL Scheme
### Endpoint
swiftbar://enableplugin
### Parameters
#### Query Parameters
- **name** (string) - Optional - Plugin name or ID.
- **plugin** (string) - Optional - Plugin name or ID (interchangeable with `name`).
### Response
Enables the plugin. No-op when the plugin is not found.
```
--------------------------------
### Create ExecutablePlugin and refresh on demand
Source: https://github.com/swiftbar/swiftbar/blob/main/_autodocs/api-reference/02-executable-plugin.md
Constructs an ExecutablePlugin from a script URL, which triggers a .FirstLaunch refresh. To refresh later, call refresh(reason:) on the main queue.
```swift
let scriptURL = URL(fileURLWithPath: "/Users/me/Documents/SwiftBar/date.1m.sh")
let plugin = ExecutablePlugin(fileURL: scriptURL) // fires .FirstLaunch refresh
// Later — refresh on demand (must be on the main queue)
DispatchQueue.main.async {
plugin.refresh(reason: .MenuAction)
}
```
--------------------------------
### importPlugin(from:completion:)
Source: https://github.com/swiftbar/swiftbar/blob/main/_autodocs/api-reference/08-plugin-manager.md
Imports a plugin from a URL with completion handling. The completion returns a Result with success or a PluginManager.ImportPluginError.
```APIDOC
## importPlugin(from:completion:)
### Description
Imports a plugin from a URL with completion handling.
### Method
importPlugin
### Parameters
- **url** (URL) - Required - The URL to import the plugin from.
- **completion** (Result) - Required - Completion handler with success or failure.
### Request Example
```swift
delegate.pluginManager.importPlugin(from: url) { result in
switch result {
case .success:
installStatus = .Installed
case .failure(let error):
// error is PluginManager.ImportPluginError — .badURL or .importFail
installStatus = .Failed
}
}
```
### Response
No direct return value; use the completion handler.
### Error Handling
- **PluginManager.ImportPluginError.badURL** - The URL is invalid.
- **PluginManager.ImportPluginError.importFail** - The import operation failed.
```
--------------------------------
### Parsing a full markup line
Source: https://github.com/swiftbar/swiftbar/blob/main/_autodocs/api-reference/09-menu-line-parameters.md
Shows how to parse a markup line into MenuLineParameters and access title, params, color, and font.
```swift
let params = MenuLineParameters(line: "Battery: 78% | color=red,orange icon | font=Menlo size=12")
params.title // "Battery: 78%"
params.params["color"] // "red,orange"
params.color // NSColor? — the theme-appropriate half
params.font // "Menlo"
```
--------------------------------
### PackagedPlugin initializer with package directory validation
Source: https://github.com/swiftbar/swiftbar/blob/main/_autodocs/api-reference/06-packaged-plugin.md
Initializes a packaged plugin from a `.swiftbar` directory URL. Returns nil when the directory is not a valid SwiftBar package (must end with `.swiftbar`), logging an error via os_log. The `createSupportDirectories` parameter defaults to true.
```swift
// SwiftBar/Plugin/PackagedPlugin.swift:55-100 (excerpt)
/// Initialize with a `.swiftbar` directory URL.
init?(packageDirectory: URL, createSupportDirectories: Bool = true) {
guard packageDirectory.isSwiftBarPackage else {
os_log("Directory %{public}@ is not a valid packaged plugin (must end with .swiftbar)",
log: Log.plugin, type: .error, packageDirectory.path)
return nil
}
self.packageDirectory = packageDirectory
name = packageDirectory.lastPathComponent.replacingOccurrences(of: ".swiftbar", with: "")
}
```
--------------------------------
### ModernLaunchAtLogin.observable
Source: https://github.com/swiftbar/swiftbar/blob/main/_autodocs/api-reference/19-launch-at-login.md
An ObservableObject that publishes the launch-at-login setting, emitting objectWillChange before every mutation. Bind this from SwiftUI to toggle the setting.
```APIDOC
## Observable: ModernLaunchAtLogin.observable
### Description
An ObservableObject that publishes the launch-at-login setting. Bind this from SwiftUI to toggle the setting; `objectWillChange` is emitted before every mutation.
### Properties
- **isEnabled** (Bool) - Read/write access to the launch-at-login setting. Getting returns the current value; setting updates it and emits `objectWillChange`.
### Example
```swift
ModernLaunchAtLogin.observable.$isEnabled.receive(on: RunLoop.main).sink { value in
// re-render when the OS-level registration changes
}
```
```
--------------------------------
### Catching and switching on RunShortcutError
Source: https://github.com/swiftbar/swiftbar/blob/main/_autodocs/errors.md
Shows how to catch and handle RunShortcutError. The catch block rethrows non-RunShortcutError errors, then switches on errorReason to handle each failure case. Comments suggest appropriate actions: grant accessibility permission, verify the shortcut name, or check the shortcut output.
```swift
do { let out = try manager.runShortcut(shortcut: name) }
catch { guard let err = error as? RunShortcutError else { throw error } }
switch err.errorReason {
case .NoPermissions: // grant Shortcuts accessibility permission
case .ShortcutNotFound: // wrong name — check ShortcutsManager.shortcuts
case .NoShortcutOutput: // shortcut returned nothing
case .CantParseShortcutOutput:// returned a non-list value
}
```
--------------------------------
### swiftbar://copysystemreport
Source: https://github.com/swiftbar/swiftbar/blob/main/_autodocs/endpoints.md
Copies the latest system report to the pasteboard.
```APIDOC
## swiftbar://copysystemreport
### Description
Copies the latest system report to the pasteboard.
### Method
URL Scheme
### Endpoint
swiftbar://copysystemreport
### Parameters
None
### Response
Copies the latest system report to the pasteboard.
```
--------------------------------
### Handle importPlugin result in UI
Source: https://github.com/swiftbar/swiftbar/blob/main/_autodocs/errors.md
Shows how the repository UI catches the import result. On success sets installStatus to .Installed; on failure sets it to .Failed, with ImportPluginError as the Result's failure value.
```swift
delegate.pluginManager.importPlugin(from: url) { result in
switch result {
case .success: installStatus = .Installed
case .failure: installStatus = .Failed // ImportPluginError is the Result's failure value
}
}
```
--------------------------------
### Read system environment for debugging
Source: https://github.com/swiftbar/swiftbar/blob/main/_autodocs/api-reference/13-environment.md
Reads the system environment and merges it with the plugin's environment, then formats the result as a sorted, newline-separated string for debugging. This mirrors the Debug view's "Print SwiftBar ENV" action.
```swift
let swiftbarEnv = Environment.shared.systemEnvStr.merging(plugin.env) { current, _ in current }
let debugString = swiftbarEnv.map { "\($0.key) = \($0.value)" }.sorted().joined(separator: "\n")
```
--------------------------------
### Run script with full options
Source: https://github.com/swiftbar/swiftbar/blob/main/_autodocs/api-reference/15-run-script.md
Runs a script via Process.launchScript with merged environment variablesholistic merging precedence: given env wins over system env but loses to parent process environment. Supports working directory, bash wrapping, streaming output, and stdin pipe. Throws ShellOutError on failure.
```swift
// SwiftBar/Utility/RunScript.swift:85-96
/// Launches a script and returns its stdout/stderr output.
///
/// - Parameter workingDirectory: If non-nil, sets `Process.currentDirectoryURL`
/// so the script runs with this as its working directory (used by packaged plugins).
@discardableResult func runScript(to command: String,
args: [String] = [],
process: Process = Process(),
env: [String: String] = [:],
workingDirectory: String? = nil,
runInBash: Bool = true,
streamOutput: Bool = false,
stdinPipe: Pipe? = nil,
onOutputUpdate: @escaping (String?) -> Void = { _ in }) throws -> (out: String, err: String?)
{
let swiftbarEnv = sharedEnv.systemEnvStr.merging(env) { _, new in new }
process.environment = swiftbarEnv.merging(ProcessInfo.processInfo.environment) { current, _ in current }
if let workingDirectory {
process.currentDirectoryURL = URL(fileURLWithPath: workingDirectory)
}
return try process.launchScript(with: command, args: args, runInBash: runInBash, streamOutput: streamOutput, stdinPipe: stdinPipe, onOutputUpdate: onOutputUpdate)
}
```
--------------------------------
### RunPluginOperation init(plugin:queue:reason:timerGeneration:failedAttempts:retryDelay:)
Source: https://github.com/swiftbar/swiftbar/blob/main/_autodocs/api-reference/16-plugin-utilities.md
Initializes a RunPluginOperation. Captures the refresh reason and timer generation at creation so retries reuse them and stale retries can be rejected. The retryDelay defaults to wakeRefreshRetryDelay(reason:failedAttempts:).
```swift
// SwiftBar/Utility/PluginUtilities.swift:84-101
init(plugin: T,
queue: OperationQueue?,
reason: PluginRefreshReason? = nil,
timerGeneration: UInt? = nil,
failedAttempts: Int = 0,
retryDelay: @escaping (PluginRefreshReason, Int) -> TimeInterval? = wakeRefreshRetryDelay(reason:failedAttempts:))
{
self.plugin = plugin
self.queue = queue
refreshReason = reason ?? plugin.lastRefreshReason
self.failedAttempts = failedAttempts
self.retryDelay = retryDelay
// A retry inherits the generation captured at chain start; reading
// the current value here could adopt a newer refresh cycle's
// generation and let a stale retry pass the currency check.
scheduledTimerGeneration = timerGeneration ?? (plugin as? TimerArmingPlugin)?.timerGeneration
super.init()
}
```
--------------------------------
### ModernLaunchAtLogin.Toggle
Source: https://github.com/swiftbar/swiftbar/blob/main/_autodocs/api-reference/19-launch-at-login.md
A ready-made SwiftUI toggle bound to ModernLaunchAtLogin.observable. Provides multiple initializers for custom labels, localized string keys, plain strings, or a default label.
```APIDOC
## Toggle: ModernLaunchAtLogin.Toggle
### Description
A SwiftUI toggle view bound to `ModernLaunchAtLogin.observable`. On macOS < 13 the toggle renders disabled with help text `"Launch at login requires macOS 13.0 or later"`.
### Initializers
- `public init(@ViewBuilder label: () -> Label)` - Custom-label view builder.
- `public init(_ titleKey: LocalizedStringKey)` - Label from a localized string key.
- `public init(_ title: some StringProtocol)` - Label from a string.
- `public init()` - Default label `"Launch at login"`.
### Example
```swift
SettingsPaneRow(title: Localizable.Preferences.LaunchAtLogin.localized) {
ModernLaunchAtLogin.Toggle {
Text(Localizable.Preferences.LaunchAtLogin.localized)
}
.labelsHidden()
}
```
```
--------------------------------
### Add a PersistentShortcutPlugin
Source: https://github.com/swiftbar/swiftbar/blob/main/_autodocs/api-reference/04-shortcut-plugin.md
Creates a persistent shortcut plugin with an ID, name, shortcut, repeat string, and cron string, then adds it to the plugin manager. This persists the plugin and reloads it.
```swift
let plugin = PersistentShortcutPlugin(
id: UUID().uuidString,
name: "My Weather",
shortcut: "SwiftBar: Fake Weather",
repeatString: "5m",
cronString: ""
)
delegate.pluginManager.addShortcutPlugin(plugin: plugin) // persists + reloads
```
--------------------------------
### swiftbar://addplugin
Source: https://github.com/swiftbar/swiftbar/blob/main/_autodocs/endpoints.md
Adds a plugin from a URL.
```APIDOC
## swiftbar://addplugin
### Description
Adds a plugin from a URL.
### Method
URL Scheme
### Endpoint
swiftbar://addplugin
### Parameters
#### Query Parameters
- **src** (URL) - Required - URL to the plugin file.
### Response
Downloads/copies the file into the plugin folder, `chmod +x`, then loads it.
```
--------------------------------
### ModernLaunchAtLogin.migrateLegacyLoginItem(isLegacyEnabled:mainAppRegistration:registerMain:unregisterLegacy:)
Source: https://github.com/swiftbar/swiftbar/blob/main/_autodocs/api-reference/19-launch-at-login.md
Function to perform legacy login item migration with injectable dependencies.
```APIDOC
## ModernLaunchAtLogin.migrateLegacyLoginItem(isLegacyEnabled:mainAppRegistration:registerMain:unregisterLegacy:)
### Description
Performs the migration logic with injectable dependencies for testing. Registers the replacement before dropping the legacy registration to never lose launch-at-login. Reports outcomes for pending approval or failures.
### Method
Function
### Endpoint
`ModernLaunchAtLogin.migrateLegacyLoginItem(isLegacyEnabled:mainAppRegistration:registerMain:unregisterLegacy:)`
### Parameters
- **isLegacyEnabled** (Bool) - Required - Whether the legacy helper is enabled.
- **mainAppRegistration** (() -> MainAppRegistration) - Required - Closure returning the current main app registration state.
- **registerMain** (() throws -> Void) - Required - Closure to register the main app.
- **unregisterLegacy** (() throws -> Void) - Required - Closure to unregister the legacy helper.
### Response
#### Return Value
- **LegacyMigrationOutcome** - The outcome of the migration (e.g., `.migrated`, `.registrationFailed`, `.pendingApproval`).
### Example
```swift
let outcome = ModernLaunchAtLogin.migrateLegacyLoginItem(
isLegacyEnabled: true,
mainAppRegistration: { .notRegistered },
registerMain: { try SMAppService.mainApp.register() },
unregisterLegacy: { try SMAppService.loginItem(identifier: legacyHelperIdentifier).unregister() }
)
```
```
--------------------------------
### swiftbar://notify
Source: https://github.com/swiftbar/swiftbar/blob/main/_autodocs/endpoints.md
Shows a system notification.
```APIDOC
## swiftbar://notify
### Description
Shows a system notification.
### Method
URL Scheme
### Endpoint
swiftbar://notify
### Parameters
#### Query Parameters
- **plugin** (string) - Required - Plugin name or ID.
- **name** (string) - Required - Plugin name or ID (interchangeable with `plugin`).
- **title** (string) - Optional - Notification title.
- **subtitle** (string) - Optional - Notification subtitle.
- **body** (string) - Optional - Notification body.
- **href** (URL) - Optional - URL opened on click.
- **silent** (boolean) - Optional - Set to `true` to disable sound.
- Additional query parameters become click action parameters (e.g., `bash=` or `href=`).
### Response
A system notification thread-grouped by plugin id, carrying `pluginID` (+ `url`, `command`) in `userInfo`.
```
--------------------------------
### ShortcutsManager.runShortcut(shortcut:)
Source: https://github.com/swiftbar/swiftbar/blob/main/_autodocs/api-reference/18-shortcuts-manager.md
Runs a shortcut by name and returns its text output as plugin markup. This is the method used by `ShortcutPlugin.invoke` to execute shortcuts as plugins.
```APIDOC
## ShortcutsManager.runShortcut(shortcut:)
### Description
Runs a shortcut by name and returns its text output as plugin markup. This is the method used by `ShortcutPlugin.invoke` to execute shortcuts as plugins.
### Method
runShortcut
### Signature
`func runShortcut(shortcut: String) throws -> String`
### Parameters
- **shortcut** (String) - Required - The name of the shortcut to run.
### Return Value
- **String** - The text output of the shortcut, which is plugin markup.
### Throws
- **RunShortcutError** - An error indicating why the shortcut failed to run.
### Example
```swift
let out = try? ShortcutsManager.shared.runShortcut(shortcut: "SwiftBar: Fake Weather")
if let out {
renderMenu(out) // shortcut text output is plugin markup
}
```
### Error Handling
```swift
do {
let out = try ShortcutsManager.shared.runShortcut(shortcut: "Missing")
} catch {
guard let err = error as? RunShortcutError else { throw error }
switch err.errorReason {
case .NoPermissions:
// grant Shortcuts accessibility permission
case .ShortcutNotFound:
// rename or re-add the plugin
case .NoShortcutOutput:
// the shortcut ran but returned nothing
case .CantParseShortcutOutput:
// the shortcut returned a non-text value
}
os_log("Shortcut failed: %{public}@", log: Log.plugin, type: .error, err.message)
}
```
```
--------------------------------
### struct Agent with cache-first run method
Source: https://github.com/swiftbar/swiftbar/blob/main/_autodocs/api-reference/20-plugin-repository.md
Defines the Agent struct used for network requests. The run method performs cache-first fetching: requests with .returnCacheDataElseLoad read from URLCache.shared first; otherwise the download is decoded, stored into the cache as CachedURLResponse, and published. All values are received on DispatchQueue.main.
```swift
// SwiftBar/UI/Plugin Repository/PluginRepositoryAPI.swift:7
struct Agent {
let session = URLSession.shared
struct Response {
let value: T
let response: URLResponse
}
func run(_ request: URLRequest, _ decoder: JSONDecoder = JSONDecoder()) -> AnyPublisher, Error>
}
```
--------------------------------
### Environment systemEnv and sleep/wake hooks (Swift)
Source: https://github.com/swiftbar/swiftbar/blob/main/_autodocs/api-reference/13-environment.md
Initializes system environment variables for SwiftBar, including version, build, plugin path, and OS version. The systemEnvStr computed property dynamically resolves the plugin directory path at access time. The init() records the launch time, and updateSleepTime(date:) updates the sleep time.
```swift
// SwiftBar/Utility/Environment.swift:36-52 (excerpt)
private var systemEnv: [Variables: String] = [
.swiftBar: "1",
.swiftBarVersion: Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "",
.swiftBarBuild: Bundle.main.infoDictionary?["CFBundleVersion"] as? String ?? "",
.swiftBarPluginsPath: PreferencesStore.shared.pluginDirectoryPath ?? "",
.osVersionMajor: String(ProcessInfo.processInfo.operatingSystemVersion.majorVersion),
.osVersionMinor: String(ProcessInfo.processInfo.operatingSystemVersion.minorVersion),
.osVersionPatch: String(ProcessInfo.processInfo.operatingSystemVersion.patchVersion),
]
var systemEnvStr: [String: String] {
var env = Dictionary(uniqueKeysWithValues:
systemEnv.map { key, value in (key.rawValue, value) })
// Always resolve plugin directory path dynamically so it reflects the current value,
// not the potentially stale value captured at init time.
env[Variables.swiftBarPluginsPath.rawValue] = PreferencesStore.shared.pluginDirectoryPath ?? ""
return env
}
init() {
systemEnv[.swiftBarLaunchTime] = dateFormatter.string(from: NSDate.now)
}
func updateSleepTime(date: Date) {
systemEnv[.swiftBarSleepTime] = dateFormatter.string(from: date)```json // (invalid JSON, see below for valid JSON)```json ong>json
{
```
--------------------------------
### Configure SwiftBar hidden preferences with defaults write
Source: https://github.com/swiftbar/swiftbar/blob/main/README.md
Use these `defaults write` commands to configure SwiftBar preferences that are not exposed in the UI. Each command sets a boolean preference: StealthMode hides the menu item when all plugins are disabled, DisableBashWrapper disables wrapping plugins in Bash, MakePluginExecutable disables auto chmod +x, PluginDeveloperMode enables editing in Preferences -> Plugins, PluginDebugMode enables the Plugin Debug View, and StreamablePluginDebugOutput enables debug output for Streamable plugins.
```bash
defaults write com.ameba.SwiftBar StealthMode -bool YES
```
```bash
defaults write com.ameba.SwiftBar DisableBashWrapper -bool YES
```
```bash
defaults write com.ameba.SwiftBar MakePluginExecutable -bool NO
```
```bash
defaults write com.ameba.SwiftBar PluginDeveloperMode -bool YES
```
```bash
defaults write com.ameba.Swiftbar PluginDebugMode -bool YES
```
```bash
defaults write com.ameba.SwiftBar StreamablePluginDebugOutput -bool YES
```
--------------------------------
### Set metadata for binary plugins using xattr
Source: https://github.com/swiftbar/swiftbar/blob/main/README.md
For binary plugins, metadata can be added as an extended file attribute. The command writes the base64-encoded content of metadata.txt to the plugin file's xattr.
```bash
xattr -w "com.ameba.SwiftBar" "$(cat metadata.txt | base64)"
```
--------------------------------
### Render image= parameter as NSImage
Source: https://github.com/swiftbar/swiftbar/blob/main/_autodocs/api-reference/23-ns-extensions.md
Used to render the 'image=' or 'sfimage=' parameters of a menu line, as `MenuLineParameters.getImage` does. Creates an `NSImage` from the parameter string (with `isTemplate: false`) and returns a resized copy of 32x32 points.
```swift
let image = NSImage.createImage(from: params.params["image"], isTemplate: false)
image?.resizedCopy(w: 32, h: 32)
```
--------------------------------
### Toggle a ShortcutPlugin at Runtime
Source: https://github.com/swiftbar/swiftbar/blob/main/_autodocs/api-reference/04-shortcut-plugin.md
Creates a shortcut plugin from a persistent item and toggles it on or off via the plugin manager.
```swift
let live = ShortcutPlugin(persistentItem: stored)
delegate.pluginManager.togglePlugin(plugin: live) // enable <-> disable
```