Skip to main content

jump_core/
model.rs

1// Copyright 2026 entro314-labs
2// SPDX-License-Identifier: MPL-2.0
3
4//! The result model shared by every frontend.
5//!
6//! The one design decision that matters here is [`ItemKey`]. pop-launcher
7//! addresses results by [`Indice`], but that index is only meaningful for the
8//! query that produced it — "Firefox" can be id 0 for `fire` and id 3 for `fi`.
9//! A frontend that keys its list on the indice therefore sees every row change
10//! identity on every keystroke, which forces a full list rebuild and makes
11//! animating the difference impossible. That is exactly why cosmic-launcher
12//! swaps its list instantly instead of transitioning.
13//!
14//! [`ItemKey`] is derived from properties that survive re-querying, so the same
15//! program keeps the same key across searches. The view can then diff two result
16//! sets and animate rows that moved, faded in, or faded out.
17
18use std::borrow::Cow;
19
20use pop_launcher::{Generation, IconSource as PopIcon, Indice, SearchResult};
21use serde::{Deserialize, Serialize};
22
23/// Identity of a result that is stable across queries.
24///
25/// Two [`Item`]s produced by different searches compare equal when they refer
26/// to the same underlying thing, which is what lets the UI animate between
27/// result sets rather than replacing them.
28#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
29pub struct ItemKey(pub String);
30
31impl ItemKey {
32    /// The key as a string slice.
33    #[must_use]
34    pub fn as_str(&self) -> &str {
35        &self.0
36    }
37}
38
39impl std::fmt::Display for ItemKey {
40    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
41        f.write_str(&self.0)
42    }
43}
44
45/// Where a result came from. Determines how it is activated.
46#[derive(Debug, Clone, PartialEq, Eq)]
47pub enum Source {
48    /// Produced by the pop-launcher service; activate by [`Indice`].
49    Launcher,
50    /// An open window, activated through the compositor rather than by
51    /// launching anything. Carries only the compositor's identifier string, so
52    /// the engine stays free of Wayland types.
53    Window {
54        /// The compositor's opaque handle for the window.
55        identifier: String,
56    },
57    /// A file on disk, opened with the user's default handler.
58    File {
59        /// Absolute path to the file.
60        path: std::path::PathBuf,
61    },
62    /// A clipboard history entry; activating it copies the text back.
63    Clipboard {
64        /// The stored text, copied back on activation.
65        text: String,
66    },
67    /// Produced by a jump plugin; activate by running the plugin's action.
68    Plugin {
69        /// Directory name of the plugin that produced this item.
70        plugin: String,
71        /// Opaque payload handed back to the plugin on activation.
72        arg: String,
73        /// Alfred-style `variables`, exported into the activation command's
74        /// environment. Sorted, so two equal items compare equal.
75        variables: Vec<(String, String)>,
76        /// Alternate actions on modifier+Enter, Alfred's `mods`.
77        mods: Vec<Mod>,
78    },
79    /// A built-in command provided by the frontend — toggling dark mode,
80    /// opening a settings page. Carries only an identifier so the engine stays
81    /// free of desktop specifics; the frontend maps it to an action.
82    System {
83        /// Stable command identifier, e.g. `dark-mode`.
84        id: String,
85    },
86    /// A running process; activating it sends `SIGTERM`.
87    Process {
88        /// Process id, valid only for the listing that produced it.
89        pid: u32,
90    },
91    /// An emoji. Activating it copies the character.
92    ///
93    /// Distinct from [`Source::Clipboard`] even though both copy, because
94    /// the row is drawn differently: the glyph *is* the icon, and reusing
95    /// Clipboard left every emoji row showing a generic placeholder in the
96    /// icon slot — caught by looking at it, not by any test.
97    Emoji {
98        /// The character itself.
99        emoji: String,
100    },
101    /// A calculator answer. Activating it copies the value, which is what
102    /// the result is for — the answer is already on screen.
103    Calc {
104        /// The value as Qalculate rendered it.
105        answer: String,
106    },
107    /// A web link — a quicklink or a fallback search; activating it opens the
108    /// URL with the user's default handler.
109    Url {
110        /// Fully-expanded URL, query already encoded in.
111        url: String,
112    },
113}
114
115/// An alternate action on a plugin item, Alfred's `mods`.
116///
117/// Held on the item rather than looked up at activation time because the
118/// plugin process that produced it is long gone by then: the payload has to
119/// travel with the row.
120#[derive(Debug, Clone, PartialEq, Eq)]
121pub struct Mod {
122    /// Modifier that selects it — `ctrl`, `alt`, `shift`, `super`. Kept as
123    /// the plugin wrote it, lowercased, so the frontend owns the display
124    /// spelling and the keybinding.
125    pub modifier: String,
126    /// Row text describing what this alternate does.
127    pub subtitle: String,
128    /// Payload handed to the plugin instead of the item's own `arg`.
129    pub arg: String,
130    /// Variables for this alternate, merged the same way the item's are.
131    pub variables: Vec<(String, String)>,
132}
133
134/// An icon to render, resolved by the frontend against the active icon theme.
135#[derive(Debug, Clone, PartialEq, Eq)]
136pub enum Icon {
137    /// An icon-theme name or an absolute path to an image.
138    Name(String),
139    /// A mime type whose generic icon should be shown.
140    Mime(String),
141}
142
143impl Icon {
144    fn from_pop(icon: PopIcon) -> Self {
145        match icon {
146            PopIcon::Name(name) => Self::Name(into_string(name)),
147            PopIcon::Mime(mime) => Self::Mime(into_string(mime)),
148        }
149    }
150}
151
152fn into_string(cow: Cow<'static, str>) -> String {
153    match cow {
154        Cow::Borrowed(s) => s.to_owned(),
155        Cow::Owned(s) => s,
156    }
157}
158
159/// A single row in the result list.
160#[derive(Debug, Clone)]
161pub struct Item {
162    /// Stable identity across queries. See the module docs.
163    pub key: ItemKey,
164    /// pop-launcher's per-query index. Only valid for the query that produced
165    /// this item, so it is refreshed on every update rather than remembered.
166    pub id: Indice,
167    /// Primary line — the application, file, or window name.
168    pub title: String,
169    /// Secondary line — the path, the command, the window's application.
170    pub subtitle: String,
171    /// Leading icon, when the provider offered one.
172    pub icon: Option<Icon>,
173    /// Icon representing the plugin/category, shown trailing.
174    pub category_icon: Option<Icon>,
175    /// Set when the result refers to an open window rather than a launchable.
176    pub window: Option<(Generation, Indice)>,
177    /// Which provider produced this, and hence how it is activated.
178    pub source: Source,
179    /// Text that replaces the query on Tab, Alfred's `autocomplete`.
180    pub autocomplete: Option<String>,
181    /// Ranking score after frecency is applied. Higher sorts first.
182    pub score: f32,
183}
184
185impl Item {
186    /// Build an [`Item`] from a pop-launcher search result.
187    #[must_use]
188    pub fn from_search_result(result: SearchResult) -> Self {
189        let SearchResult {
190            id,
191            name,
192            description,
193            icon,
194            category_icon,
195            window,
196        } = result;
197
198        let key = Self::derive_key(&name, &description, window);
199
200        Self {
201            key,
202            id,
203            title: name,
204            subtitle: description,
205            icon: icon.map(Icon::from_pop),
206            category_icon: category_icon.map(Icon::from_pop),
207            window,
208            source: Source::Launcher,
209            // pop-launcher completion goes through Request::Complete instead.
210            autocomplete: None,
211            score: 0.0,
212        }
213    }
214
215    /// Windows are keyed by their compositor handle because two windows of the
216    /// same application share a title and description; everything else is keyed
217    /// by name plus description, which together identify a desktop entry well
218    /// enough to survive re-querying.
219    fn derive_key(name: &str, description: &str, window: Option<(Generation, Indice)>) -> ItemKey {
220        match window {
221            Some((generation, indice)) => ItemKey(format!("window:{generation}:{indice}")),
222            None => ItemKey(format!("entry:{name}\u{1f}{description}")),
223        }
224    }
225
226    /// Whether activating this item should dismiss the launcher.
227    ///
228    /// Calculator results are the notable exception: the user usually wants to
229    /// copy the value and keep going.
230    #[must_use]
231    pub fn dismisses_on_activate(&self) -> bool {
232        true
233    }
234}
235
236/// A complete result set for one query, plus the query that produced it.
237#[derive(Debug, Clone, Default)]
238pub struct Results {
239    /// Monotonic query generation. Used to discard responses that arrive after
240    /// the user has already typed something newer.
241    pub seq: u64,
242    /// The query text these items answer. The frontend compares it against the
243    /// current input to detect a stale set. See [`crate::launcher`].
244    pub query: String,
245    /// The rows, best first.
246    pub items: Vec<Item>,
247}
248
249impl Results {
250    /// Whether there are no items.
251    #[must_use]
252    pub fn is_empty(&self) -> bool {
253        self.items.is_empty()
254    }
255
256    /// Number of items.
257    #[must_use]
258    pub fn len(&self) -> usize {
259        self.items.len()
260    }
261
262    /// Position of `key` in this result set, if present.
263    ///
264    /// The view uses this to decide whether a row moved (animate to the new
265    /// position) or is new (fade in).
266    #[must_use]
267    pub fn position_of(&self, key: &ItemKey) -> Option<usize> {
268        self.items.iter().position(|item| &item.key == key)
269    }
270}