Skip to content

A lightweight Clip Studio Paint alternative with real-time multiplayer collaborative drawing. Built with Tauri and React.

11.1 KB
Raw Blame
use std::collections::HashSet;
use std::path::{Path, PathBuf};
use std::sync::{LazyLock, Mutex};

pub const OPEN_FILES_EVENT: &str = "inkstudio://open-files";

/// Extensions accepted when files are opened via OS file association / CLI args / `RunEvent::Opened`.
pub const OPENABLE_LAUNCH_EXTS: &[&str] = &[
    "ink", "inkb", "psd", "psb", "clip", "csp", "lip", "sut", "sora", "png", "jpg", "jpeg",
    "webp", "bmp", "gif", "svg", "cls",
];

#[derive(Default)]
struct OpenFileQueueState {
    frontend_ready: bool,
    pending: Vec<String>,
}

static OPEN_FILE_QUEUE: LazyLock<Mutex<OpenFileQueueState>> =
    LazyLock::new(|| Mutex::new(OpenFileQueueState::default()));

/// Strip Windows verbatim prefix (`\\?\C:\...` -> `C:\...`, `\\?\UNC\server\share` -> `\\server\share`)
/// so paths sent to the frontend are clean and consistent with user-facing paths.
pub fn normalize_display_path(path: &Path) -> String {
    let raw = path.to_string_lossy();
    #[cfg(target_os = "windows")]
    {
        if let Some(rest) = raw.strip_prefix(r"\\?\UNC\") {
            return format!(r"\\{}", rest);
        }
        if let Some(rest) = raw.strip_prefix(r"\\?\") {
            return rest.to_string();
        }
    }
    raw.into_owned()
}

fn path_dedup_key(path: &str) -> String {
    #[cfg(target_os = "windows")]
    {
        path.replace('/', "\\").to_ascii_lowercase()
    }
    #[cfg(not(target_os = "windows"))]
    {
        path.to_string()
    }
}

fn percent_decode_url_path(input: &str) -> String {
    let bytes = input.as_bytes();
    let mut out = Vec::with_capacity(bytes.len());
    let mut i = 0;
    while i < bytes.len() {
        if bytes[i] == b'%' && i + 2 < bytes.len() {
            if let (Some(hi), Some(lo)) = (
                (bytes[i + 1] as char).to_digit(16),
                (bytes[i + 2] as char).to_digit(16),
            ) {
                out.push(((hi << 4) | lo) as u8);
                i += 3;
                continue;
            }
        }
        out.push(bytes[i]);
        i += 1;
    }
    String::from_utf8_lossy(&out).into_owned()
}

/// Converts a raw CLI argument or `file://` URL into a candidate filesystem path,
/// resolving relative paths against `cwd` when supplied.
pub fn parse_arg_to_candidate_path(raw: &str, cwd: Option<&Path>) -> Option<PathBuf> {
    let trimmed = raw.trim().trim_matches('"').trim();
    if trimmed.is_empty() || trimmed.contains('\0') {
        return None;
    }

    // Handle file:// URLs (e.g. macOS RunEvent::Opened or desktop launchers)
    if trimmed
        .get(..7)
        .is_some_and(|p| p.eq_ignore_ascii_case("file://"))
    {
        let rest = &trimmed[7..];
        let without_host = if let Some(after_localhost) = rest
            .strip_prefix("localhost/")
            .or_else(|| rest.strip_prefix("LOCALHOST/"))
        {
            format!("/{}", after_localhost)
        } else {
            rest.to_string()
        };
        let decoded = percent_decode_url_path(&without_host);
        // Strip leading slash before Windows drive letter: "/C:/foo.ink" -> "C:/foo.ink"
        let bytes = decoded.as_bytes();
        let normalized = if bytes.len() >= 3
            && bytes[0] == b'/'
            && bytes[1].is_ascii_alphabetic()
            && bytes[2] == b':'
        {
            &decoded[1..]
        } else {
            &decoded
        };
        return Some(PathBuf::from(normalized));
    }

    // Ignore CLI flags like `--dev` or `-psn_0_1234` unless a literal file with that name exists.
    if trimmed.starts_with('-') {
        let candidate = match cwd {
            Some(dir) => dir.join(trimmed),
            None => PathBuf::from(trimmed),
        };
        return if candidate.is_file() {
            Some(candidate)
        } else {
            None
        };
    }

    let p = PathBuf::from(trimmed);
    if p.is_absolute() {
        Some(p)
    } else if let Some(dir) = cwd {
        Some(dir.join(p))
    } else {
        Some(p)
    }
}

