Skip to main content
← rust.krizaka.comkrizaka.com

tauri_plugin_krizaka/
commands.rs

1//! The commands the page calls through `@krizaka/app-desktop`. Each one goes through the kit's rules: the folder scope for
2//! a path, the key and value rules for a secret, the menu checks for the menu bar.
3
4use crate::error::{lock, CommandError};
5use crate::{menu, watch, Kit, FOLDER_CHANGED};
6use krizaka_rust::files::{self, Limits, Listing};
7use krizaka_rust::menu::MenuSpec;
8use krizaka_rust::settings;
9use krizaka_rust::update::{self, Channel};
10use serde::{Deserialize, Serialize};
11use std::path::{Path, PathBuf};
12use tauri::{command, AppHandle, Runtime, State};
13use tauri_plugin_dialog::DialogExt;
14
15type Res<T> = Result<T, CommandError>;
16
17fn paths_of(roots: &[PathBuf]) -> Vec<String> {
18    roots.iter().map(|r| r.display().to_string()).collect()
19}
20
21fn save_scope(kit: &Kit, access: &krizaka_rust::access::Access) -> Res<()> {
22    Ok(access.scope().save(&kit.scope_file())?)
23}
24
25/// The folders the person granted.
26#[command]
27pub fn folders(kit: State<'_, Kit>) -> Res<Vec<String>> {
28    Ok(paths_of(lock(&kit.access)?.scope().roots()))
29}
30
31/// The native folder picker; the chosen folder is granted if it may be (never the home, the system, `~/.ssh`…).
32/// `None` when the person closed the picker.
33#[command]
34pub async fn grant_folder<R: Runtime>(
35    app: AppHandle<R>,
36    kit: State<'_, Kit>,
37) -> Res<Option<String>> {
38    let Some(picked) = app.dialog().file().blocking_pick_folder() else {
39        return Ok(None);
40    };
41    let folder = picked
42        .into_path()
43        .map_err(|e| CommandError::Platform(e.to_string()))?;
44    let mut access = lock(&kit.access)?;
45    let granted = access.scope_mut().grant(&folder)?;
46    save_scope(&kit, &access)?;
47    Ok(Some(granted.display().to_string()))
48}
49
50/// Revokes a grant (and stops watching anything under it). Returns the folders still granted.
51#[command]
52pub fn revoke_folder(kit: State<'_, Kit>, path: String) -> Res<Vec<String>> {
53    let root = PathBuf::from(&path);
54    let roots = {
55        let mut access = lock(&kit.access)?;
56        access.scope_mut().revoke(&root);
57        save_scope(&kit, &access)?;
58        access.scope().roots().to_vec()
59    };
60    lock(&kit.watches)?.retain(|watched, _| roots.iter().any(|r| watched.starts_with(r)));
61    Ok(paths_of(&roots))
62}
63
64/// A folder's entries (folders first, hidden and partial files skipped, links never followed), sorted then cut to the
65/// `limits` of the call (the kit default for what the app leaves out, never above the ceiling).
66#[command]
67pub fn list_folder(kit: State<'_, Kit>, path: String, limits: Option<Limits>) -> Res<Listing> {
68    let limits = limits.unwrap_or_default();
69    Ok(files::list_dir(&kit.resolve(Path::new(&path))?, &limits)?)
70}
71
72/// Watches a granted folder: [`FOLDER_CHANGED`] is sent (debounced) when something in it changes. Watching twice is
73/// watching once.
74#[command]
75pub fn watch_folder<R: Runtime>(
76    app: AppHandle<R>,
77    kit: State<'_, Kit>,
78    path: String,
79) -> Res<String> {
80    let dir = kit.resolve(Path::new(&path))?.into_path_buf();
81    if !dir.is_dir() {
82        return Err(CommandError::NotAFolder);
83    }
84    let mut watches = lock(&kit.watches)?;
85    if !watches.contains_key(&dir) {
86        watches.insert(dir.clone(), watch::start(app, dir.clone(), FOLDER_CHANGED)?);
87    }
88    Ok(dir.display().to_string())
89}
90
91#[command]
92pub fn unwatch_folder(kit: State<'_, Kit>, path: String) -> Res<()> {
93    let mut watches = lock(&kit.watches)?;
94    let target = Path::new(&path)
95        .canonicalize()
96        .unwrap_or_else(|_| PathBuf::from(&path));
97    watches.remove(&target);
98    Ok(())
99}
100
101/// A small secret from the Keychain (the session token): `null` when there is none.
102#[command]
103pub fn secret_get(kit: State<'_, Kit>, key: String) -> Res<Option<String>> {
104    Ok(kit.secrets.get(&key)?)
105}
106
107#[command]
108pub fn secret_set(kit: State<'_, Kit>, key: String, value: String) -> Res<()> {
109    Ok(kit.secrets.set(&key, &value)?)
110}
111
112#[command]
113pub fn secret_remove(kit: State<'_, Kit>, key: String) -> Res<()> {
114    Ok(kit.secrets.remove(&key)?)
115}
116
117/// Replaces the menu bar with the one the page describes, in its language.
118#[command]
119pub fn set_menu<R: Runtime>(app: AppHandle<R>, kit: State<'_, Kit>, spec: MenuSpec) -> Res<()> {
120    apply_menu(&app, &kit, &spec)
121}
122
123fn platform(error: tauri::Error) -> CommandError {
124    CommandError::Platform(error.to_string())
125}
126
127pub(crate) fn apply_menu<R: Runtime>(app: &AppHandle<R>, kit: &Kit, spec: &MenuSpec) -> Res<()> {
128    spec.validate()?;
129    let built = menu::build(app, spec).map_err(platform)?;
130    app.set_menu(built).map_err(platform)?;
131    *lock(&kit.menu_ids)? = spec
132        .menus
133        .iter()
134        .flat_map(|m| m.items.iter().map(|i| i.id.clone()))
135        .collect();
136    Ok(())
137}
138
139/// The routes of the deep links that arrived since the last call (the app may have been opened by one before the page
140/// listened). The page listens to `krizaka://open` first, then takes these.
141#[command]
142pub fn take_links(kit: State<'_, Kit>) -> Res<Vec<String>> {
143    Ok(std::mem::take(&mut *lock(&kit.pending)?))
144}
145
146#[derive(Debug, Default, Serialize, Deserialize)]
147struct Prefs {
148    #[serde(default)]
149    channel: Channel,
150}
151
152#[derive(Debug, Serialize)]
153#[serde(rename_all = "camelCase")]
154pub struct UpdateInfo {
155    channel: Channel,
156    /// The feed this channel reads, when the product has one.
157    feed: Option<String>,
158}
159
160fn info(kit: &Kit, channel: Channel) -> Res<UpdateInfo> {
161    let feed = match &kit.update_feed {
162        Some(template) => Some(update::feed_url(template, channel)?.to_string()),
163        None => None,
164    };
165    Ok(UpdateInfo { channel, feed })
166}
167
168/// The update channel on this Mac (`stable` unless the person chose `beta`).
169#[command]
170pub fn update_channel(kit: State<'_, Kit>) -> Res<UpdateInfo> {
171    info(&kit, settings::load::<Prefs>(&kit.prefs_file()).channel)
172}
173
174#[command]
175pub fn set_update_channel(kit: State<'_, Kit>, channel: Channel) -> Res<UpdateInfo> {
176    let mut prefs = settings::load::<Prefs>(&kit.prefs_file());
177    prefs.channel = channel;
178    settings::save(&kit.prefs_file(), &prefs)?;
179    info(&kit, channel)
180}