Skip to content

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

25.7 KB
Raw Blame
use serde::{Deserialize, Serialize};
use std::io::Write;
use std::path::{Path, PathBuf};
use tauri::Manager;

const MAX_SAVE_DIALOG_BYTES: usize = 512 * 1024 * 1024; // 512 MB ceiling

const KNOWN_DOC_EXTS: &[&str] = &[
    "ink", "sora", "psd", "psb", "clip", "csp", "lip", "png", "jpg", "jpeg", "webp", "bmp", "gif",
    "svg",
];

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct NativeSaveDialogResult {
    pub saved: bool,
    pub canceled: bool,
    pub file_name: String,
    pub path: Option<String>,
    pub directory: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct SaveFilterSpec {
    pub name: String,
    pub extensions: Vec<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct NativePickSavePathResult {
    pub canceled: bool,
    pub file_name: Option<String>,
    pub path: Option<String>,
    pub directory: Option<String>,
    pub extension: Option<String>,
    pub filter_index: usize,
}

/// Sanitizes a suggested filename (strips directory separators and filesystem-illegal chars,
/// while preserving Unicode characters, spaces, dots in version numbers, etc.).
pub fn sanitize_suggested_filename(raw: &str) -> String {
    let base = Path::new(raw)
        .file_name()
        .and_then(|s| s.to_str())
        .unwrap_or("export");
    let cleaned: String = base
        .chars()
        .filter(|&c| {
            !matches!(
                c,
                '<' | '>' | ':' | '"' | '/' | '\\' | '|' | '?' | '*' | '\0'..='\x1f'
            )
        })
        .collect();
    let trimmed = cleaned.trim().trim_matches('.');
    if trimmed.is_empty() {
        "export".to_string()
    } else {
        trimmed.to_string()
    }
}

/// Strips trailing chained known document/image extensions (e.g. `"art.ink.ink.png.ink"` -> `"art"`),
/// preserving version dots like `"Chapter 1.2"`.
pub fn strip_known_doc_extensions(raw: &str) -> String {
    let mut current = sanitize_suggested_filename(raw);
    loop {
        let Some(dot) = current.rfind('.') else {
            break;
        };
        if dot == 0 {
            break;
        }
        let ext = current[dot + 1..].to_ascii_lowercase();
        if KNOWN_DOC_EXTS.contains(&ext.as_str()) {
            let next = current[..dot].trim_end_matches([' ', '.']);
            if next.is_empty() {
                break;
            }
            current = next.to_string();
        } else {
            break;
        }
    }
    current
}

/// Normalizes a chosen Save As path to prevent chained/doubled extensions such as
/// `foo.ink.ink`, `foo.ink.png`, or `foo.png.ink` produced when switching filters or re-saving.
pub fn normalize_chosen_save_path(chosen: &Path, expected_extensions: &[String]) -> PathBuf {
    let Some(file_name_os) = chosen.file_name() else {
        return chosen.to_path_buf();
    };
    let file_name = file_name_os.to_string_lossy();

    let clean_expected: Vec<String> = expected_extensions
        .iter()
        .map(|e| e.trim().trim_start_matches('.').to_ascii_lowercase())
        .filter(|e| !e.is_empty())
        .collect();

    // Determine final extension: prefer the path's own trailing extension if it matches
    // the expected list or is a known document ext; otherwise append the first expected ext.
    let current_ext = chosen
        .extension()
        .and_then(|e| e.to_str())
        .map(|e| e.to_ascii_lowercase());

    let final_ext = match current_ext.as_deref() {
        Some(ext) if clean_expected.is_empty() || clean_expected.iter().any(|e| e == ext) => {
            Some(ext.to_string())
        }
        Some(ext) if KNOWN_DOC_EXTS.contains(&ext) => {
            // If expected_extensions specifies a concrete format (e.g. user selected PNG filter),
            // prefer the expected format; otherwise keep the known extension.
            clean_expected
                .first()
                .cloned()
                .or_else(|| Some(ext.to_string()))
        }
        _ => clean_expected.first().cloned(),
    };

    let Some(target_ext) = final_ext else {
        return chosen.to_path_buf();
    };

    // Strip any chained known document extensions or duplicate expected extensions from the stem
    let mut stem = strip_known_doc_extensions(&file_name);
    loop {
        let Some(dot) = stem.rfind('.') else {
            break;
        };
        if dot == 0 {
            break;
        }
        let tail = stem[dot + 1..].to_ascii_lowercase();
        if tail == target_ext || clean_expected.iter().any(|e| e == &tail) {
            let next = stem[..dot].trim_end_matches([' ', '.']);
            if next.is_empty() {
                break;
            }
            stem = next.to_string();
        } else {
            break;
        }
    }

    let clean_stem = stem.trim().trim_end_matches('.');
    let final_name = if clean_stem.is_empty() {
        format!("Untitled.{}", target_ext)
    } else {
        format!("{}.{}", clean_stem, target_ext)
    };

    match chosen.parent() {
        Some(parent) if !parent.as_os_str().is_empty() => parent.join(final_name),
        _ => PathBuf::from(final_name),
    }
}

/// Atomically writes `data` to `target` using a sibling temporary file + flush + atomic replace,
/// ensuring an existing `.ink` or image file is never truncated or corrupted mid-save.
pub fn write_file_atomic(target: &Path, data: &[u8]) -> Result<(), String> {
    let parent = target
        .parent()
        .filter(|p| !p.as_os_str().is_empty())
        .unwrap_or_else(|| Path::new("."));

    let pid = std::process::id();
    let nanos = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_nanos())
        .unwrap_or(0);

    let mut tmp_path = parent.join(format!(".inkstudio_tmp_{}_{}.tmp", pid, nanos));
    let mut attempt: u32 = 0;
    let mut file = loop {
        match std::fs::OpenOptions::new()
            .write(true)
            .create_new(true)
            .open(&tmp_path)
        {
            Ok(f) => break f,
            Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists && attempt < 16 => {
                attempt += 1;
                tmp_path = parent.join(format!(".inkstudio_tmp_{}_{}_{}.tmp", pid, nanos, attempt));
            }
            Err(e) => {
                return Err(format!(
                    "Failed to create temporary save file in \"{}\": {}",
                    parent.to_string_lossy(),
                    e
                ));
            }
        }
    };

    let write_res = (|| -> Result<(), String> {
        file.write_all(data)
            .map_err(|e| format!("Failed to write file data: {}", e))?;
        file.sync_all()
            .map_err(|e| format!("Failed to flush file data to disk: {}", e))?;
        Ok(())
    })();

    drop(file);

    if let Err(err) = write_res {
        let _ = std::fs::remove_file(&tmp_path);
        return Err(err);
    }

    #[cfg(target_os = "windows")]
    {
        use windows_sys::Win32::Storage::FileSystem::{
            MoveFileExW, MOVEFILE_REPLACE_EXISTING, MOVEFILE_WRITE_THROUGH,
        };
        let src_wide = to_utf16_null(&tmp_path.to_string_lossy());
        let dst_wide = to_utf16_null(&target.to_string_lossy());
        let moved = unsafe {
            MoveFileExW(
                src_wide.as_ptr(),
                dst_wide.as_ptr(),
                MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH,
            )
        };
        if moved == 0 {
            let err = std::io::Error::last_os_error();
            let _ = std::fs::remove_file(&tmp_path);
            return Err(format!(
                "Failed to replace \"{}\": {}",
                target.to_string_lossy(),
                err
            ));
        }
    }

    #[cfg(not(target_os = "windows"))]
    {
        if let Err(err) = std::fs::rename(&tmp_path, target) {
            let _ = std::fs::remove_file(&tmp_path);
            return Err(format!(
                "Failed to replace \"{}\": {}",
                target.to_string_lossy(),
                err
            ));
        }
    }

    Ok(())
}

/// Parses comma-separated extensions (e.g. `".inkb, .json"`) into clean lowercase alphanumeric tokens.
pub fn parse_filter_extensions(raw: &str) -> Vec<String> {
    let mut out = Vec::new();
    for part in raw.split(',') {
        let cleaned: String = part
            .trim()
            .trim_start_matches('*')
            .trim_start_matches('.')
            .to_ascii_lowercase()
            .chars()
            .filter(|c| c.is_ascii_alphanumeric() || *c == '_' || *c == '-')
            .collect();
        if !cleaned.is_empty() && cleaned.len() <= 24 && !out.contains(&cleaned) {
            out.push(cleaned);
        }
    }
    out
}

/// Builds a double-null-terminated UTF-16 Win32 OPENFILENAMEW filter string for a single filter group.
#[cfg(test)]
pub fn build_win32_filter_utf16(filter_name: &str, extensions: &[String]) -> Vec<u16> {
    let specs = if extensions.is_empty() {
        Vec::new()
    } else {
        vec![SaveFilterSpec {
            name: filter_name.to_string(),
            extensions: extensions.to_vec(),
        }]
    };
    build_win32_multi_filter_utf16(&specs)
}

/// Builds a double-null-terminated UTF-16 Win32 OPENFILENAMEW filter string for multiple filter groups.
pub fn build_win32_multi_filter_utf16(filters: &[SaveFilterSpec]) -> Vec<u16> {
    let mut wide: Vec<u16> = Vec::new();
    for spec in filters {
        let clean_exts: Vec<String> = spec
            .extensions
            .iter()
            .map(|e| {
                e.trim()
                    .trim_start_matches('*')
                    .trim_start_matches('.')
                    .to_ascii_lowercase()
            })
            .filter(|e| !e.is_empty() && e.chars().all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-'))
            .collect();
        if clean_exts.is_empty() {
            continue;
        }
        let pattern = clean_exts
            .iter()
            .map(|e| format!("*.{}", e))
            .collect::<Vec<_>>()
            .join(";");
        let clean_name = spec.name.trim().replace('\0', "");
        let label = if clean_name.is_empty() {
            format!("Files ({})", pattern)
        } else if clean_name.contains("*.") {
            clean_name
        } else {
            format!("{} ({})", clean_name, pattern)
        };
        wide.extend(label.encode_utf16());
        wide.push(0);
        wide.extend(pattern.encode_utf16());
        wide.push(0);
    }
    wide.extend("All Files (*.*)".encode_utf16());
    wide.push(0);
    wide.extend("*.*".encode_utf16());
    wide.push(0);
    wide.push(0); // Double-null terminator
    wide
}

fn to_utf16_null(s: &str) -> Vec<u16> {
    s.encode_utf16().chain(std::iter::once(0)).collect()
}

fn validate_existing_dir(raw: Option<&str>) -> Option<PathBuf> {
    let candidate = raw?.trim();
    if candidate.is_empty() || candidate.contains('\0') {
        return None;
    }
    let p = PathBuf::from(candidate);
    if p.is_dir() {
        Some(p)
    } else {
        None
    }
}

#[cfg(target_os = "windows")]
mod win_save_dialog {
    use super::*;
    use std::ffi::c_void;

    const OFN_OVERWRITEPROMPT: u32 = 0x0000_0002;
    const OFN_NOCHANGEDIR: u32 = 0x0000_0008;
    const OFN_PATHMUSTEXIST: u32 = 0x0000_0800;
    const OFN_EXPLORER: u32 = 0x0008_0000;

    #[repr(C)]
    struct OpenFileNameW {
        l_struct_size: u32,
        hwnd_owner: *mut c_void,
        h_instance: *mut c_void,
        lpstr_filter: *const u16,
        lpstr_custom_filter: *mut u16,
        n_max_cust_filter: u32,
        n_filter_index: u32,
        lpstr_file: *mut u16,
        n_max_file: u32,
        lpstr_file_title: *mut u16,
        n_max_file_title: u32,
        lpstr_initial_dir: *const u16,
        lpstr_title: *const u16,
        flags: u32,
        n_file_offset: u16,
        n_file_extension: u16,
        lpstr_def_ext: *const u16,
        l_cust_data: isize,
        lpfn_hook: *const c_void,
        lp_template_name: *const u16,
        pv_reserved: *mut c_void,
        dw_reserved: u32,
        flags_ex: u32,
    }

    #[link(name = "comdlg32")]
    extern "system" {
        fn GetSaveFileNameW(lpofn: *mut OpenFileNameW) -> i32;
        fn CommDlgExtendedError() -> u32;
    }

    pub fn prompt_pick_path(
        hwnd_raw: isize,
        suggested_name: &str,
        filters: &[SaveFilterSpec],
        default_filter_index: usize,
        title: Option<&str>,
        initial_dir: Option<&Path>,
    ) -> Result<NativePickSavePathResult, String> {
        let safe_initial = sanitize_suggested_filename(suggested_name);
        let filter_wide = build_win32_multi_filter_utf16(filters);
        let title_wide = title
            .map(|t| t.trim())
            .filter(|t| !t.is_empty())
            .map(to_utf16_null);
        let initial_dir_wide = initial_dir.map(|d| to_utf16_null(&d.to_string_lossy()));

        let clamped_idx = if filters.is_empty() {
            0
        } else {
            default_filter_index.min(filters.len() - 1)
        };
        let def_ext = filters
            .get(clamped_idx)
            .and_then(|f| f.extensions.first())
            .map(|e| e.trim().trim_start_matches('.').to_ascii_lowercase())
            .filter(|e| !e.is_empty());
        let def_ext_wide = def_ext.as_deref().map(to_utf16_null);

        // 4096 UTF-16 code units buffer for returned path
        let mut file_buf: Vec<u16> = vec![0u16; 4096];
        let name_wide: Vec<u16> = safe_initial.encode_utf16().collect();
        let copy_len = name_wide.len().min(file_buf.len().saturating_sub(1));
        file_buf[..copy_len].copy_from_slice(&name_wide[..copy_len]);

        let mut ofn = OpenFileNameW {
            l_struct_size: std::mem::size_of::<OpenFileNameW>() as u32,
            hwnd_owner: hwnd_raw as *mut c_void,
            h_instance: std::ptr::null_mut(),
            lpstr_filter: filter_wide.as_ptr(),
            lpstr_custom_filter: std::ptr::null_mut(),
            n_max_cust_filter: 0,
            n_filter_index: (clamped_idx as u32) + 1, // 1-based for Win32
            lpstr_file: file_buf.as_mut_ptr(),
            n_max_file: file_buf.len() as u32,
            lpstr_file_title: std::ptr::null_mut(),
            n_max_file_title: 0,
            lpstr_initial_dir: initial_dir_wide
                .as_ref()
                .map(|v| v.as_ptr())
                .unwrap_or(std::ptr::null()),
            lpstr_title: title_wide
                .as_ref()
                .map(|v| v.as_ptr())
                .unwrap_or(std::ptr::null()),
            flags: OFN_OVERWRITEPROMPT | OFN_PATHMUSTEXIST | OFN_NOCHANGEDIR | OFN_EXPLORER,
            n_file_offset: 0,
            n_file_extension: 0,
            lpstr_def_ext: def_ext_wide
                .as_ref()
                .map(|v| v.as_ptr())
                .unwrap_or(std::ptr::null()),
            l_cust_data: 0,
            lpfn_hook: std::ptr::null(),
            lp_template_name: std::ptr::null(),
            pv_reserved: std::ptr::null_mut(),
            dw_reserved: 0,
            flags_ex: 0,
        };

        let ok = unsafe { GetSaveFileNameW(&mut ofn) };
        if ok == 0 {
            let err_code = unsafe { CommDlgExtendedError() };
            if err_code == 0 {
                return Ok(NativePickSavePathResult {
                    canceled: true,
                    file_name: None,
                    path: None,
                    directory: None,
                    extension: None,
                    filter_index: clamped_idx,
                });
            }
            return Err(format!("Native Save dialog failed (code 0x{:X})", err_code));
        }

        let nul_pos = file_buf
            .iter()
            .position(|&c| c == 0)
            .unwrap_or(file_buf.len());
        let raw_chosen_str = String::from_utf16_lossy(&file_buf[..nul_pos]);
        let selected_filter_idx = ofn.n_filter_index.saturating_sub(1) as usize;
        let expected_exts: Vec<String> = filters
            .get(selected_filter_idx)
            .map(|f| f.extensions.clone())
            .unwrap_or_default();

        let normalized_path = normalize_chosen_save_path(Path::new(&raw_chosen_str), &expected_exts);
        let chosen_str = normalized_path.to_string_lossy().to_string();
        let file_name = normalized_path
            .file_name()
            .and_then(|s| s.to_str())
            .unwrap_or(&safe_initial)
            .to_string();
        let directory = normalized_path
            .parent()
            .map(|p| p.to_string_lossy().to_string());
        let extension = normalized_path
            .extension()
            .and_then(|e| e.to_str())
            .map(|e| format!(".{}", e.to_ascii_lowercase()));

        Ok(NativePickSavePathResult {
            canceled: false,
            file_name: Some(file_name),
            path: Some(chosen_str),
            directory,
            extension,
            filter_index: selected_filter_idx,
        })
    }

    pub fn prompt_and_write(
        hwnd_raw: isize,
        suggested_name: &str,
        filter_name: &str,
        extensions: &[String],
        title: Option<&str>,
        initial_dir: Option<&Path>,
        data: &[u8],
    ) -> Result<NativeSaveDialogResult, String> {
        let filters = if extensions.is_empty() {
            Vec::new()
        } else {
            vec![SaveFilterSpec {
                name: filter_name.to_string(),
                extensions: extensions.to_vec(),
            }]
        };
        let picked = prompt_pick_path(hwnd_raw, suggested_name, &filters, 0, title, initial_dir)?;
        if picked.canceled {
            return Ok(NativeSaveDialogResult {
                saved: false,
                canceled: true,
                file_name: sanitize_suggested_filename(suggested_name),
                path: None,
                directory: None,
            });
        }
        let chosen_str = picked
            .path
            .ok_or_else(|| "Save dialog returned no path".to_string())?;
        let chosen_path = PathBuf::from(&chosen_str);

        write_file_atomic(&chosen_path, data)?;

        Ok(NativeSaveDialogResult {
            saved: true,
            canceled: false,
            file_name: picked
                .file_name
                .unwrap_or_else(|| sanitize_suggested_filename(suggested_name)),
            path: Some(chosen_str),
            directory: picked.directory,
        })
    }
}

pub async fn pick_save_path_with_dialog(
    app: &tauri::AppHandle,
    suggested_name: String,
    filters: Vec<SaveFilterSpec>,
    default_filter_index: usize,
    title: Option<String>,
    initial_dir_raw: Option<String>,
) -> Result<NativePickSavePathResult, String> {
    #[cfg(target_os = "windows")]
    {
        let hwnd_raw = app
            .get_webview_window("main")
            .and_then(|w| w.hwnd().ok())
            .map(|h| h.0 as isize)
            .unwrap_or(0);
        let initial_dir = validate_existing_dir(initial_dir_raw.as_deref());

        tokio::task::spawn_blocking(move || {
            win_save_dialog::prompt_pick_path(
                hwnd_raw,
                &suggested_name,
                &filters,
                default_filter_index,
                title.as_deref(),
                initial_dir.as_deref(),
            )
        })
        .await
        .map_err(|e| format!("Save dialog worker failed: {}", e))?
    }

    #[cfg(not(target_os = "windows"))]
    {
        let _ = (
            app,
            suggested_name,
            filters,
            default_filter_index,
            title,
            initial_dir_raw,
        );
        Err("Native Save dialog is not supported on this platform".to_string())
    }
}

pub async fn save_file_with_dialog(
    app: &tauri::AppHandle,
    suggested_name: String,
    filter_name: String,
    extensions_raw: String,
    title: Option<String>,
    initial_dir_raw: Option<String>,
    data: Vec<u8>,
) -> Result<NativeSaveDialogResult, String> {
    if data.len() > MAX_SAVE_DIALOG_BYTES {
        return Err("File exceeds 512 MB save safety limit".to_string());
    }

    #[cfg(target_os = "windows")]
    {
        let hwnd_raw = app
            .get_webview_window("main")
            .and_then(|w| w.hwnd().ok())
            .map(|h| h.0 as isize)
            .unwrap_or(0);
        let extensions = parse_filter_extensions(&extensions_raw);
        let initial_dir = validate_existing_dir(initial_dir_raw.as_deref());

        tokio::task::spawn_blocking(move || {
            win_save_dialog::prompt_and_write(
                hwnd_raw,
                &suggested_name,
                &filter_name,
                &extensions,
                title.as_deref(),
                initial_dir.as_deref(),
                &data,
            )
        })
        .await
        .map_err(|e| format!("Save dialog worker failed: {}", e))?
    }

    #[cfg(not(target_os = "windows"))]
    {
        let _ = (
            app,
            suggested_name,
            filter_name,
            extensions_raw,
            title,
            initial_dir_raw,
            data,
        );
        Err("Native Save dialog is not supported on this platform".to_string())
    }
}

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

    #[test]
    fn test_sanitize_suggested_filename() {
        assert_eq!(sanitize_suggested_filename("My Brush.inkb"), "My Brush.inkb");
        assert_eq!(sanitize_suggested_filename("../evil/brush:1?.inkb"), "brush1.inkb");
        assert_eq!(sanitize_suggested_filename("   ...  "), "export");
        assert_eq!(sanitize_suggested_filename("イラスト v1.2.ink"), "イラスト v1.2.ink");
    }

    #[test]
    fn test_strip_known_doc_extensions() {
        assert_eq!(strip_known_doc_extensions("Hero.ink.ink.ink.png.ink"), "Hero");
        assert_eq!(strip_known_doc_extensions("Chapter 1.2.ink"), "Chapter 1.2");
        assert_eq!(strip_known_doc_extensions("Cover.PNG"), "Cover");
        assert_eq!(strip_known_doc_extensions("イラスト.psd.ink"), "イラスト");
    }

    #[test]
    fn test_normalize_chosen_save_path_prevents_chained_extensions() {
        let ink = vec!["ink".to_string()];
        let png = vec!["png".to_string()];

        assert_eq!(
            normalize_chosen_save_path(Path::new("C:\\Art\\Hero.ink.ink.ink.png.ink"), &ink),
            PathBuf::from("C:\\Art\\Hero.ink")
        );
        assert_eq!(
            normalize_chosen_save_path(Path::new("C:\\Art\\Hero.ink.png"), &png),
            PathBuf::from("C:\\Art\\Hero.png")
        );
        assert_eq!(
            normalize_chosen_save_path(Path::new("C:\\Art\\Hero.png.ink"), &ink),
            PathBuf::from("C:\\Art\\Hero.ink")
        );
        assert_eq!(
            normalize_chosen_save_path(Path::new("C:\\Art\\Chapter 1.2"), &ink),
            PathBuf::from("C:\\Art\\Chapter 1.2.ink")
        );
        assert_eq!(
            normalize_chosen_save_path(Path::new("C:\\Art\\Chapter 1.2.ink"), &ink),
            PathBuf::from("C:\\Art\\Chapter 1.2.ink")
        );
        // Compound color-set JSON extension stays clean when expected is json
        let json = vec!["json".to_string()];
        assert_eq!(
            normalize_chosen_save_path(Path::new("C:\\Art\\palette.inkcolorset.json"), &json),
            PathBuf::from("C:\\Art\\palette.inkcolorset.json")
        );
    }

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

        write_file_atomic(&target, b"first version").unwrap();
        assert_eq!(std::fs::read(&target).unwrap(), b"first version");

        write_file_atomic(&target, b"second version overwritten").unwrap();
        assert_eq!(std::fs::read(&target).unwrap(), b"second version overwritten");

        // Ensure no leftover .tmp files remain
        let entries: Vec<_> = std::fs::read_dir(&dir)
            .unwrap()
            .flatten()
            .map(|e| e.file_name().to_string_lossy().to_string())
            .collect();
        assert_eq!(entries, vec!["artwork.ink".to_string()]);

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

    #[test]
    fn test_parse_filter_extensions() {
        assert_eq!(
            parse_filter_extensions(".inkb, *.JSON, .inktheme, .inkb"),
            vec!["inkb", "json", "inktheme"]
        );
        assert!(parse_filter_extensions(" , . , ").is_empty());
    }

    #[test]
    fn test_build_win32_filter_utf16_double_null() {
        let exts = vec!["inkworkspace".to_string(), "json".to_string()];
        let wide = build_win32_filter_utf16("Ink Studio Workspace", &exts);
        assert!(wide.len() >= 4);
        assert_eq!(&wide[wide.len() - 2..], &[0u16, 0u16]);
        let decoded = String::from_utf16_lossy(&wide);
        assert!(decoded.contains("Ink Studio Workspace (*.inkworkspace;*.json)"));
        assert!(decoded.contains("*.inkworkspace;*.json"));
        assert!(decoded.contains("All Files (*.*)"));
    }

    #[test]
    fn test_build_win32_multi_filter_utf16() {
        let specs = vec![
            SaveFilterSpec {
                name: "Ink Studio Project".to_string(),
                extensions: vec!["ink".to_string()],
            },
            SaveFilterSpec {
                name: "PNG Image".to_string(),
                extensions: vec!["png".to_string()],
            },
        ];
        let wide = build_win32_multi_filter_utf16(&specs);
        let decoded = String::from_utf16_lossy(&wide);
        assert!(decoded.contains("Ink Studio Project (*.ink)"));
        assert!(decoded.contains("PNG Image (*.png)"));
        assert!(decoded.contains("All Files (*.*)"));
    }
}