fn has_openable_extension(path: &Path) -> bool {
    path.extension()
        .and_then(|e| e.to_str())
        .map(|e| e.to_ascii_lowercase())
        .map(|ext| OPENABLE_LAUNCH_EXTS.contains(&ext.as_str()))
        .unwrap_or(false)
}

/// Filters, validates (regular non-symlink file with supported extension), canonicalizes,
/// registers via `register_allowed`, and deduplicates openable file paths from OS args.
pub fn extract_openable_file_paths<I, S, F>(
    args: I,
    cwd: Option<&Path>,
    mut register_allowed: F,
) -> Vec<String>
where
    I: IntoIterator<Item = S>,
    S: AsRef<str>,
    F: FnMut(&Path),
{
    let mut out = Vec::new();
    let mut seen = HashSet::new();

    for raw in args {
        let Some(candidate) = parse_arg_to_candidate_path(raw.as_ref(), cwd) else {
            continue;
        };
        if !has_openable_extension(&candidate) {
            continue;
        }
        let Ok(meta) = std::fs::symlink_metadata(&candidate) else {
            continue;
        };
        if meta.file_type().is_symlink() || !meta.is_file() {
            continue;
        }
        let Ok(canonical) = std::fs::canonicalize(&candidate) else {
            continue;
        };
        if !has_openable_extension(&canonical) {
            continue;
        }

        let display = normalize_display_path(&canonical);
        let key = path_dedup_key(&display);
        if seen.insert(key) {
            register_allowed(&canonical);
            out.push(display);
        }
    }

    out
}

/// Queues paths before the frontend is ready, or returns the paths to emit immediately
/// if the frontend has already mounted its listener and drained startup files.
pub fn enqueue_or_take_for_emit(paths: Vec<String>) -> Option<Vec<String>> {
    if paths.is_empty() {
        return None;
    }
    let Ok(mut state) = OPEN_FILE_QUEUE.lock() else {
        return Some(paths);
    };
    if state.frontend_ready {
        return Some(paths);
    }

    let mut existing_keys: HashSet<String> =
        state.pending.iter().map(|p| path_dedup_key(p)).collect();
    for p in paths {
        let key = path_dedup_key(&p);
        if existing_keys.insert(key) {
            state.pending.push(p);
        }
    }
    None
}

