Skip to content

armgit / clipy

Public Imported from GitHub
0

The AI-native screen recorder. Record your screen and talk; the people you share it with and your AI agents both get it.

5.0 KB
Raw Blame
use std::fs;
use std::io::{self, ErrorKind, Write};
use std::path::Path;

pub(super) fn is_enabled(entry: &Path) -> io::Result<bool> {
    let contents = match fs::read_to_string(entry) {
        Ok(contents) => contents,
        Err(error) if error.kind() == ErrorKind::NotFound => return Ok(false),
        Err(error) => return Err(error),
    };

    let keys = contents
        .lines()
        .map(str::trim)
        .skip_while(|line| *line != "[Desktop Entry]")
        .skip(1)
        .take_while(|line| !line.starts_with('['))
        .filter_map(|line| line.split_once('='));
    let mut has_command = false;
    for (key, value) in keys {
        match (key.trim(), value.trim()) {
            ("Hidden", "true") | ("X-GNOME-Autostart-enabled", "false") => return Ok(false),
            ("Exec", command) => has_command = !command.is_empty(),
            _ => {}
        }
    }
    Ok(has_command)
}

pub(super) fn enable(entry: &Path, executable: &Path) -> io::Result<()> {
    let command = exec_value(executable)?;
    let directory = entry.with_file_name("");
    fs::create_dir_all(&directory)?;
    let mut file = tempfile::NamedTempFile::new_in(directory)?;
    write!(
        file,
        "[Desktop Entry]\nType=Application\nName=Clipy Local\nExec={command}\n"
    )?;
    file.persist(entry).map_err(|error| error.error)?;
    Ok(())
}

pub(super) fn disable(entry: &Path) -> io::Result<()> {
    match fs::remove_file(entry) {
        Err(error) if error.kind() == ErrorKind::NotFound => Ok(()),
        result => result,
    }
}

fn exec_value(executable: &Path) -> io::Result<String> {
    let path = executable
        .to_str()
        .filter(|path| !path.contains('=') && !path.chars().any(char::is_control))
        .filter(|_| executable.is_absolute())
        .ok_or_else(|| {
            io::Error::new(
                ErrorKind::InvalidInput,
                "Use an absolute UTF-8 executable path without control characters or '='.",
            )
        })?;

    // GIO checks the program name before expanding %% in Exec. Put the app path
    // in an argument so paths containing a literal percent sign can start.
    let mut command = String::from("/usr/bin/env -- \"");
    // Desktop entries unescape string values before interpreting Exec quoting.
    for character in path.chars() {
        match character {
            '\\' => command.push_str(r"\\\\"),
            '"' | '`' | '$' => {
                command.push_str(r"\\");
                command.push(character);
            }
            '%' => command.push_str("%%"),
            _ => command.push(character),
        }
    }
    command.push('"');
    Ok(command)
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::os::unix::fs::PermissionsExt;

    #[test]
    fn toggles_autostart_in_a_new_config_directory() {
        let config = tempfile::tempdir().unwrap();
        let entry = config.path().join("autostart/online.clipy.local.desktop");
        let executable = Path::new("/usr/bin/clipy-desktop");

        assert!(!is_enabled(&entry).unwrap());
        disable(&entry).unwrap();
        assert!(!entry.parent().unwrap().exists());
        enable(&entry, executable).unwrap();
        enable(&entry, executable).unwrap();
        assert!(is_enabled(&entry).unwrap());
        assert_eq!(
            fs::metadata(&entry).unwrap().permissions().mode() & 0o777,
            0o600
        );
        assert_eq!(fs::read_dir(entry.parent().unwrap()).unwrap().count(), 1);
        disable(&entry).unwrap();
        assert!(!is_enabled(&entry).unwrap());
    }

    #[test]
    fn respects_a_disabled_entry_and_can_enable_it_again() {
        let config = tempfile::tempdir().unwrap();
        let entry = config.path().join("online.clipy.local.desktop");
        let executable = Path::new("/usr/bin/clipy-desktop");

        for flag in ["Hidden=true", "X-GNOME-Autostart-enabled=false"] {
            fs::write(
                &entry,
                format!("[Desktop Entry]\nType=Application\nExec=/usr/bin/clipy-desktop\n{flag}\n"),
            )
            .unwrap();
            assert!(!is_enabled(&entry).unwrap());
            enable(&entry, executable).unwrap();
            assert!(is_enabled(&entry).unwrap());
        }
    }

    #[test]
    fn shell_metacharacters_are_escaped_in_the_exec_value() {
        let path = Path::new(r#"/tmp/Clipy $100% "Local" `AppImage`\.AppImage"#);
        assert_eq!(
            exec_value(path).unwrap(),
            r#"/usr/bin/env -- "/tmp/Clipy \\$100%% \\"Local\\" \\`AppImage\\`\\\\.AppImage""#
        );
    }

    #[test]
    fn an_invalid_executable_path_keeps_the_previous_entry() {
        let config = tempfile::tempdir().unwrap();
        let entry = config.path().join("online.clipy.local.desktop");
        enable(&entry, Path::new("/usr/bin/clipy-desktop")).unwrap();
        let original = fs::read(&entry).unwrap();

        let error = enable(&entry, Path::new("/tmp/Clipy\nHidden=true.AppImage")).unwrap_err();
        assert_eq!(error.kind(), ErrorKind::InvalidInput);
        assert_eq!(fs::read(entry).unwrap(), original);
    }
}