Refactor and improve code clarity across multiple files

- Simplified the timeout handling in `is_daemon_running` for better readability.
- Updated type definitions in the macOS Tauri library for clarity.
- Reformatted JSON configuration for better structure and readability.
- Changed function signatures in `files.rs` and `server.rs` to use `Path` instead of `PathBuf` for consistency.
- Enhanced error handling and argument passing in various functions for improved clarity.
- Added `#[allow(dead_code)]` annotations to unused functions in several modules to suppress warnings.
- Improved the display string methods in `volume.rs` and `pairing/types.rs` for better performance and clarity.
This commit is contained in:
Jamie Pine
2025-12-10 15:08:46 -08:00
parent 0717d8dd0a
commit 651e9bae46
26 changed files with 128 additions and 98 deletions

View File

@@ -352,15 +352,14 @@ async fn is_daemon_running(socket_addr: &str) -> bool {
let mut buf_reader = BufReader::new(reader);
let mut response_line = String::new();
match tokio::time::timeout(
tokio::time::Duration::from_millis(500),
buf_reader.read_line(&mut response_line),
matches!(
tokio::time::timeout(
tokio::time::Duration::from_millis(500),
buf_reader.read_line(&mut response_line),
)
.await,
Ok(Ok(_)) if !response_line.is_empty()
)
.await
{
Ok(Ok(_)) if !response_line.is_empty() => true,
_ => false,
}
}
/// Graceful shutdown handler

View File

@@ -42,7 +42,8 @@ swift!(pub fn end_native_drag(session_id: &SRString));
swift!(pub fn update_drag_overlay_position(session_id: &SRString, x: f64, y: f64));
// Callback from Swift when drag session ends
static mut DRAG_ENDED_CALLBACK: Option<Box<dyn Fn(&str, bool) + Send + Sync>> = None;
type DragEndedCallback = Option<Box<dyn Fn(&str, bool) + Send + Sync>>;
static mut DRAG_ENDED_CALLBACK: DragEndedCallback = None;
pub fn set_drag_ended_callback<F>(callback: F)
where
@@ -53,8 +54,12 @@ where
}
}
/// # Safety
///
/// This function is called from Swift when a drag session ends.
/// The `session_id` must be a valid null-terminated C string pointer.
#[no_mangle]
pub extern "C" fn rust_drag_ended_callback(session_id: *const std::ffi::c_char, was_dropped: Bool) {
pub unsafe extern "C" fn rust_drag_ended_callback(session_id: *const std::ffi::c_char, was_dropped: Bool) {
let session_id_str = unsafe {
std::ffi::CStr::from_ptr(session_id)
.to_string_lossy()

View File

@@ -92,6 +92,7 @@ impl DragCoordinator {
Ok(())
}
#[allow(dead_code)]
pub fn update_position(&self, app: &AppHandle, x: f64, y: f64) {
if let Some((session, _)) = self.state.read().as_ref() {
app.emit(
@@ -106,6 +107,7 @@ impl DragCoordinator {
}
}
#[allow(dead_code)]
pub fn enter_window(&self, app: &AppHandle, window_label: String) {
if let Some((session, _)) = self.state.read().as_ref() {
app.emit(
@@ -119,6 +121,7 @@ impl DragCoordinator {
}
}
#[allow(dead_code)]
pub fn leave_window(&self, app: &AppHandle, window_label: String) {
if let Some((session, _)) = self.state.read().as_ref() {
app.emit(

View File

@@ -1,4 +1,4 @@
use std::path::PathBuf;
use std::path::{Path, PathBuf};
use tracing::error;
/// Reveal a file in the native file manager (Finder on macOS, Explorer on Windows, etc.)
@@ -59,7 +59,7 @@ pub async fn get_sidecar_path(
}
/// Find library folder by UUID (reads library.json files to match ID)
async fn find_library_folder(data_dir: &PathBuf, library_id: &str) -> Result<PathBuf, String> {
async fn find_library_folder(data_dir: &Path, library_id: &str) -> Result<PathBuf, String> {
let libraries_dir = data_dir.join("libraries");
// Read all .sdlibrary folders
@@ -92,7 +92,7 @@ async fn find_library_folder(data_dir: &PathBuf, library_id: &str) -> Result<Pat
}
#[cfg(target_os = "macos")]
fn reveal_path(path: &PathBuf) -> Result<(), std::io::Error> {
fn reveal_path(path: &Path) -> Result<(), std::io::Error> {
std::process::Command::new("open")
.arg("-R")
.arg(path)
@@ -102,7 +102,7 @@ fn reveal_path(path: &PathBuf) -> Result<(), std::io::Error> {
}
#[cfg(target_os = "windows")]
fn reveal_path(path: &PathBuf) -> Result<(), std::io::Error> {
fn reveal_path(path: &Path) -> Result<(), std::io::Error> {
std::process::Command::new("explorer")
.arg("/select,")
.arg(path)
@@ -112,7 +112,7 @@ fn reveal_path(path: &PathBuf) -> Result<(), std::io::Error> {
}
#[cfg(target_os = "linux")]
fn reveal_path(path: &PathBuf) -> Result<(), std::io::Error> {
fn reveal_path(path: &Path) -> Result<(), std::io::Error> {
// On Linux, we'll try to open the parent directory
// Different desktop environments have different file managers
if let Some(parent) = path.parent() {
@@ -125,7 +125,7 @@ fn reveal_path(path: &PathBuf) -> Result<(), std::io::Error> {
}
#[cfg(not(any(target_os = "macos", target_os = "windows", target_os = "linux")))]
fn reveal_path(path: &PathBuf) -> Result<(), std::io::Error> {
fn reveal_path(path: &Path) -> Result<(), std::io::Error> {
Err(std::io::Error::new(
std::io::ErrorKind::Unsupported,
"Reveal is not supported on this platform",

View File

@@ -88,6 +88,7 @@ struct DaemonState {
/// Daemon connection pool - maintains ONE persistent connection for all subscriptions
/// Multiplexes Subscribe/Unsubscribe messages over a single TCP connection
#[allow(dead_code)]
struct DaemonConnectionPool {
socket_addr: String,
writer: Arc<tokio::sync::Mutex<Option<tokio::net::tcp::OwnedWriteHalf>>>,
@@ -96,6 +97,7 @@ struct DaemonConnectionPool {
initialized: Arc<tokio::sync::Mutex<bool>>,
}
#[allow(dead_code)]
impl DaemonConnectionPool {
fn new(socket_addr: String) -> Self {
Self {
@@ -940,13 +942,13 @@ async fn install_daemon_service(
// Unload any existing service first
tracing::info!("Unloading any existing service");
let _ = std::process::Command::new("launchctl")
.args(&["unload", plist_path.to_str().unwrap()])
.args(["unload", plist_path.to_str().unwrap()])
.output();
// Load the service (this starts the daemon)
tracing::info!("Loading service with launchctl");
let output = std::process::Command::new("launchctl")
.args(&["load", plist_path.to_str().unwrap()])
.args(["load", plist_path.to_str().unwrap()])
.output()
.map_err(|e| format!("Failed to load service: {}", e))?;
@@ -1278,7 +1280,7 @@ async fn uninstall_daemon_service() -> Result<(), String> {
if plist_path.exists() {
// Unload the service
let _ = std::process::Command::new("launchctl")
.args(&["unload", plist_path.to_str().unwrap()])
.args(["unload", plist_path.to_str().unwrap()])
.output();
std::fs::remove_file(&plist_path)
@@ -1792,7 +1794,7 @@ fn main() {
])
.setup(|app| {
// Setup native menu
if let Err(e) = setup_menu(&app.handle()) {
if let Err(e) = setup_menu(app.handle()) {
tracing::warn!("Failed to setup menu: {}", e);
}
tracing::info!("Spacedrive Tauri app starting...");

View File

@@ -23,7 +23,7 @@ pub struct ServerState {
}
/// Find library folder by UUID (reads library.json files to match ID)
async fn find_library_folder(data_dir: &PathBuf, library_id: &str) -> Result<PathBuf, StatusCode> {
async fn find_library_folder(data_dir: &std::path::Path, library_id: &str) -> Result<PathBuf, StatusCode> {
let libraries_dir = data_dir.join("libraries");
// Read all .sdlibrary folders

View File

@@ -279,17 +279,15 @@ impl SpacedriveWindow {
{
use tauri::Position;
// Get screen size and position window
if let Ok(monitor) = window.current_monitor() {
if let Some(monitor) = monitor {
let size = monitor.size();
// Bottom center, 40px from bottom
window
.set_position(Position::Physical(tauri::PhysicalPosition {
x: (size.width as i32) / 2 - 100,
y: (size.height as i32) - 120,
}))
.ok();
}
if let Ok(Some(monitor)) = window.current_monitor() {
let size = monitor.size();
// Bottom center, 40px from bottom
window
.set_position(Position::Physical(tauri::PhysicalPosition {
x: (size.width as i32) / 2 - 100,
y: (size.height as i32) - 120,
}))
.ok();
}
}
@@ -362,6 +360,7 @@ impl SpacedriveWindow {
}
/// Helper to create a window with common configuration
#[allow(clippy::too_many_arguments)]
fn create_window(
app: &AppHandle,
label: &str,
@@ -448,11 +447,7 @@ pub fn apply_macos_styling(app: AppHandle) -> Result<(), String> {
/// Tauri command to list all open windows
#[tauri::command]
pub async fn list_windows(app: AppHandle) -> Result<Vec<String>, String> {
Ok(app
.webview_windows()
.into_iter()
.map(|(label, _)| label)
.collect())
Ok(app.webview_windows().into_keys().collect())
}
/// Tauri command to position and show context menu with screen boundary detection

View File

@@ -27,7 +27,9 @@
"dragDropEnabled": true,
"decorations": true,
"windowEffects": {
"effects": ["sidebar"],
"effects": [
"sidebar"
],
"state": "followsWindowActiveState",
"radius": 9
}
@@ -42,7 +44,10 @@
},
"assetProtocol": {
"enable": true,
"scope": ["$HOME/**", "/Volumes/**"]
"scope": [
"$HOME/**",
"/Volumes/**"
]
}
}
},
@@ -62,7 +67,9 @@
},
"fileAssociations": [
{
"ext": ["memory"],
"ext": [
"memory"
],
"name": "Spacedrive Memory",
"description": "Spacedrive Memory File",
"role": "Editor",
@@ -71,14 +78,21 @@
],
"linux": {
"deb": {
"depends": ["libc6", "libxdo3", "libwebkit2gtk-4.1-0", "libgtk-3-0"]
"depends": [
"libc6",
"libxdo3",
"libwebkit2gtk-4.1-0",
"libgtk-3-0"
]
}
},
"macOS": {
"minimumSystemVersion": "10.15",
"signingIdentity": "-",
"infoPlist": "Info.plist",
"frameworks": ["../apps/.deps/Frameworks/Spacedrive.framework"]
"frameworks": [
"../../.deps/Spacedrive.framework"
]
},
"windows": {
"webviewInstallMode": {
@@ -88,4 +102,4 @@
}
},
"plugins": {}
}
}

View File

@@ -113,10 +113,12 @@ fn generate_swift_api_code(
eprintln!("This may cause Swift compilation errors.");
}
if individual_types.contains(": Codable {") && !individual_types.contains(": String, Codable") {
if individual_types.contains("case") && individual_types.contains(" = \"") {
eprintln!("WARNING: String enums without String raw type detected!");
}
if individual_types.contains(": Codable {")
&& !individual_types.contains(": String, Codable")
&& individual_types.contains("case")
&& individual_types.contains(" = \"")
{
eprintln!("WARNING: String enums without String raw type detected!");
}
println!(
@@ -140,7 +142,7 @@ fn generate_swift_api_code(
// }
swift_code.push_str(&individual_types);
swift_code.push_str("\n");
swift_code.push('\n');
// Generate the main API enum
swift_code.push_str("/// Complete Spacedrive API structure\n");
@@ -284,7 +286,7 @@ fn to_pascal_case(s: &str) -> String {
let mut chars = subpart.chars();
match chars.next() {
None => String::new(),
Some(first) => first.to_uppercase().collect::<String>() + &chars.as_str(),
Some(first) => first.to_uppercase().collect::<String>() + chars.as_str(),
}
})
.collect::<String>()

View File

@@ -91,7 +91,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
);
typescript_code.push_str(&individual_types);
typescript_code.push_str("\n");
typescript_code.push('\n');
// Generate operation/query type unions (like Swift enums)
typescript_code.push_str("// ===== API Type Unions =====\n\n");

View File

@@ -868,20 +868,20 @@ impl TrackedVolume {
impl FileSystem {
/// Convert to string for storage
pub fn to_string(&self) -> String {
pub fn as_str(&self) -> &str {
match self {
FileSystem::APFS => "APFS".to_string(),
FileSystem::NTFS => "NTFS".to_string(),
FileSystem::Ext4 => "ext4".to_string(),
FileSystem::Btrfs => "btrfs".to_string(),
FileSystem::ZFS => "ZFS".to_string(),
FileSystem::ReFS => "ReFS".to_string(),
FileSystem::FAT32 => "FAT32".to_string(),
FileSystem::ExFAT => "exFAT".to_string(),
FileSystem::HFSPlus => "HFS+".to_string(),
FileSystem::NFS => "NFS".to_string(),
FileSystem::SMB => "SMB".to_string(),
FileSystem::Other(name) => name.clone(),
FileSystem::APFS => "APFS",
FileSystem::NTFS => "NTFS",
FileSystem::Ext4 => "ext4",
FileSystem::Btrfs => "btrfs",
FileSystem::ZFS => "ZFS",
FileSystem::ReFS => "ReFS",
FileSystem::FAT32 => "FAT32",
FileSystem::ExFAT => "exFAT",
FileSystem::HFSPlus => "HFS+",
FileSystem::NFS => "NFS",
FileSystem::SMB => "SMB",
FileSystem::Other(name) => name.as_str(),
}
}
@@ -922,7 +922,7 @@ impl std::fmt::Display for VolumeType {
impl std::fmt::Display for FileSystem {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.to_string())
write!(f, "{}", self.as_str())
}
}

View File

@@ -96,7 +96,7 @@ impl HLC {
///
/// Format: "{timestamp:016x}-{counter:016x}-{device_id}"
/// This format is lexicographically sortable and can be used as a database key.
pub fn to_string(&self) -> String {
pub fn as_display(&self) -> String {
format!(
"{:016x}-{:016x}-{}",
self.timestamp, self.counter, self.device_id

View File

@@ -157,7 +157,7 @@ impl PairingCode {
}
/// Convert to display string (for local pairing - BIP39 words only)
pub fn to_string(&self) -> String {
pub fn as_display(&self) -> String {
self.words.join(" ")
}
@@ -278,7 +278,7 @@ impl PairingCode {
impl std::fmt::Display for PairingCode {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.to_string())
write!(f, "{}", self.as_display())
}
}

View File

@@ -168,6 +168,8 @@ impl<Id: ActorId> ActorsCollection<Id> {
}
#[instrument(skip(self))]
/// # Panics
/// Panics if the actor is already running.
pub async fn start(&self, identifier: Id) {
let mut actors_map = self.actors_map.write().await;
if let Some(actor) = actors_map.get_mut(&identifier) {
@@ -223,6 +225,8 @@ impl<Id: ActorId> ActorsCollection<Id> {
}
#[instrument(skip(self))]
/// # Panics
/// Panics if the actor handle finished without setting `is_running` to false.
pub async fn stop(&self, identifier: Id) {
let mut actors_map = self.actors_map.write().await;
if let Some(actor) = actors_map.get_mut(&identifier) {

View File

@@ -175,7 +175,7 @@ impl ConstantTimeEqNull for [u8] {
#[inline]
fn ct_eq_null(&self) -> Choice {
let mut x = 1u8;
for b in self.iter() { b.cmovne(&0, 0u8, &mut x); }
for b in self { b.cmovne(&0, 0u8, &mut x); }
Choice::from(x)
}
}

View File

@@ -1,5 +1,6 @@
use std::{
ffi::{CStr, CString},
fmt::Write,
ptr,
};
@@ -218,12 +219,12 @@ fn thumb_scale_filter_args(
let mut scale = String::new();
if let Some(height) = height {
scale.push_str(&format!("w={width}:h={height}"));
let _ = write!(scale, "w={width}:h={height}");
if maintain_aspect_ratio {
scale.push_str(":force_original_aspect_ratio=decrease");
}
} else if !maintain_aspect_ratio {
scale.push_str(&format!("w={width}:h={width}"));
let _ = write!(scale, "w={width}:h={width}");
} else {
let size = width;
let mut width = codec_ctx.as_ref().width.unsigned_abs();
@@ -252,11 +253,11 @@ fn thumb_scale_filter_args(
}
}
scale.push_str(&format!("w={width}:h={height}"));
let _ = write!(scale, "w={width}:h={height}");
} else if height > width {
scale.push_str(&format!("w=-1:h={}", if size == 0 { height } else { size }));
let _ = write!(scale, "w=-1:h={}", if size == 0 { height } else { size });
} else {
scale.push_str(&format!("h=-1:w={}", if size == 0 { width } else { size }));
let _ = write!(scale, "h=-1:w={}", if size == 0 { width } else { size });
}
}

View File

@@ -66,6 +66,7 @@ impl FFmpegFormatContext {
Some(duration)
}
#[allow(clippy::mut_from_ref)]
pub(crate) fn stream(&self, index: u32) -> Option<&mut AVStream> {
let streams = self.as_ref().streams;
if streams.is_null() {
@@ -128,6 +129,7 @@ impl FFmpegFormatContext {
Ok(self)
}
#[allow(clippy::mut_from_ref)]
pub(crate) fn find_preferred_video_stream(
&self,
prefer_embedded_metadata: bool,

View File

@@ -244,6 +244,7 @@ impl FrameDecoder {
}
}
#[allow(clippy::mut_from_ref)]
fn is_packet_for_stream(&self) -> Option<&mut AVPacket> {
let packet = (unsafe { self.packet.as_mut() })?;

View File

@@ -17,7 +17,7 @@ use crate::platform::EventHandler;
use crate::Result;
use std::collections::HashMap;
use std::os::unix::fs::MetadataExt;
use std::path::PathBuf;
use std::path::{Path, PathBuf};
use std::time::{Duration, Instant};
use tokio::sync::RwLock;
use tracing::{debug, trace};
@@ -101,7 +101,7 @@ impl MacOsHandler {
}
/// Try to match a create event with a pending remove (rename detection)
async fn try_match_rename(&self, path: &PathBuf, inode: u64) -> Option<PathBuf> {
async fn try_match_rename(&self, path: &Path, inode: u64) -> Option<PathBuf> {
let mut removes = self.pending_removes.write().await;
if let Some(pending) = removes.remove(&inode) {
debug!(

View File

@@ -49,11 +49,11 @@ pub fn detect_sequences(groups: &[LogGroup]) -> Vec<SequencePattern> {
if !used_indices[current]
&& template_ids[current..current + window_size] == *pattern
{
repetitions += 1;
// Mark as used
for idx in current..current + window_size {
used_indices[idx] = true;
}
repetitions += 1;
// Mark as used
for item in used_indices.iter_mut().skip(current).take(window_size) {
*item = true;
}
current += window_size;
} else {
break;

View File

@@ -11,7 +11,9 @@ use serde::{
pub const UTC_FORMAT_STR: &str = "%F %T %z";
pub const NAIVE_FORMAT_STR: &str = "%F %T";
/// This can be either naive with no TZ (`YYYY-MM-DD HH-MM-SS`) or UTC (`YYYY-MM-DD HH-MM-SS ±HHMM`),
/// Media date representation.
///
/// Can be either naive with no TZ (`YYYY-MM-DD HH-MM-SS`) or UTC (`YYYY-MM-DD HH-MM-SS ±HHMM`),
/// where `±HHMM` is the timezone data. It may be negative if West of the Prime Meridian, or positive if East.
#[derive(Clone, Debug, PartialEq, Eq, specta::Type)]
#[serde(untagged)]

View File

@@ -30,6 +30,7 @@ pub struct FFmpegMetadata {
}
impl FFmpegMetadata {
#[allow(clippy::unused_async)]
pub async fn from_path(path: impl AsRef<Path> + Send) -> Result<Self> {
#[cfg(not(feature = "ffmpeg"))]
{

View File

@@ -41,18 +41,10 @@ impl SpacedriveClient {
{
let is_query = wire_method.starts_with("query:");
let request = if is_query {
QueryRequest {
method: wire_method.to_string(),
library_id: self.library_id.clone(),
payload: serde_json::to_value(input)?,
}
} else {
QueryRequest {
method: wire_method.to_string(),
library_id: self.library_id.clone(),
payload: serde_json::to_value(input)?,
}
let request = QueryRequest {
method: wire_method.to_string(),
library_id: self.library_id.clone(),
payload: serde_json::to_value(input)?,
};
let request_json = if is_query {
@@ -77,7 +69,9 @@ impl SpacedriveClient {
#[derive(serde::Deserialize)]
struct MediaListingResponse {
files: Vec<File>,
#[allow(dead_code)]
has_more: bool,
#[allow(dead_code)]
total_count: usize,
}
@@ -103,10 +97,7 @@ impl SpacedriveClient {
format!(
"{}/sidecar/{}/{}/thumb/{}.{}",
self.http_base_url,
self.library_id
.as_ref()
.map(|s| s.as_str())
.unwrap_or("None"),
self.library_id.as_deref().unwrap_or("None"),
content_uuid,
variant,
format

View File

@@ -53,7 +53,7 @@ pub extern "C" fn wasm_alloc(size: i32) -> *mut u8 {
/// Free memory allocated by wasm_alloc
#[no_mangle]
pub extern "C" fn wasm_free(ptr: *mut u8, size: i32) {
pub unsafe extern "C" fn wasm_free(ptr: *mut u8, size: i32) {
if !ptr.is_null() {
let layout = std::alloc::Layout::from_size_align(size as usize, 1).unwrap();
unsafe { std::alloc::dealloc(ptr, layout) };

View File

@@ -213,6 +213,7 @@ impl<E: RunError> System<E> {
///
/// If the system message channel is closed for some unknown reason or if we fail to respond to
/// oneshot channel with shutdown response.
#[allow(clippy::cognitive_complexity)]
pub async fn shutdown(&self) {
self.has_shutdown.store(true, Ordering::Release);
if let Some(handle) = self

View File

@@ -182,6 +182,7 @@ impl<E: RunError> Runner<E> {
handle
}
#[allow(clippy::cognitive_complexity)]
#[instrument(skip(self, task_work_state))]
pub(super) fn new_task(
&mut self,
@@ -204,6 +205,7 @@ impl<E: RunError> Runner<E> {
}
}
#[allow(clippy::cognitive_complexity)]
#[instrument(skip(self))]
pub(super) fn resume_task(&mut self, task_id: TaskId) -> Result<(), SystemError> {
trace!("Resume task request");
@@ -303,6 +305,7 @@ impl<E: RunError> Runner<E> {
false
}
#[allow(clippy::cognitive_complexity)]
#[instrument(skip(self))]
pub(super) fn cancel_not_running_task(&mut self, task_id: &TaskId) -> Result<(), SystemError> {
trace!("Cancel not running task request");
@@ -397,6 +400,7 @@ impl<E: RunError> Runner<E> {
self.is_idle = false;
}
#[allow(clippy::cognitive_complexity)]
#[instrument(skip(self, task_work_state))]
#[inline]
fn add_task_when_busy(
@@ -996,6 +1000,7 @@ impl<E: RunError> Runner<E> {
}
}
#[allow(clippy::cognitive_complexity)]
#[instrument(skip(self))]
pub(crate) fn clean_suspended_task(&mut self, task_id: &TaskId) {
match self.waiting_suspension {
@@ -1026,6 +1031,7 @@ impl<E: RunError> Runner<E> {
type RunTaskOutput<E> = (Box<dyn Task<E>>, Result<Result<ExecStatus, E>, SystemError>);
#[allow(clippy::cognitive_complexity)]
#[instrument(skip(task, worktable, interrupter))]
fn handle_run_task_attempt<E: RunError>(
task_id: TaskId,
@@ -1121,6 +1127,7 @@ type PartialTaskWorkState<E> = (
Arc<Interrupter>,
);
#[allow(clippy::cognitive_complexity)]
async fn emit_task_completed_message<E: RunError>(
run_task_output: RunTaskOutput<E>,
has_suspended: Arc<AtomicBool>,