cursor tracker start loop bug fix

This commit is contained in:
2026-09-01 22:26:25 +08:00
parent 3c1cc256c7
commit 304211a25f
4 changed files with 104 additions and 51 deletions
+6 -6
View File
@@ -15,7 +15,7 @@ pub async fn init(handle: &AppHandle) -> Result<(), String> {
.map_err(crate::db::command_error)?; .map_err(crate::db::command_error)?;
if settings.onboarding_done { if settings.onboarding_done {
start(handle); start(handle).await;
if cfg!(target_os = "macos") && !accessibility_permission_granted { if cfg!(target_os = "macos") && !accessibility_permission_granted {
crate::ui::onboarding::show_accessibility_page(handle)?; crate::ui::onboarding::show_accessibility_page(handle)?;
} }
@@ -25,7 +25,7 @@ pub async fn init(handle: &AppHandle) -> Result<(), String> {
Ok(()) Ok(())
} }
pub fn start(handle: &AppHandle) { pub async fn start(handle: &AppHandle) {
let state = handle.state::<ApplicationState>(); let state = handle.state::<ApplicationState>();
if state if state
.started .started
@@ -36,7 +36,7 @@ pub fn start(handle: &AppHandle) {
} }
crate::ui::init(handle); crate::ui::init(handle);
reconcile_cursor(handle); reconcile_cursor(handle).await;
} }
pub fn is_started(handle: &AppHandle) -> bool { pub fn is_started(handle: &AppHandle) -> bool {
@@ -46,12 +46,12 @@ pub fn is_started(handle: &AppHandle) -> bool {
.load(Ordering::Acquire) .load(Ordering::Acquire)
} }
pub fn reconcile_cursor(handle: &AppHandle) { pub async fn reconcile_cursor(handle: &AppHandle) {
if !is_started(handle) || !crate::macos::accessibility_permission_granted(handle) { if !is_started(handle) || !crate::macos::accessibility_permission_granted(handle) {
return; return;
} }
if let Err(error) = crate::cursor::start_tracking(handle) { if let Err(error) = crate::cursor::start_tracking(handle).await {
eprintln!("failed to initialize cursor tracking; will retry: {error}"); eprintln!("failed to initialize cursor tracking: {error}");
} }
} }
+81 -38
View File
@@ -8,8 +8,7 @@ use std::sync::RwLock;
use std::time::Duration; use std::time::Duration;
use tauri::{AppHandle, Manager}; use tauri::{AppHandle, Manager};
use tauri_specta::Event; use tauri_specta::Event;
use tokio::sync::mpsc; use tokio::sync::{mpsc, oneshot, watch};
use tokio::sync::watch;
#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Type)] #[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Type)]
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
@@ -104,13 +103,18 @@ fn current_position(handle: &AppHandle) -> Result<CursorPositions, String> {
// complains even when there's no external references. // complains even when there's no external references.
// Possibly because of `lazy_static!`. // Possibly because of `lazy_static!`.
// Just leave it public I guess. // Just leave it public I guess.
pub struct CursorTask { struct CursorTask {
stop_tx: watch::Sender<bool>, stop_tx: watch::Sender<bool>,
task: tauri::async_runtime::JoinHandle<()>, task: tauri::async_runtime::JoinHandle<()>,
} }
enum CursorTracker {
Starting,
Running(CursorTask),
}
lazy_static! { lazy_static! {
pub static ref CURSOR_TASK: Mutex<Option<CursorTask>> = Mutex::new(None); static ref CURSOR_TRACKER: Mutex<Option<CursorTracker>> = Mutex::new(None);
} }
pub fn init(app: &AppHandle) { pub fn init(app: &AppHandle) {
@@ -118,47 +122,71 @@ pub fn init(app: &AppHandle) {
} }
/// Starts cursor tracking after Accessibility permission is available. /// Starts cursor tracking after Accessibility permission is available.
pub fn start_tracking(app: &AppHandle) -> Result<(), String> { pub async fn start_tracking(app: &AppHandle) -> Result<(), String> {
println!("init_cursor_tracking called");
if !crate::macos::accessibility_permission_granted(app) { if !crate::macos::accessibility_permission_granted(app) {
return Err("macOS Accessibility permission has not been granted".to_owned()); return Err("macOS Accessibility permission has not been granted".to_owned());
} }
let mut tracker = match CURSOR_TASK.lock() {
Ok(tracker) => tracker,
Err(e) => {
return Err(format!("Failed to lock cursor tracker state: {e}"));
}
};
if tracker.is_some() {
println!("Cursor tracking already initialized");
return Ok(());
}
match current_position(app) {
Ok(positions) => update_cursor_position(app, positions),
Err(error) => eprintln!("Failed to resolve current cursor position: {error}"),
}
let (stop_tx, stop_rx) = watch::channel(false);
println!("Spawning cursor tracking task");
let primary_monitor = app let primary_monitor = app
.primary_monitor() .primary_monitor()
.map_err(|error| error.to_string())? .map_err(|error| error.to_string())?
.ok_or_else(|| "Failed to resolve primary monitor".to_owned())?; .ok_or_else(|| "Failed to resolve primary monitor".to_owned())?;
{
let mut tracker = CURSOR_TRACKER
.lock()
.map_err(|error| format!("Failed to lock cursor tracker state: {error}"))?;
if tracker.is_some() {
return Ok(());
}
*tracker = Some(CursorTracker::Starting);
}
println!("Initializing cursor tracking...");
match current_position(app) {
Ok(positions) => update_cursor_position(app, positions),
Err(error) => eprintln!("Failed to resolve current cursor position: {error}"),
}
let (stop_tx, stop_rx) = watch::channel(false);
let (ready_tx, ready_rx) = oneshot::channel();
let handle = app.clone(); let handle = app.clone();
let task = tauri::async_runtime::spawn(async move { let task = tauri::async_runtime::spawn(async move {
if let Err(e) = init_cursor_tracking_i(stop_rx, primary_monitor, handle).await { if let Err(e) = init_cursor_tracking_i(stop_rx, primary_monitor, handle, ready_tx).await {
println!("Failed to initialize cursor tracking: {}", e); println!("Failed to initialize cursor tracking: {}", e);
} }
}); });
*tracker = Some(CursorTask { stop_tx, task }); let startup = ready_rx
.await
.unwrap_or_else(|_| Err("Cursor tracking task stopped during initialization".to_owned()));
if let Err(error) = startup {
if let Ok(mut tracker) = CURSOR_TRACKER.lock()
&& matches!(*tracker, Some(CursorTracker::Starting))
{
*tracker = None;
}
let _ = task.await;
return Err(error);
}
let installed = {
let mut tracker = CURSOR_TRACKER
.lock()
.map_err(|error| format!("Failed to lock cursor tracker state: {error}"))?;
if matches!(*tracker, Some(CursorTracker::Starting)) {
*tracker = Some(CursorTracker::Running(CursorTask { stop_tx, task }));
true
} else {
false
}
};
if !installed {
return Err("Cursor tracking startup was cancelled".to_owned());
}
println!("EVENT: Cursor Tracker Enabled"); println!("EVENT: Cursor Tracker Enabled");
Ok(()) Ok(())
} }
@@ -297,7 +325,7 @@ mod tests {
pub async fn stop_cursor_tracking() { pub async fn stop_cursor_tracking() {
println!("stop_cursor_tracking called"); println!("stop_cursor_tracking called");
let tracker = match CURSOR_TASK.lock() { let tracker = match CURSOR_TRACKER.lock() {
Ok(mut tracker) => tracker.take(), Ok(mut tracker) => tracker.take(),
Err(e) => { Err(e) => {
println!("Failed to lock cursor tracker state: {}", e); println!("Failed to lock cursor tracker state: {}", e);
@@ -305,9 +333,16 @@ pub async fn stop_cursor_tracking() {
} }
}; };
let Some(tracker) = tracker else { let tracker = match tracker {
println!("Cursor tracking is not running"); Some(CursorTracker::Running(tracker)) => tracker,
return; Some(CursorTracker::Starting) => {
println!("Cursor tracking startup cancelled");
return;
}
None => {
println!("Cursor tracking is not running");
return;
}
}; };
if let Err(e) = tracker.stop_tx.send(true) { if let Err(e) = tracker.stop_tx.send(true) {
@@ -325,9 +360,8 @@ async fn init_cursor_tracking_i(
mut stop_rx: watch::Receiver<bool>, mut stop_rx: watch::Receiver<bool>,
monitor: tauri::Monitor, monitor: tauri::Monitor,
handle: AppHandle, handle: AppHandle,
ready_tx: oneshot::Sender<Result<(), String>>,
) -> Result<(), String> { ) -> Result<(), String> {
println!("Initializing cursor tracking...");
// Create a channel to decouple event generation (producer) from processing (consumer). // Create a channel to decouple event generation (producer) from processing (consumer).
// Capacity 100 is plenty for 500ms polling (2Hz). // Capacity 100 is plenty for 500ms polling (2Hz).
let (tx, mut rx) = mpsc::channel::<CursorPositions>(100); let (tx, mut rx) = mpsc::channel::<CursorPositions>(100);
@@ -345,8 +379,14 @@ async fn init_cursor_tracking_i(
println!("Cursor event consumer stopped (channel closed)"); println!("Cursor event consumer stopped (channel closed)");
}); });
let device_state = DeviceEventsHandler::new(Duration::from_millis(500)) let device_state = match DeviceEventsHandler::new(Duration::from_millis(500)) {
.ok_or("Failed to create device event handler (already running?)")?; Some(device_state) => device_state,
None => {
let error = "Failed to create device event handler (already running?)".to_owned();
let _ = ready_tx.send(Err(error.clone()));
return Err(error);
}
};
println!("Device event handler created successfully"); println!("Device event handler created successfully");
println!("Setting up mouse move handler for event broadcasting..."); println!("Setting up mouse move handler for event broadcasting...");
@@ -383,6 +423,9 @@ async fn init_cursor_tracking_i(
} }
}); });
ready_tx
.send(Ok(()))
.map_err(|_| "Cursor tracking startup was cancelled".to_owned())?;
println!("Mouse move handler registered - now broadcasting cursor events to all windows"); println!("Mouse move handler registered - now broadcasting cursor events to all windows");
// Keep the handler alive while tracking is enabled. // Keep the handler alive while tracking is enabled.
+16 -6
View File
@@ -49,11 +49,6 @@ pub fn accessibility_permission_granted(handle: &AppHandle) -> bool {
} }
async fn apply_permission_state(handle: &AppHandle, granted: bool) -> Result<bool, String> { async fn apply_permission_state(handle: &AppHandle, granted: bool) -> Result<bool, String> {
if handle.state::<AccessibilityPermissionState>().granted() == granted {
crate::application::reconcile_cursor(handle);
return Ok(false);
}
if !handle if !handle
.state::<AccessibilityPermissionState>() .state::<AccessibilityPermissionState>()
.replace(granted) .replace(granted)
@@ -64,7 +59,7 @@ async fn apply_permission_state(handle: &AppHandle, granted: bool) -> Result<boo
let status = crate::onboarding::emit_status(handle, &database).await?; let status = crate::onboarding::emit_status(handle, &database).await?;
if status.onboarding_done { if status.onboarding_done {
if granted { if granted {
crate::application::reconcile_cursor(handle); crate::application::reconcile_cursor(handle).await;
} else { } else {
crate::ui::onboarding::show_accessibility_page(handle)?; crate::ui::onboarding::show_accessibility_page(handle)?;
} }
@@ -106,3 +101,18 @@ pub async fn request_accessibility_permission(handle: AppHandle) -> Result<bool,
apply_permission_state(&handle, granted).await?; apply_permission_state(&handle, granted).await?;
Ok(granted) Ok(granted)
} }
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn permission_state_reports_only_actual_transitions() {
let state = AccessibilityPermissionState::new(false);
assert!(!state.replace(false));
assert!(state.replace(true));
assert!(!state.replace(true));
assert!(state.replace(false));
}
}
+1 -1
View File
@@ -84,7 +84,7 @@ pub async fn complete_onboarding(
.await .await
.map_err(db::command_error)?; .map_err(db::command_error)?;
emit_status(&handle, &database).await?; emit_status(&handle, &database).await?;
crate::application::start(&handle); crate::application::start(&handle).await;
Ok(()) Ok(())
} }