|
| 1 | +use std::num::NonZeroUsize; |
| 2 | + |
1 | 3 | use accessibility_ng::{AXAttribute, AXUIElement};
|
2 | 4 | use accessibility_sys_ng::{kAXFocusedUIElementAttribute, kAXSelectedTextAttribute};
|
| 5 | +use active_win_pos_rs::get_active_window; |
3 | 6 | use core_foundation::string::CFString;
|
| 7 | +use debug_print::debug_println; |
| 8 | +use lru::LruCache; |
| 9 | +use parking_lot::Mutex; |
| 10 | + |
| 11 | +static GET_SELECTED_TEXT_METHOD: Mutex<Option<LruCache<String, u8>>> = Mutex::new(None); |
4 | 12 |
|
5 | 13 | pub fn get_selected_text() -> Result<String, Box<dyn std::error::Error>> {
|
| 14 | + if GET_SELECTED_TEXT_METHOD.lock().is_none() { |
| 15 | + let cache = LruCache::new(NonZeroUsize::new(100).unwrap()); |
| 16 | + *GET_SELECTED_TEXT_METHOD.lock() = Some(cache); |
| 17 | + } |
| 18 | + let mut cache = GET_SELECTED_TEXT_METHOD.lock(); |
| 19 | + let cache = cache.as_mut().unwrap(); |
| 20 | + let app_name = match get_active_window() { |
| 21 | + Ok(window) => window.app_name, |
| 22 | + Err(_) => return Err("No active window found".into()), |
| 23 | + }; |
| 24 | + // debug_println!("app_name: {}", app_name); |
| 25 | + if let Some(text) = cache.get(&app_name) { |
| 26 | + if *text == 0 { |
| 27 | + return get_selected_text_by_ax(); |
| 28 | + } |
| 29 | + return get_selected_text_by_clipboard_using_applescript(); |
| 30 | + } |
6 | 31 | match get_selected_text_by_ax() {
|
7 |
| - Ok(text) => Ok(text), |
8 |
| - Err(_) => get_selected_text_by_clipboard_using_applescript(), |
| 32 | + Ok(text) => { |
| 33 | + cache.put(app_name, 0); |
| 34 | + Ok(text) |
| 35 | + } |
| 36 | + Err(_) => match get_selected_text_by_clipboard_using_applescript() { |
| 37 | + Ok(text) => { |
| 38 | + if !text.is_empty() { |
| 39 | + cache.put(app_name, 1); |
| 40 | + } |
| 41 | + Ok(text) |
| 42 | + } |
| 43 | + Err(e) => Err(e), |
| 44 | + }, |
9 | 45 | }
|
10 | 46 | }
|
11 | 47 |
|
12 | 48 | fn get_selected_text_by_ax() -> Result<String, Box<dyn std::error::Error>> {
|
| 49 | + // debug_println!("get_selected_text_by_ax"); |
13 | 50 | let system_element = AXUIElement::system_wide();
|
14 | 51 | let Some(selected_element) = system_element
|
15 | 52 | .attribute(&AXAttribute::new(&CFString::from_static_string(
|
@@ -79,6 +116,7 @@ theSelectedText
|
79 | 116 |
|
80 | 117 | fn get_selected_text_by_clipboard_using_applescript() -> Result<String, Box<dyn std::error::Error>>
|
81 | 118 | {
|
| 119 | + // debug_println!("get_selected_text_by_clipboard_using_applescript"); |
82 | 120 | let output = std::process::Command::new("osascript")
|
83 | 121 | .arg("-e")
|
84 | 122 | .arg(APPLE_SCRIPT)
|
|
0 commit comments