Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .agents/rules/objc-ffi.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ paths:
- "crates/openlogi-camera/**"
- "crates/openlogi-agent/src/activity_macos.rs"
- "crates/openlogi-agent/src/tray.rs"
- "crates/openlogi-agent/src/power_source/**"
- "crates/openlogi-agent/src/status_item.rs"
- "crates/openlogi-agent/src/lifecycle/armed_session.rs"
- "crates/openlogi-agent-core/src/watchers/camera.rs"
Expand All @@ -27,6 +28,7 @@ files; **keep this table in sync when you add or move one**:
| File | What it carries |
|---|---|
| `openlogi-agent/src/activity_macos.rs` | the device-I/O gate's levels: the `IOPMConnection` powerd subscription (hand-declared SPI, see below) and the `CGSessionCopyCurrentDictionary` console read |
| `openlogi-agent/src/power_source/macos/iokit.rs` | opt-in Batteries-widget publisher: `dlopen`/`dlsym` of private `IOPSCreatePowerSource` / `IOPSSetPowerSourceDetails` / `IOPSReleasePowerSource` |
| `openlogi-agent/src/status_item.rs` | safe `objc2` wrappers over `NSStatusItem` / `NSMenu` / `NSMenuItem` |
| `openlogi-agent/src/tray.rs` | the menu-bar semantics, `MenuTarget` + `SessionTarget` (`define_class!`), the Accessory `NSApplication` loop, the `NSWorkspace` session (fast-user-switch) notifications |
| `openlogi-agent-core/src/watchers/camera.rs` | the CoreMediaIO "camera is running" property read |
Expand Down Expand Up @@ -246,6 +248,8 @@ its single user. The current set, all deliberate:
`UCKeyTranslate` — `objc2-carbon` skips HIToolbox and `objc2-core-services`
skips CarbonCore. `UCKeyTranslate`'s lengths are `UniCharCount`, an
`unsigned long`: `usize`, not `u32`.
- `openlogi-agent/src/power_source/macos/iokit.rs`: private `IOPS*` power-source SPI
(experimental Batteries-widget integration).
- the `disclaim` crate: `responsibility_spawnattrs_setdisclaim` (private SPI).

`openlogi-camera`'s `AVAuthorizationStatus` integers remain on the
Expand All @@ -270,6 +274,9 @@ under a `SAFETY` comment. Where it currently lives on macOS:
- `agent/lifecycle/armed_session.rs` — `SessionGetInfo` (`objc2-security`,
`AuthSession`) and `sysctlbyname("kern.bootsessionuuid")`: two out-pointer reads
that identify the login session, so the dormancy gate can re-arm a crash respawn.
- `agent/power_source/macos/iokit.rs`: `dlopen`/`dlsym` of the private `IOPS*`
power-source functions and the three calls through them. A source's release
consumes it, so a handle cannot be released twice.
- `hook/macos.rs` — the whole tap (Core Graphics / Core Foundation C APIs),
`AXIsProcessTrusted[WithOptions]` with the two extern statics they need
(`kAXTrustedCheckOptionPrompt`, `kCFBooleanTrue`), and the `kern.sleeptime` /
Expand Down
4 changes: 2 additions & 2 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,7 @@ Feature coverage depends on what each device reports; the app shows only the con
| Window-manager actions (desktops, Mission Control, …) | Native | Native equivalents | GNOME, KDE (KWin), Hyprland; some macOS-only actions do nothing |
| Menu-bar / tray icon | ✓ | ✓ | — |
| Device controls in the menu-bar / tray menu | ✓ | — | — |
| [Receiver batteries in the Batteries widget](docs/CONFIGURATION.md#macos-batteries-widget) | Experimental | — | — |
| In-app updates | Sparkle | Built-in | Built-in |

## Install
Expand Down
40 changes: 39 additions & 1 deletion crates/openlogi-agent-core/src/observable.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
use openlogi_core::app::ForegroundApp;
use openlogi_core::brand::is_openlogi_foreground_id;
use openlogi_core::config::ConfigRevision;
use openlogi_core::device::{DeviceInventory, StandaloneDevice};
use openlogi_core::device::{BatteryWidgetStatus, DeviceInventory, StandaloneDevice};
use openlogi_hook::Hook;
use openlogi_ipc::{
AgentSnapshot, AgentStatus, FlowPairingPhase, FlowPeerStatus, FlowStatus, ForegroundApps,
Expand Down Expand Up @@ -73,6 +73,7 @@ impl ObservableState {
} else {
VirtualKeyboardStatus::Unsupported
},
battery_widget: BatteryWidgetStatus::Disabled,
},
inventory: Vec::new(),
standalone: Vec::new(),
Expand Down Expand Up @@ -181,6 +182,17 @@ impl ObservableState {
});
}

