Skip to content

YC (S26) | Open Computer History | Continuously record your company computer work, map your workflows, help you find work worth automating, and power your agents' context

fix a few function in windows operator

louis030195e7d0d7198bda
diff --git a/screenpipe-core/examples/win_automation.rs b/screenpipe-core/examples/win_automation.rs
index 180c57851..5ffd19940 100644
--- a/screenpipe-core/examples/win_automation.rs
+++ b/screenpipe-core/examples/win_automation.rs
@@ -1,3 +1,6 @@
+use std::thread;
+use std::time::Duration;
+
use screenpipe_core::operator::platforms;
use screenpipe_core::operator::Selector;
use screenpipe_core::operator::AutomationError;
@@ -46,8 +49,8 @@ fn main() -> Result<(), AutomationError> {
// perform actions on an element
// get root of an application
- let element = engine.get_application_by_name("firefox")?;
- println!("app element: {:?}", element);
+ // let element = engine.get_application_by_name("edge")?;
+ // println!("app element: {:?}", element);
// find a button
// let sel = Selector::Role { role: "button".to_string(), name: None };
// let but = engine.find_element(&sel, Some(&element))?;
@@ -73,10 +76,199 @@ fn main() -> Result<(), AutomationError> {
// inp.set_value("")?;
+ // let element = engine.open_application("msedge")?;
+ // let inputs = element.locator(Selector::Text("Search".to_string())).unwrap().all().unwrap();
+ // for input in inputs.iter() {
+ // println!("input: {:?}", input.attributes().properties);
+ // println!("input: {:?}", input.text(10).unwrap_or_default());
+ // println!("input: {:?}", input.attributes().label);
+ // // type text
+ // input.focus()?;
+ // input.type_text("hi").map_err(|e| println!("error: {:?}", e)).unwrap_or_default();
+ // // input.press_key("{enter}")?;
+ // }
+
+
+ // Initialize the automation engine
+ // Use true, true if you need debug logs and accessibility mode
+ let engine = platforms::create_engine(false, false)?;
+
+ // --- Part 1: Open Notepad and Simulate Legacy App ---
+
+ // Ensure the file exists before trying to open it
+ // Open Notepad with the specific file
+ // Note: Opening notepad directly with a file might be OS dependent or tricky.
+ // A more robust way might be to open notepad first, then use 'ctrl+o', then type the path.
+ // Or, just open notepad blank and paste the data (less realistic simulation).
+ // Let's try opening notepad blank first, then finding the edit area and setting its value.
+ // let notepad_app = engine.open_application("notepad")?;
+ let notepad_app = engine.get_application_by_name("notepad")?;
+ println!("Notepad opened: {:?}", notepad_app.attributes());
+ thread::sleep(Duration::from_secs(2)); // Wait for app to load
+ notepad_app.focus()?;
+
+ // Find the main text editing area in Notepad
+ // The role might be "document" or "edit" - requires inspection
+ // let notepad_edit_selector = Selector::Name("Text Editor".to_string());
+ // let notepad_edit_area = notepad_app.locator(notepad_edit_selector).unwrap().first().unwrap().unwrap();
+ // println!("Found Notepad edit area: {:?}", notepad_edit_area.attributes().properties);
+ // println!("Found Notepad edit area: {:?}", notepad_edit_area.text(10).unwrap_or_default());
+
+ // Read the data from the file
+ // let legacy_data = fs::read_to_string(data_file_path)
+ // .map_err(|e| AutomationError::action(format!("failed to read data file: {}", e)))?;
+
+ // Set the value (paste) the legacy data into Notepad's edit area
+ // Alternatively use type_text if set_value isn't reliable for this element
+ // notepad_edit_area.focus()?;
+ // let edit = notepad_app.children().unwrap();
+ // println!("edit: {:?}", edit);
+ thread::sleep(Duration::from_millis(200));
+ // notepad_edit_area.set_value(&legacy_data)?; // Might work
+ let formatted_text = r"CUSTOMER RECORD
+ID 10039485 Created 2023 04 17
+Acme Industries Ltd
+Status ACTIVE Contact John Smith Phone 555 123 4567
+Email jsmith at acmeindustries dot com
+
+ORDERS
+Order 7782 Date 2023 09 10 Amount 4750.00 USD
+Items 3x Widget Pro 1000 2x Support Package Annual
+Approved by Martinez Ship via Express
+
+Order 6691 Date 2023 06 22 Amount 1275.50 USD
+Items 1x Widget Basic 5x Connector Kit
+Backordered items 2x Power Supply
+
+NOTES
+Called on 2023 10 05 regarding shipment delay
+Customer requested invoice copies sent to accounting
+accounting email is invoices at acmeindustries dot com
+
+PAYMENT TERMS
+Net 30 Credit Limit 10000
+Last Payment 2023 08 28 Amount 3200.00
+Balance 2825.50
+
+TODO follow up on missing documentation for order 7782
+remind about maintenance renewal coming up in December";
+
+ // notepad_edit_area.type_text(formatted_text)?;
+ // sleep for 100ms
+ println!("Pasted data into Notepad.");
+ thread::sleep(Duration::from_millis(300));
+
+ // --- Part 2: Extract Data from Notepad ---
+ // Re-fetch the element or use the existing one
+ // Get the text *value* from the edit area
+ let extracted_text = notepad_app.text(10)?; // Use .value() or maybe .text() depending on API
+ println!("Extracted text from Notepad:\n{}", extracted_text);
+
+ // Basic parsing (replace with robust regex or parsing logic)
+ // let mut customer_id = "not found";
+ // let mut name = "not found";
+ // let mut total = "not found";
+
+ // for line in extracted_text.lines() {
+ // if line.starts_with("Customer ID:") {
+ // customer_id = line.split(':').nth(1).map_or("parse error", |s| s.trim());
+ // } else if line.starts_with("Name:") {
+ // name = line.split(':').nth(1).map_or("parse error", |s| s.trim());
+ // } else if line.starts_with("Order Total:") {
+ // total = line.split(':').nth(1).map_or("parse error", |s| s.trim());
+ // }
+ // }
+ // println!("Parsed - ID: {}, Name: {}, Total: {}", customer_id, name, total);
+
+
+ // --- Part 3: Open Google Sheets and Input Data ---
+ println!("Opening Google Sheets...");
+ let sheets_app = engine.open_url("https://docs.google.com/spreadsheets/d/1u2vPS43pkFdIrtWbl4Ug7D1ROmrtSD-YTo24FwGqDdo/edit?gid=0#gid=0", None)?;
+ // let sheets_app = engine.open_url("https://docs.google.com/spreadsheets/u/1/", None)?;
+ println!("Sheets opened: {:?}", sheets_app.attributes());
+ // Wait for Sheets to load
+ // thread::sleep(Duration::from_secs(5));
+
+ // sheets_app.focus()?;
+ // println!("Focused Sheets window.");
+ // thread::sleep(Duration::from_millis(500));
+
+ // open new sheet using
+ // let new_sheet = sheets_app.locator(Selector::Text("Blank spreadsheet".to_string())).unwrap().first().unwrap().unwrap();
+ // println!("new sheet: {:?}", new_sheet);
+ // new_sheet.focus()?;
+ // new_sheet.press_key("{enter}")?;
+ thread::sleep(Duration::from_millis(500));
+
+ // Instead of a single string with {enter} characters, break into separate lines
+ let sheet_data = [
+ "Customer ID\tCompany\tContact\tPhone\tEmail\tStatus\tBalance",
+ "10039485\tAcme Industries Ltd\tJohn Smith\t555 123 4567\[email protected]\tACTIVE\t2825.50",
+ "Order ID\tDate\tAmount\tItems\tStatus",
+ "7782\t2023-09-10\t4750.00 USD\t3x Widget Pro 1000, 2x Support Package Annual\tShipped",
+ "6691\t2023-06-22\t1275.50 USD\t1x Widget Basic, 5x Connector Kit\tBackordered",
+ "Notes\tDate\tFollow-up",
+ "Shipment delay\t2023-10-05\tResolved",
+ "Invoice copies requested\t2023-10-02\tSent to [email protected]",
+ "Maintenance renewal\t2023-12-15\tReminder sent"
+ ];
+
+ // Visual indication of AI processing before pasting
+ println!("ai analyzing legacy system data...");
+ thread::sleep(Duration::from_millis(800));
+ println!("extracting structured information...");
+ thread::sleep(Duration::from_millis(800));
+ println!("transforming to tabular format...");
+ thread::sleep(Duration::from_millis(800));
+ println!("data ready for input. filling spreadsheet...");
+
+ // Get the currently focused element (should be in the sheet)
+ let focused_element = engine.get_focused_element()?;
+ focused_element.focus()?;
+
+ // Type each line and press Enter between them
+ for line in sheet_data.iter() {
+ focused_element.type_text(line)?;
+ focused_element.press_key("{enter}")?;
+ thread::sleep(Duration::from_millis(100)); // Small delay between lines
+ }
+
+ println!("data successfully transferred from legacy system to google sheets!");
+ thread::sleep(Duration::from_secs(2));
+
+
+ // --- Part 4: Close Applications (Optional Cleanup) ---
+ // This might require specific 'close window' buttons or alt+f4
+ // println!("Closing Notepad...");
+ // Find close button? Or send Alt+F4?
+ // notepad_app.press_key("{alt down}{f4}{alt up}")?;
+ // thread::sleep(Duration::from_millis(500));
+ // // Handle potential "Save?" dialog - find "Don't Save" button
+
+ // println!("Closing Excel...");
+ // excel_app.press_key("{alt down}{f4}{alt up}")?;
+ // thread::sleep(Duration::from_millis(500));
+ // // Handle potential "Save?" dialog
+
+
+
+ println!("Demo script finished.");
+ // input.focus()?;
+ // input.type_text("hi")?;
+ // input.press_key("{enter}")?;
// get some texts from application root
// (heavy computational task keep depth low)
- let text = element.text(10)?;
- println!("element text: {:?}", text);
+ // let text = element.text(10)?;
+ // println!("element text: {:?}", text);
+
+ // let locator = element.locator(Selector::Role { role: "button".to_string(), name: None }).unwrap().all().unwrap();
+ // for l in locator.iter() {
+ // println!("locator: {:?}", l.attributes().properties);
+ // println!("locator: {:?}", l.attributes().role);
+ // println!("locator: {:?}", l.attributes().description);
+ // println!("locator: {:?}", l.attributes().value);
+ // println!("locator: {:?}", l.bounds());
+ // }
// check if enabled
diff --git a/screenpipe-core/src/operator/platforms/windows.rs b/screenpipe-core/src/operator/platforms/windows.rs
index 7879d5f6b..45bcc7d5c 100644
--- a/screenpipe-core/src/operator/platforms/windows.rs
+++ b/screenpipe-core/src/operator/platforms/windows.rs
@@ -2,9 +2,11 @@ use crate::operator::element::UIElementImpl;
use crate::operator::platforms::AccessibilityEngine;
use crate::operator::ClickResult;
use crate::operator::{AutomationError, Locator, Selector, UIElement, UIElementAttributes};
+use std::error::Error;
use std::sync::Arc;
use std::fmt::Debug;
use std::hash::{Hash, Hasher};
+use uiautomation::filters::{ControlTypeFilter, NameFilter, OrFilter};
use uiautomation::UIAutomation;
use uiautomation::controls::ControlType;
use uiautomation::inputs::Mouse;
@@ -17,9 +19,7 @@ use std::collections::{
hash_map::DefaultHasher
};
use uiautomation::types::{
- TreeScope,
- UIProperty,
- ScrollAmount
+ Point, PropertyConditionFlags, ScrollAmount, TreeScope, UIProperty
};
// thread-safety
@@ -179,11 +179,30 @@ impl AccessibilityEngine for WindowsEngine {
Variant::from(ControlType::Window as i32),
None
).unwrap(),
- Selector::Text(_text) => self.automation.0.create_property_condition(
- UIProperty::ControlType,
- Variant::from(ControlType::Text as i32),
- None
- ).unwrap(),
+ Selector::Text(text) => {
+
+ let filter = OrFilter {
+ left: Box::new(NameFilter { value: String::from(text), casesensitive: false, partial: true }),
+ right: Box::new(ControlTypeFilter { control_type: ControlType::Text }),
+ };
+ // Create a matcher that uses contains_name which is more reliable for text searching
+ let matcher = self.automation.0.create_matcher()
+ .from_ref(root_ele)
+ .filter(Box::new(filter))// This is the key improvement from the example
+ .depth(10) // Search deep enough to find most elements
+ .timeout(3000); // Allow enough time for search
+
+ // Get the first matching element
+ let elements = matcher.find_all()
+ .map_err(|e| AutomationError::ElementNotFound(
+ format!("Text: '{}', Err: {}", text, e.to_string())))?;
+
+ return Ok(
+ elements.into_iter()
+ .map(|ele| UIElement::new(Box::new(WindowsUIElement { element: ThreadSafeWinUIElement(Arc::new(ele)) })))
+ .collect()
+ );
+ },
Selector::Path(_) => {
return Err(AutomationError::UnsupportedOperation("`Path` selector not supported".to_string()));
},
@@ -223,22 +242,14 @@ impl AccessibilityEngine for WindowsEngine {
match selector {
Selector::Role { role, name: _ } => {
let roles = map_generic_role_to_win_roles(role);
- let role_condition = self.automation.0.create_property_condition(
- UIProperty::ControlType,
- Variant::from(roles as i32),
- None
- ).unwrap();
- debug!("role conditions: {:#?} for finding element: {:#?}",
- role_condition, root_ele);
- // find a element that satisfies the roles
- let element = root_ele.find_first(TreeScope::Subtree, &role_condition)
- .map_err(|e| AutomationError::ElementNotFound(
- format!("element not found, Err: {}", e.to_string()
- )))?;
- debug!("found element: {:#?}", element);
-
+ // use create matcher api
+ let matcher = self.automation.0.create_matcher()
+ .from_ref(root_ele)
+ .control_type(roles)
+ .timeout(3000);
+ let element = matcher.find_first()
+ .map_err(|e| AutomationError::ElementNotFound(e.to_string()))?;
let arc_ele = ThreadSafeWinUIElement(Arc::new(element));
-
Ok(UIElement::new(Box::new(WindowsUIElement { element: arc_ele })))
},
Selector::Id(id) => {
@@ -256,34 +267,42 @@ impl AccessibilityEngine for WindowsEngine {
Ok(UIElement::new(Box::new(WindowsUIElement { element: arc_ele })))
},
Selector::Name(name) => {
- // `name` and `window` can be same
- let condition = self.automation.0.create_property_condition(
- UIProperty::ControlType,
- Variant::from(ControlType::Window as i32),
- None
- ).unwrap();
+ // find use create matcher api
- let ele = root_ele.find_first(TreeScope::Subtree, &condition)
+ let matcher = self.automation.0.create_matcher()
+ .from_ref(root_ele)
+ .contains_name(name)
+ .depth(10)
+ .timeout(3000);
+
+ let element = matcher.find_first()
.map_err(|e| AutomationError::ElementNotFound(
format!("Name: '{}', Err: {}", name, e.to_string())))?;
- let arc_ele = ThreadSafeWinUIElement(Arc::new(ele));
- Ok(UIElement::new(Box::new(WindowsUIElement { element: arc_ele })))
+ let arc_ele = ThreadSafeWinUIElement(Arc::new(element));
+ return Ok(UIElement::new(Box::new(WindowsUIElement { element: arc_ele })));
},
- Selector::Text(text) => {
- let condition = self.automation.0.create_property_condition(
- UIProperty::ControlType,
- Variant::from(ControlType::Text as i32),
- None
- ).unwrap();
+ Selector::Text(text) => {
- let ele = root_ele.find_first(TreeScope::Subtree, &condition)
+ let filter = OrFilter {
+ left: Box::new(NameFilter { value: String::from(text), casesensitive: false, partial: true }),
+ right: Box::new(ControlTypeFilter { control_type: ControlType::Text }),
+ };
+ // Create a matcher that uses contains_name which is more reliable for text searching
+ let matcher = self.automation.0.create_matcher()
+ .from_ref(root_ele)
+ .filter(Box::new(filter))// This is the key improvement from the example
+ .depth(10) // Search deep enough to find most elements
+ .timeout(3000); // Allow enough time for search
+
+ // Get the first matching element
+ let element = matcher.find_first()
.map_err(|e| AutomationError::ElementNotFound(
format!("Text: '{}', Err: {}", text, e.to_string())))?;
- let arc_ele = ThreadSafeWinUIElement(Arc::new(ele));
-
- Ok(UIElement::new(Box::new(WindowsUIElement { element: arc_ele })))
- }
+
+ let arc_ele = ThreadSafeWinUIElement(Arc::new(element));
+ return Ok(UIElement::new(Box::new(WindowsUIElement { element: arc_ele })));
+ },
Selector::Path(_) => {
return Err(AutomationError::UnsupportedOperation("`Path` selector not supported".to_string()));
},
@@ -438,17 +457,59 @@ impl UIElementImpl for WindowsUIElement {
fn click(&self) -> Result<ClickResult, AutomationError> {
self.element.0.try_focus();
- let point = self.element.0.get_clickable_point()
- .map_err(|e| AutomationError::PlatformError(e.to_string()))?
- .ok_or_else(|| AutomationError::PlatformError("No clickable point found".to_string()))?;
- let mouse = Mouse::default();
- mouse.click(point).map_err(|e| AutomationError::PlatformError(e.to_string()))?;
-
- Ok(ClickResult {
- method: "Single Click".to_string(),
- coordinates: Some((point.get_x() as f64, point.get_y() as f64)),
- details: "Clicked by Mouse".to_string(),
- })
+ debug!("attempting to click element: {:?}", self.element.0);
+
+ let click_result = self.element.0.click();
+
+ if click_result.is_ok() {
+ return Ok(ClickResult {
+ method: "Single Click".to_string(),
+ coordinates: None,
+ details: "Clicked by Mouse".to_string(),
+ });
+ }
+ // First try using the standard clickable point
+ let click_result = self.element.0.get_clickable_point()
+ .and_then(|maybe_point| {
+ if let Some(point) = maybe_point {
+ debug!("using clickable point: {:?}", point);
+ let mouse = Mouse::default();
+ mouse.click(point).map(|_| ClickResult {
+ method: "Single Click (Clickable Point)".to_string(),
+ coordinates: Some((point.get_x() as f64, point.get_y() as f64)),
+ details: "Clicked by Mouse using element's clickable point".to_string(),
+ })
+ } else {
+ Err(AutomationError::PlatformError("No clickable point found".to_string()).to_string().into())
+ }
+ });
+
+ // If first method fails, try using the bounding rectangle
+ if let Err(_) = click_result {
+ debug!("clickable point unavailable, falling back to bounding rectangle");
+ if let Ok(rect) = self.element.0.get_bounding_rectangle() {
+ println!("bounding rectangle: {:?}", rect);
+ // Calculate center point of the element
+ let center_x = rect.get_left() + rect.get_width() / 2;
+ let center_y = rect.get_top() + rect.get_height() / 2;
+
+ let point = Point::new(center_x, center_y);
+ let mouse = Mouse::default();
+
+ debug!("clicking at center point: ({}, {})", center_x, center_y);
+ mouse.click(point)
+ .map_err(|e| AutomationError::PlatformError(e.to_string()))?;
+
+ return Ok(ClickResult {
+ method: "Single Click (Fallback)".to_string(),
+ coordinates: Some((center_x as f64, center_y as f64)),
+ details: "Clicked by Mouse using element's center coordinates".to_string(),
+ });
+ }
+ }
+
+ // Return the result of the first attempt or propagate the error
+ click_result.map_err(|e| AutomationError::PlatformError(e.to_string()))
}
fn double_click(&self) -> Result<ClickResult, AutomationError> {
@@ -488,58 +549,73 @@ impl UIElementImpl for WindowsUIElement {
let control_type = self.element.0.get_control_type()
.map_err(|e| AutomationError::PlatformError(e.to_string()))?;
// check if element accepts input
- if control_type == ControlType::Edit {
+ println!("control_type: {:#?}", control_type);
+ // if control_type == ControlType::Edit {
let keyboard = Keyboard::default();
keyboard.send_text(text)
.map_err(|e| AutomationError::PlatformError(e.to_string()))?;
Ok(())
- } else {
- Err(AutomationError::PlatformError("Element is not editable".to_string()))
- }
+ // } else {
+ // Err(AutomationError::PlatformError("Element is not editable".to_string()))
+ // }
}
fn press_key(&self, key: &str) -> Result<(), AutomationError> {
let control_type = self.element.0.get_control_type()
.map_err(|e| AutomationError::PlatformError(e.to_string()))?;
// check if element accepts input, similar :D
- if control_type == ControlType::Edit {
+ // if control_type == ControlType::Edit {
let keyboard = Keyboard::default();
keyboard.send_keys(key)
.map_err(|e| AutomationError::PlatformError(e.to_string()))?;
Ok(())
- } else {
- Err(AutomationError::PlatformError("Element is not editable".to_string()))
- }
+ // } else {
+ // Err(AutomationError::PlatformError("Element is not editable".to_string()))
+ // }
}
fn get_text(&self, max_depth: usize) -> Result<String, AutomationError> {
- let automation = WindowsEngine::new(false, false)
- .map_err(|e| AutomationError::PlatformError(e.to_string()))?;
- let mut all_texts = String::new();
- // run the text matcher
- let txt_matcher = automation.automation.0.create_matcher()
- .control_type(ControlType::Text)
- .from_ref(&self.element.0)
- .depth(max_depth as u32)
- .timeout(1000);
-
- if let Ok(text_eles) = txt_matcher.find_all() {
- for text_ele in text_eles {
- // get name
- if let Ok(name) = text_ele.get_property_value(UIProperty::Name) {
- if let Ok(name_text) = name.get_string() {
- all_texts.push_str(&name_text);
+ let mut all_texts = Vec::new();
+
+ // Create a function to extract text recursively
+ fn extract_text_from_element(element: &uiautomation::UIElement, texts: &mut Vec<String>, current_depth: usize, max_depth: usize) -> Result<(), AutomationError> {
+ if current_depth > max_depth {
+ return Ok(());
+ }
+
+ // Check Name property
+ if let Ok(name) = element.get_property_value(UIProperty::Name) {
+ if let Ok(name_text) = name.get_string() {
+ if !name_text.is_empty() {
+ texts.push(name_text);
}
}
- // get value
- if let Ok(value) = text_ele.get_property_value(UIProperty::ValueValue) {
- if let Ok(val_text) = value.get_string(){
- all_texts.push_str(&val_text);
+ }
+
+ // Check Value property
+ if let Ok(value) = element.get_property_value(UIProperty::ValueValue) {
+ if let Ok(value_text) = value.get_string() {
+ if !value_text.is_empty() {
+ texts.push(value_text);
}
}
}
+
+ // Recursively process children
+ if let Ok(children) = element.get_cached_children() {
+ for child in children {
+ let _ = extract_text_from_element(&child, texts, current_depth + 1, max_depth);
+ }
+ }
+
+ Ok(())
}
- Ok(all_texts)
+
+ // Extract text from the element and its descendants
+ extract_text_from_element(&self.element.0, &mut all_texts, 0, max_depth)?;
+
+ // Join the texts with spaces
+ Ok(all_texts.join(" "))
}
fn set_value(&self, value: &str) -> Result<(), AutomationError> {