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

fixes windows build (#1367)

SREEHARI2e3d04a644be
diff --git a/screenpipe-server/src/bin/screenpipe-server.rs b/screenpipe-server/src/bin/screenpipe-server.rs
index 0f5c7ac7d..1115fc670 100644
--- a/screenpipe-server/src/bin/screenpipe-server.rs
+++ b/screenpipe-server/src/bin/screenpipe-server.rs
@@ -222,19 +222,19 @@ async fn main() -> anyhow::Result<()> {
OutputFormat::Json => println!(
"{}",
serde_json::to_string_pretty(&json!({
- "data": futures::future::join_all(monitors.iter().map(|m| async move {
+ "data": monitors.iter().map(|m| {
json!({
"id": m.id(),
- "name": m.inner().await.name()
+ "name": m.name()
})
- })).await,
+ }).collect::<Vec<_>>(),
"success": true
}))?
),
OutputFormat::Text => {
println!("available monitors:");
for monitor in monitors.iter() {
- println!(" {}. {:?}", monitor.id(), monitor.inner().await.name());
+ println!(" {}. {:?}", monitor.id(), monitor.name());
}
}
}
@@ -624,7 +624,7 @@ async fn main() -> anyhow::Result<()> {
let (audio_devices_tx, _) = broadcast::channel(100);
- let realtime_vision_sender_clone = realtime_vision_sender_clone.clone();
+ let _realtime_vision_sender_clone = realtime_vision_sender_clone.clone();
// TODO: Add SSE stream for realtime audio transcription
let server = Server::new(
db_server,
diff --git a/screenpipe-server/src/lib.rs b/screenpipe-server/src/lib.rs
index ef51ff969..329c984e8 100644
--- a/screenpipe-server/src/lib.rs
+++ b/screenpipe-server/src/lib.rs
@@ -32,3 +32,8 @@ pub use server::HealthCheckResponse;
pub use server::PaginatedResponse;
pub use server::Server;
pub use video::VideoCapture;
+pub use axum::Json as JsonResponse;
+pub use server::{
+ api_list_monitors,
+ MonitorInfo,
+};
diff --git a/screenpipe-server/src/server.rs b/screenpipe-server/src/server.rs
index 003726285..166f0a65f 100644
--- a/screenpipe-server/src/server.rs
+++ b/screenpipe-server/src/server.rs
@@ -38,7 +38,7 @@ use screenpipe_audio::{
};
use tracing::{debug, error, info};
-use screenpipe_vision::monitor::list_monitors;
+use screenpipe_vision::monitor::{list_monitors, get_monitor_by_id};
use screenpipe_vision::OcrEngine;
use serde::{Deserialize, Deserializer, Serialize};
use serde_json::{json, Value};
@@ -227,11 +227,11 @@ pub(crate) struct ListDeviceResponse {
#[derive(Serialize)]
pub struct MonitorInfo {
- id: u32,
- name: String,
- width: u32,
- height: u32,
- is_default: bool,
+ pub id: u32,
+ pub name: String,
+ pub width: u32,
+ pub height: u32,
+ pub is_default: bool,
}
#[derive(Deserialize)]
@@ -465,13 +465,22 @@ pub async fn api_list_monitors(
) -> Result<JsonResponse<Vec<MonitorInfo>>, (StatusCode, JsonResponse<serde_json::Value>)> {
let monitors = list_monitors().await;
let monitor_info = futures::future::join_all(monitors.into_iter().map(|monitor| async move {
- let monitor = monitor.inner().await;
- MonitorInfo {
- id: monitor.id(),
- name: monitor.name().to_string(),
- width: monitor.width(),
- height: monitor.height(),
- is_default: monitor.is_primary(),
+ let monitor_id = monitor.id();
+ match get_monitor_by_id(monitor_id).await {
+ Some(monitor) => MonitorInfo {
+ id: monitor.id(),
+ name: monitor.name().to_string(),
+ width: monitor.width(),
+ height: monitor.height(),
+ is_default: monitor.is_primary(),
+ },
+ None => MonitorInfo {
+ id: monitor_id,
+ name: "Unknown".to_string(),
+ width: 0,
+ height: 0,
+ is_default: false,
+ },
}
}))
.await;
@@ -2472,7 +2481,6 @@ pub struct RestartVisionDevicesResponse {
message: String,
restarted_devices: Vec<u32>,
}
-
// async fn restart_vision_devices(
// State(state): State<Arc<AppState>>,
// ) -> Result<JsonResponse<RestartVisionDevicesResponse>, (StatusCode, JsonResponse<Value>)> {
@@ -2524,3 +2532,4 @@ pub struct RestartVisionDevicesResponse {
// restarted_devices,
// }))
// }
+
diff --git a/screenpipe-vision/src/bin/screenpipe-vision.rs b/screenpipe-vision/src/bin/screenpipe-vision.rs
index 7c777096b..c15d23a2e 100644
--- a/screenpipe-vision/src/bin/screenpipe-vision.rs
+++ b/screenpipe-vision/src/bin/screenpipe-vision.rs
@@ -1,12 +1,14 @@
use clap::Parser;
use screenpipe_core::Language;
use screenpipe_vision::{
- capture_screenshot_by_window::WindowFilters, continuous_capture, monitor::get_default_monitor,
+ capture_screenshot_by_window::WindowFilters,
+ continuous_capture,
OcrEngine,
};
use std::{sync::Arc, time::Duration};
use tokio::sync::mpsc::channel;
use tracing_subscriber::{fmt::format::FmtSpan, EnvFilter};
+use xcap::Monitor;
#[derive(Parser)]
#[command(author, version, about, long_about = None)]
@@ -32,25 +34,31 @@ async fn main() {
let cli = Cli::parse();
let (result_tx, mut result_rx) = channel(512);
-
let languages = cli.language;
- let monitor = get_default_monitor().await;
- let id = monitor.id();
- let window_filters = WindowFilters::new(&[], &[]);
+ // Get monitor ID before spawning the task
+ let monitor_id = tokio::task::spawn_blocking(|| {
+ Monitor::all()
+ .unwrap()
+ .first()
+ .unwrap()
+ .id()
+ })
+ .await
+ .unwrap();
- tokio::spawn(async move {
- continuous_capture(
- result_tx,
- Duration::from_secs_f32(1.0 / cli.fps),
- OcrEngine::AppleNative,
- id,
- Arc::new(window_filters),
- languages.clone(),
- false,
- )
- .await
- });
+ let window_filters = Arc::new(WindowFilters::new(&[], &[]));
+
+ continuous_capture(
+ result_tx,
+ Duration::from_secs_f32(1.0 / cli.fps),
+ OcrEngine::AppleNative,
+ monitor_id,
+ window_filters,
+ languages.clone(),
+ false,
+ )
+ .await;
// Example: Process results for 10 seconds, then pause for 5 seconds, then stop
loop {
diff --git a/screenpipe-vision/src/capture_screenshot_by_window.rs b/screenpipe-vision/src/capture_screenshot_by_window.rs
index 2c01376dd..3eb306442 100644
--- a/screenpipe-vision/src/capture_screenshot_by_window.rs
+++ b/screenpipe-vision/src/capture_screenshot_by_window.rs
@@ -196,59 +196,51 @@ pub async fn capture_all_visible_windows(
let mut all_captured_images = Vec::new();
// Get windows and immediately extract the data we need
- let windows_data = tokio::task::spawn_blocking(|| {
- Window::all().map(|windows| {
- windows
- .into_iter()
- .map(|window| {
- (
- window.app_name().to_string(),
- window.title().to_string(),
- window.is_focused(),
- window,
- )
- })
- .collect::<Vec<_>>()
+ let windows_data = Window::all()?
+ .into_iter()
+ .filter_map(|window| {
+ // Extract all necessary data from the window while in the main thread
+ let app_name = window.app_name().to_string();
+ let title = window.title().to_string();
+ let is_focused = window.is_focused();
+
+ // Capture image immediately while we have access to the window
+ match window.capture_image() {
+ Ok(buffer) => Some((app_name, title, is_focused, buffer)),
+ Err(_) => None,
+ }
})
- })
- .await??;
+ .collect::<Vec<_>>();
if windows_data.is_empty() {
return Err(Box::new(CaptureError::NoWindows));
}
- for (app_name, window_name, is_focused, window) in windows_data {
- let is_valid = is_valid_window(&window, monitor, window_filters, capture_unfocused_windows);
-
- if !is_valid {
- continue;
- }
-
- // Capture image in blocking context
- match tokio::task::spawn_blocking(move || window.capture_image()).await? {
- Ok(buffer) => {
- let image = DynamicImage::ImageRgba8(
- image::ImageBuffer::from_raw(
- buffer.width(),
- buffer.height(),
- buffer.into_raw(),
- )
- .unwrap(),
- );
-
- all_captured_images.push(CapturedWindow {
- image,
- app_name,
- window_name,
- is_focused,
- });
- }
- Err(e) => error!(
- "Failed to capture image for window {} on monitor {}: {}",
+ // Process the captured data
+ for (app_name, window_name, is_focused, buffer) in windows_data {
+ // Convert to DynamicImage
+ let image = DynamicImage::ImageRgba8(
+ image::ImageBuffer::from_raw(
+ buffer.width(),
+ buffer.height(),
+ buffer.into_raw(),
+ )
+ .unwrap(),
+ );
+
+ // Apply filters
+ let is_valid = !SKIP_APPS.contains(app_name.as_str())
+ && !SKIP_TITLES.contains(window_name.as_str())
+ && (!capture_unfocused_windows || (is_focused && monitor.id() == monitor.id()))
+ && window_filters.is_valid(&app_name, &window_name);
+
+ if is_valid {
+ all_captured_images.push(CapturedWindow {
+ image,
+ app_name,
window_name,
- monitor.inner().await.name(),
- e
- ),
+ is_focused,
+ });
}
}
diff --git a/screenpipe-vision/src/monitor.rs b/screenpipe-vision/src/monitor.rs
index 83205203f..7c893d1d8 100644
--- a/screenpipe-vision/src/monitor.rs
+++ b/screenpipe-vision/src/monitor.rs
@@ -1,57 +1,119 @@
-use anyhow::Result;
+use anyhow::{Result, Error};
use image::DynamicImage;
use std::sync::Arc;
-use tokio::sync::Mutex;
use xcap::Monitor;
-// Thread-safe wrapper around Monitor
#[derive(Clone)]
pub struct SafeMonitor {
monitor_id: u32,
- // We use Arc<Mutex> since we need to share state between threads
- monitor: Arc<Mutex<Monitor>>,
+ monitor_data: Arc<MonitorData>,
+}
+
+#[derive(Clone)]
+pub struct MonitorData {
+ pub width: u32,
+ pub height: u32,
+ pub name: String,
+ pub is_primary: bool,
}
impl SafeMonitor {
pub fn new(monitor: Monitor) -> Self {
let monitor_id = monitor.id();
+ let monitor_data = Arc::new(MonitorData {
+ width: monitor.width(),
+ height: monitor.height(),
+ name: monitor.name().to_string(),
+ is_primary: monitor.is_primary(),
+ });
+
Self {
monitor_id,
- monitor: Arc::new(Mutex::new(monitor)),
+ monitor_data,
}
}
pub async fn capture_image(&self) -> Result<DynamicImage> {
- let monitor = self.monitor.lock().await;
- let image = monitor.capture_image()?;
- Ok(image.into())
+ let monitor_id = self.monitor_id;
+
+ let image = std::thread::spawn(move || -> Result<DynamicImage> {
+ let monitor = Monitor::all()
+ .map_err(Error::from)?
+ .into_iter()
+ .find(|m| m.id() == monitor_id)
+ .ok_or_else(|| anyhow::anyhow!("Monitor not found"))?;
+
+ if monitor.width() == 0 || monitor.height() == 0 {
+ return Err(anyhow::anyhow!("Invalid monitor dimensions"));
+ }
+
+ monitor.capture_image()
+ .map_err(Error::from)
+ .map(DynamicImage::ImageRgba8)
+ })
+ .join()
+ .unwrap()?;
+
+ Ok(image)
}
pub fn id(&self) -> u32 {
self.monitor_id
}
- pub async fn inner(&self) -> tokio::sync::MutexGuard<'_, Monitor> {
- self.monitor.lock().await
+ pub fn dimensions(&self) -> (u32, u32) {
+ (self.monitor_data.width, self.monitor_data.height)
+ }
+
+ pub fn name(&self) -> &str {
+ &self.monitor_data.name
+ }
+
+ pub fn width(&self) -> u32 {
+ self.monitor_data.width
+ }
+
+ pub fn height(&self) -> u32 {
+ self.monitor_data.height
+ }
+
+ pub fn is_primary(&self) -> bool {
+ self.monitor_data.is_primary
+ }
+
+ pub fn get_info(&self) -> MonitorData {
+ (*self.monitor_data).clone()
}
}
pub async fn list_monitors() -> Vec<SafeMonitor> {
- Monitor::all()
- .unwrap()
- .into_iter()
- .map(SafeMonitor::new)
- .collect()
+ tokio::task::spawn_blocking(|| {
+ Monitor::all()
+ .unwrap()
+ .into_iter()
+ .map(SafeMonitor::new)
+ .collect()
+ })
+ .await
+ .unwrap()
}
pub async fn get_default_monitor() -> SafeMonitor {
- SafeMonitor::new(Monitor::all().unwrap().first().unwrap().clone())
+ tokio::task::spawn_blocking(|| {
+ SafeMonitor::new(Monitor::all().unwrap().first().unwrap().clone())
+ })
+ .await
+ .unwrap()
}
pub async fn get_monitor_by_id(id: u32) -> Option<SafeMonitor> {
- Monitor::all()
- .unwrap()
- .into_iter()
- .find(|m| m.id() == id)
- .map(SafeMonitor::new)
+ tokio::task::spawn_blocking(move || {
+ Monitor::all()
+ .unwrap()
+ .into_iter()
+ .find(|m| m.id() == id)
+ .map(SafeMonitor::new)
+ })
+ .await
+ .unwrap()
}