use std::borrow::Cow;
use pop_launcher::{Generation, IconSource as PopIcon, Indice, SearchResult};
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
pub struct ItemKey(pub String);
impl ItemKey {
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
}
impl std::fmt::Display for ItemKey {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.0)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Source {
Launcher,
Window {
identifier: String,
},
File {
path: std::path::PathBuf,
},
Clipboard {
text: String,
},
Plugin {
plugin: String,
arg: String,
variables: Vec<(String, String)>,
mods: Vec<Mod>,
},
System {
id: String,
},
Process {
pid: u32,
},
Emoji {
emoji: String,
},
Calc {
answer: String,
},
Url {
url: String,
},
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Mod {
pub modifier: String,
pub subtitle: String,
pub arg: String,
pub variables: Vec<(String, String)>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Icon {
Name(String),
Mime(String),
}
impl Icon {
fn from_pop(icon: PopIcon) -> Self {
match icon {
PopIcon::Name(name) => Self::Name(into_string(name)),
PopIcon::Mime(mime) => Self::Mime(into_string(mime)),
}
}
}
fn into_string(cow: Cow<'static, str>) -> String {
match cow {
Cow::Borrowed(s) => s.to_owned(),
Cow::Owned(s) => s,
}
}
#[derive(Debug, Clone)]
pub struct Item {
pub key: ItemKey,
pub id: Indice,
pub title: String,
pub subtitle: String,
pub icon: Option<Icon>,
pub category_icon: Option<Icon>,
pub window: Option<(Generation, Indice)>,
pub source: Source,
pub autocomplete: Option<String>,
pub score: f32,
}
impl Item {
#[must_use]
pub fn from_search_result(result: SearchResult) -> Self {
let SearchResult {
id,
name,
description,
icon,
category_icon,
window,
} = result;
let key = Self::derive_key(&name, &description, window);
Self {
key,
id,
title: name,
subtitle: description,
icon: icon.map(Icon::from_pop),
category_icon: category_icon.map(Icon::from_pop),
window,
source: Source::Launcher,
autocomplete: None,
score: 0.0,
}
}
fn derive_key(name: &str, description: &str, window: Option<(Generation, Indice)>) -> ItemKey {
match window {
Some((generation, indice)) => ItemKey(format!("window:{generation}:{indice}")),
None => ItemKey(format!("entry:{name}\u{1f}{description}")),
}
}
#[must_use]
pub fn dismisses_on_activate(&self) -> bool {
true
}
}
#[derive(Debug, Clone, Default)]
pub struct Results {
pub seq: u64,
pub query: String,
pub items: Vec<Item>,
}
impl Results {
#[must_use]
pub fn is_empty(&self) -> bool {
self.items.is_empty()
}
#[must_use]
pub fn len(&self) -> usize {
self.items.len()
}
#[must_use]
pub fn position_of(&self, key: &ItemKey) -> Option<usize> {
self.items.iter().position(|item| &item.key == key)
}
}