/// Publish the publisher's actual registry state, independently of inventory.
pub fn set_battery_widget(&self, status: BatteryWidgetStatus) {
self.update(|snapshot| {
if snapshot.status.battery_widget == status {
return false;
}
snapshot.status.battery_widget = status;
true
});
}

/// Publish the latest aggregate camera-use sample.
pub fn set_camera_active(&self, active: bool) {
self.update(|snapshot| {
Expand Down Expand Up @@ -462,6 +474,32 @@ mod tests {
assert_eq!(recent(&state), ["com.example.App"]);
}

#[test]
fn battery_widget_changes_wake_observers_without_an_inventory_change() {
use openlogi_core::device::BatteryWidgetStatus;

let state = state();
let mut rx = state.subscribe();
let active = BatteryWidgetStatus::Active {
published_devices: 2,
};
state.set_battery_widget(active.clone());
assert!(rx.has_changed().unwrap());
rx.borrow_and_update();

state.set_battery_widget(active);
assert!(!rx.has_changed().unwrap());

let failed = BatteryWidgetStatus::Failed {
published_devices: 1,
reason: "registration failed".into(),
};
state.set_battery_widget(failed.clone());
assert!(rx.has_changed().unwrap());
assert_eq!(state.snapshot().status.battery_widget, failed);
assert_eq!(state.snapshot().status.inventory, InventoryHealth::Scanning);
}

#[test]
fn a_repeated_enumeration_notifies_nobody() {
let state = state();
Expand Down
31 changes: 18 additions & 13 deletions crates/openlogi-agent-core/src/orchestrator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ use openlogi_core::config::{
};
use openlogi_core::device::{
BatteryInfo, Capabilities, ChangedOnLight, DeviceInventory, DeviceKind, LightCapabilities,
LightState, StandaloneDevice, prettify_codename,
LightState, StandaloneDevice,
};
use openlogi_core::device_order::{DeviceIdentity, DeviceStableId, PhysicalDeviceKey};
use openlogi_hid::{
Expand Down Expand Up @@ -667,6 +667,8 @@ impl SharedHandles {
/// Owns the config + device selection and keeps [`SharedHandles`] in sync.
pub struct Orchestrator {
config: Config,
/// Wakes runtime integrations after a configuration has been adopted.
config_changes: watch::Sender<()>,
devices: Vec<AgentDevice>,
current: usize,
current_app: Option<String>,
Expand Down Expand Up @@ -932,6 +934,7 @@ impl Orchestrator {
};
let orch = Self {
config,
config_changes: watch::channel(()).0,
devices: Vec::new(),
current: 0,
current_app: None,
Expand Down Expand Up @@ -1831,20 +1834,9 @@ impl Orchestrator {
) {
continue;
}
// The same precedence the tray and the GUI use: a user-assigned
// name, then the product name the settings app persisted, then the
// firmware codename.
let name = self
.config
.device_custom_name(&device.config_key)
.map(str::to_owned)
.or_else(|| {
self.config
.device_identity(&device.config_key)
.map(|identity| identity.display_name.trim().to_owned())
.filter(|name| !name.is_empty())
})
.or_else(|| device.codename.as_deref().map(prettify_codename));
.device_display_name(Some(&device.config_key), device.codename.as_deref());
info!(device = %device.config_key, ?battery, "announcing a low battery");
self.observable.notices().post(
NoticeKind::LowBattery {
Expand Down Expand Up @@ -2351,6 +2343,18 @@ impl Orchestrator {
previous != self.mouse_context().1
}

/// Borrow the live agent config (custom names, settings).
#[must_use]
pub fn config(&self) -> &Config {
&self.config
}

/// Subscribe to adopted configuration changes, including custom device names.
#[must_use]
pub fn subscribe_config_changes(&self) -> watch::Receiver<()> {
self.config_changes.subscribe()
}

/// Replace the config (after `config.toml` changed) and rebuild everything.
/// The file is one the agent did not see saved, as at startup or after a
/// hand edit (see [`ConfigSource::Loaded`]).
Expand Down Expand Up @@ -2463,6 +2467,7 @@ impl Orchestrator {
// Focused mode ignores pointer contexts, so the watcher parks; a
// switch back to pointer mode resumes it with an immediate query.
crate::watchers::pointer::set_profile_target(self.config.app_settings.mouse_profile_target);
self.config_changes.send_replace(());
self.changed_lights(&previous_lights)
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -151,3 +151,41 @@ fn equal_runtime_projection_does_not_wake_managers() {
.expect("publication remains open")
);
}

#[test]
fn config_reload_wakes_integrations_without_an_inventory_change() {
let mut orch = orchestrator(Config::default());
let mut changes = orch.subscribe_config_changes();
assert!(!changes.has_changed().unwrap());

let mut config = Config::default();
config.app_settings.macos_battery_widget = true;
orch.reload_config(config);
assert!(changes.has_changed().unwrap());
assert!(orch.config().app_settings.macos_battery_widget);
changes.borrow_and_update();

orch.reload_config(Config::default());
assert!(changes.has_changed().unwrap());
assert!(!orch.config().app_settings.macos_battery_widget);
}

#[test]
fn saved_config_reload_wakes_integrations_without_an_inventory_change() {
use openlogi_core::config::ConfigRevision;
use openlogi_ipc::SavedConfig;

let mut orch = orchestrator(Config::default());
let changes = orch.subscribe_config_changes();
let mut config = Config::default();
config.app_settings.macos_battery_widget = true;
let saved = SavedConfig {
revision: ConfigRevision::of("the GUI's save"),
chosen: Vec::new(),
};

orch.reload_saved_config(config, saved.revision, &saved);

assert!(changes.has_changed().unwrap());
assert!(orch.config().app_settings.macos_battery_widget);
}
1 change: 1 addition & 0 deletions crates/openlogi-agent/src/bin/mock_agent.rs
Original file line number Diff line number Diff line change
Expand Up @@ -911,6 +911,7 @@ fn agent_status() -> AgentStatus {
hid_open_failures: false,
secure_input: openlogi_ipc::SecureInput::Off,
virtual_keyboard: openlogi_ipc::VirtualKeyboardStatus::Unsupported,
battery_widget: openlogi_core::device::BatteryWidgetStatus::Disabled,
}
}

Expand Down
21 changes: 20 additions & 1 deletion crates/openlogi-agent/src/lifecycle.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ use tracing::{debug, info, warn};
use openlogi_ipc::ClientKind;

use self::transition::{Replacement, WatcherFleet};
use crate::power_source::PowerSources;
use crate::shutdown::{self, ShutdownRequest, ShutdownRequests, ShutdownSignals};
use crate::startup::{self, Core, InputServices};
use crate::virtual_keyboard::VirtualKeyboard;
Expand Down Expand Up @@ -272,6 +273,7 @@ impl Wanted {
capture_mouse_events,
held_pointer: None,
virtual_keyboard,
power_sources: PowerSources::new(),
},
}
}
Expand Down Expand Up @@ -309,6 +311,8 @@ struct Running {
/// `CGEvent`s. The exit path releases it only after the action workers
/// that press keys stopped.
virtual_keyboard: VirtualKeyboard,
/// Opt-in Batteries-widget publisher for Bolt/Unifying accessories.
power_sources: PowerSources,
}

impl Armed {
Expand All @@ -329,6 +333,9 @@ impl Armed {
let (mut watchers, inventory_refresh) = startup::spawn_state_watchers(&running.shared);
let mut ring = running.inputs.ring.subscribe();

let config_changes = running.orchestrator.lock().await.subscribe_config_changes();
running.power_sources.watch_config(config_changes);
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved

info!("openlogi-agent started");
loop {
tokio::select! {
Expand All @@ -347,6 +354,9 @@ impl Armed {
(request, stopped) = running.hidpp_watchers.replacement_ready() => {
running.complete_replacement(request, stopped);
}
() = running.power_sources.wake() => {
running.reconcile_power_sources().await;
}
Some(event) = watchers.next() => {
running.apply_watcher(event, &inventory_refresh).await;
}
Expand Down Expand Up @@ -395,6 +405,13 @@ impl Armed {
}

impl Running {
/// Reconcile config, inventory and expiry through the publisher's single owner.
async fn reconcile_power_sources(&mut self) {
self.power_sources
.reconcile(&self.orchestrator, &self.observable)
.await;
}

/// Retire a terminal hook worker and publish that input capture is no
/// longer installed. The native callbacks have already been cleared, so
/// the interval before this check remains pass-through rather than
Expand Down Expand Up @@ -510,7 +527,7 @@ impl Running {
}

/// Fold one inventory-watcher event into the orchestrator.
async fn apply_inventory(&self, event: InventoryEvent, refresh: &InventoryRefresh) {
async fn apply_inventory(&mut self, event: InventoryEvent, refresh: &InventoryRefresh) {
match event {
InventoryEvent::Snapshot {
inventories,
Expand All @@ -530,6 +547,7 @@ impl Running {
}
let confirm_settings = orchestrator.needs_reapply_confirmation();
drop(orchestrator);
self.reconcile_power_sources().await;
if confirm_settings {
refresh.request_settings_confirmation();
}
Expand Down Expand Up @@ -845,6 +863,7 @@ impl Running {
reason: &str,
tray_guard: Option<tokio::sync::oneshot::Sender<()>>,
) -> ! {
self.power_sources.clear_all();
shutdown::release_hook_and_exit(
self.hook.take(),
&mut self.inputs,
Expand Down
1 change: 1 addition & 0 deletions crates/openlogi-agent/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ mod resume_windows;
// generates itself, hence the relative path — see
// `tests::the_shared_catalog_is_wired_up` for why a wrong path is silent.
rust_i18n::i18n!("../openlogi-ui/locales", fallback = "en");
mod power_source;
mod server;
mod shutdown;
mod startup;
Expand Down
18 changes: 18 additions & 0 deletions crates/openlogi-agent/src/power_source.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
//! Opt-in publication of receiver accessory batteries to the macOS Batteries
//! widget. One module per OS, both exposing the same [`PowerSources`] API:
//!
//! - **macOS** ([`macos`]): the publisher policy and its private IOKit backend.
//! - **Other platforms** ([`unsupported`]): a no-op that never wakes the run loop.
//!
//! The lifecycle drives it through [`PowerSources::wake`] and
//! [`PowerSources::reconcile`] without platform checks of its own.

#[cfg(target_os = "macos")]
mod macos;
#[cfg(not(target_os = "macos"))]
mod unsupported;

#[cfg(target_os = "macos")]
pub(crate) use macos::PowerSources;
#[cfg(not(target_os = "macos"))]
pub(crate) use unsupported::PowerSources;
Loading
Loading