feature/prod-ready (#1)
Reviewed-on: #1
This commit was merged in pull request #1.
This commit is contained in:
@@ -107,8 +107,7 @@ impl Default for PluginsCfg {
|
||||
}
|
||||
|
||||
pub fn load() -> Config {
|
||||
let path = dirs::config_dir()
|
||||
.map(|d| d.join("k-launcher").join("config.toml"));
|
||||
let path = dirs::config_dir().map(|d| d.join("k-launcher").join("config.toml"));
|
||||
let Some(path) = path else {
|
||||
return Config::default();
|
||||
};
|
||||
|
||||
@@ -29,7 +29,9 @@ impl ResultTitle {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, serde::Serialize, serde::Deserialize)]
|
||||
#[derive(
|
||||
Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, serde::Serialize, serde::Deserialize,
|
||||
)]
|
||||
pub struct Score(u32);
|
||||
|
||||
impl Score {
|
||||
@@ -104,7 +106,10 @@ pub struct Kernel {
|
||||
|
||||
impl Kernel {
|
||||
pub fn new(plugins: Vec<Arc<dyn Plugin>>, max_results: usize) -> Self {
|
||||
Self { plugins, max_results }
|
||||
Self {
|
||||
plugins,
|
||||
max_results,
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn search(&self, query: &str) -> Vec<SearchResult> {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use std::process::{Command, Stdio};
|
||||
use std::os::unix::process::CommandExt;
|
||||
use std::process::{Command, Stdio};
|
||||
|
||||
use k_launcher_kernel::{AppLauncher, LaunchAction};
|
||||
|
||||
@@ -77,21 +77,31 @@ impl AppLauncher for UnixAppLauncher {
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::null())
|
||||
.stderr(Stdio::null())
|
||||
.pre_exec(|| { libc::setsid(); Ok(()) })
|
||||
.pre_exec(|| {
|
||||
libc::setsid();
|
||||
Ok(())
|
||||
})
|
||||
.spawn()
|
||||
};
|
||||
}
|
||||
}
|
||||
LaunchAction::SpawnInTerminal(cmd) => {
|
||||
let Some((term_bin, term_args)) = resolve_terminal() else { return };
|
||||
let Some((term_bin, term_args)) = resolve_terminal() else {
|
||||
return;
|
||||
};
|
||||
let _ = unsafe {
|
||||
Command::new(&term_bin)
|
||||
.args(&term_args)
|
||||
.arg("sh").arg("-c").arg(cmd)
|
||||
.arg("sh")
|
||||
.arg("-c")
|
||||
.arg(cmd)
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::null())
|
||||
.stderr(Stdio::null())
|
||||
.pre_exec(|| { libc::setsid(); Ok(()) })
|
||||
.pre_exec(|| {
|
||||
libc::setsid();
|
||||
Ok(())
|
||||
})
|
||||
.spawn()
|
||||
};
|
||||
}
|
||||
|
||||
@@ -43,7 +43,9 @@ async fn do_search(
|
||||
io: &mut ProcessIo,
|
||||
query: &str,
|
||||
) -> Result<Vec<ExternalResult>, Box<dyn std::error::Error + Send + Sync>> {
|
||||
let line = serde_json::to_string(&Query { query: query.to_string() })?;
|
||||
let line = serde_json::to_string(&Query {
|
||||
query: query.to_string(),
|
||||
})?;
|
||||
io.stdin.write_all(line.as_bytes()).await?;
|
||||
io.stdin.write_all(b"\n").await?;
|
||||
io.stdin.flush().await?;
|
||||
@@ -143,7 +145,9 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn query_serializes_correctly() {
|
||||
let q = Query { query: "firefox".to_string() };
|
||||
let q = Query {
|
||||
query: "firefox".to_string(),
|
||||
};
|
||||
assert_eq!(serde_json::to_string(&q).unwrap(), r#"{"query":"firefox"}"#);
|
||||
}
|
||||
|
||||
@@ -155,21 +159,27 @@ mod tests {
|
||||
assert_eq!(results[0].id, "1");
|
||||
assert_eq!(results[0].title, "Firefox");
|
||||
assert_eq!(results[0].score, 80);
|
||||
assert!(matches!(&results[0].action, ExternalAction::SpawnProcess { cmd } if cmd == "firefox"));
|
||||
assert!(
|
||||
matches!(&results[0].action, ExternalAction::SpawnProcess { cmd } if cmd == "firefox")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn result_parses_copy_action() {
|
||||
let json = r#"[{"id":"c","title":"= 4","score":90,"action":{"type":"CopyToClipboard","text":"4"}}]"#;
|
||||
let results: Vec<ExternalResult> = serde_json::from_str(json).unwrap();
|
||||
assert!(matches!(&results[0].action, ExternalAction::CopyToClipboard { text } if text == "4"));
|
||||
assert!(
|
||||
matches!(&results[0].action, ExternalAction::CopyToClipboard { text } if text == "4")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn result_parses_open_path_action() {
|
||||
let json = r#"[{"id":"f","title":"/home/user","score":50,"action":{"type":"OpenPath","path":"/home/user"}}]"#;
|
||||
let results: Vec<ExternalResult> = serde_json::from_str(json).unwrap();
|
||||
assert!(matches!(&results[0].action, ExternalAction::OpenPath { path } if path == "/home/user"));
|
||||
assert!(
|
||||
matches!(&results[0].action, ExternalAction::OpenPath { path } if path == "/home/user")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -182,7 +192,8 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn result_parses_missing_optional_fields() {
|
||||
let json = r#"[{"id":"x","title":"X","score":10,"action":{"type":"SpawnProcess","cmd":"x"}}]"#;
|
||||
let json =
|
||||
r#"[{"id":"x","title":"X","score":10,"action":{"type":"SpawnProcess","cmd":"x"}}]"#;
|
||||
let results: Vec<ExternalResult> = serde_json::from_str(json).unwrap();
|
||||
assert!(results[0].description.is_none());
|
||||
assert!(results[0].icon.is_none());
|
||||
|
||||
@@ -127,11 +127,20 @@ impl eframe::App for KLauncherApp {
|
||||
ui.set_width(ui.available_width());
|
||||
for (i, result) in self.results.iter().enumerate() {
|
||||
let is_selected = i == self.selected;
|
||||
let bg = if is_selected { SELECTED_BG } else { Color32::TRANSPARENT };
|
||||
let bg = if is_selected {
|
||||
SELECTED_BG
|
||||
} else {
|
||||
Color32::TRANSPARENT
|
||||
};
|
||||
|
||||
let row_frame = egui::Frame::new()
|
||||
.fill(bg)
|
||||
.inner_margin(egui::Margin { left: 8, right: 8, top: 6, bottom: 6 })
|
||||
.inner_margin(egui::Margin {
|
||||
left: 8,
|
||||
right: 8,
|
||||
top: 6,
|
||||
bottom: 6,
|
||||
})
|
||||
.corner_radius(egui::CornerRadius::same(4));
|
||||
|
||||
row_frame.show(ui, |ui| {
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use iced::{
|
||||
Border, Color, Element, Length, Size, Subscription, Task,
|
||||
event,
|
||||
Border, Color, Element, Length, Size, Subscription, Task, event,
|
||||
keyboard::{Event as KeyEvent, Key, key::Named},
|
||||
widget::{column, container, image, row, scrollable, svg, text, text_input, Space},
|
||||
widget::{Space, column, container, image, row, scrollable, svg, text, text_input},
|
||||
window,
|
||||
};
|
||||
|
||||
@@ -26,6 +25,8 @@ pub struct KLauncherApp {
|
||||
results: Arc<Vec<SearchResult>>,
|
||||
selected: usize,
|
||||
cfg: AppearanceCfg,
|
||||
error: Option<String>,
|
||||
search_epoch: u64,
|
||||
}
|
||||
|
||||
impl KLauncherApp {
|
||||
@@ -41,6 +42,8 @@ impl KLauncherApp {
|
||||
results: Arc::new(vec![]),
|
||||
selected: 0,
|
||||
cfg,
|
||||
error: None,
|
||||
search_epoch: 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -48,23 +51,31 @@ impl KLauncherApp {
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum Message {
|
||||
QueryChanged(String),
|
||||
ResultsReady(Arc<Vec<SearchResult>>),
|
||||
ResultsReady(u64, Arc<Vec<SearchResult>>),
|
||||
KeyPressed(KeyEvent),
|
||||
}
|
||||
|
||||
fn update(state: &mut KLauncherApp, message: Message) -> Task<Message> {
|
||||
match message {
|
||||
Message::QueryChanged(q) => {
|
||||
state.error = None;
|
||||
state.query = q.clone();
|
||||
state.selected = 0;
|
||||
state.search_epoch += 1;
|
||||
let epoch = state.search_epoch;
|
||||
let engine = state.engine.clone();
|
||||
Task::perform(
|
||||
async move { engine.search(&q).await },
|
||||
|results| Message::ResultsReady(Arc::new(results)),
|
||||
async move {
|
||||
tokio::time::sleep(std::time::Duration::from_millis(50)).await;
|
||||
(epoch, engine.search(&q).await)
|
||||
},
|
||||
|(epoch, results)| Message::ResultsReady(epoch, Arc::new(results)),
|
||||
)
|
||||
}
|
||||
Message::ResultsReady(results) => {
|
||||
state.results = results;
|
||||
Message::ResultsReady(epoch, results) => {
|
||||
if epoch == state.search_epoch {
|
||||
state.results = results;
|
||||
}
|
||||
Task::none()
|
||||
}
|
||||
Message::KeyPressed(event) => {
|
||||
@@ -114,8 +125,13 @@ fn view(state: &KLauncherApp) -> Element<'_, Message> {
|
||||
.padding(12)
|
||||
.size(cfg.search_font_size)
|
||||
.style(|theme, _status| {
|
||||
let mut s = iced::widget::text_input::default(theme, iced::widget::text_input::Status::Active);
|
||||
s.border = Border { color: Color::TRANSPARENT, width: 0.0, radius: 0.0.into() };
|
||||
let mut s =
|
||||
iced::widget::text_input::default(theme, iced::widget::text_input::Status::Active);
|
||||
s.border = Border {
|
||||
color: Color::TRANSPARENT,
|
||||
width: 0.0,
|
||||
radius: 0.0.into(),
|
||||
};
|
||||
s
|
||||
});
|
||||
|
||||
@@ -135,26 +151,27 @@ fn view(state: &KLauncherApp) -> Element<'_, Message> {
|
||||
Color::from_rgba8(255, 255, 255, 0.07)
|
||||
};
|
||||
let icon_el: Element<'_, Message> = match &result.icon {
|
||||
Some(p) if p.ends_with(".svg") =>
|
||||
svg(svg::Handle::from_path(p)).width(24).height(24).into(),
|
||||
Some(p) =>
|
||||
image(image::Handle::from_path(p)).width(24).height(24).into(),
|
||||
Some(p) if p.ends_with(".svg") => {
|
||||
svg(svg::Handle::from_path(p)).width(24).height(24).into()
|
||||
}
|
||||
Some(p) => image(image::Handle::from_path(p))
|
||||
.width(24)
|
||||
.height(24)
|
||||
.into(),
|
||||
None => Space::new().width(24).height(24).into(),
|
||||
};
|
||||
let title_col: Element<'_, Message> = if let Some(desc) = &result.description {
|
||||
column![
|
||||
text(result.title.as_str()).size(title_size),
|
||||
text(desc).size(desc_size).color(Color::from_rgba8(210, 215, 230, 1.0)),
|
||||
text(desc)
|
||||
.size(desc_size)
|
||||
.color(Color::from_rgba8(210, 215, 230, 1.0)),
|
||||
]
|
||||
.into()
|
||||
} else {
|
||||
text(result.title.as_str()).size(title_size).into()
|
||||
};
|
||||
container(
|
||||
row![icon_el, title_col]
|
||||
.spacing(8)
|
||||
.align_y(iced::Center),
|
||||
)
|
||||
container(row![icon_el, title_col].spacing(8).align_y(iced::Center))
|
||||
.width(Length::Fill)
|
||||
.padding([6, 12])
|
||||
.style(move |_theme| container::Style {
|
||||
@@ -186,7 +203,23 @@ fn view(state: &KLauncherApp) -> Element<'_, Message> {
|
||||
scrollable(column(result_rows).spacing(2).width(Length::Fill)).height(Length::Fill)
|
||||
};
|
||||
|
||||
let content = column![search_bar, results_list]
|
||||
let maybe_error: Option<Element<'_, Message>> = state.error.as_ref().map(|msg| {
|
||||
container(
|
||||
text(msg.as_str())
|
||||
.size(12.0)
|
||||
.color(Color::from_rgba8(255, 80, 80, 1.0)),
|
||||
)
|
||||
.width(Length::Fill)
|
||||
.padding([4, 12])
|
||||
.into()
|
||||
});
|
||||
|
||||
let mut content_children: Vec<Element<'_, Message>> =
|
||||
vec![search_bar.into(), results_list.into()];
|
||||
if let Some(err) = maybe_error {
|
||||
content_children.push(err);
|
||||
}
|
||||
let content = column(content_children)
|
||||
.spacing(8)
|
||||
.padding(12)
|
||||
.width(Length::Fill)
|
||||
@@ -234,15 +267,15 @@ pub fn run(
|
||||
update,
|
||||
view,
|
||||
)
|
||||
.title("K-Launcher")
|
||||
.subscription(subscription)
|
||||
.window(window::Settings {
|
||||
size: Size::new(wc.width, wc.height),
|
||||
position: window::Position::Centered,
|
||||
decorations: wc.decorations,
|
||||
transparent: wc.transparent,
|
||||
resizable: wc.resizable,
|
||||
..Default::default()
|
||||
})
|
||||
.run()
|
||||
.title("K-Launcher")
|
||||
.subscription(subscription)
|
||||
.window(window::Settings {
|
||||
size: Size::new(wc.width, wc.height),
|
||||
position: window::Position::Centered,
|
||||
decorations: wc.decorations,
|
||||
transparent: wc.transparent,
|
||||
resizable: wc.resizable,
|
||||
..Default::default()
|
||||
})
|
||||
.run()
|
||||
}
|
||||
|
||||
@@ -35,3 +35,4 @@ plugin-calc = { path = "../plugins/plugin-calc" }
|
||||
plugin-cmd = { path = "../plugins/plugin-cmd" }
|
||||
plugin-files = { path = "../plugins/plugin-files" }
|
||||
tokio = { workspace = true }
|
||||
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
|
||||
|
||||
10
crates/k-launcher/src/client.rs
Normal file
10
crates/k-launcher/src/client.rs
Normal file
@@ -0,0 +1,10 @@
|
||||
use std::io::Write;
|
||||
|
||||
pub fn send_show() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let runtime_dir =
|
||||
std::env::var("XDG_RUNTIME_DIR").unwrap_or_else(|_| "/run/user/1000".to_string());
|
||||
let socket_path = format!("{runtime_dir}/k-launcher.sock");
|
||||
let mut stream = std::os::unix::net::UnixStream::connect(&socket_path)?;
|
||||
stream.write_all(b"show\n")?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -1,29 +1,62 @@
|
||||
mod client;
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use k_launcher_kernel::Kernel;
|
||||
use k_launcher_os_bridge::UnixAppLauncher;
|
||||
use k_launcher_plugin_host::ExternalPlugin;
|
||||
use plugin_apps::{AppsPlugin, frecency::FrecencyStore};
|
||||
#[cfg(target_os = "linux")]
|
||||
use plugin_apps::linux::FsDesktopEntrySource;
|
||||
use plugin_apps::{AppsPlugin, frecency::FrecencyStore};
|
||||
use plugin_calc::CalcPlugin;
|
||||
use plugin_cmd::CmdPlugin;
|
||||
use plugin_files::FilesPlugin;
|
||||
|
||||
fn main() -> iced::Result {
|
||||
fn main() {
|
||||
tracing_subscriber::fmt::init();
|
||||
|
||||
let args: Vec<String> = std::env::args().collect();
|
||||
if args.get(1).map(|s| s.as_str()) == Some("show") {
|
||||
if let Err(e) = client::send_show() {
|
||||
eprintln!("error: failed to send show command: {e}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if let Err(e) = run_ui() {
|
||||
eprintln!("error: UI: {e}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
fn run_ui() -> iced::Result {
|
||||
let cfg = k_launcher_config::load();
|
||||
let launcher = Arc::new(UnixAppLauncher::new());
|
||||
let frecency = FrecencyStore::load();
|
||||
|
||||
let mut plugins: Vec<Arc<dyn k_launcher_kernel::Plugin>> = vec![];
|
||||
if cfg.plugins.cmd { plugins.push(Arc::new(CmdPlugin::new())); }
|
||||
if cfg.plugins.calc { plugins.push(Arc::new(CalcPlugin::new())); }
|
||||
if cfg.plugins.files { plugins.push(Arc::new(FilesPlugin::new())); }
|
||||
if cfg.plugins.apps {
|
||||
plugins.push(Arc::new(AppsPlugin::new(FsDesktopEntrySource::new(), frecency)));
|
||||
if cfg.plugins.cmd {
|
||||
plugins.push(Arc::new(CmdPlugin::new()));
|
||||
}
|
||||
if cfg.plugins.calc {
|
||||
plugins.push(Arc::new(CalcPlugin::new()));
|
||||
}
|
||||
if cfg.plugins.files {
|
||||
plugins.push(Arc::new(FilesPlugin::new()));
|
||||
}
|
||||
if cfg.plugins.apps {
|
||||
plugins.push(Arc::new(AppsPlugin::new(
|
||||
FsDesktopEntrySource::new(),
|
||||
frecency,
|
||||
)));
|
||||
}
|
||||
for ext in &cfg.plugins.external {
|
||||
plugins.push(Arc::new(ExternalPlugin::new(&ext.name, &ext.path, ext.args.clone())));
|
||||
plugins.push(Arc::new(ExternalPlugin::new(
|
||||
&ext.name,
|
||||
&ext.path,
|
||||
ext.args.clone(),
|
||||
)));
|
||||
}
|
||||
|
||||
let kernel: Arc<dyn k_launcher_kernel::SearchEngine> =
|
||||
|
||||
@@ -2,9 +2,9 @@ use std::sync::Arc;
|
||||
|
||||
use k_launcher_kernel::Kernel;
|
||||
use k_launcher_os_bridge::UnixAppLauncher;
|
||||
use plugin_apps::{AppsPlugin, frecency::FrecencyStore};
|
||||
#[cfg(target_os = "linux")]
|
||||
use plugin_apps::linux::FsDesktopEntrySource;
|
||||
use plugin_apps::{AppsPlugin, frecency::FrecencyStore};
|
||||
use plugin_calc::CalcPlugin;
|
||||
use plugin_cmd::CmdPlugin;
|
||||
use plugin_files::FilesPlugin;
|
||||
@@ -12,12 +12,15 @@ use plugin_files::FilesPlugin;
|
||||
fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let launcher = Arc::new(UnixAppLauncher::new());
|
||||
let frecency = FrecencyStore::load();
|
||||
let kernel: Arc<dyn k_launcher_kernel::SearchEngine> = Arc::new(Kernel::new(vec![
|
||||
Arc::new(CmdPlugin::new()),
|
||||
Arc::new(CalcPlugin::new()),
|
||||
Arc::new(FilesPlugin::new()),
|
||||
Arc::new(AppsPlugin::new(FsDesktopEntrySource::new(), frecency)),
|
||||
], 8));
|
||||
let kernel: Arc<dyn k_launcher_kernel::SearchEngine> = Arc::new(Kernel::new(
|
||||
vec![
|
||||
Arc::new(CmdPlugin::new()),
|
||||
Arc::new(CalcPlugin::new()),
|
||||
Arc::new(FilesPlugin::new()),
|
||||
Arc::new(AppsPlugin::new(FsDesktopEntrySource::new(), frecency)),
|
||||
],
|
||||
8,
|
||||
));
|
||||
k_launcher_ui_egui::run(kernel, launcher)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -10,9 +10,12 @@ path = "src/lib.rs"
|
||||
[dependencies]
|
||||
async-trait = { workspace = true }
|
||||
k-launcher-kernel = { path = "../../k-launcher-kernel" }
|
||||
nucleo-matcher = "0.3"
|
||||
serde = { workspace = true }
|
||||
serde_json = "1.0"
|
||||
tokio = { workspace = true }
|
||||
tracing = { workspace = true }
|
||||
|
||||
[target.'cfg(target_os = "linux")'.dependencies]
|
||||
linicon = "2.3.0"
|
||||
xdg = "3"
|
||||
|
||||
@@ -24,7 +24,10 @@ impl FrecencyStore {
|
||||
.ok()
|
||||
.and_then(|s| serde_json::from_str(&s).ok())
|
||||
.unwrap_or_default();
|
||||
Arc::new(Self { path, data: Mutex::new(data) })
|
||||
Arc::new(Self {
|
||||
path,
|
||||
data: Mutex::new(data),
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -36,11 +39,14 @@ impl FrecencyStore {
|
||||
}
|
||||
|
||||
pub fn load() -> Arc<Self> {
|
||||
let path = xdg::BaseDirectories::new()
|
||||
.get_data_home()
|
||||
.unwrap_or_else(|| PathBuf::from("."))
|
||||
.join("k-launcher")
|
||||
.join("frecency.json");
|
||||
let Some(data_home) = xdg::BaseDirectories::new().get_data_home() else {
|
||||
tracing::warn!("XDG_DATA_HOME unavailable; frecency disabled (in-memory only)");
|
||||
return Arc::new(Self {
|
||||
path: PathBuf::from("/dev/null"),
|
||||
data: Mutex::new(HashMap::new()),
|
||||
});
|
||||
};
|
||||
let path = data_home.join("k-launcher").join("frecency.json");
|
||||
Self::new(path)
|
||||
}
|
||||
|
||||
@@ -50,7 +56,10 @@ impl FrecencyStore {
|
||||
.unwrap_or_default()
|
||||
.as_secs();
|
||||
let mut data = self.data.lock().unwrap();
|
||||
let entry = data.entry(id.to_string()).or_insert(Entry { count: 0, last_used: 0 });
|
||||
let entry = data.entry(id.to_string()).or_insert(Entry {
|
||||
count: 0,
|
||||
last_used: 0,
|
||||
});
|
||||
entry.count += 1;
|
||||
entry.last_used = now;
|
||||
if let Some(parent) = self.path.parent() {
|
||||
@@ -69,7 +78,13 @@ impl FrecencyStore {
|
||||
.unwrap_or_default()
|
||||
.as_secs();
|
||||
let age_secs = now.saturating_sub(entry.last_used);
|
||||
let decay = if age_secs < 3600 { 4 } else if age_secs < 86400 { 2 } else { 1 };
|
||||
let decay = if age_secs < 3600 {
|
||||
4
|
||||
} else if age_secs < 86400 {
|
||||
2
|
||||
} else {
|
||||
1
|
||||
};
|
||||
entry.count * decay
|
||||
}
|
||||
|
||||
@@ -83,7 +98,13 @@ impl FrecencyStore {
|
||||
.iter()
|
||||
.map(|(id, entry)| {
|
||||
let age_secs = now.saturating_sub(entry.last_used);
|
||||
let decay = if age_secs < 3600 { 4 } else if age_secs < 86400 { 2 } else { 1 };
|
||||
let decay = if age_secs < 3600 {
|
||||
4
|
||||
} else if age_secs < 86400 {
|
||||
2
|
||||
} else {
|
||||
1
|
||||
};
|
||||
(id.clone(), entry.count * decay)
|
||||
})
|
||||
.collect();
|
||||
|
||||
@@ -68,7 +68,6 @@ pub trait DesktopEntrySource: Send + Sync {
|
||||
struct CachedEntry {
|
||||
id: String,
|
||||
name: AppName,
|
||||
name_lc: String,
|
||||
keywords_lc: Vec<String>,
|
||||
category: Option<String>,
|
||||
icon: Option<String>,
|
||||
@@ -90,10 +89,12 @@ impl AppsPlugin {
|
||||
.into_iter()
|
||||
.map(|e| {
|
||||
let id = format!("app-{}", e.name.as_str());
|
||||
let name_lc = e.name.as_str().to_lowercase();
|
||||
let keywords_lc = e.keywords.iter().map(|k| k.to_lowercase()).collect();
|
||||
#[cfg(target_os = "linux")]
|
||||
let icon = e.icon.as_ref().and_then(|p| linux::resolve_icon_path(p.as_str()));
|
||||
let icon = e
|
||||
.icon
|
||||
.as_ref()
|
||||
.and_then(|p| linux::resolve_icon_path(p.as_str()));
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
let icon: Option<String> = None;
|
||||
let exec = e.exec.as_str().to_string();
|
||||
@@ -104,7 +105,6 @@ impl AppsPlugin {
|
||||
});
|
||||
let cached = CachedEntry {
|
||||
id: id.clone(),
|
||||
name_lc,
|
||||
keywords_lc,
|
||||
category: e.category,
|
||||
icon,
|
||||
@@ -120,15 +120,37 @@ impl AppsPlugin {
|
||||
}
|
||||
|
||||
fn initials(name_lc: &str) -> String {
|
||||
name_lc.split_whitespace().filter_map(|w| w.chars().next()).collect()
|
||||
name_lc
|
||||
.split_whitespace()
|
||||
.filter_map(|w| w.chars().next())
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn score_match(name_lc: &str, query_lc: &str) -> Option<u32> {
|
||||
if name_lc == query_lc { return Some(100); }
|
||||
if name_lc.starts_with(query_lc) { return Some(80); }
|
||||
if name_lc.contains(query_lc) { return Some(60); }
|
||||
if initials(name_lc).starts_with(query_lc) { return Some(70); }
|
||||
None
|
||||
fn score_match(name: &str, query: &str) -> Option<u32> {
|
||||
use nucleo_matcher::{
|
||||
Config, Matcher, Utf32Str,
|
||||
pattern::{CaseMatching, Normalization, Pattern},
|
||||
};
|
||||
|
||||
let mut matcher = Matcher::new(Config::DEFAULT);
|
||||
let pattern = Pattern::parse(query, CaseMatching::Ignore, Normalization::Smart);
|
||||
|
||||
let mut name_chars: Vec<char> = name.chars().collect();
|
||||
let haystack = Utf32Str::new(name, &mut name_chars);
|
||||
let score = pattern.score(haystack, &mut matcher);
|
||||
|
||||
if let Some(s) = score {
|
||||
let name_lc = name.to_lowercase();
|
||||
let query_lc = query.to_lowercase();
|
||||
let bonus: u32 = if initials(&name_lc).starts_with(&query_lc) {
|
||||
20
|
||||
} else {
|
||||
0
|
||||
};
|
||||
Some(s.saturating_add(bonus))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn humanize_category(s: &str) -> String {
|
||||
@@ -150,7 +172,9 @@ impl Plugin for AppsPlugin {
|
||||
|
||||
async fn search(&self, query: &str) -> Vec<SearchResult> {
|
||||
if query.is_empty() {
|
||||
return self.frecency.top_ids(5)
|
||||
return self
|
||||
.frecency
|
||||
.top_ids(5)
|
||||
.iter()
|
||||
.filter_map(|id| {
|
||||
let e = self.entries.get(id)?;
|
||||
@@ -172,8 +196,11 @@ impl Plugin for AppsPlugin {
|
||||
self.entries
|
||||
.values()
|
||||
.filter_map(|e| {
|
||||
let score = score_match(&e.name_lc, &query_lc).or_else(|| {
|
||||
e.keywords_lc.iter().any(|k| k.contains(&query_lc)).then_some(50)
|
||||
let score = score_match(e.name.as_str(), query).or_else(|| {
|
||||
e.keywords_lc
|
||||
.iter()
|
||||
.any(|k| k.contains(&query_lc))
|
||||
.then_some(50)
|
||||
})?;
|
||||
Some(SearchResult {
|
||||
id: ResultId::new(&e.id),
|
||||
@@ -226,7 +253,14 @@ mod tests {
|
||||
Self {
|
||||
entries: entries
|
||||
.into_iter()
|
||||
.map(|(n, e, kw)| (n.to_string(), e.to_string(), None, kw.into_iter().map(|s| s.to_string()).collect()))
|
||||
.map(|(n, e, kw)| {
|
||||
(
|
||||
n.to_string(),
|
||||
e.to_string(),
|
||||
None,
|
||||
kw.into_iter().map(|s| s.to_string()).collect(),
|
||||
)
|
||||
})
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
@@ -249,35 +283,49 @@ mod tests {
|
||||
|
||||
#[tokio::test]
|
||||
async fn apps_prefix_match() {
|
||||
let p = AppsPlugin::new(MockSource::with(vec![("Firefox", "firefox")]), ephemeral_frecency());
|
||||
let p = AppsPlugin::new(
|
||||
MockSource::with(vec![("Firefox", "firefox")]),
|
||||
ephemeral_frecency(),
|
||||
);
|
||||
let results = p.search("fire").await;
|
||||
assert_eq!(results[0].title.as_str(), "Firefox");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn apps_no_match_returns_empty() {
|
||||
let p = AppsPlugin::new(MockSource::with(vec![("Firefox", "firefox")]), ephemeral_frecency());
|
||||
let p = AppsPlugin::new(
|
||||
MockSource::with(vec![("Firefox", "firefox")]),
|
||||
ephemeral_frecency(),
|
||||
);
|
||||
assert!(p.search("zz").await.is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn apps_empty_query_no_frecency_returns_empty() {
|
||||
let p = AppsPlugin::new(MockSource::with(vec![("Firefox", "firefox")]), ephemeral_frecency());
|
||||
let p = AppsPlugin::new(
|
||||
MockSource::with(vec![("Firefox", "firefox")]),
|
||||
ephemeral_frecency(),
|
||||
);
|
||||
assert!(p.search("").await.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn score_match_abbreviation() {
|
||||
assert_eq!(initials("visual studio code"), "vsc");
|
||||
assert_eq!(score_match("visual studio code", "vsc"), Some(70));
|
||||
assert!(score_match("visual studio code", "vsc").is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn score_match_exact_beats_prefix_beats_abbrev_beats_substr() {
|
||||
assert_eq!(score_match("firefox", "firefox"), Some(100));
|
||||
assert_eq!(score_match("firefox", "fire"), Some(80));
|
||||
assert_eq!(score_match("gnu firefox", "gf"), Some(70));
|
||||
assert_eq!(score_match("ice firefox", "fire"), Some(60));
|
||||
let exact = score_match("firefox", "firefox");
|
||||
let prefix = score_match("firefox", "fire");
|
||||
let abbrev = score_match("gnu firefox", "gf");
|
||||
let substr = score_match("ice firefox", "fire");
|
||||
assert!(exact.is_some());
|
||||
assert!(prefix.is_some());
|
||||
assert!(abbrev.is_some());
|
||||
assert!(substr.is_some());
|
||||
assert!(exact.unwrap() > prefix.unwrap());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -289,7 +337,7 @@ mod tests {
|
||||
let results = p.search("vsc").await;
|
||||
assert_eq!(results.len(), 1);
|
||||
assert_eq!(results[0].title.as_str(), "Visual Studio Code");
|
||||
assert_eq!(results[0].score.value(), 70);
|
||||
assert!(results[0].score.value() > 0);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -303,6 +351,20 @@ mod tests {
|
||||
assert_eq!(results[0].score.value(), 50);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn apps_fuzzy_typo_match() {
|
||||
let p = AppsPlugin::new(
|
||||
MockSource::with(vec![("Firefox", "firefox")]),
|
||||
ephemeral_frecency(),
|
||||
);
|
||||
let results = p.search("frefox").await;
|
||||
assert!(
|
||||
!results.is_empty(),
|
||||
"nucleo should fuzzy-match 'frefox' to 'Firefox'"
|
||||
);
|
||||
assert!(results[0].score.value() > 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn humanize_category_splits_camel_case() {
|
||||
assert_eq!(humanize_category("TextEditor"), "Text Editor");
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use std::path::Path;
|
||||
|
||||
use crate::{AppName, DesktopEntry, DesktopEntrySource, ExecCommand, IconPath};
|
||||
use crate::humanize_category;
|
||||
use crate::{AppName, DesktopEntry, DesktopEntrySource, ExecCommand, IconPath};
|
||||
|
||||
pub struct FsDesktopEntrySource;
|
||||
|
||||
@@ -45,15 +45,79 @@ impl DesktopEntrySource for FsDesktopEntrySource {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn clean_exec(exec: &str) -> String {
|
||||
// Tokenize respecting double-quoted strings, then filter field codes.
|
||||
let mut tokens: Vec<String> = Vec::new();
|
||||
let mut chars = exec.chars().peekable();
|
||||
|
||||
while let Some(&ch) = chars.peek() {
|
||||
if ch.is_whitespace() {
|
||||
chars.next();
|
||||
continue;
|
||||
}
|
||||
if ch == '"' {
|
||||
// Consume opening quote
|
||||
chars.next();
|
||||
let mut token = String::from('"');
|
||||
while let Some(&c) = chars.peek() {
|
||||
chars.next();
|
||||
if c == '"' {
|
||||
token.push('"');
|
||||
break;
|
||||
}
|
||||
token.push(c);
|
||||
}
|
||||
// Strip embedded field codes like %f inside the quoted string
|
||||
// (between the quotes, before re-assembling)
|
||||
let inner = &token[1..token.len().saturating_sub(1)];
|
||||
let cleaned_inner: String = inner
|
||||
.split_whitespace()
|
||||
.filter(|s| !is_field_code(s))
|
||||
.collect::<Vec<_>>()
|
||||
.join(" ");
|
||||
tokens.push(format!("\"{cleaned_inner}\""));
|
||||
} else {
|
||||
let mut token = String::new();
|
||||
while let Some(&c) = chars.peek() {
|
||||
if c.is_whitespace() {
|
||||
break;
|
||||
}
|
||||
chars.next();
|
||||
token.push(c);
|
||||
}
|
||||
if !is_field_code(&token) {
|
||||
tokens.push(token);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
tokens.join(" ")
|
||||
}
|
||||
|
||||
fn is_field_code(s: &str) -> bool {
|
||||
let b = s.as_bytes();
|
||||
b.len() == 2 && b[0] == b'%' && b[1].is_ascii_alphabetic()
|
||||
}
|
||||
|
||||
pub fn resolve_icon_path(name: &str) -> Option<String> {
|
||||
if name.starts_with('/') && Path::new(name).exists() {
|
||||
return Some(name.to_string());
|
||||
}
|
||||
// Try linicon freedesktop theme traversal
|
||||
let themes = ["hicolor", "Adwaita", "breeze", "Papirus"];
|
||||
for theme in &themes {
|
||||
if let Some(icon_path) = linicon::lookup_icon(name)
|
||||
.from_theme(theme)
|
||||
.with_size(48)
|
||||
.find_map(|r| r.ok())
|
||||
{
|
||||
return Some(icon_path.path.to_string_lossy().into_owned());
|
||||
}
|
||||
}
|
||||
// Fallback to pixmaps
|
||||
let candidates = [
|
||||
format!("/usr/share/pixmaps/{name}.png"),
|
||||
format!("/usr/share/pixmaps/{name}.svg"),
|
||||
format!("/usr/share/icons/hicolor/48x48/apps/{name}.png"),
|
||||
format!("/usr/share/icons/hicolor/scalable/apps/{name}.svg"),
|
||||
];
|
||||
candidates.into_iter().find(|p| Path::new(p).exists())
|
||||
}
|
||||
@@ -90,13 +154,15 @@ fn parse_desktop_file(path: &Path) -> Option<DesktopEntry> {
|
||||
"Type" if !is_application => is_application = value.trim() == "Application",
|
||||
"NoDisplay" => no_display = value.trim().eq_ignore_ascii_case("true"),
|
||||
"Categories" if category.is_none() => {
|
||||
category = value.trim()
|
||||
category = value
|
||||
.trim()
|
||||
.split(';')
|
||||
.find(|s| !s.is_empty())
|
||||
.map(|s| humanize_category(s.trim()));
|
||||
}
|
||||
"Keywords" if keywords.is_empty() => {
|
||||
keywords = value.trim()
|
||||
keywords = value
|
||||
.trim()
|
||||
.split(';')
|
||||
.filter(|s| !s.is_empty())
|
||||
.map(|s| s.trim().to_string())
|
||||
@@ -111,16 +177,7 @@ fn parse_desktop_file(path: &Path) -> Option<DesktopEntry> {
|
||||
return None;
|
||||
}
|
||||
|
||||
let exec_clean: String = exec?
|
||||
.split_whitespace()
|
||||
.filter(|s| !s.starts_with('%'))
|
||||
.fold(String::new(), |mut acc, s| {
|
||||
if !acc.is_empty() {
|
||||
acc.push(' ');
|
||||
}
|
||||
acc.push_str(s);
|
||||
acc
|
||||
});
|
||||
let exec_clean: String = clean_exec(&exec?);
|
||||
|
||||
Some(DesktopEntry {
|
||||
name: AppName::new(name?),
|
||||
@@ -130,3 +187,31 @@ fn parse_desktop_file(path: &Path) -> Option<DesktopEntry> {
|
||||
keywords,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod exec_tests {
|
||||
use super::clean_exec;
|
||||
|
||||
#[test]
|
||||
fn strips_bare_field_code() {
|
||||
assert_eq!(clean_exec("app --file %f"), "app --file");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strips_multiple_field_codes() {
|
||||
assert_eq!(clean_exec("app %U --flag"), "app --flag");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preserves_quoted_value() {
|
||||
assert_eq!(
|
||||
clean_exec(r#"app --arg="value" %U"#),
|
||||
r#"app --arg="value""#
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn handles_plain_exec() {
|
||||
assert_eq!(clean_exec("firefox"), "firefox");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,8 +22,8 @@ fn strip_numeric_separators(expr: &str) -> String {
|
||||
}
|
||||
|
||||
const MATH_FNS: &[&str] = &[
|
||||
"sqrt", "sin", "cos", "tan", "asin", "acos", "atan",
|
||||
"ln", "log2", "log10", "exp", "abs", "ceil", "floor", "round",
|
||||
"sqrt", "sin", "cos", "tan", "asin", "acos", "atan", "ln", "log2", "log10", "exp", "abs",
|
||||
"ceil", "floor", "round",
|
||||
];
|
||||
|
||||
fn should_eval(query: &str) -> bool {
|
||||
@@ -36,8 +36,8 @@ fn should_eval(query: &str) -> bool {
|
||||
|| MATH_FNS.iter().any(|f| q.starts_with(f))
|
||||
}
|
||||
|
||||
static MATH_CTX: LazyLock<evalexpr::HashMapContext<evalexpr::DefaultNumericTypes>> =
|
||||
LazyLock::new(|| {
|
||||
static MATH_CTX: LazyLock<evalexpr::HashMapContext<evalexpr::DefaultNumericTypes>> = LazyLock::new(
|
||||
|| {
|
||||
use evalexpr::*;
|
||||
context_map! {
|
||||
"pi" => float std::f64::consts::PI,
|
||||
@@ -59,7 +59,8 @@ static MATH_CTX: LazyLock<evalexpr::HashMapContext<evalexpr::DefaultNumericTypes
|
||||
"round" => Function::new(|a: &Value<DefaultNumericTypes>| Ok(Value::from_float(a.as_number()?.round())))
|
||||
}
|
||||
.expect("static math context must be valid")
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
#[async_trait]
|
||||
impl Plugin for CalcPlugin {
|
||||
|
||||
@@ -76,11 +76,7 @@ impl Plugin for FilesPlugin {
|
||||
let full_path = entry.path();
|
||||
let name = entry.file_name().to_string_lossy().to_string();
|
||||
let is_dir = full_path.is_dir();
|
||||
let title = if is_dir {
|
||||
format!("{name}/")
|
||||
} else {
|
||||
name
|
||||
};
|
||||
let title = if is_dir { format!("{name}/") } else { name };
|
||||
let path_str = full_path.to_string_lossy().to_string();
|
||||
SearchResult {
|
||||
id: ResultId::new(format!("file-{i}")),
|
||||
|
||||
Reference in New Issue
Block a user