Skip to main content

kitchen_shell/
plugins_view.rs

1//! The plugin manager's Settings page: every plugin found, its version, licence, capabilities,
2//! whether its runtime is ready and the room it takes; install one from a file, refresh, remove
3//! one (with what it downloaded). Discovery and installs run off the UI thread. An app shows the
4//! page as a section of its Settings (`kitchen-shell`'s `SettingsSection`).
5
6use gpui_kit::assets::IconName;
7use gpui_kit::component::button::{Button, ButtonVariants as _};
8use gpui_kit::component::{Disableable as _, Sizable as _, h_flex, v_flex};
9use gpui_kit::{
10    Context, EventEmitter, FontWeight, IntoElement, ParentElement as _, PathPromptOptions, Render, SharedString,
11    Styled as _, Window, div, px,
12};
13use kitchen_ui::theme::{self, color};
14use kitchen_ui::widgets::{EmptyState, Section};
15
16use kitchen_tools::{Installed, Manager};
17
18/// The page tells its owner when plugins were installed or removed (to look again at what they
19/// can do).
20#[derive(Clone, Debug, PartialEq, Eq)]
21pub struct PluginsChanged;
22
23/// The plugin manager's page.
24pub struct PluginsPage {
25    manager: Manager,
26    rows: Vec<Installed>,
27    loading: bool,
28    message: Option<(bool, String)>,
29}
30
31impl EventEmitter<PluginsChanged> for PluginsPage {}
32
33impl PluginsPage {
34    /// The page over `manager`; starts looking for plugins.
35    pub fn new(manager: Manager, cx: &mut Context<Self>) -> Self {
36        let mut page = Self { manager, rows: Vec::new(), loading: false, message: None };
37        page.refresh(cx);
38        page
39    }
40
41    /// The plugins found (after the last refresh).
42    pub fn rows(&self) -> &[Installed] {
43        &self.rows
44    }
45
46    /// Whether it is looking for plugins.
47    pub fn loading(&self) -> bool {
48        self.loading
49    }
50
51    /// The last message (`true`: an error).
52    pub fn message(&self) -> Option<&(bool, String)> {
53        self.message.as_ref()
54    }
55
56    /// Looks for plugins again (off the UI thread).
57    pub fn refresh(&mut self, cx: &mut Context<Self>) {
58        self.loading = true;
59        let manager = self.manager.clone();
60        cx.spawn(async move |this, cx| {
61            let rows = cx.background_executor().spawn(async move { manager.list() }).await;
62            let _ = this.update(cx, |p, cx| {
63                p.rows = rows;
64                p.loading = false;
65                cx.notify();
66            });
67        })
68        .detach();
69        cx.notify();
70    }
71
72    /// Installs the plugin program at `path` (off the UI thread), then looks again.
73    pub fn install(&mut self, path: std::path::PathBuf, cx: &mut Context<Self>) {
74        let manager = self.manager.clone();
75        self.message = Some((false, format!("Installing {}…", path.display())));
76        cx.spawn(async move |this, cx| {
77            let r = cx.background_executor().spawn(async move { manager.install_from(&path) }).await;
78            let _ = this.update(cx, |p, cx| {
79                p.message = Some(match r {
80                    Ok(info) => (false, format!("Installed {} {}", info.name, info.version)),
81                    Err(e) => (true, e),
82                });
83                cx.emit(PluginsChanged);
84                p.refresh(cx);
85            });
86        })
87        .detach();
88        cx.notify();
89    }
90
91    /// Removes the plugin `name` and what it downloaded.
92    pub fn remove(&mut self, name: &str, cx: &mut Context<Self>) {
93        self.message = Some(match self.manager.remove(name, true) {
94            Ok(()) => (false, format!("Removed {name}")),
95            Err(e) => (true, e),
96        });
97        cx.emit(PluginsChanged);
98        self.refresh(cx);
99    }
100
101    fn pick_file(&mut self, cx: &mut Context<Self>) {
102        let rx = cx.prompt_for_paths(PathPromptOptions {
103            files: true,
104            directories: false,
105            multiple: false,
106            prompt: Some("Install plugin".into()),
107        });
108        cx.spawn(async move |this, cx| {
109            if let Ok(Ok(Some(paths))) = rx.await
110                && let Some(path) = paths.into_iter().next()
111            {
112                let _ = this.update(cx, |p, cx| p.install(path, cx));
113            }
114        })
115        .detach();
116    }
117
118    fn row(&self, i: usize, r: &Installed, cx: &mut Context<Self>) -> impl IntoElement {
119        let remove = r.removable.then(|| {
120            let name = r.name.clone();
121            Button::new(SharedString::from(format!("plugin-remove-{i}")))
122                .small()
123                .outline()
124                .icon(IconName::Trash)
125                .label("Remove")
126                .tooltip("Remove the plugin and what it downloaded")
127                .on_click(cx.listener(move |p, _, _, cx| p.remove(&name, cx)))
128        });
129        let head = |title: String, version: String| {
130            h_flex()
131                .gap(px(theme::SM))
132                .items_center()
133                .child(div().flex_1().min_w_0().truncate().text_sm().font_weight(FontWeight::SEMIBOLD).child(title))
134                .child(div().text_xs().text_color(color::text_muted()).child(version))
135                .child(
136                    div()
137                        .text_xs()
138                        .font_family("monospace")
139                        .text_color(color::text_muted())
140                        .child(human_bytes(r.bytes)),
141                )
142        };
143        let body = match &r.info {
144            Ok(info) => {
145                let runtime = info.runtime.as_ref().map(|rt| {
146                    div().text_xs().text_color(if rt.ready { color::text_muted() } else { color::warning() }).child(
147                        if rt.ready { format!("Ready: {}", rt.detail) } else { format!("Not ready: {}", rt.detail) },
148                    )
149                });
150                v_flex()
151                    .gap(px(theme::XS))
152                    .child(head(
153                        info.name.clone(),
154                        format!(
155                            "{} · {}",
156                            info.version,
157                            if info.licence.is_empty() { "licence not stated" } else { &info.licence }
158                        ),
159                    ))
160                    .child(h_flex().gap(px(theme::XS)).flex_wrap().children(info.capabilities.iter().map(|c| {
161                        div()
162                            .px(px(theme::SM))
163                            .py(px(2.))
164                            .rounded(px(theme::RADIUS_SM))
165                            .bg(color::control())
166                            .text_xs()
167                            .child(c.clone())
168                    })))
169                    .children(runtime)
170                    .child(
171                        div()
172                            .text_xs()
173                            .text_color(color::text_muted())
174                            .truncate()
175                            .child(r.program.display().to_string()),
176                    )
177            }
178            Err(e) => v_flex()
179                .gap(px(theme::XS))
180                .child(head(r.name.clone(), "does not answer".into()))
181                .child(div().text_xs().text_color(color::danger()).child(e.clone())),
182        };
183        h_flex()
184            .w_full()
185            .gap(px(theme::MD))
186            .items_start()
187            .p(px(theme::MD))
188            .rounded(px(theme::RADIUS_LG))
189            .border_1()
190            .border_color(color::border())
191            .bg(color::raised())
192            .child(div().flex_1().min_w_0().child(body))
193            .children(remove)
194    }
195}
196
197/// `1 234 567` bytes as "1.2 MB".
198pub fn human_bytes(b: u64) -> String {
199    let b = b as f64;
200    match b {
201        b if b >= 1e9 => format!("{:.1} GB", b / 1e9),
202        b if b >= 1e6 => format!("{:.1} MB", b / 1e6),
203        b if b >= 1e3 => format!("{:.0} kB", b / 1e3),
204        b => format!("{b:.0} B"),
205    }
206}
207
208impl Render for PluginsPage {
209    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
210        let total: u64 = self.rows.iter().map(|r| r.bytes).sum();
211        let summary = if self.loading {
212            "Looking for plugins…".to_string()
213        } else {
214            format!("{} found · {} with what they downloaded", self.rows.len(), human_bytes(total))
215        };
216        let actions = h_flex()
217            .gap(px(theme::SM))
218            .child(
219                Button::new("plugins-install")
220                    .small()
221                    .primary()
222                    .icon(IconName::Plus)
223                    .label("Install from file…")
224                    .on_click(cx.listener(|p, _, _, cx| p.pick_file(cx))),
225            )
226            .child(
227                Button::new("plugins-refresh")
228                    .small()
229                    .outline()
230                    .icon(IconName::RefreshCw)
231                    .label("Refresh")
232                    .disabled(self.loading)
233                    .on_click(cx.listener(|p, _, _, cx| p.refresh(cx))),
234            );
235        let rows: Vec<_> =
236            self.rows.clone().iter().enumerate().map(|(i, r)| self.row(i, r, cx).into_any_element()).collect();
237        let list = if rows.is_empty() && !self.loading {
238            div()
239                .h(px(220.))
240                .child(EmptyState::new(
241                    IconName::Blocks,
242                    "No plugins",
243                    format!(
244                        "Plugins are programs named {}…; install one from a file, or put it in {}.",
245                        self.manager.kind.prefix,
246                        self.manager.kind.user_dir.display()
247                    ),
248                ))
249                .into_any_element()
250        } else {
251            v_flex().gap(px(theme::SM)).children(rows).into_any_element()
252        };
253        v_flex()
254            .w_full()
255            .gap(px(theme::MD))
256            .child(
257                h_flex()
258                    .gap(px(theme::SM))
259                    .items_center()
260                    .flex_wrap()
261                    .child(div().flex_1().min_w_0().text_sm().text_color(color::text_muted()).child(summary))
262                    .child(actions),
263            )
264            .children(self.message.clone().map(|(err, m)| {
265                div().text_sm().text_color(if err { color::danger() } else { color::text_muted() }).child(m)
266            }))
267            .child(Section::new("Installed").child(list))
268    }
269}