kairo_cli/
cli.rs

1use std::path::PathBuf;
2
3use clap::{Parser, Subcommand};
4use console::style;
5use dialoguer::{Select, theme::ColorfulTheme};
6use kairo_core::{Url, UrlHandlerApp};
7
8/// Kairo
9#[derive(Parser, Debug)]
10#[command(version, author, about, long_about = None)]
11#[command(next_line_help = true)]
12pub struct Cli {
13    #[command(subcommand)]
14    command: Commands,
15
16    /// Paths to search for desktop entries.
17    #[arg(long, default_value = None, global = true)]
18    search_paths: Option<Vec<std::path::PathBuf>>,
19
20    #[command(flatten)]
21    verbose: clap_verbosity::Verbosity<clap_verbosity::WarnLevel>,
22}
23
24impl Cli {
25    pub fn new() -> Self {
26        Cli::parse()
27    }
28
29    pub fn run(&self) -> anyhow::Result<()> {
30        pretty_env_logger::formatted_builder()
31            .filter_level(log::LevelFilter::Info)
32            .filter(
33                Some(env!("CARGO_CRATE_NAME")),
34                self.verbose.log_level_filter(),
35            )
36            .init();
37
38        self.command.process()?;
39
40        Ok(())
41    }
42}
43
44impl Default for Cli {
45    fn default() -> Self {
46        Self::new()
47    }
48}
49
50#[derive(Subcommand, Debug)]
51enum Commands {
52    /// Lists all applications that can handle a given URL scheme.
53    List {
54        /// The URL to query (conflicts with --scheme).
55        #[arg(
56            short,
57            long,
58            conflicts_with("scheme"),
59            required_unless_present("scheme")
60        )]
61        url: Option<Url>,
62
63        /// The URL scheme to query (conflicts with --url).
64        #[arg(short, long, conflicts_with("url"), required_unless_present("url"))]
65        scheme: Option<String>,
66    },
67
68    /// Opens the given URL with one of its associated applications.
69    Open {
70        /// The URL to open.
71        url: Url,
72
73        /// Opens the URL using the default or last application used without prompting.
74        #[arg(long, default_value = "false")]
75        no_prompt: bool,
76    },
77}
78
79impl Commands {
80    fn process(&self) -> kairo_core::Result<()> {
81        match self {
82            Commands::List { url, scheme } => Self::list(url.clone(), scheme.clone(), None),
83            Commands::Open { url, no_prompt } => Self::open(url.clone(), None, *no_prompt),
84        }
85    }
86
87    fn list(
88        url: Option<Url>,
89        scheme: Option<String>,
90        search_paths: Option<Vec<PathBuf>>,
91    ) -> kairo_core::Result<()> {
92        let scheme = match (url, scheme) {
93            (Some(url), _) => url.scheme().to_string(),
94            (_, Some(scheme)) => scheme,
95            _ => unreachable!(),
96        };
97        let apps = UrlHandlerApp::handlers_for_scheme(&scheme, None, search_paths)?;
98
99        println!(
100            "{: <16} {}",
101            style("App ID").bold().green(),
102            style("Name").bold().green()
103        );
104
105        for app in apps {
106            println!("{:<16} {}", app.appid, app.name);
107        }
108
109        Ok(())
110    }
111
112    fn open(
113        url: Url,
114        search_paths: Option<Vec<PathBuf>>,
115        no_prompt: bool,
116    ) -> kairo_core::Result<()> {
117        let apps = UrlHandlerApp::handlers_for_scheme(url.scheme(), None, search_paths)?;
118
119        if no_prompt || apps.len() == 1 {
120            Self::open_with_app(&apps[0], url)?;
121            return Ok(());
122        }
123
124        let app_names: Vec<String> = apps
125            .iter()
126            .map(|app| format!("{:<16} {}", app.appid, app.name))
127            .collect();
128        let selection = Select::with_theme(&ColorfulTheme::default())
129        .with_prompt("Select an application to open the URL with")
130        .report(false)
131        // TODO: save the last used app as default
132        .default(0)
133        .items(&app_names)
134        .interact_opt()
135        .unwrap();
136
137        if let Some(selection) = selection {
138            Self::open_with_app(&apps[selection], url)?;
139        }
140
141        Ok(())
142    }
143
144    fn open_with_app(app: &UrlHandlerApp, url: Url) -> kairo_core::Result<u32> {
145        println!("Opening URL with {}...", style(&app.name).bold().green());
146        app.open_url(url)
147    }
148}
149
150pub fn run() -> anyhow::Result<()> {
151    let cli = Cli::new();
152    cli.run()
153}