gravel_provider_system/
lib.rs1use anyhow::Result;
5use gravel_ffi::prelude::*;
6use serde::Deserialize;
7use std::env;
8
9#[cfg_attr(target_os = "linux", path = "linux.rs")]
10#[cfg_attr(windows, path = "windows.rs")]
11mod implementation;
12
13const DEFAULT_CONFIG: &str = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/config.yml"));
14
15struct SystemProvider {
16 hits: StaticHitCache,
17}
18
19#[gravel_provider("system")]
20impl Provider for SystemProvider {
21 fn new(config: &PluginConfigAdapter<'_>) -> Self {
22 let config = config.get::<Config>(DEFAULT_CONFIG);
23 let hits = [
24 context_hit(config.exit, |ctx| ctx.exit()),
25 context_hit(config.reload, |ctx| ctx.restart()),
26 context_hit(config.clear_caches, clear_caches),
27 shell_hit(config.lock, implementation::lock),
28 shell_hit(config.logout, implementation::logout),
29 shell_hit(config.restart, implementation::restart),
30 shell_hit(config.shutdown, implementation::shutdown),
31 shell_hit(config.sleep, implementation::sleep),
32 ];
33
34 Self {
35 hits: StaticHitCache::new(hits),
36 }
37 }
38
39 fn query(&self, _query: &str) -> ProviderResult {
40 ProviderResult::from_cached(self.hits.get())
41 }
42}
43
44fn clear_caches(context: RefDynHitActionContext<'_>) {
45 context.clear_caches();
46 context.hide_frontend();
47}
48
49fn context_hit(
50 config: CommandConfig,
51 action: impl Fn(RefDynHitActionContext<'_>) + Send + Sync + 'static,
52) -> SimpleHit {
53 SimpleHit::new(config.title, config.subtitle, move |_, ctx| action(ctx))
54}
55
56fn shell_hit(config: ShellCommandConfig, action: impl Fn(&str) -> Result<()> + Send + Sync + 'static) -> SimpleHit {
57 SimpleHit::new(config.title, config.subtitle, move |hit, context| {
58 action(&config.command_linux)
59 .inspect_err(|e| log::error!("unable to perform system operation {}: {e}", hit.title()))
60 .ok();
61
62 context.hide_frontend();
63 })
64}
65
66#[derive(Deserialize, Debug)]
67struct Config {
68 pub exit: CommandConfig,
69 pub reload: CommandConfig,
70 pub clear_caches: CommandConfig,
71 pub lock: ShellCommandConfig,
72 pub logout: ShellCommandConfig,
73 pub restart: ShellCommandConfig,
74 pub shutdown: ShellCommandConfig,
75 pub sleep: ShellCommandConfig,
76}
77
78#[derive(Deserialize, Debug)]
79struct CommandConfig {
80 pub title: String,
81 pub subtitle: String,
82}
83
84#[derive(Deserialize, Debug)]
85struct ShellCommandConfig {
86 pub title: String,
87 pub subtitle: String,
88 pub command_linux: String,
89}