1mod commands;
29mod error;
30mod menu;
31mod watch;
32
33pub use krizaka_rust as kit;
34pub use tauri_plugin_dialog as dialog;
38
39use krizaka_rust::access::Access;
40use krizaka_rust::deep_link::{self, LinkRules};
41use krizaka_rust::nav_guard::{self, Navigation};
42use krizaka_rust::scope::{ScopeStore, ScopedPath};
43use krizaka_rust::secrets::{Checked, SecretStore};
44use std::collections::{HashMap, HashSet};
45use std::path::{Path, PathBuf};
46use std::sync::Mutex;
47use tauri::plugin::{Builder as PluginBuilder, TauriPlugin};
48use tauri::{AppHandle, DragDropEvent, Emitter, Manager, Runtime, State, WindowEvent};
49
50pub use commands::take_links;
51pub use error::{CommandError, CODES};
52
53pub const DROPPED: &str = "krizaka://dropped";
55pub const DRAGGING: &str = "krizaka://dragging";
57pub const OPEN: &str = "krizaka://open";
59pub const MENU: &str = "krizaka://menu";
61pub const FOLDER_CHANGED: &str = "krizaka://folder-changed";
63
64const SCOPE_FILE: &str = "scope.json";
65const PREFS_FILE: &str = "krizaka.json";
66
67pub struct Kit {
69 access: Mutex<Access>,
70 secrets: Box<dyn SecretStore>,
71 links: LinkRules,
72 pending: Mutex<Vec<String>>,
73 hosted: Vec<String>,
74 hosted_window: Option<String>,
76 update_feed: Option<String>,
77 data_dir: PathBuf,
78 menu_ids: Mutex<HashSet<String>>,
79 watches: Mutex<HashMap<PathBuf, watch::Watch>>,
80}
81
82impl Kit {
83 pub fn resolve(&self, path: &Path) -> Result<ScopedPath, CommandError> {
86 Ok(error::lock(&self.access)?.resolve(path)?)
87 }
88
89 fn scope_file(&self) -> PathBuf {
90 self.data_dir.join(SCOPE_FILE)
91 }
92
93 fn prefs_file(&self) -> PathBuf {
94 self.data_dir.join(PREFS_FILE)
95 }
96}
97
98pub trait KitExt<R: Runtime> {
100 fn kit(&self) -> State<'_, Kit>;
101}
102
103impl<R: Runtime, T: Manager<R>> KitExt<R> for T {
104 fn kit(&self) -> State<'_, Kit> {
105 self.state::<Kit>()
106 }
107}
108
109pub struct Builder {
111 scheme: String,
112 hosts: Vec<String>,
113 prefixes: Vec<String>,
114 hosted: Vec<String>,
115 hosted_window: Option<String>,
116 update_feed: Option<String>,
117}
118
119impl Builder {
120 pub fn new(scheme: &str) -> Self {
122 Builder {
123 scheme: scheme.to_ascii_lowercase(),
124 hosts: vec![],
125 prefixes: vec![],
126 hosted: vec![],
127 hosted_window: None,
128 update_feed: None,
129 }
130 }
131
132 pub fn link_hosts<I: IntoIterator<Item = S>, S: Into<String>>(mut self, hosts: I) -> Self {
134 self.hosts = hosts.into_iter().map(Into::into).collect();
135 self
136 }
137
138 pub fn link_prefixes<I: IntoIterator<Item = S>, S: Into<String>>(
140 mut self,
141 prefixes: I,
142 ) -> Self {
143 self.prefixes = prefixes.into_iter().map(Into::into).collect();
144 self
145 }
146
147 pub fn hosted_origin(mut self, origin: &str) -> Self {
149 self.hosted.push(origin.to_string());
150 self
151 }
152
153 pub fn hosted_window(mut self, label: &str) -> Self {
156 self.hosted_window = Some(label.to_string());
157 self
158 }
159
160 pub fn update_feed(mut self, template: &str) -> Self {
163 self.update_feed = Some(template.to_string());
164 self
165 }
166
167 pub fn build<R: Runtime>(self) -> TauriPlugin<R> {
168 let Builder {
169 scheme,
170 hosts,
171 prefixes,
172 hosted,
173 hosted_window,
174 update_feed,
175 } = self;
176 PluginBuilder::<R>::new("krizaka")
177 .invoke_handler(tauri::generate_handler![
178 commands::folders,
179 commands::grant_folder,
180 commands::revoke_folder,
181 commands::list_folder,
182 commands::watch_folder,
183 commands::unwatch_folder,
184 commands::secret_get,
185 commands::secret_set,
186 commands::secret_remove,
187 commands::set_menu,
188 commands::take_links,
189 commands::update_channel,
190 commands::set_update_channel,
191 ])
192 .setup(move |app, _api| {
193 let updater = app.config().plugins.0.get("updater");
194 if update_feed.is_some() || updater.is_some() {
195 krizaka_rust::update::require_pubkey(updater)?;
196 }
197 if let Some(template) = &update_feed {
198 krizaka_rust::update::feed_url(template, Default::default())?;
199 }
200 let hosted = hosted
201 .iter()
202 .map(|o| nav_guard::normalize_origin(o))
203 .collect::<Result<Vec<_>, _>>()?;
204 let data_dir = app.path().app_data_dir()?;
205 let scope = ScopeStore::load(&data_dir.join(SCOPE_FILE));
206 app.manage(Kit {
207 access: Mutex::new(Access::new(scope)),
208 secrets: Box::new(Checked(krizaka_rust::keychain::Keychain::new(
209 &app.config().identifier,
210 ))),
211 links: LinkRules {
212 scheme,
213 hosts,
214 prefixes,
215 },
216 pending: Mutex::new(vec![]),
217 hosted,
218 hosted_window,
219 update_feed,
220 data_dir,
221 menu_ids: Mutex::new(HashSet::new()),
222 watches: Mutex::new(HashMap::new()),
223 });
224 app.on_menu_event(|app, event| menu::clicked(app, event.id().as_ref()));
225 Ok(())
226 })
227 .on_navigation(|webview, url| {
228 let mut places = own_places(webview.app_handle());
229 if let Some(kit) = webview.try_state::<Kit>() {
230 places.extend(kit.hosted.iter().cloned());
231 }
232 match nav_guard::decide(&places, url) {
233 Navigation::Stay => true,
234 Navigation::Browser => {
235 open_in_browser(url.as_str());
236 false
237 }
238 Navigation::Refuse => false,
239 }
240 })
241 .on_window_ready(|window| {
242 let target = window.clone();
243 window.on_window_event(move |event| {
244 match event {
245 WindowEvent::DragDrop(DragDropEvent::Enter { .. }) => {
246 let _ = target.emit_to(target.label(), DRAGGING, true);
247 }
248 WindowEvent::DragDrop(DragDropEvent::Leave) => {
249 let _ = target.emit_to(target.label(), DRAGGING, false);
250 }
251 _ => {}
252 }
253 if let WindowEvent::DragDrop(DragDropEvent::Drop { paths, .. }) = event {
254 let _ = target.emit_to(target.label(), DRAGGING, false);
255 let allowed: Vec<String> = {
256 let kit = target.kit();
257 let mut access = match kit.access.lock() {
258 Ok(a) => a,
259 Err(_) => return,
260 };
261 paths
262 .iter()
263 .filter_map(|p| access.allow_dropped(p))
264 .map(|p| p.display().to_string())
265 .collect()
266 };
267 let _ = target.emit_to(target.label(), DROPPED, allowed);
268 }
269 });
270 })
271 .on_event(|_app, _event| {
272 #[cfg(target_os = "macos")]
273 if let tauri::RunEvent::Opened { urls } = _event {
274 opened(_app, urls.iter().map(|u| u.as_str()));
275 }
276 })
277 .build()
278 }
279}
280
281fn own_places<R: Runtime>(app: &AppHandle<R>) -> Vec<String> {
283 let mut places = vec![
284 "tauri://localhost".to_string(),
285 "http://tauri.localhost".to_string(),
286 ];
287 if cfg!(debug_assertions) {
288 if let Some(dev) = &app.config().build.dev_url {
289 places.push(dev.as_str().to_string());
290 }
291 }
292 places
293}
294
295fn open_in_browser(url: &str) {
296 #[cfg(target_os = "macos")]
297 {
298 let _ = std::process::Command::new("open").arg(url).spawn();
299 }
300 #[cfg(not(target_os = "macos"))]
301 let _ = url;
302}
303
304fn opened<'a, R: Runtime>(app: &AppHandle<R>, urls: impl Iterator<Item = &'a str>) {
307 let Some(kit) = app.try_state::<Kit>() else {
308 return;
309 };
310 let routes: Vec<String> = urls
311 .filter_map(|u| deep_link::route(&kit.links, u).ok())
312 .collect();
313 if routes.is_empty() {
314 return;
315 }
316 if let Ok(mut pending) = kit.pending.lock() {
317 pending.extend(routes.iter().cloned());
318 }
319 let hosted = kit
320 .hosted_window
321 .as_ref()
322 .and_then(|label| Some((app.get_webview_window(label)?, kit.hosted.first()?.clone())));
323 if let Some(window) = hosted
324 .as_ref()
325 .map(|(w, _)| w.clone())
326 .or_else(|| app.webview_windows().into_values().next())
327 {
328 let _ = window.unminimize();
329 let _ = window.show();
330 let _ = window.set_focus();
331 }
332 if let (Some((window, origin)), Some(last)) = (&hosted, routes.last()) {
333 if let Ok(target) = url::Url::parse(origin).and_then(|o| o.join(last)) {
334 let _ = window.navigate(target);
335 }
336 }
337 for route in routes {
338 let _ = app.emit(OPEN, route);
339 }
340}
341
342pub fn set_menu<R: Runtime>(
344 app: &AppHandle<R>,
345 spec: &krizaka_rust::menu::MenuSpec,
346) -> Result<(), CommandError> {
347 commands::apply_menu(app, &app.kit(), spec)
348}