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(self.verbose.log_level_filter())
32            .init();
33
34        self.command.process()?;
35
36        Ok(())
37    }
38}
39
40impl Default for Cli {
41    fn default() -> Self {
42        Self::new()
43    }
44}
45
46#[derive(Subcommand, Debug)]
47enum Commands {
48    /// Lists all applications that can handle a given URL scheme.
49    List {
50        /// The URL to query (conflicts with --scheme).
51        #[arg(
52            short,
53            long,
54            conflicts_with("scheme"),
55            required_unless_present("scheme")
56        )]
57        url: Option<Url>,
58
59        /// The URL scheme to query (conflicts with --url).
60        #[arg(short, long, conflicts_with("url"), required_unless_present("url"))]
61        scheme: Option<String>,
62    },
63
64    /// Opens the given URL with one of its associated applications.
65    Open {
66        /// The URL to open.
67        url: Url,
68
69        /// Opens the URL using the default or last application used without prompting.
70        #[arg(long, default_value = "false")]
71        no_prompt: bool,
72    },
73}
74
75impl Commands {
76    fn process(&self) -> kairo_core::Result<()> {
77        match self {
78            Commands::List { url, scheme } => Self::list(url.clone(), scheme.clone(), None),
79            Commands::Open { url, no_prompt } => Self::open(url.clone(), None, *no_prompt),
80        }
81    }
82
83    fn list(
84        url: Option<Url>,
85        scheme: Option<String>,
86        search_paths: Option<Vec<PathBuf>>,
87    ) -> kairo_core::Result<()> {
88        let scheme = match (url, scheme) {
89            (Some(url), _) => url.scheme().to_string(),
90            (_, Some(scheme)) => scheme,
91            _ => unreachable!(),
92        };
93        let apps = UrlHandlerApp::handlers_for_scheme(&scheme, None, search_paths)?;
94
95        println!(
96            "{: <16} {}",
97            style("App ID").bold().green(),
98            style("Name").bold().green()
99        );
100
101        for app in apps {
102            println!("{:<16} {}", app.appid, app.name);
103        }
104
105        Ok(())
106    }
107
108    fn open(
109        url: Url,
110        search_paths: Option<Vec<PathBuf>>,
111        no_prompt: bool,
112    ) -> kairo_core::Result<()> {
113        let apps = UrlHandlerApp::handlers_for_scheme(url.scheme(), None, search_paths)?;
114
115        if no_prompt || apps.len() == 1 {
116            Self::open_with_app(&apps[0], url)?;
117            return Ok(());
118        }
119
120        let app_names: Vec<String> = apps
121            .iter()
122            .map(|app| format!("{:<16} {}", app.appid, app.name))
123            .collect();
124        let selection = Select::with_theme(&ColorfulTheme::default())
125        .with_prompt("Select an application to open the URL with")
126        .report(false)
127        // TODO: save the last used app as default
128        .default(0)
129        .items(&app_names)
130        .interact_opt()
131        .unwrap();
132
133        if let Some(selection) = selection {
134            Self::open_with_app(&apps[selection], url)?;
135        }
136
137        Ok(())
138    }
139
140    fn open_with_app(app: &UrlHandlerApp, url: Url) -> kairo_core::Result<u32> {
141        println!("Opening URL with {}...", style(&app.name).bold().green());
142        app.open_url(url)
143    }
144}
145
146pub fn run() -> anyhow::Result<()> {
147    let cli = Cli::new();
148    cli.run()
149}