Skip to content

Commit

Permalink
fix all warnings, tests
Browse files Browse the repository at this point in the history
* refactor: clean up code and improve readability across multiple files

- Added missing `None` argument in `bench_search` function.
- Simplified match statements to if conditions in `handle_index_command`.
- Removed unnecessary `unwrap_or_else` and replaced with `unwrap_or` in `read_to_string`.
- Updated argument passing style for `Command::args` to use array syntax.
- Improved formatting and removed redundant lines in various functions.
- Added `#[allow(clippy::too_many_arguments)]` to several functions to suppress warnings.
- Enhanced test cases by removing unnecessary lines and improving readability.
- General code cleanup for better maintainability.

* chore: add rust toolchain configuration file for version 1.84.0

* refactor: enhance AudioTranscriptionEngine with Default implementation and clean up core.rs

* refactor: update path handling in audio processing and encoding modules to use `Path` instead of `PathBuf`, and enhance VAD sensitivity enum with a default variant

* refactor: simplify OCR benchmark code and improve memory handling; clean up monitor and screenshot capture functions

* refactor: improve code readability and suppress clippy warnings across multiple files; update assertions and argument passing style in tests

* refactor: simplify language filtering and confidence calculation in unstructured OCR; improve code readability and reduce unnecessary lines

* chore: update dependencies and improve code formatting; bump screenpipe-app version to 0.26.6, clean up argument passing style, and enhance permission handling

* chore: update Rust version to 1.84 in Cargo.toml

---------

Co-authored-by: Louis Beaumont <[email protected]>
  • Loading branch information
EzraEllette and louis030195 authored Jan 27, 2025
1 parent 8cd040e commit 26a1618
Show file tree
Hide file tree
Showing 49 changed files with 304 additions and 345 deletions.
3 changes: 3 additions & 0 deletions rust-toolchain.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
[toolchain]
channel = "stable"
versioned = "1.84.0"
10 changes: 5 additions & 5 deletions screenpipe-app-tauri/src-tauri/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,16 @@ license = ""
repository = ""
default-run = "screenpipe-app"
edition = "2021"
rust-version = "1.75"
rust-version = "1.84"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[build-dependencies]
tauri-build = { version = "=2.0.3", features = [] }

