mirror of
https://github.com/infinilabs/coco-app.git
synced 2025-12-24 07:19:23 +01:00
Compare commits
3 Commits
selection-
...
abled-1215
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
06da6c941e | ||
|
|
26386ec295 | ||
|
|
cc72c59894 |
1
.vscode/settings.json
vendored
1
.vscode/settings.json
vendored
@@ -59,7 +59,6 @@
|
||||
"serde",
|
||||
"Shadcn",
|
||||
"swatinem",
|
||||
"systempreferences",
|
||||
"tailwindcss",
|
||||
"tauri",
|
||||
"thiserror",
|
||||
|
||||
@@ -36,6 +36,8 @@
|
||||
<string>Coco AI needs access to your microphone for voice input and audio recording features.</string>
|
||||
<key>NSCameraUsageDescription</key>
|
||||
<string>Coco AI requires camera access for scanning documents and capturing images.</string>
|
||||
<key>NSCameraUseContinuityCameraDeviceType</key>
|
||||
<true/>
|
||||
<key>NSSpeechRecognitionUsageDescription</key>
|
||||
<string>Coco AI uses speech recognition to convert your voice into text for a hands-free experience.</string>
|
||||
<key>NSAppleEventsUsageDescription</key>
|
||||
@@ -43,4 +45,4 @@
|
||||
<key>NSAccessibility</key>
|
||||
<true/>
|
||||
</dict>
|
||||
</plist>
|
||||
</plist>
|
||||
|
||||
@@ -2,14 +2,12 @@ mod assistant;
|
||||
mod autostart;
|
||||
mod common;
|
||||
mod extension;
|
||||
mod macos;
|
||||
mod search;
|
||||
mod selection_monitor;
|
||||
mod server;
|
||||
mod settings;
|
||||
mod setup;
|
||||
mod shortcut;
|
||||
|
||||
// We need this in main.rs, so it has to be pub
|
||||
pub mod util;
|
||||
|
||||
@@ -208,10 +206,6 @@ pub fn run() {
|
||||
util::logging::app_log_dir,
|
||||
selection_monitor::set_selection_enabled,
|
||||
selection_monitor::get_selection_enabled,
|
||||
macos::permissions::check_accessibility_trusted,
|
||||
macos::permissions::open_accessibility_settings,
|
||||
macos::permissions::open_screen_recording_settings,
|
||||
macos::permissions::open_microphone_settings,
|
||||
])
|
||||
.setup(|app| {
|
||||
#[cfg(target_os = "macos")]
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
pub mod permissions;
|
||||
@@ -1,58 +0,0 @@
|
||||
#[tauri::command]
|
||||
pub fn check_accessibility_trusted() -> bool {
|
||||
cfg_if::cfg_if! {
|
||||
if #[cfg(target_os = "macos")] {
|
||||
let trusted = macos_accessibility_client::accessibility::application_is_trusted();
|
||||
log::info!(target: "coco_lib::permissions", "check_accessibility_trusted invoked: {}", trusted);
|
||||
trusted
|
||||
} else {
|
||||
log::info!(target: "coco_lib::permissions", "check_accessibility_trusted invoked on non-macOS: false");
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn open_accessibility_settings() {
|
||||
cfg_if::cfg_if! {
|
||||
if #[cfg(target_os = "macos")] {
|
||||
use std::process::Command;
|
||||
log::info!(target: "coco_lib::permissions", "open_accessibility_settings invoked");
|
||||
let _ = Command::new("open")
|
||||
.arg("x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility")
|
||||
.status();
|
||||
} else {
|
||||
// no-op on non-macOS
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn open_screen_recording_settings() {
|
||||
cfg_if::cfg_if! {
|
||||
if #[cfg(target_os = "macos")] {
|
||||
use std::process::Command;
|
||||
log::info!(target: "coco_lib::permissions", "open_screen_recording_settings invoked");
|
||||
let _ = Command::new("open")
|
||||
.arg("x-apple.systempreferences:com.apple.preference.security?Privacy_ScreenRecording")
|
||||
.status();
|
||||
} else {
|
||||
// no-op on non-macOS
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn open_microphone_settings() {
|
||||
cfg_if::cfg_if! {
|
||||
if #[cfg(target_os = "macos")] {
|
||||
use std::process::Command;
|
||||
log::info!(target: "coco_lib::permissions", "open_microphone_settings invoked");
|
||||
let _ = Command::new("open")
|
||||
.arg("x-apple.systempreferences:com.apple.preference.security?Privacy_Microphone")
|
||||
.status();
|
||||
} else {
|
||||
// no-op on non-macOS
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,6 @@
|
||||
/// Coordinates use logical (Quartz) points with a top-left origin.
|
||||
/// Note: `y` is flipped on the backend to match the frontend’s usage.
|
||||
use tauri::Emitter;
|
||||
use tauri::Manager;
|
||||
|
||||
#[derive(serde::Serialize, Clone)]
|
||||
struct SelectionEventPayload {
|
||||
@@ -15,7 +14,7 @@ use once_cell::sync::Lazy;
|
||||
use std::sync::Mutex;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
|
||||
/// Global toggle: selection monitoring enabled for this release.
|
||||
/// Global toggle: selection monitoring enabled by default.
|
||||
static SELECTION_ENABLED: AtomicBool = AtomicBool::new(true);
|
||||
|
||||
/// Ensure we only start the monitor thread once. Allows delayed start after
|
||||
@@ -25,9 +24,6 @@ static MONITOR_THREAD_STARTED: AtomicBool = AtomicBool::new(false);
|
||||
/// Guard to avoid spawning multiple permission watcher threads.
|
||||
#[cfg(target_os = "macos")]
|
||||
static PERMISSION_WATCHER_STARTED: AtomicBool = AtomicBool::new(false);
|
||||
/// Guard to avoid spawning multiple selection store watcher threads.
|
||||
#[cfg(target_os = "macos")]
|
||||
static SELECTION_STORE_WATCHER_STARTED: AtomicBool = AtomicBool::new(false);
|
||||
|
||||
/// Session flags for controlling macOS Accessibility prompts.
|
||||
#[cfg(target_os = "macos")]
|
||||
@@ -35,8 +31,6 @@ static SEEN_ACCESSIBILITY_TRUSTED_ONCE: AtomicBool = AtomicBool::new(false);
|
||||
#[cfg(target_os = "macos")]
|
||||
static LAST_ACCESSIBILITY_PROMPT: Lazy<Mutex<Option<std::time::Instant>>> =
|
||||
Lazy::new(|| Mutex::new(None));
|
||||
#[cfg(target_os = "macos")]
|
||||
static LAST_READ_WARN: Lazy<Mutex<Option<std::time::Instant>>> = Lazy::new(|| Mutex::new(None));
|
||||
|
||||
#[derive(serde::Serialize, Clone)]
|
||||
struct SelectionEnabledPayload {
|
||||
@@ -101,19 +95,7 @@ pub fn start_selection_monitor(app_handle: tauri::AppHandle) {
|
||||
use tauri::Emitter;
|
||||
|
||||
// Sync initial enabled state to the frontend on startup.
|
||||
// Prefer disk-persisted Zustand store if present
|
||||
#[cfg(target_os = "macos")]
|
||||
ensure_selection_store_bootstrap(&app_handle);
|
||||
if let Some(enabled) = read_selection_enabled_from_store(&app_handle) {
|
||||
log::info!(target: "coco_lib::selection_monitor", "initial selection-enabled loaded from store: {}", enabled);
|
||||
set_selection_enabled_internal(&app_handle, enabled);
|
||||
} else {
|
||||
log::warn!(target: "coco_lib::selection_monitor", "initial selection-enabled not found in store, falling back to in-memory flag");
|
||||
set_selection_enabled_internal(&app_handle, is_selection_enabled());
|
||||
}
|
||||
// Start a light watcher to keep SELECTION_ENABLED in sync with disk
|
||||
start_selection_store_watcher(app_handle.clone());
|
||||
log::info!(target: "coco_lib::selection_monitor", "selection store watcher started");
|
||||
set_selection_enabled_internal(&app_handle, is_selection_enabled());
|
||||
|
||||
// Accessibility permission is required to read selected text in the foreground app.
|
||||
// If not granted, prompt the user once; if still not granted, skip starting the watcher.
|
||||
@@ -299,13 +281,19 @@ pub fn start_selection_monitor(app_handle: tauri::AppHandle) {
|
||||
let mut stable_text = String::new();
|
||||
let mut stable_count = 0;
|
||||
let mut empty_count = 0;
|
||||
let mut loop_idx: u64 = 0;
|
||||
|
||||
loop {
|
||||
loop_idx = loop_idx.wrapping_add(1);
|
||||
let verbose = loop_idx % 50 == 0; // Log roughly every 1.5s (30ms * 50)
|
||||
|
||||
std::thread::sleep(Duration::from_millis(30));
|
||||
|
||||
// If disabled: do not read AX / do not show popup; hide if currently visible.
|
||||
if !is_selection_enabled() {
|
||||
log::debug!(target: "coco_lib::selection_monitor", "monitor loop: selection disabled");
|
||||
if verbose {
|
||||
println!("[SelectionMonitor] Disabled");
|
||||
}
|
||||
if popup_visible {
|
||||
let _ = app_handle.emit("selection-detected", "");
|
||||
popup_visible = false;
|
||||
@@ -320,6 +308,13 @@ pub fn start_selection_monitor(app_handle: tauri::AppHandle) {
|
||||
// system-wide focused element belongs to this process.
|
||||
let front_is_me = is_frontmost_app_me() || is_focused_element_me();
|
||||
|
||||
if verbose {
|
||||
println!(
|
||||
"[SelectionMonitor] Loop heartbeat. front_is_me={}",
|
||||
front_is_me
|
||||
);
|
||||
}
|
||||
|
||||
// When Coco is frontmost, disable detection but do NOT hide the popup.
|
||||
// Users may be clicking the popup; we must keep it visible.
|
||||
if front_is_me {
|
||||
@@ -332,9 +327,16 @@ pub fn start_selection_monitor(app_handle: tauri::AppHandle) {
|
||||
// Lightweight retries to smooth out transient AX focus instability.
|
||||
let selected_text = {
|
||||
// Up to 2 retries, 35ms apart.
|
||||
read_selected_text_with_retries(2, 35)
|
||||
read_selected_text_with_retries(2, 35, verbose)
|
||||
};
|
||||
|
||||
if verbose {
|
||||
println!(
|
||||
"[SelectionMonitor] read_selected_text result: {:?}",
|
||||
selected_text
|
||||
);
|
||||
}
|
||||
|
||||
match selected_text {
|
||||
Some(text) if !text.is_empty() => {
|
||||
empty_count = 0;
|
||||
@@ -444,6 +446,7 @@ fn ensure_accessibility_permission(app_handle: &tauri::AppHandle) -> bool {
|
||||
}
|
||||
|
||||
// Still not trusted — notify frontend and deep-link to settings.
|
||||
println!("[SelectionMonitor] Accessibility permission NOT granted. Opening System Settings...");
|
||||
let _ = app_handle.emit("selection-permission-required", true);
|
||||
log::debug!(target: "coco_lib::selection_monitor", "selection-permission-required emitted");
|
||||
|
||||
@@ -463,118 +466,6 @@ fn ensure_accessibility_permission(app_handle: &tauri::AppHandle) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
/// Resolve the path to the zustand store file `selection-store.json`.
|
||||
#[cfg(target_os = "macos")]
|
||||
fn selection_store_path(app_handle: &tauri::AppHandle) -> std::path::PathBuf {
|
||||
let mut dir = app_handle
|
||||
.path()
|
||||
.app_data_dir()
|
||||
.expect("failed to find the local dir");
|
||||
dir.push("zustand");
|
||||
dir.push("selection-store.json");
|
||||
log::debug!(target: "coco_lib::selection_monitor", "selection_store_path resolved: {}", dir.display());
|
||||
dir
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
fn ensure_selection_store_bootstrap(app_handle: &tauri::AppHandle) {
|
||||
use std::fs;
|
||||
use std::io::Write;
|
||||
let mut dir = app_handle
|
||||
.path()
|
||||
.app_data_dir()
|
||||
.expect("failed to find the local dir");
|
||||
dir.push("zustand");
|
||||
let _ = fs::create_dir_all(&dir);
|
||||
let file = dir.join("selection-store.json");
|
||||
if !file.exists() {
|
||||
let initial = serde_json::json!({
|
||||
"selectionEnabled": true,
|
||||
"iconsOnly": false,
|
||||
"toolbarConfig": []
|
||||
});
|
||||
if let Ok(mut f) = fs::File::create(&file) {
|
||||
let _ = f.write_all(
|
||||
serde_json::to_string(&initial)
|
||||
.unwrap_or_else(|_| "{}".to_string())
|
||||
.as_bytes(),
|
||||
);
|
||||
log::info!(target: "coco_lib::selection_monitor", "bootstrap selection-store.json created: {}", file.display());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Read `selectionEnabled` from the persisted zustand store.
|
||||
/// Returns Some(bool) if read succeeds; None otherwise.
|
||||
#[cfg(target_os = "macos")]
|
||||
fn read_selection_enabled_from_store(app_handle: &tauri::AppHandle) -> Option<bool> {
|
||||
use std::fs;
|
||||
let path = selection_store_path(app_handle);
|
||||
match fs::read_to_string(&path) {
|
||||
Ok(content) => match serde_json::from_str::<serde_json::Value>(&content) {
|
||||
Ok(v) => {
|
||||
let val = v.get("selectionEnabled").and_then(|b| b.as_bool());
|
||||
log::info!(target: "coco_lib::selection_monitor", "read_selection_enabled_from_store: {} -> {:?}", path.display(), val);
|
||||
val
|
||||
}
|
||||
Err(e) => {
|
||||
log::warn!(target: "coco_lib::selection_monitor", "read_selection_enabled_from_store: JSON parse failed for {}: {}", path.display(), e);
|
||||
None
|
||||
}
|
||||
},
|
||||
Err(e) => {
|
||||
use std::time::Duration;
|
||||
use std::time::Instant;
|
||||
let mut last = LAST_READ_WARN.lock().unwrap();
|
||||
let now = Instant::now();
|
||||
let allow = match *last {
|
||||
Some(ts) => now.duration_since(ts) > Duration::from_secs(30),
|
||||
None => true,
|
||||
};
|
||||
if allow {
|
||||
log::warn!(target: "coco_lib::selection_monitor", "read_selection_enabled_from_store: read failed for {}: {}", path.display(), e);
|
||||
*last = Some(now);
|
||||
} else {
|
||||
log::debug!(target: "coco_lib::selection_monitor", "read_selection_enabled_from_store: read failed suppressed for {}", path.display());
|
||||
}
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Spawn a background watcher to sync `SELECTION_ENABLED` with disk every ~1s.
|
||||
#[cfg(target_os = "macos")]
|
||||
fn start_selection_store_watcher(app_handle: tauri::AppHandle) {
|
||||
if SELECTION_STORE_WATCHER_STARTED.swap(true, Ordering::Relaxed) {
|
||||
return;
|
||||
}
|
||||
std::thread::Builder::new()
|
||||
.name("selection-store-watcher".into())
|
||||
.spawn(move || {
|
||||
use std::time::{Duration, Instant};
|
||||
let mut last_check = Instant::now();
|
||||
let mut last_val: Option<bool> = None;
|
||||
loop {
|
||||
// Check approximately every second
|
||||
if last_check.elapsed() >= Duration::from_secs(1) {
|
||||
let current = read_selection_enabled_from_store(&app_handle);
|
||||
if current.is_some() && current != last_val {
|
||||
let enabled = current.unwrap();
|
||||
set_selection_enabled_internal(&app_handle, enabled);
|
||||
log::info!(target: "coco_lib::selection_monitor", "selection-store-watcher: detected change, enabled={}", enabled);
|
||||
last_val = current;
|
||||
}
|
||||
last_check = Instant::now();
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(200));
|
||||
}
|
||||
})
|
||||
.unwrap_or_else(|e| {
|
||||
SELECTION_STORE_WATCHER_STARTED.store(false, Ordering::Relaxed);
|
||||
panic!("selection-store-watcher: failed to spawn: {}", e);
|
||||
});
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
fn collect_selection_permission_info() -> SelectionPermissionInfo {
|
||||
let exe_path = std::env::current_exe()
|
||||
@@ -694,12 +585,16 @@ fn is_focused_element_me() -> bool {
|
||||
/// Read the selected text of the frontmost application (without using the clipboard).
|
||||
/// macOS only. Returns `None` when the frontmost app is Coco to avoid false empties.
|
||||
#[cfg(target_os = "macos")]
|
||||
fn read_selected_text() -> Option<String> {
|
||||
fn read_selected_text(verbose: bool) -> Option<String> {
|
||||
use objc2_app_kit::NSWorkspace;
|
||||
use objc2_application_services::{AXError, AXUIElement};
|
||||
use objc2_core_foundation::{CFRetained, CFString, CFType};
|
||||
use std::ptr::NonNull;
|
||||
|
||||
if verbose {
|
||||
println!("[SelectionMonitor] read_selected_text: Attempting to read...");
|
||||
}
|
||||
|
||||
// Prefer system-wide focused element; if unavailable, fall back to app/window focused element.
|
||||
let mut focused_ui_ptr: *const CFType = std::ptr::null();
|
||||
let focused_attr = CFString::from_static_str("AXFocusedUIElement");
|
||||
@@ -714,12 +609,23 @@ fn read_selected_text() -> Option<String> {
|
||||
.copy_attribute_value(&focused_attr, NonNull::new(&mut focused_ui_ptr).unwrap())
|
||||
};
|
||||
if err != AXError::Success {
|
||||
if verbose {
|
||||
println!(
|
||||
"[SelectionMonitor] Failed to get AXFocusedUIElement from system wide element: {:?}",
|
||||
err
|
||||
);
|
||||
}
|
||||
focused_ui_ptr = std::ptr::null();
|
||||
}
|
||||
} else if verbose {
|
||||
println!("[SelectionMonitor] AXUIElementCreateSystemWide returned null");
|
||||
}
|
||||
|
||||
// Fallback to the frontmost app's focused/window element.
|
||||
if focused_ui_ptr.is_null() {
|
||||
if verbose {
|
||||
println!("[SelectionMonitor] System-wide focus not found, trying frontmost app...");
|
||||
}
|
||||
let workspace = unsafe { NSWorkspace::sharedWorkspace() };
|
||||
let frontmost_app = unsafe { workspace.frontmostApplication() }?;
|
||||
let pid = unsafe { frontmost_app.processIdentifier() };
|
||||
@@ -727,6 +633,9 @@ fn read_selected_text() -> Option<String> {
|
||||
// Skip if frontmost is Coco (this process).
|
||||
let my_pid = std::process::id() as i32;
|
||||
if pid == my_pid {
|
||||
if verbose {
|
||||
println!("[SelectionMonitor] Frontmost app is Coco, skipping.");
|
||||
}
|
||||
return None;
|
||||
}
|
||||
|
||||
@@ -736,6 +645,12 @@ fn read_selected_text() -> Option<String> {
|
||||
.copy_attribute_value(&focused_attr, NonNull::new(&mut focused_ui_ptr).unwrap())
|
||||
};
|
||||
if err != AXError::Success || focused_ui_ptr.is_null() {
|
||||
if verbose {
|
||||
println!(
|
||||
"[SelectionMonitor] Failed to get AXFocusedUIElement from app (pid={}), trying AXFocusedWindow...",
|
||||
pid
|
||||
);
|
||||
}
|
||||
// Try `AXFocusedWindow` as a lightweight fallback.
|
||||
let mut focused_window_ptr: *const CFType = std::ptr::null();
|
||||
let focused_window_attr = CFString::from_static_str("AXFocusedWindow");
|
||||
@@ -746,9 +661,41 @@ fn read_selected_text() -> Option<String> {
|
||||
)
|
||||
};
|
||||
if w_err != AXError::Success || focused_window_ptr.is_null() {
|
||||
if verbose {
|
||||
println!(
|
||||
"[SelectionMonitor] Failed to get AXFocusedWindow from app (pid={})",
|
||||
pid
|
||||
);
|
||||
}
|
||||
return None;
|
||||
}
|
||||
focused_ui_ptr = focused_window_ptr;
|
||||
let focused_window_elem: CFRetained<AXUIElement> = unsafe {
|
||||
CFRetained::from_raw(
|
||||
NonNull::new(focused_window_ptr.cast::<AXUIElement>().cast_mut()).unwrap(),
|
||||
)
|
||||
};
|
||||
let mut inner_focused_ptr: *const CFType = std::ptr::null();
|
||||
let w_focused_err = unsafe {
|
||||
focused_window_elem.copy_attribute_value(
|
||||
&focused_attr,
|
||||
NonNull::new(&mut inner_focused_ptr).unwrap(),
|
||||
)
|
||||
};
|
||||
if w_focused_err == AXError::Success && !inner_focused_ptr.is_null() {
|
||||
if verbose {
|
||||
println!(
|
||||
"[SelectionMonitor] Resolved AXFocusedUIElement via AXFocusedWindow (pid={})",
|
||||
pid
|
||||
);
|
||||
}
|
||||
focused_ui_ptr = inner_focused_ptr;
|
||||
} else if verbose {
|
||||
println!(
|
||||
"[SelectionMonitor] Failed to get AXFocusedUIElement from focused window (pid={}), err={:?}",
|
||||
pid, w_focused_err
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -766,6 +713,12 @@ fn read_selected_text() -> Option<String> {
|
||||
)
|
||||
};
|
||||
if err != AXError::Success || selected_text_ptr.is_null() {
|
||||
if verbose {
|
||||
println!(
|
||||
"[SelectionMonitor] Failed to get AXSelectedText (err={:?})",
|
||||
err
|
||||
);
|
||||
}
|
||||
return None;
|
||||
}
|
||||
|
||||
@@ -774,27 +727,40 @@ fn read_selected_text() -> Option<String> {
|
||||
CFRetained::from_raw(NonNull::new(selected_text_ptr.cast::<CFString>().cast_mut()).unwrap())
|
||||
};
|
||||
|
||||
Some(selected_cfstr.to_string())
|
||||
let s = selected_cfstr.to_string();
|
||||
if verbose {
|
||||
println!("[SelectionMonitor] Success! Found text length: {}", s.len());
|
||||
}
|
||||
Some(s)
|
||||
}
|
||||
|
||||
/// Read selected text with lightweight retries to handle transient AX focus instability.
|
||||
#[cfg(target_os = "macos")]
|
||||
fn read_selected_text_with_retries(retries: u32, delay_ms: u64) -> Option<String> {
|
||||
fn read_selected_text_with_retries(retries: u32, delay_ms: u64, verbose: bool) -> Option<String> {
|
||||
use std::thread;
|
||||
use std::time::Duration;
|
||||
for attempt in 0..=retries {
|
||||
if let Some(text) = read_selected_text() {
|
||||
if let Some(text) = read_selected_text(verbose) {
|
||||
if !text.is_empty() {
|
||||
if attempt > 0 {
|
||||
// log::info!(
|
||||
// "read_selected_text: 第{}次重试成功,获取到选中文本",
|
||||
// attempt
|
||||
// );
|
||||
log::info!(
|
||||
"read_selected_text: 第{}次重试成功,获取到选中文本",
|
||||
attempt
|
||||
);
|
||||
if verbose {
|
||||
println!("[SelectionMonitor] Retry success on attempt {}", attempt);
|
||||
}
|
||||
}
|
||||
return Some(text);
|
||||
}
|
||||
}
|
||||
if attempt < retries {
|
||||
if verbose {
|
||||
println!(
|
||||
"[SelectionMonitor] Attempt {} failed/empty, retrying...",
|
||||
attempt
|
||||
);
|
||||
}
|
||||
thread::sleep(Duration::from_millis(delay_ms));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -110,7 +110,6 @@ pub(crate) async fn backend_setup(tauri_app_handle: AppHandle, app_lang: String)
|
||||
// Start system-wide selection monitor (macOS-only currently)
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
log::info!("backend_setup: starting system-wide selection monitor");
|
||||
crate::selection_monitor::start_selection_monitor(tauri_app_handle.clone());
|
||||
}
|
||||
|
||||
|
||||
@@ -1,207 +0,0 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useMount } from "ahooks";
|
||||
import { ShieldCheck, Monitor, Mic, RotateCcw } from "lucide-react";
|
||||
import clsx from "clsx";
|
||||
|
||||
import platformAdapter from "@/utils/platformAdapter";
|
||||
import SettingsItem from "@/components/Settings/SettingsItem";
|
||||
|
||||
const Permissions = () => {
|
||||
const { t } = useTranslation();
|
||||
const [accessibilityAuthorized, setAccessibilityAuthorized] = useState<boolean | null>(null);
|
||||
const [screenAuthorized, setScreenAuthorized] = useState<boolean | null>(null);
|
||||
const [microphoneAuthorized, setMicrophoneAuthorized] = useState<boolean | null>(null);
|
||||
|
||||
const refresh = async () => {
|
||||
const [ax, sr, mic] = await Promise.all([
|
||||
platformAdapter.invokeBackend<boolean>("check_accessibility_trusted"),
|
||||
platformAdapter.checkScreenRecordingPermission(),
|
||||
platformAdapter.checkMicrophonePermission(),
|
||||
]);
|
||||
console.info("[permissions] refreshed", { accessibility: ax, screenRecording: sr, microphone: mic });
|
||||
setAccessibilityAuthorized(ax);
|
||||
setScreenAuthorized(sr);
|
||||
setMicrophoneAuthorized(mic);
|
||||
};
|
||||
|
||||
useMount(refresh);
|
||||
|
||||
const openAccessibilitySettings = async () => {
|
||||
const window = await platformAdapter.getCurrentWebviewWindow();
|
||||
await window.setAlwaysOnTop(false);
|
||||
console.info("[permissions] open accessibility settings");
|
||||
await platformAdapter.invokeBackend("open_accessibility_settings");
|
||||
await refresh();
|
||||
};
|
||||
|
||||
const requestScreenRecording = async () => {
|
||||
const window = await platformAdapter.getCurrentWebviewWindow();
|
||||
await window.setAlwaysOnTop(false);
|
||||
console.info("[permissions] request screen recording");
|
||||
await platformAdapter.requestScreenRecordingPermission();
|
||||
await platformAdapter.invokeBackend("open_screen_recording_settings");
|
||||
await refresh();
|
||||
};
|
||||
|
||||
const requestMicrophone = async () => {
|
||||
const window = await platformAdapter.getCurrentWebviewWindow();
|
||||
await window.setAlwaysOnTop(false);
|
||||
console.info("[permissions] request microphone");
|
||||
await platformAdapter.requestMicrophonePermission();
|
||||
await platformAdapter.invokeBackend("open_microphone_settings");
|
||||
await refresh();
|
||||
};
|
||||
|
||||
const [refreshing, setRefreshing] = useState(false);
|
||||
const handleRefresh = async () => {
|
||||
if (refreshing) return;
|
||||
setRefreshing(true);
|
||||
try {
|
||||
await refresh();
|
||||
} finally {
|
||||
setRefreshing(false);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
const unlisten1 = platformAdapter.listenEvent("selection-permission-required", async () => {
|
||||
console.info("[permissions] selection-permission-required received");
|
||||
await refresh();
|
||||
});
|
||||
const unlisten2 = platformAdapter.listenEvent("selection-permission-info", async (evt: any) => {
|
||||
console.info("[permissions] selection-permission-info", evt?.payload);
|
||||
await refresh();
|
||||
});
|
||||
return () => {
|
||||
unlisten1.then((fn) => fn());
|
||||
unlisten2.then((fn) => fn());
|
||||
};
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<>
|
||||
<h2 className="text-lg font-semibold text-gray-900 dark:text-white mb-4">
|
||||
{t("settings.advanced.permissions.title")}
|
||||
</h2>
|
||||
|
||||
<div className="space-y-6">
|
||||
<SettingsItem
|
||||
icon={ShieldCheck}
|
||||
title={t("settings.advanced.permissions.accessibility.title")}
|
||||
description={t("settings.advanced.permissions.accessibility.description")}
|
||||
>
|
||||
<div className="flex items-center gap-3">
|
||||
{accessibilityAuthorized ? (
|
||||
<span className="text-sm font-medium text-green-600 dark:text-green-500">
|
||||
{t("settings.common.status.authorized")}
|
||||
</span>
|
||||
) : (
|
||||
<span className="text-sm font-medium text-red-600 dark:text-red-500">
|
||||
{t("settings.common.status.notAuthorized")}
|
||||
</span>
|
||||
)}
|
||||
<button
|
||||
className="px-3 py-1.5 bg-blue-600 hover:bg-blue-700 text-white rounded-lg text-sm"
|
||||
onClick={openAccessibilitySettings}
|
||||
>
|
||||
{t("settings.common.actions.openNow")}
|
||||
</button>
|
||||
<button
|
||||
className={clsx(
|
||||
"flex items-center justify-center size-8 rounded-[6px] border border-black/5 dark:border-white/10 transition bg-gray-200 dark:bg-gray-800 text-gray-900 dark:text-gray-100",
|
||||
{ "opacity-70 cursor-not-allowed": refreshing }
|
||||
)}
|
||||
onClick={handleRefresh}
|
||||
title={t("settings.common.actions.refresh")}
|
||||
>
|
||||
<RotateCcw
|
||||
className={clsx("size-4", {
|
||||
"animate-spin": refreshing,
|
||||
})}
|
||||
/>
|
||||
</button>
|
||||
</div>
|
||||
</SettingsItem>
|
||||
|
||||
<SettingsItem
|
||||
icon={Monitor}
|
||||
title={t("settings.advanced.permissions.screenRecording.title")}
|
||||
description={t("settings.advanced.permissions.screenRecording.description")}
|
||||
>
|
||||
<div className="flex items-center gap-3">
|
||||
{screenAuthorized ? (
|
||||
<span className="text-sm font-medium text-green-600 dark:text-green-500">
|
||||
{t("settings.common.status.authorized")}
|
||||
</span>
|
||||
) : (
|
||||
<span className="text-sm font-medium text-red-600 dark:text-red-500">
|
||||
{t("settings.common.status.notAuthorized")}
|
||||
</span>
|
||||
)}
|
||||
<button
|
||||
className="px-3 py-1.5 bg-blue-600 hover:bg-blue-700 text-white rounded-lg text-sm"
|
||||
onClick={requestScreenRecording}
|
||||
>
|
||||
{t("settings.common.actions.openNow")}
|
||||
</button>
|
||||
<button
|
||||
className={clsx(
|
||||
"flex items-center justify-center size-8 rounded-[6px] border border-black/5 dark:border-white/10 transition bg-gray-200 dark:bg-gray-800 text-gray-900 dark:text-gray-100",
|
||||
{ "opacity-70 cursor-not-allowed": refreshing }
|
||||
)}
|
||||
onClick={handleRefresh}
|
||||
title={t("settings.common.actions.refresh")}
|
||||
>
|
||||
<RotateCcw
|
||||
className={clsx("size-4", {
|
||||
"animate-spin": refreshing,
|
||||
})}
|
||||
/>
|
||||
</button>
|
||||
</div>
|
||||
</SettingsItem>
|
||||
|
||||
<SettingsItem
|
||||
icon={Mic}
|
||||
title={t("settings.advanced.permissions.microphone.title")}
|
||||
description={t("settings.advanced.permissions.microphone.description")}
|
||||
>
|
||||
<div className="flex items-center gap-3">
|
||||
{microphoneAuthorized ? (
|
||||
<span className="text-sm font-medium text-green-600 dark:text-green-500">
|
||||
{t("settings.common.status.authorized")}
|
||||
</span>
|
||||
) : (
|
||||
<span className="text-sm font-medium text-red-600 dark:text-red-500">
|
||||
{t("settings.common.status.notAuthorized")}
|
||||
</span>
|
||||
)}
|
||||
<button
|
||||
className="px-3 py-1.5 bg-blue-600 hover:bg-blue-700 text-white rounded-lg text-sm"
|
||||
onClick={requestMicrophone}
|
||||
>
|
||||
{t("settings.common.actions.openNow")}
|
||||
</button>
|
||||
<button
|
||||
className={clsx(
|
||||
"flex items-center justify-center size-8 rounded-[6px] border border-black/5 dark:border-white/10 transition bg-gray-200 dark:bg-gray-800 text-gray-900 dark:text-gray-100",
|
||||
{ "opacity-70 cursor-not-allowed": refreshing }
|
||||
)}
|
||||
onClick={handleRefresh}
|
||||
title={t("settings.common.actions.refresh")}
|
||||
>
|
||||
<RotateCcw
|
||||
className={clsx("size-4", {
|
||||
"animate-spin": refreshing,
|
||||
})}
|
||||
/>
|
||||
</button>
|
||||
</div>
|
||||
</SettingsItem>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default Permissions;
|
||||
@@ -11,13 +11,6 @@ import {
|
||||
} from "lucide-react";
|
||||
import { useMount } from "ahooks";
|
||||
import { isNil } from "lodash-es";
|
||||
import {
|
||||
Select,
|
||||
SelectTrigger,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select";
|
||||
|
||||
import Shortcuts from "./components/Shortcuts";
|
||||
import SettingsItem from "../SettingsItem";
|
||||
@@ -30,8 +23,13 @@ import UpdateSettings from "./components/UpdateSettings";
|
||||
import SettingsToggle from "../SettingsToggle";
|
||||
import SelectionSettings from "./components/Selection";
|
||||
import { isMac } from "@/utils/platform";
|
||||
import Permissions from "./components/Permissions";
|
||||
|
||||
import {
|
||||
Select,
|
||||
SelectTrigger,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select";
|
||||
|
||||
const Advanced = () => {
|
||||
const { t } = useTranslation();
|
||||
@@ -198,8 +196,6 @@ const Advanced = () => {
|
||||
})}
|
||||
</div>
|
||||
|
||||
{isMac && <Permissions />}
|
||||
|
||||
{isMac && <SelectionSettings />}
|
||||
|
||||
<Shortcuts />
|
||||
|
||||
@@ -14,19 +14,19 @@ export default function SettingsItem({
|
||||
children,
|
||||
}: SettingsItemProps) {
|
||||
return (
|
||||
<div className="flex items-center justify-between gap-6 min-w-0">
|
||||
<div className="flex items-center space-x-3 min-w-0">
|
||||
<div className="flex items-center justify-between gap-6">
|
||||
<div className="flex items-center space-x-3">
|
||||
<Icon className="h-5 min-w-5 text-gray-400 dark:text-gray-500" />
|
||||
<div className="max-w-[680px] min-w-0">
|
||||
<div>
|
||||
<h3 className="text-sm font-medium text-gray-900 dark:text-gray-100">
|
||||
{title}
|
||||
</h3>
|
||||
<p className="text-sm text-gray-500 dark:text-gray-400 whitespace-normal break-words">
|
||||
<p className="text-sm text-gray-500 dark:text-gray-400">
|
||||
{description}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex-shrink-0">{children}</div>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
26
src/hooks/useSelectionEnabled.ts
Normal file
26
src/hooks/useSelectionEnabled.ts
Normal file
@@ -0,0 +1,26 @@
|
||||
import { useMount } from "ahooks";
|
||||
|
||||
import platformAdapter from "@/utils/platformAdapter";
|
||||
import { useSelectionStore } from "@/stores/selectionStore";
|
||||
|
||||
export default function useSelectionEnabled() {
|
||||
useMount(async () => {
|
||||
try {
|
||||
const enabled = await platformAdapter.invokeBackend<boolean>("get_selection_enabled");
|
||||
useSelectionStore.getState().setSelectionEnabled(!!enabled);
|
||||
} catch (e) {
|
||||
console.error("get_selection_enabled failed:", e);
|
||||
}
|
||||
|
||||
const unlisten = await platformAdapter.listenEvent(
|
||||
"selection-enabled",
|
||||
({ payload }: any) => {
|
||||
useSelectionStore.getState().setSelectionEnabled(!!payload?.enabled);
|
||||
}
|
||||
);
|
||||
|
||||
return () => {
|
||||
unlisten && unlisten();
|
||||
};
|
||||
});
|
||||
}
|
||||
@@ -187,21 +187,6 @@
|
||||
"description": "Get early access to new features. May be unstable."
|
||||
}
|
||||
},
|
||||
"permissions": {
|
||||
"title": "Permissions",
|
||||
"accessibility": {
|
||||
"title": "Accessibility",
|
||||
"description": "Required to read selected text in the foreground app. Grant in System Settings → Privacy & Security → Accessibility."
|
||||
},
|
||||
"screenRecording": {
|
||||
"title": "Screen Recording",
|
||||
"description": "Required for window/screen screenshots and sharing. Grant in System Settings → Privacy & Security → Screen Recording."
|
||||
},
|
||||
"microphone": {
|
||||
"title": "Microphone",
|
||||
"description": "Required for voice input and recording. Grant in System Settings → Privacy & Security → Microphone."
|
||||
}
|
||||
},
|
||||
"other": {
|
||||
"title": "Other Settings",
|
||||
"connectionTimeout": {
|
||||
@@ -244,16 +229,6 @@
|
||||
"extensionsContent": "Extensions settings content",
|
||||
"advancedContent": "Advanced Settings content"
|
||||
},
|
||||
"common": {
|
||||
"status": {
|
||||
"authorized": "Authorized",
|
||||
"notAuthorized": "Not Authorized"
|
||||
},
|
||||
"actions": {
|
||||
"openNow": "Open Settings",
|
||||
"refresh": "Refresh"
|
||||
}
|
||||
},
|
||||
"extensions": {
|
||||
"title": "Extensions",
|
||||
"list": {
|
||||
|
||||
@@ -187,21 +187,6 @@
|
||||
"description": "抢先体验新功能,可能不稳定。"
|
||||
}
|
||||
},
|
||||
"permissions": {
|
||||
"title": "权限设置",
|
||||
"accessibility": {
|
||||
"title": "辅助功能(Accessibility)",
|
||||
"description": "用于读取前台应用的选中文本,需在「隐私与安全 → 辅助功能」中授权。"
|
||||
},
|
||||
"screenRecording": {
|
||||
"title": "屏幕录制",
|
||||
"description": "用于窗口/屏幕截图与共享,需要在「隐私与安全 → 屏幕录制」中授权。"
|
||||
},
|
||||
"microphone": {
|
||||
"title": "麦克风",
|
||||
"description": "用于语音输入与录音功能,需要在「隐私与安全 → 麦克风」中授权。"
|
||||
}
|
||||
},
|
||||
"other": {
|
||||
"title": "其它设置",
|
||||
"connectionTimeout": {
|
||||
@@ -244,16 +229,6 @@
|
||||
"extensionsContent": "扩展设置内容",
|
||||
"advancedContent": "高级设置内容"
|
||||
},
|
||||
"common": {
|
||||
"status": {
|
||||
"authorized": "已授权",
|
||||
"notAuthorized": "未授权"
|
||||
},
|
||||
"actions": {
|
||||
"openNow": "去授权",
|
||||
"refresh": "刷新状态"
|
||||
}
|
||||
},
|
||||
"extensions": {
|
||||
"title": "扩展",
|
||||
"list": {
|
||||
|
||||
@@ -58,14 +58,6 @@ export interface EventPayloads {
|
||||
"selection-detected": string;
|
||||
"selection-enabled": boolean;
|
||||
"change-selection-store": any;
|
||||
"selection-permission-required": boolean;
|
||||
"selection-permission-info": {
|
||||
bundle_id: string;
|
||||
exe_path: string;
|
||||
in_applications: boolean;
|
||||
is_dmg: boolean;
|
||||
is_dev_guess: boolean;
|
||||
};
|
||||
}
|
||||
|
||||
// Window operation interface
|
||||
|
||||
Reference in New Issue
Block a user