/// Called once by the frontend after registering its `inkstudio://open-files` event listener.
/// Marks the frontend ready and atomically drains any files queued during cold launch.
pub fn mark_frontend_ready_and_take_pending() -> Vec<String> {
    let Ok(mut state) = OPEN_FILE_QUEUE.lock() else {
        return Vec::new();
    };
    state.frontend_ready = true;
    std::mem::take(&mut state.pending)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn parses_plain_quoted_relative_and_file_urls_and_skips_flags() {
        let cwd = PathBuf::from("/tmp/work");

        assert_eq!(parse_arg_to_candidate_path("", Some(&cwd)), None);
        assert_eq!(parse_arg_to_candidate_path("--inspect", Some(&cwd)), None);
        assert_eq!(parse_arg_to_candidate_path("-psn_0_1234", Some(&cwd)), None);

        assert_eq!(
            parse_arg_to_candidate_path("sketch.ink", Some(&cwd)),
            Some(cwd.join("sketch.ink"))
        );
        assert_eq!(
            parse_arg_to_candidate_path("\"quoted.ink\"", Some(&cwd)),
            Some(cwd.join("quoted.ink"))
        );
        assert_eq!(
            parse_arg_to_candidate_path("file:///C:/Users/Artist/My%20Art.ink", None),
            Some(PathBuf::from("C:/Users/Artist/My Art.ink"))
        );
    }

    #[test]
    fn parses_non_ascii_cyrillic_and_cjk_paths_without_utf8_panic() {
        // Byte index 7 falls inside a multi-byte UTF-8 sequence for Cyrillic/CJK paths
        assert_eq!(
            parse_arg_to_candidate_path("C:\\Кисти\\рисунок.ink", None),
            Some(PathBuf::from("C:\\Кисти\\рисунок.ink"))
        );
        assert_eq!(
            parse_arg_to_candidate_path("C:\\Абв\\арт.ink", None),
            Some(PathBuf::from("C:\\Абв\\арт.ink"))
        );
        assert_eq!(
            parse_arg_to_candidate_path("C:\\日本語\\絵.ink", None),
            Some(PathBuf::from("C:\\日本語\\絵.ink"))
        );
        assert_eq!(
            parse_arg_to_candidate_path("file:///C:/Кисти/art.ink", None),
            Some(PathBuf::from("C:/Кисти/art.ink"))
        );
        assert_eq!(
            parse_arg_to_candidate_path("FILE:///C:/%D0%9A%D0%B8%D1%81%D1%82%D0%B8/art.ink", None),
            Some(PathBuf::from("C:/Кисти/art.ink"))
        );
    }

    #[test]
    fn extracts_only_existing_openable_files_and_deduplicates() {
        let dir = std::env::temp_dir().join(format!(
            "inkstudio_file_open_test_{}",
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        ));
        std::fs::create_dir_all(&dir).unwrap();

        let ink_file = dir.join("Chapter 1.ink");
        let txt_file = dir.join("notes.txt");
        let brush_file = dir.join("gpen.inkb");
        std::fs::write(&ink_file, b"INK2").unwrap();
        std::fs::write(&txt_file, b"ignored").unwrap();
        std::fs::write(&brush_file, b"brush").unwrap();

        let mut registered: Vec<PathBuf> = Vec::new();
        let args = vec![
            "--flag".to_string(),
            "Chapter 1.ink".to_string(),
            ink_file.to_string_lossy().to_string(), // duplicate of relative arg above
            txt_file.to_string_lossy().to_string(), // unsupported extension
            dir.join("missing.ink").to_string_lossy().to_string(), // does not exist
            brush_file.to_string_lossy().to_string(),
        ];

        let extracted = extract_openable_file_paths(&args, Some(&dir), |p| {
            registered.push(p.to_path_buf());
        });

        assert_eq!(extracted.len(), 2);
        assert!(extracted[0].ends_with("Chapter 1.ink"));
        assert!(extracted[1].ends_with("gpen.inkb"));
        assert_eq!(registered.len(), 2);

        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn queue_buffers_before_ready_and_emits_after_ready() {
        {
            let mut state = OPEN_FILE_QUEUE.lock().unwrap();
            state.frontend_ready = false;
            state.pending.clear();
        }

        // Before frontend ready -> buffered, returns None
        assert_eq!(
            enqueue_or_take_for_emit(vec!["C:\\art\\one.ink".to_string()]),
            None
        );
        // Duplicate buffered path is deduplicated
        assert_eq!(
            enqueue_or_take_for_emit(vec![
                "C:\\art\\one.ink".to_string(),
                "C:\\art\\two.ink".to_string()
            ]),
            None
        );

        // Frontend mounts and drains
        let initial = mark_frontend_ready_and_take_pending();
        assert_eq!(
            initial,
            vec!["C:\\art\\one.ink".to_string(), "C:\\art\\two.ink".to_string()]
        );

        // Subsequent drain is empty
        assert!(mark_frontend_ready_and_take_pending().is_empty());

        // After frontend ready -> returned immediately for event emit
        let warm = enqueue_or_take_for_emit(vec!["C:\\art\\three.ink".to_string()]);
        assert_eq!(warm, Some(vec!["C:\\art\\three.ink".to_string()]));
    }
}