[dependencies]
tauri = { version = "=2.1.1", features = [ "protocol-asset",
tauri = { version = "=2.1.1", features = [
"protocol-asset",
"macos-private-api",
"tray-icon",
"devtools",
Expand Down Expand Up @@ -60,8 +61,6 @@ tracing-subscriber = { version = "0.3.18", features = ["env-filter"] }
tracing-appender = "0.2.3"




anyhow = "1.0.71"

# System information
Expand All @@ -71,7 +70,7 @@ sysinfo = "=0.29.0"
fix-path-env = { git = "https://github.com/tauri-apps/fix-path-env-rs" }

# server
axum = "0.6.0" # or your current version
axum = "0.6.0" # or your current version


dirs = "5.0.1"
Expand Down Expand Up @@ -119,6 +118,7 @@ cudart = []
metal = []
mkl = []
llm = []
cargo-clippy = []
default = ["custom-protocol"]

# DO NOT REMOVE!!
Expand Down
17 changes: 10 additions & 7 deletions screenpipe-app-tauri/src-tauri/src/disk_usage.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
use serde::{Deserialize, Serialize};
use std::fs;
use std::io;
use tracing::info;
use std::path::{Path, PathBuf};
use serde::{Deserialize, Serialize};
use sysinfo::{System, SystemExt, DiskExt};
use sysinfo::{DiskExt, System, SystemExt};
use tracing::info;

#[derive(Debug, Serialize, Deserialize)]
pub struct DiskUsage {
Expand Down Expand Up @@ -79,12 +79,15 @@ pub async fn disk_usage(screenpipe_dir: &PathBuf) -> Result<Option<DiskUsage>, S
let path = entry.path();
if path.is_dir() {
let size = directory_size(&path).map_err(|e| e.to_string())?;
pipes.push((path.file_name().unwrap().to_string_lossy().to_string(), readable(size)));
pipes.push((
path.file_name().unwrap().to_string_lossy().to_string(),
readable(size),
));
}
}

let total_data_size = directory_size(&screenpipe_dir).map_err(|e| e.to_string())?;
let total_media_size= directory_size(&data_dir).map_err(|e| e.to_string())?;
let total_data_size = directory_size(screenpipe_dir).map_err(|e| e.to_string())?;
let total_media_size = directory_size(&data_dir).map_err(|e| e.to_string())?;
let total_pipes_size = directory_size(&pipes_dir).map_err(|e| e.to_string())?;
let total_cache_size = directory_size(&cache_dir).map_err(|e| e.to_string())?;

Expand Down Expand Up @@ -124,7 +127,7 @@ pub async fn disk_usage(screenpipe_dir: &PathBuf) -> Result<Option<DiskUsage>, S
total_media_size: readable(total_media_size),
},
total_data_size: readable(total_data_size + total_cache_size),
total_cache_size: readable(total_cache_size),
total_cache_size: readable(total_cache_size),
avaiable_space: readable(avaiable_space),
};

Expand Down
10 changes: 5 additions & 5 deletions screenpipe-app-tauri/src-tauri/src/llm_sidecar.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,10 +50,10 @@ impl LLMSidecar {
info!("Starting Ollama serve command...");
let mut serve_command = app.shell().sidecar("ollama").unwrap();
serve_command = serve_command
.args(&["serve"])
.args(["serve"])
.env(
"OLLAMA_HOST",
&format!("http://localhost:{}", self.settings.port),
format!("http://localhost:{}", self.settings.port),
)
.env("CUDA_PATH", &new_cuda_path);

Expand All @@ -74,7 +74,7 @@ impl LLMSidecar {
info!("Starting Ollama model...");
let mut model_command = app.shell().sidecar("ollama").unwrap();
model_command = model_command
.args(&["run", &self.settings.model])
.args(["run", &self.settings.model])
.env("CUDA_PATH", &new_cuda_path);

#[cfg(target_os = "windows")]
Expand Down Expand Up @@ -172,7 +172,7 @@ impl LLMSidecar {
async fn attempt_model_test(&self) -> Result<String> {
let client = reqwest::Client::new();
let response = client
.post(&format!(
.post(format!(
"http://localhost:{}/v1/chat/completions",
self.settings.port
))
Expand Down Expand Up @@ -212,7 +212,7 @@ impl LLMSidecar {
{
app.shell()
.command("taskkill")
.args(&["/F", "/IM", "ollama.exe"])
.args(["/F", "/IM", "ollama.exe"])
.spawn()
.unwrap();
}
Expand Down
47 changes: 24 additions & 23 deletions screenpipe-app-tauri/src-tauri/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,14 +39,14 @@ mod icons;
use crate::analytics::start_analytics;

mod commands;
mod disk_usage;
mod llm_sidecar;
mod permissions;
mod server;
mod sidecar;
mod store;
mod tray;
mod updates;
mod disk_usage;
pub use commands::reset_all_pipes;
pub use commands::set_tray_health_icon;
pub use commands::set_tray_unhealth_icon;
Expand Down Expand Up @@ -96,7 +96,7 @@ impl ShortcutConfig {
.into_iter()
.filter_map(|profile| {
profiles_store
.get(&format!("shortcuts.{}", profile))
.get(format!("shortcuts.{}", profile))
.and_then(|v| v.as_str().map(String::from))
.map(|shortcut| (profile, shortcut))
})
Expand Down Expand Up @@ -179,13 +179,14 @@ async fn register_shortcut(
.on_shortcut(shortcut, move |app, _shortcut, event| {
// Only trigger on key press, not release
if matches!(event.state, ShortcutState::Pressed) {
handler(&app);
handler(app);
}
})
.map_err(|e| e.to_string())
}

#[tauri::command]
#[allow(clippy::too_many_arguments)]
async fn update_global_shortcuts(
app: AppHandle,
show_shortcut: String,
Expand Down Expand Up @@ -288,7 +289,7 @@ async fn apply_shortcuts(app: &AppHandle, config: &ShortcutConfig) -> Result<(),
},
)
.await?;

// Register stop audio shortcut
register_shortcut(
app,
Expand Down Expand Up @@ -366,13 +367,12 @@ async fn list_pipes() -> anyhow::Result<Value> {
Ok(response)
}


fn get_base_dir(app: &tauri::AppHandle, custom_path: Option<String>) -> anyhow::Result<PathBuf> {
let default_path = app.path().local_data_dir().unwrap().join("screenpipe");

let local_data_dir = custom_path.map(PathBuf::from).unwrap_or(default_path);

fs::create_dir_all(&local_data_dir.join("data"))?;
fs::create_dir_all(local_data_dir.join("data"))?;
Ok(local_data_dir)
}

Expand All @@ -387,10 +387,12 @@ pub struct LogFile {
async fn get_log_files(app: AppHandle) -> Result<Vec<LogFile>, String> {
let data_dir = get_data_dir(&app).map_err(|e| e.to_string())?;
let mut log_files = Vec::new();

// Collect all entries first
let mut entries = Vec::new();
let mut dir = tokio::fs::read_dir(&data_dir).await.map_err(|e| e.to_string())?;
let mut dir = tokio::fs::read_dir(&data_dir)
.await
.map_err(|e| e.to_string())?;
while let Some(entry) = dir.next_entry().await.map_err(|e| e.to_string())? {
// Get metadata immediately for each entry
if let Ok(metadata) = entry.metadata().await {
Expand All @@ -406,7 +408,7 @@ async fn get_log_files(app: AppHandle) -> Result<Vec<LogFile>, String> {
.ok()
.and_then(|m| m.duration_since(std::time::SystemTime::UNIX_EPOCH).ok())
.map(|d| d.as_secs())
.unwrap_or(0)
.unwrap_or(0),
)
});

Expand Down Expand Up @@ -438,7 +440,6 @@ async fn get_log_files(app: AppHandle) -> Result<Vec<LogFile>, String> {
Ok(log_files)
}


fn send_recording_notification(
app_handle: &tauri::AppHandle,
success: bool,
Expand Down Expand Up @@ -681,7 +682,7 @@ async fn main() {
// Logging setup
let app_handle = app.handle();
let base_dir =
get_base_dir(&app_handle, None).expect("Failed to ensure local data directory");
get_base_dir(app_handle, None).expect("Failed to ensure local data directory");

// Set up rolling file appender
let file_appender = RollingFileAppender::builder()
Expand All @@ -690,7 +691,7 @@ async fn main() {
.filename_suffix("log")
.max_log_files(5)
.build(
&get_data_dir(&app.handle())
get_data_dir(app.handle())
.unwrap_or_else(|_| dirs::home_dir().unwrap().join(".screenpipe")),
)?;

Expand Down Expand Up @@ -793,7 +794,7 @@ async fn main() {
if pipe["enabled"].as_bool().unwrap_or(false) {
if let Some(id) = pipe["id"].as_str() {
let _ = reqwest::Client::new()
.post(format!("http://localhost:3030/pipes/disable"))
.post("http://localhost:3030/pipes/disable")
.json(&serde_json::json!({
"pipe_id": id
}))
Expand All @@ -804,10 +805,12 @@ async fn main() {
}
}
}

// Stop any running recordings
let state = app_handle_clone.state::<SidecarState>();
if let Err(e) = kill_all_sreenpipes(state, app_handle_clone.clone()).await {
if let Err(e) =
kill_all_sreenpipes(state, app_handle_clone.clone()).await
{
error!("Error stopping recordings during quit: {}", e);
}
});
Expand Down Expand Up @@ -909,7 +912,7 @@ async fn main() {
let _ = window.show();
let _ = window.set_focus();
} else {
show_main_window(&app, true);
show_main_window(app, true);
}
}
}
Expand All @@ -922,7 +925,8 @@ async fn main() {
.build()
.unwrap();

if store.keys().len() == 0 {
// TODO: proper lookup of keys rather than assuming they exist
if store.is_empty() {
store.set("analyticsEnabled".to_string(), Value::Bool(true));
store.set(
"config".to_string(),
Expand Down Expand Up @@ -1000,10 +1004,7 @@ async fn main() {

info!("use_dev_mode: {}", use_dev_mode);

info!(
"will start sidecar: {}",
!use_dev_mode && has_files
);
info!("will start sidecar: {}", !use_dev_mode && has_files);

// if non dev mode and previously started sidecar, start sidecar
if !use_dev_mode && has_files {
Expand Down Expand Up @@ -1087,7 +1088,7 @@ async fn main() {

// Add this to shut down the server
if let Some(server_shutdown_tx) = app_handle.try_state::<mpsc::Sender<()>>() {
let _ = server_shutdown_tx.send(());
drop(server_shutdown_tx.send(()));
}
}
tauri::RunEvent::WindowEvent {
Expand All @@ -1107,7 +1108,7 @@ async fn main() {
..
} => {
if !has_visible_windows {
show_main_window(&app_handle, false);
show_main_window(app_handle, false);
}
}
_ => {}
Expand Down
51 changes: 22 additions & 29 deletions screenpipe-app-tauri/src-tauri/src/permissions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,31 +24,27 @@ pub fn open_permission_settings(permission: OSPermission) {
use std::process::Command;

match permission {
OSPermission::ScreenRecording => {
Command::new("open")
.arg("x-apple.systempreferences:com.apple.preference.security?Privacy_ScreenCapture")
.spawn()
.expect("Failed to open Screen Recording settings");
}
OSPermission::Camera => {
Command::new("open")
.arg("x-apple.systempreferences:com.apple.preference.security?Privacy_Camera")
.spawn()
.expect("Failed to open Camera settings");
}
OSPermission::Microphone => {
Command::new("open")
.arg("x-apple.systempreferences:com.apple.preference.security?Privacy_Microphone")
.spawn()
.expect("Failed to open Microphone settings");
}
OSPermission::Accessibility => {
Command::new("open")
.arg("x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility")
.spawn()
.expect("Failed to open Accessibility settings");
}
}
OSPermission::ScreenRecording => Command::new("open")
.arg(
"x-apple.systempreferences:com.apple.preference.security?Privacy_ScreenCapture",
)
.spawn()
.expect("Failed to open Screen Recording settings"),
OSPermission::Camera => Command::new("open")
.arg("x-apple.systempreferences:com.apple.preference.security?Privacy_Camera")
.spawn()
.expect("Failed to open Camera settings"),
OSPermission::Microphone => Command::new("open")
.arg("x-apple.systempreferences:com.apple.preference.security?Privacy_Microphone")
.spawn()
.expect("Failed to open Microphone settings"),
OSPermission::Accessibility => Command::new("open")
.arg(
"x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility",
)
.spawn()
.expect("Failed to open Accessibility settings"),
};
}
}

Expand Down Expand Up @@ -97,10 +93,7 @@ pub enum OSPermissionStatus {

impl OSPermissionStatus {
pub fn permitted(&self) -> bool {
match self {
Self::NotNeeded | Self::Granted => true,
_ => false,
}
matches!(self, Self::NotNeeded | Self::Granted)
}
}

Expand Down
2 changes: 1 addition & 1 deletion screenpipe-app-tauri/src-tauri/src/sidecar.rs
Original file line number Diff line number Diff line change
Expand Up @@ -367,7 +367,7 @@ fn spawn_sidecar(app: &tauri::AppHandle) -> Result<CommandChild, String> {
args.push("--enable-ui-monitoring");
}

if data_dir != "default" && data_dir != "" {
if data_dir != "default" && !data_dir.is_empty() {
args.push("--data-dir");
args.push(data_dir.as_str());
}
Expand Down
Loading

0 comments on commit 26a1618

Please sign in to comment.