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

release-app: ignore unfocused windows by default

Louis Beaumontdb2232041985
diff --git a/Cargo.toml b/Cargo.toml
index d04ef3b49..136ee95bd 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -14,7 +14,7 @@ resolver = "2"
[workspace.package]
-version = "0.2.14"
+version = "0.2.15"
authors = ["louis030195 <[email protected]>"]
description = ""
repository = "https://github.com/mediar-ai/screenpipe"
@@ -41,6 +41,8 @@ criterion = { version = "0.5.1", features = ["async_tokio"] }
vcpkg = "0.2"
cc = "1.0"
+once_cell = "1.20.2"
+
[patch.crates-io]
# enables chinese mirror (hf is banned in china)
hf-hub = { git = "https://github.com/king-jingxiang/hf-hub" }
diff --git a/screenpipe-app-tauri/components/cli-command-dialog.tsx b/screenpipe-app-tauri/components/cli-command-dialog.tsx
index 0169ca637..dc21856f2 100644
--- a/screenpipe-app-tauri/components/cli-command-dialog.tsx
+++ b/screenpipe-app-tauri/components/cli-command-dialog.tsx
@@ -29,8 +29,12 @@ export function CliCommandDialog({ localSettings }: CliCommandDialogProps) {
let args = [];
if (localSettings.audioTranscriptionEngine !== "default") {
+ const audioTranscriptionEngine =
+ localSettings.audioTranscriptionEngine === "screenpipe-cloud"
+ ? "deepgram"
+ : localSettings.audioTranscriptionEngine;
args.push(
- `--audio-transcription-engine ${localSettings.audioTranscriptionEngine}`
+ `--audio-transcription-engine ${audioTranscriptionEngine}`
);
}
if (localSettings.ocrEngine !== "default") {
diff --git a/screenpipe-app-tauri/src-tauri/Cargo.toml b/screenpipe-app-tauri/src-tauri/Cargo.toml
index 641c45c8b..b51863804 100644
--- a/screenpipe-app-tauri/src-tauri/Cargo.toml
+++ b/screenpipe-app-tauri/src-tauri/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "screenpipe-app"
-version = "0.16.9"
+version = "0.17.0"
description = ""
authors = ["you"]
license = ""
diff --git a/screenpipe-server/src/bin/screenpipe-server.rs b/screenpipe-server/src/bin/screenpipe-server.rs
index 9b9aa812d..82163edb9 100644
--- a/screenpipe-server/src/bin/screenpipe-server.rs
+++ b/screenpipe-server/src/bin/screenpipe-server.rs
@@ -444,7 +444,6 @@ async fn main() -> anyhow::Result<()> {
vision_control_clone.clone(),
audio_devices_control.clone(),
cli.disable_audio,
- cli.save_text_files,
Arc::new(cli.audio_transcription_engine.clone().into()),
Arc::new(cli.ocr_engine.clone().into()),
monitor_ids_clone.clone(),
@@ -458,6 +457,7 @@ async fn main() -> anyhow::Result<()> {
cli.deepgram_api_key.clone(),
cli.vad_sensitivity.clone(),
languages.clone(),
+ cli.capture_unfocused_windows,
);
let result = tokio::select! {
@@ -540,7 +540,6 @@ async fn main() -> anyhow::Result<()> {
println!("│ port │ {:<34} │", cli.port);
println!("│ audio disabled │ {:<34} │", cli.disable_audio);
println!("│ vision disabled │ {:<34} │", cli.disable_vision);
- println!("│ save text files │ {:<34} │", cli.save_text_files);
println!(
"│ audio engine │ {:<34} │",
format!("{:?}", warning_audio_transcription_engine_clone)
diff --git a/screenpipe-server/src/cli.rs b/screenpipe-server/src/cli.rs
index 7f612312b..25190fcef 100644
--- a/screenpipe-server/src/cli.rs
+++ b/screenpipe-server/src/cli.rs
@@ -136,10 +136,6 @@ pub struct Cli {
#[arg(long)]
pub debug: bool,
- /// Save text files
- #[arg(long, default_value_t = false)]
- pub save_text_files: bool,
-
/// Audio transcription engine to use.
/// Deepgram is a very high quality cloud-based transcription service (free of charge on us for now), recommended for high quality audio.
/// WhisperTiny is a local, lightweight transcription model, recommended for high data privacy.
@@ -239,6 +235,10 @@ pub struct Cli {
#[arg(long, default_value_t = false)]
pub enable_frame_cache: bool,
+ /// Capture windows that are not focused (default: false)
+ #[arg(long, default_value_t = false)]
+ pub capture_unfocused_windows: bool,
+
#[command(subcommand)]
pub command: Option<Command>,
diff --git a/screenpipe-server/src/core.rs b/screenpipe-server/src/core.rs
index 41a7ffd55..24adfcbcc 100644
--- a/screenpipe-server/src/core.rs
+++ b/screenpipe-server/src/core.rs
@@ -31,7 +31,6 @@ pub async fn start_continuous_recording(
vision_control: Arc<AtomicBool>,
audio_devices_control: Arc<SegQueue<(AudioDevice, DeviceControl)>>,
audio_disabled: bool,
- save_text_files: bool,
audio_transcription_engine: Arc<AudioTranscriptionEngine>,
ocr_engine: Arc<OcrEngine>,
monitor_ids: Vec<u32>,
@@ -45,6 +44,7 @@ pub async fn start_continuous_recording(
deepgram_api_key: Option<String>,
vad_sensitivity: CliVadSensitivity,
languages: Vec<Language>,
+ capture_unfocused_windows: bool,
) -> Result<()> {
debug!("Starting video recording for monitor {:?}", monitor_ids);
let video_tasks = if !vision_disabled {
@@ -67,7 +67,6 @@ pub async fn start_continuous_recording(
output_path_video,
fps,
is_running_video,
- save_text_files,
ocr_engine,
monitor_id,
use_pii_removal,
@@ -75,6 +74,7 @@ pub async fn start_continuous_recording(
&include_windows_video,
video_chunk_duration,
languages.clone(),
+ capture_unfocused_windows,
)
.await
})
@@ -165,7 +165,6 @@ async fn record_video(
output_path: Arc<String>,
fps: f64,
is_running: Arc<AtomicBool>,
- save_text_files: bool,
ocr_engine: Arc<OcrEngine>,
monitor_id: u32,
use_pii_removal: bool,
@@ -173,6 +172,7 @@ async fn record_video(
include_windows: &[String],
video_chunk_duration: Duration,
languages: Vec<Language>,
+ capture_unfocused_windows: bool,
) -> Result<()> {
debug!("record_video: Starting");
let db_chunk_callback = Arc::clone(&db);
@@ -203,12 +203,12 @@ async fn record_video(
fps,
video_chunk_duration,
new_chunk_callback,
- save_text_files,
Arc::clone(&ocr_engine),
monitor_id,
ignored_windows,
include_windows,
languages,
+ capture_unfocused_windows,
);
while is_running.load(Ordering::SeqCst) {
diff --git a/screenpipe-server/src/video.rs b/screenpipe-server/src/video.rs
index 6c155c476..eb35b694b 100644
--- a/screenpipe-server/src/video.rs
+++ b/screenpipe-server/src/video.rs
@@ -4,7 +4,9 @@ use image::ImageFormat::{self};
use log::{debug, error};
use log::{info, warn};
use screenpipe_core::{find_ffmpeg_path, Language};
-use screenpipe_vision::{continuous_capture, CaptureResult, OcrEngine};
+use screenpipe_vision::{
+ capture_screenshot_by_window::WindowFilters, continuous_capture, CaptureResult, OcrEngine,
+};
use std::path::PathBuf;
use std::process::Stdio;
use std::sync::Arc;
@@ -31,12 +33,12 @@ impl VideoCapture {
fps: f64,
video_chunk_duration: Duration,
new_chunk_callback: impl Fn(&str) + Send + Sync + 'static,
- save_text_files: bool,
ocr_engine: Arc<OcrEngine>,
monitor_id: u32,
ignore_list: &[String],
include_list: &[String],
languages: Vec<Language>,
+ capture_unfocused_windows: bool,
) -> Self {
let fps = if fps.is_finite() && fps > 0.0 {
fps
@@ -53,23 +55,21 @@ impl VideoCapture {
let capture_video_frame_queue = video_frame_queue.clone();
let capture_ocr_frame_queue = ocr_frame_queue.clone();
let (result_sender, mut result_receiver) = channel(512);
- let ignore_list_clone = ignore_list.to_vec();
- let include_list_clone = include_list.to_vec();
+ let window_filters = Arc::new(WindowFilters::new(ignore_list, include_list));
+ let window_filters_clone = Arc::clone(&window_filters);
let _capture_thread = tokio::spawn(async move {
continuous_capture(
result_sender,
interval,
- save_text_files,
*ocr_engine,
monitor_id,
- &ignore_list_clone,
- &include_list_clone,
+ window_filters_clone,
languages.clone(),
+ capture_unfocused_windows,
)
.await;
});
-
// In the _queue_thread
let _queue_thread = tokio::spawn(async move {
// Helper function to push to queue and handle errors
@@ -170,7 +170,7 @@ pub async fn start_ffmpeg_process(output_file: &str, fps: f64) -> Result<Child,
// TODO: issue on macos https://github.com/mediar-ai/screenpipe/pull/580
#[cfg(target_os = "macos")]
args.extend_from_slice(&["-vcodec", "libx264", "-preset", "ultrafast", "-crf", "23"]);
-
+
#[cfg(not(target_os = "macos"))]
args.extend_from_slice(&["-vcodec", "libx265", "-preset", "ultrafast", "-crf", "23"]);
diff --git a/screenpipe-vision/Cargo.toml b/screenpipe-vision/Cargo.toml
index 88e01de98..93c58f47f 100644
--- a/screenpipe-vision/Cargo.toml
+++ b/screenpipe-vision/Cargo.toml
@@ -42,6 +42,8 @@ tracing-subscriber = { workspace = true }
tracing = { workspace = true }
which = "6.0"
+once_cell = { workspace = true }
+
[dev-dependencies]
tempfile = "3.3.0"
criterion = { workspace = true }
@@ -90,7 +92,7 @@ xcap = "0.0.12"
[target.'cfg(target_os = "macos")'.dependencies]
libc = "=0.2.164"
-xcap = "0.0.13"
+xcap-macos = { package = "xcap", git = "https://github.com/mediar-ai/xcap", rev = "965bc99" }
[target.'cfg(target_os = "linux")'.dependencies]
libc = "=0.2.164"
diff --git a/screenpipe-vision/examples/window-properties.rs b/screenpipe-vision/examples/window-properties.rs
new file mode 100644
index 000000000..ca7befcb4
--- /dev/null
+++ b/screenpipe-vision/examples/window-properties.rs
@@ -0,0 +1,30 @@
+use anyhow::Result;
+use tokio::time::{sleep, Duration};
+use xcap::{Monitor, Window};
+
+#[tokio::main]
+async fn main() -> Result<()> {
+ loop {
+ println!("\n=== Windows State ===");
+
+ match Window::all() {
+ Ok(windows) => {
+ for window in windows {
+ println!("Window: {}", window.title());
+ println!(" App: {}", window.app_name());
+ println!(" ID: {}", window.id());
+ println!(" Is Minimized: {}", window.is_minimized());
+ println!(" Is Visible: {}", window.is_maximized());
+ println!(" Title: {:?}", window.title());
+ println!(" Height: {:?}", window.height());
+ println!(" Width: {:?}", window.width());
+
+ println!("---");
+ }
+ }
+ Err(e) => println!("failed to get windows: {:?}", e),
+ }
+
+ sleep(Duration::from_secs(1)).await;
+ }
+}
diff --git a/screenpipe-vision/src/bin/screenpipe-vision.rs b/screenpipe-vision/src/bin/screenpipe-vision.rs
index 22198b456..7c777096b 100644
--- a/screenpipe-vision/src/bin/screenpipe-vision.rs
+++ b/screenpipe-vision/src/bin/screenpipe-vision.rs
@@ -1,17 +1,16 @@
use clap::Parser;
use screenpipe_core::Language;
-use screenpipe_vision::{continuous_capture, monitor::get_default_monitor, OcrEngine};
-use std::time::Duration;
+use screenpipe_vision::{
+ capture_screenshot_by_window::WindowFilters, continuous_capture, monitor::get_default_monitor,
+ OcrEngine,
+};
+use std::{sync::Arc, time::Duration};
use tokio::sync::mpsc::channel;
use tracing_subscriber::{fmt::format::FmtSpan, EnvFilter};
#[derive(Parser)]
#[command(author, version, about, long_about = None)]
struct Cli {
- /// Save text files
- #[arg(long, default_value_t = false)]
- save_text_files: bool,
-
/// FPS
#[arg(long, default_value_t = 1.0)]
fps: f32,
@@ -34,22 +33,21 @@ async fn main() {
let (result_tx, mut result_rx) = channel(512);
- let save_text_files = cli.save_text_files;
let languages = cli.language;
let monitor = get_default_monitor().await;
let id = monitor.id();
+ let window_filters = WindowFilters::new(&[], &[]);
tokio::spawn(async move {
continuous_capture(
result_tx,
Duration::from_secs_f32(1.0 / cli.fps),
- save_text_files,
OcrEngine::AppleNative,
id,
- &[],
- &[],
+ Arc::new(window_filters),
languages.clone(),
+ false,
)
.await
});
diff --git a/screenpipe-vision/src/capture_screenshot_by_window.rs b/screenpipe-vision/src/capture_screenshot_by_window.rs
index 9fae645bc..9cc00491f 100644
--- a/screenpipe-vision/src/capture_screenshot_by_window.rs
+++ b/screenpipe-vision/src/capture_screenshot_by_window.rs
@@ -1,9 +1,16 @@
use image::DynamicImage;
use log::error;
+use once_cell::sync::Lazy;
+use std::collections::HashSet;
use std::error::Error;
use std::fmt;
use std::time::Duration;
use tokio::time;
+
+#[cfg(target_os = "macos")]
+use xcap_macos::{Monitor, Window, XCapError};
+
+#[cfg(not(target_os = "macos"))]
use xcap::{Monitor, Window, XCapError};
#[derive(Debug)]
@@ -30,11 +37,165 @@ impl From<XCapError> for CaptureError {
}
}
+// Platform specific skip lists
+#[cfg(target_os = "macos")]
+static SKIP_APPS: Lazy<HashSet<&'static str>> = Lazy::new(|| {
+ HashSet::from([
+ "Window Server",
+ "SystemUIServer",
+ "ControlCenter",
+ "Dock",
+ "NotificationCenter",
+ "loginwindow",
+ "WindowManager",
+ "Contexts",
+ ])
+});
+
+#[cfg(target_os = "windows")]
+static SKIP_APPS: Lazy<HashSet<&'static str>> = Lazy::new(|| {
+ HashSet::from([
+ "Windows Shell Experience Host",
+ "Microsoft Text Input Application",
+ "Windows Explorer",
+ "Program Manager",
+ "Microsoft Store",
+ "Search",
+ "TaskBar",
+ ])
+});
+
+#[cfg(target_os = "linux")]
+static SKIP_APPS: Lazy<HashSet<&'static str>> = Lazy::new(|| {
+ HashSet::from([
+ "Gnome-shell",
+ "Plasma",
+ "Xfdesktop",
+ "Polybar",
+ "i3bar",
+ "Plank",
+ "Dock",
+ ])
+});
+
+#[cfg(target_os = "macos")]
+static SKIP_TITLES: Lazy<HashSet<&'static str>> = Lazy::new(|| {
+ HashSet::from([
+ "Item-0",
+ "App Icon Window",
+ "Dock",
+ "NowPlaying",
+ "FocusModes",
+ "Shortcuts",
+ "AudioVideoModule",
+ "Clock",
+ "WiFi",
+ "Battery",
+ "BentoBox",
+ "Menu Bar",
+ "Notification Center",
+ "Control Center",
+ "Spotlight",
+ "Mission Control",
+ "Desktop",
+ "Screen Sharing",
+ "Touch Bar",
+ "Status Bar",
+ "Menu Extra",
+ "System Settings",
+ ])
+});
+
+#[cfg(target_os = "windows")]
+static SKIP_TITLES: Lazy<HashSet<&'static str>> = Lazy::new(|| {
+ HashSet::from([
+ "Program Manager",
+ "Windows Input Experience",
+ "Microsoft Text Input Application",
+ "Task View",
+ "Start",
+ "System Tray",
+ "Notification Area",
+ "Action Center",
+ "Task Bar",
+ "Desktop",
+ ])
+});
+
+#[cfg(target_os = "linux")]
+static SKIP_TITLES: Lazy<HashSet<&'static str>> = Lazy::new(|| {
+ HashSet::from([
+ "Desktop",
+ "Panel",
+ "Top Bar",
+ "Status Bar",
+ "Dock",
+ "Dashboard",
+ "Activities",
+ "System Tray",
+ "Notification Area",
+ ])
+});
+
+#[derive(Debug, Clone)]
+pub struct CapturedWindow {
+ pub image: DynamicImage,
+ pub app_name: String,
+ pub window_name: String,
+ pub is_focused: bool,
+}
+
+pub struct WindowFilters {
+ ignore_set: HashSet<String>,
+ include_set: HashSet<String>,
+}
+
+impl WindowFilters {
+ pub fn new(ignore_list: &[String], include_list: &[String]) -> Self {
+ Self {
+ ignore_set: ignore_list.iter().map(|s| s.to_lowercase()).collect(),
+ include_set: include_list.iter().map(|s| s.to_lowercase()).collect(),
+ }
+ }
+
+ // O(n) - we could figure out a better way to do this
+ pub fn is_valid(&self, app_name: &str, title: &str) -> bool {
+ let app_name_lower = app_name.to_lowercase();
+ let title_lower = title.to_lowercase();
+
+ // If include list is empty, we're done
+ if self.include_set.is_empty() {
+ return true;
+ }
+
+ // Check include list
+ if self
+ .include_set
+ .iter()
+ .any(|include| app_name_lower.contains(include) || title_lower.contains(include))
+ {
+ return true;
+ }
+
+ // Check ignore list first (usually smaller)
+ if !self.ignore_set.is_empty()
+ && self
+ .ignore_set
+ .iter()
+ .any(|ignore| app_name_lower.contains(ignore) || title_lower.contains(ignore))
+ {
+ return false;
+ }
+
+ false
+ }
+}
+
pub async fn capture_all_visible_windows(
monitor: &Monitor,
- ignore_list: &[String],
- include_list: &[String],
-) -> Result<Vec<(DynamicImage, String, String, bool)>, Box<dyn Error>> {
+ window_filters: &WindowFilters,
+ capture_unfocused_windows: bool,
+) -> Result<Vec<CapturedWindow>, Box<dyn Error>> {
let mut all_captured_images = Vec::new();
let windows = retry_with_backoff(
@@ -51,85 +212,74 @@ pub async fn capture_all_visible_windows(
)
.await?;
- let focused_window = windows
- .iter()
- .find(|&w| is_valid_window(w, monitor, ignore_list, include_list));
-
for window in &windows {
- if is_valid_window(window, monitor, ignore_list, include_list) {
- let app_name = window.app_name();
- let window_name = window.title();
- let is_focused = focused_window
- .as_ref()
- .map_or(false, |fw| fw.id() == window.id());
-
- match window.capture_image() {
- Ok(buffer) => {
- let image = DynamicImage::ImageRgba8(
- image::ImageBuffer::from_raw(
- buffer.width() as u32,
- buffer.height() as u32,
- buffer.into_raw(),
- )
- .unwrap(),
- );
-
- all_captured_images.push((
- image,
- app_name.to_string(),
- window_name.to_string(),
- is_focused,
- ));
- }
- Err(e) => error!(
- "Failed to capture image for window {} on monitor {}: {}",
- window_name,
- monitor.name(),
- e
- ),
+ let is_valid = is_valid_window(window, monitor, window_filters, capture_unfocused_windows);
+
+ if !is_valid {
+ continue;
+ }
+
+ let app_name = window.app_name();
+ let window_name = window.title();
+
+ match window.capture_image() {
+ Ok(buffer) => {
+ let image = DynamicImage::ImageRgba8(
+ image::ImageBuffer::from_raw(
+ buffer.width() as u32,
+ buffer.height() as u32,
+ buffer.into_raw(),
+ )
+ .unwrap(),
+ );
+
+ all_captured_images.push(CapturedWindow {
+ image,
+ app_name: app_name.to_string(),
+ window_name: window_name.to_string(),
+ is_focused: is_valid,
+ });
}
+ Err(e) => error!(
+ "Failed to capture image for window {} on monitor {}: {}",
+ window_name,
+ monitor.name(),
+ e
+ ),
}
}
Ok(all_captured_images)
}
-fn is_valid_window(
+pub fn is_valid_window(
window: &Window,
monitor: &Monitor,
- ignore_list: &[String],
- include_list: &[String],
+ filters: &WindowFilters,
+ capture_unfocused_windows: bool,
) -> bool {
- // Early returns for simple checks
- if window.current_monitor().id() != monitor.id()
- || window.is_minimized()
- || window.app_name() == "Window Server"
- || window.app_name() == "Contexts"
- || window.title().is_empty() {
- return false;
- }
+ if !capture_unfocused_windows {
+ // Early returns for simple checks
+ #[cfg(target_os = "macos")]
+ let is_focused = window.current_monitor().id() == monitor.id() && window.is_focused();
- // Cache lowercase strings to avoid multiple conversions
- let app_name_lower = window.app_name().to_lowercase();
- let title_lower = window.title().to_lowercase();
+ #[cfg(not(target_os = "macos"))]
+ let is_focused = window.current_monitor().id() == monitor.id() && !window.is_minimized();
- // Check ignore list first (might exit early)
- if ignore_list.iter().any(|ignore| {
- let ignore_lower = ignore.to_lowercase();
- app_name_lower.contains(&ignore_lower) || title_lower.contains(&ignore_lower)
- }) {
- return false;
+ if !is_focused {
+ return false;
+ }
}
- // If include list is empty, return true
- if include_list.is_empty() {
- return true;
+ // Fast O(1) lookups using HashSet
+ let app_name = window.app_name();
+ let title = window.title();
+
+ if SKIP_APPS.contains(app_name) || SKIP_TITLES.contains(title) {
+ return false;
}
- return include_list.iter().any(|include| {
- let include_lower = include.to_lowercase();
- app_name_lower.contains(&include_lower) || title_lower.contains(&include_lower)
- });
+ filters.is_valid(app_name, title)
}
async fn retry_with_backoff<F, T, E>(
diff --git a/screenpipe-vision/src/core.rs b/screenpipe-vision/src/core.rs
index fbb4627ff..3dea68919 100644
--- a/screenpipe-vision/src/core.rs
+++ b/screenpipe-vision/src/core.rs
@@ -2,24 +2,32 @@
use crate::apple::parse_apple_ocr_result;
#[cfg(target_os = "macos")]
use crate::apple::perform_ocr_apple;
+use crate::capture_screenshot_by_window::CapturedWindow;
+use crate::capture_screenshot_by_window::WindowFilters;
#[cfg(target_os = "windows")]
use crate::microsoft::perform_ocr_windows;
use crate::monitor::get_monitor_by_id;
use crate::tesseract::perform_ocr_tesseract;
use crate::utils::OcrEngine;
-use crate::utils::{capture_screenshot, compare_with_previous_image, save_text_files};
+use crate::utils::{capture_screenshot, compare_with_previous_image};
use anyhow::{anyhow, Result};
use image::DynamicImage;
use log::{debug, error};
use screenpipe_core::Language;
use screenpipe_integrations::unstructured_ocr::perform_ocr_cloud;
use serde_json;
+use std::sync::Arc;
use std::{
collections::HashMap,
time::{Duration, Instant},
};
use tokio::sync::mpsc::Sender;
use tokio::time::sleep;
+
+#[cfg(target_os = "macos")]
+use xcap_macos::Monitor;
+
+#[cfg(not(target_os = "macos"))]
use xcap::Monitor;
pub struct CaptureResult {
@@ -41,7 +49,7 @@ pub struct WindowOcrResult {
pub struct OcrTaskData {
pub image: DynamicImage,
- pub window_images: Vec<(DynamicImage, String, String, bool)>,
+ pub window_images: Vec<CapturedWindow>,
pub frame_number: u64,
pub timestamp: Instant,
pub result_tx: Sender<CaptureResult>,
@@ -50,12 +58,11 @@ pub struct OcrTaskData {
pub async fn continuous_capture(
result_tx: Sender<CaptureResult>,
interval: Duration,
- save_text_files_flag: bool,
ocr_engine: OcrEngine,
monitor_id: u32,
- ignore_list: &[String],
- include_list: &[String],
+ window_filters: Arc<WindowFilters>,
languages: Vec<Language>,
+ capture_unfocused_windows: bool,
) {
let mut frame_counter: u64 = 0;
let mut previous_image: Option<DynamicImage> = None;
@@ -75,19 +82,20 @@ pub async fn continuous_capture(
continue;
}
};
- let capture_result = match capture_screenshot(&monitor, ignore_list, include_list).await {
- Ok((image, window_images, image_hash, _capture_duration)) => {
- debug!(
- "Captured screenshot on monitor {} with hash: {}",
- monitor_id, image_hash
- );
- Some((image, window_images, image_hash))
- }
- Err(e) => {
- error!("Failed to capture screenshot: {}", e);
- None
- }
- };
+ let capture_result =
+ match capture_screenshot(&monitor, &window_filters, capture_unfocused_windows).await {
+ Ok((image, window_images, image_hash, _capture_duration)) => {
+ debug!(
+ "Captured screenshot on monitor {} with hash: {}",
+ monitor_id, image_hash
+ );
+ Some((image, window_images, image_hash))
+ }
+ Err(e) => {
+ error!("Failed to capture screenshot: {}", e);
+ None
+ }
+ };
if let Some((image, window_images, image_hash)) = capture_result {
let current_average = match compare_with_previous_image(
@@ -146,13 +154,8 @@ pub async fn continuous_capture(
result_tx: max_avg_frame.result_tx,
};
- if let Err(e) = process_ocr_task(
- ocr_task_data,
- save_text_files_flag,
- &ocr_engine,
- languages.clone(),
- )
- .await
+ if let Err(e) =
+ process_ocr_task(ocr_task_data, &ocr_engine, languages.clone()).await
{
error!("Error processing OCR task: {}", e);
}
@@ -171,7 +174,7 @@ pub async fn continuous_capture(
pub struct MaxAverageFrame {
pub image: DynamicImage,
- pub window_images: Vec<(DynamicImage, String, String, bool)>,
+ pub window_images: Vec<CapturedWindow>,
pub image_hash: u64,
pub frame_number: u64,
pub timestamp: Instant,
@@ -181,7 +184,6 @@ pub struct MaxAverageFrame {
pub async fn process_ocr_task(
ocr_task_data: OcrTaskData,
- save_text_files_flag: bool,
ocr_engine: &OcrEngine,
languages: Vec<Language>,
) -> Result<(), std::io::Error> {
@@ -203,20 +205,23 @@ pub async fn process_ocr_task(
let mut total_confidence = 0.0;
let mut window_count = 0;
- for (window_image, window_app_name, window_name, focused) in window_images {
+ for captured_window in window_images {
let (window_text, window_json_output, confidence) = match ocr_engine {
- OcrEngine::Unstructured => perform_ocr_cloud(&window_image, languages.clone())
+ OcrEngine::Unstructured => perform_ocr_cloud(&captured_window.image, languages.clone())
.await
.map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e))?,
- OcrEngine::Tesseract => perform_ocr_tesseract(&window_image, languages.clone()),
+ OcrEngine::Tesseract => {
+ perform_ocr_tesseract(&captured_window.image, languages.clone())
+ }
#[cfg(target_os = "windows")]
- OcrEngine::WindowsNative => perform_ocr_windows(&window_image)
+ OcrEngine::WindowsNative => perform_ocr_windows(&captured_window.image)
.await
.map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e))?,
#[cfg(target_os = "macos")]
- OcrEngine::AppleNative => {
- parse_apple_ocr_result(&perform_ocr_apple(&window_image, languages.clone()))
- }
+ OcrEngine::AppleNative => parse_apple_ocr_result(&perform_ocr_apple(
+ &captured_window.image,
+ languages.clone(),
+ )),
_ => {
return Err(std::io::Error::new(
std::io::ErrorKind::Other,
@@ -231,28 +236,16 @@ pub async fn process_ocr_task(
}
window_ocr_results.push(WindowOcrResult {
- image: window_image,
- window_name,
- app_name: window_app_name,
+ image: captured_window.image,
+ window_name: captured_window.window_name,
+ app_name: captured_window.app_name,
text: window_text,
text_json: parse_json_output(&window_json_output),
- focused,
+ focused: captured_window.is_focused,
confidence: confidence.unwrap_or(0.0),
});
}
- if save_text_files_flag {
- for (index, window_result) in window_ocr_results.iter().enumerate() {
- save_text_files(
- frame_number * 1000 + index as u64,
- &window_result.text_json,
- &window_result.text_json,
- &None,
- )
- .await;
- }
- }
-
let capture_result = CaptureResult {
image,
frame_number,
diff --git a/screenpipe-vision/src/monitor.rs b/screenpipe-vision/src/monitor.rs
index b3329f42c..142c6c49a 100644
--- a/screenpipe-vision/src/monitor.rs
+++ b/screenpipe-vision/src/monitor.rs
@@ -1,44 +1,8 @@
-use std::sync::Arc;
+#[cfg(target_os = "macos")]
+use xcap_macos::Monitor;
-use xcap::{Monitor, Window};
-
-// ! logic here: we pick the biggest window and assume it's the one showing the most text that will be grabbed by OCR
-// TODO: longer term we should define a data structure for OCR on specific monitor, window, etc.
-pub async fn get_focused_window(monitor: Arc<Monitor>) -> Option<Window> {
- let windows = Window::all().unwrap_or_default();
-
- let focused_window = windows
- .into_iter()
- .filter(|w| w.current_monitor().id() == monitor.id())
- .filter(|w| !is_system_window(w))
- .filter(|w| is_significant_size(w, &monitor))
- .max_by_key(|w| w.width() * w.height());
-
- focused_window
-}
-
-fn is_system_window(window: &Window) -> bool {
- // TODO linux windows
- let system_apps = ["Dock", "Window Server", "Control Centre", "WindowManager"];
- system_apps.contains(&window.app_name())
-}
-
-fn is_significant_size(window: &Window, monitor: &Monitor) -> bool {
- let window_area = window.width() * window.height();
- let monitor_area = monitor.width() * monitor.height();
- let ratio = window_area as f64 / monitor_area as f64;
-
- // Consider windows that take up between 20% and 100% of the screen
- ratio > 0.2 && ratio <= 1.0
-}
-
-pub async fn get_windows_for_monitor(monitor: Monitor) -> Vec<Window> {
- Window::all()
- .unwrap_or_default()
- .into_iter()
- .filter(|w| w.current_monitor().id() == monitor.id())
- .collect()
-}
+#[cfg(not(target_os = "macos"))]
+use xcap::Monitor;
pub async fn list_monitors() -> Vec<Monitor> {
let monitors = Monitor::all().unwrap();
diff --git a/screenpipe-vision/src/utils.rs b/screenpipe-vision/src/utils.rs
index 75f993e7b..75a1eb828 100644
--- a/screenpipe-vision/src/utils.rs
+++ b/screenpipe-vision/src/utils.rs
@@ -1,14 +1,17 @@
-use crate::capture_screenshot_by_window::capture_all_visible_windows;
+use crate::capture_screenshot_by_window::{
+ capture_all_visible_windows, CapturedWindow, WindowFilters,
+};
use crate::core::MaxAverageFrame;
use image::DynamicImage;
use image_compare::{Algorithm, Metric, Similarity};
use log::{debug, error, warn};
-use std::collections::HashMap;
-use std::fs::{self, File};
use std::hash::{DefaultHasher, Hash, Hasher};
-use std::io::Write;
-use std::path::PathBuf;
use std::time::{Duration, Instant};
+
+#[cfg(target_os = "macos")]
+use xcap_macos::Monitor;
+
+#[cfg(not(target_os = "macos"))]
use xcap::Monitor;
#[derive(Clone, Debug, Copy)]
@@ -51,17 +54,9 @@ pub fn compare_images_ssim(image1: &DynamicImage, image2: &DynamicImage) -> f64
pub async fn capture_screenshot(
monitor: &Monitor,
- ignore_list: &[String],
- include_list: &[String],
-) -> Result<
- (
- DynamicImage,
- Vec<(DynamicImage, String, String, bool)>,
- u64,
- Duration,
- ),
- anyhow::Error,
-> {
+ window_filters: &WindowFilters,
+ capture_unfocused_windows: bool,
+) -> Result<(DynamicImage, Vec<CapturedWindow>, u64, Duration), anyhow::Error> {
// info!("Starting screenshot capture for monitor: {:?}", monitor);
let capture_start = Instant::now();
let buffer = monitor.capture_image().map_err(|e| {
@@ -72,17 +67,18 @@ pub async fn capture_screenshot(
let image_hash = calculate_hash(&image);
let capture_duration = capture_start.elapsed();
- let window_images = match capture_all_visible_windows(monitor, ignore_list, include_list).await
- {
- Ok(images) => images,
- Err(e) => {
- warn!(
- "Failed to capture window images: {}. Continuing with empty result.",
- e
- );
- Vec::new()
- }
- };
+ let window_images =
+ match capture_all_visible_windows(monitor, window_filters, capture_unfocused_windows).await
+ {
+ Ok(images) => images,
+ Err(e) => {
+ warn!(
+ "Failed to capture window images: {}. Continuing with empty result.",
+ e
+ );
+ Vec::new()
+ }
+ };
Ok((image, window_images, image_hash, capture_duration))
}
@@ -109,73 +105,3 @@ pub async fn compare_with_previous_image(
}
Ok(current_average)
}
-
-pub async fn save_text_files(
- frame_number: u64,
- new_text_json: &Vec<HashMap<String, String>>,
- current_text_json: &Vec<HashMap<String, String>>,
- previous_text_json: &Option<Vec<HashMap<String, String>>>,
-) {
- let id = frame_number;
- debug!("Saving text files for frame {}", frame_number);
-
- if let Err(e) = fs::create_dir_all("text_json") {
- error!("Failed to create text_json directory: {}", e);
- return;
- }
-
- let new_text_lines: Vec<String> = new_text_json
- .iter()
- .map(|record| record.get("text").cloned().unwrap_or_default())
- .collect();
-
- let current_text_lines: Vec<String> = current_text_json
- .iter()
- .map(|record| record.get("text").cloned().unwrap_or_default())
- .collect();
- let base_path = PathBuf::from("text_json");
- let new_text_file_path = base_path.join(format!("new_text_{}.txt", id));
- let mut new_text_file = match File::create(&new_text_file_path) {
- Ok(file) => file,
- Err(e) => {
- error!("Failed to create new text file: {}", e);
- return;
- }
- };
- for line in new_text_lines {
- writeln!(new_text_file, "{}", line).unwrap();
- }
-
- let current_text_file_path = base_path.join(format!("current_text_{}.txt", id));
- let mut current_text_file = match File::create(&current_text_file_path) {
- Ok(file) => file,
- Err(e) => {
- error!("Failed to create current text file: {}", e);
- return;
- }
- };
- for line in current_text_lines {
- writeln!(current_text_file, "{}", line).unwrap();
- }
-
- if let Some(prev_json) = previous_text_json {
- let prev_text_lines: Vec<String> = prev_json
- .iter()
- .map(|record| record.get("text").cloned().unwrap_or_default())
- .collect();
- let prev_text_file_path = base_path.join(format!("previous_text_{}.txt", id));
- let mut prev_text_file = match File::create(&prev_text_file_path) {
- Ok(file) => file,
- Err(e) => {
- error!("Failed to create previous text file: {}", e);
- return;
- }
- };
- for line in prev_text_lines {
- if let Err(e) = writeln!(prev_text_file, "{}", line) {
- error!("Failed to write to previous text file: {}", e);
- return;
- }
- }
- }
-}