repl_sessions_ui.rs

  1use editor::Editor;
  2use gpui::{
  3    AnyElement, App, Entity, EventEmitter, FocusHandle, Focusable, Subscription, actions,
  4    prelude::*,
  5};
  6use project::ProjectItem as _;
  7use ui::{ButtonLike, ElevationIndex, KeyBinding, prelude::*};
  8use util::ResultExt as _;
  9use workspace::WorkspaceId;
 10use workspace::item::ItemEvent;
 11use workspace::{Workspace, item::Item};
 12
 13use crate::jupyter_settings::JupyterSettings;
 14use crate::repl_store::ReplStore;
 15
 16actions!(
 17    repl,
 18    [
 19        /// Runs the current cell and advances to the next one.
 20        Run,
 21        /// Runs the current cell without advancing.
 22        RunInPlace,
 23        /// Clears all outputs in the REPL.
 24        ClearOutputs,
 25        /// Opens the REPL sessions panel.
 26        Sessions,
 27        /// Interrupts the currently running kernel.
 28        Interrupt,
 29        /// Shuts down the current kernel.
 30        Shutdown,
 31        /// Restarts the current kernel.
 32        Restart,
 33        /// Refreshes the list of available kernelspecs.
 34        RefreshKernelspecs
 35    ]
 36);
 37
 38pub fn init(cx: &mut App) {
 39    cx.observe_new(
 40        |workspace: &mut Workspace, _window, _cx: &mut Context<Workspace>| {
 41            workspace.register_action(|workspace, _: &Sessions, window, cx| {
 42                let existing = workspace
 43                    .active_pane()
 44                    .read(cx)
 45                    .items()
 46                    .find_map(|item| item.downcast::<ReplSessionsPage>());
 47
 48                if let Some(existing) = existing {
 49                    workspace.activate_item(&existing, true, true, window, cx);
 50                } else {
 51                    let repl_sessions_page = ReplSessionsPage::new(window, cx);
 52                    workspace.add_item_to_active_pane(
 53                        Box::new(repl_sessions_page),
 54                        None,
 55                        true,
 56                        window,
 57                        cx,
 58                    )
 59                }
 60            });
 61
 62            workspace.register_action(|_workspace, _: &RefreshKernelspecs, _, cx| {
 63                let store = ReplStore::global(cx);
 64                store.update(cx, |store, cx| {
 65                    store.refresh_kernelspecs(cx).detach();
 66                });
 67            });
 68        },
 69    )
 70    .detach();
 71
 72    cx.observe_new(
 73        move |editor: &mut Editor, window, cx: &mut Context<Editor>| {
 74            let Some(window) = window else {
 75                return;
 76            };
 77
 78            if !editor.use_modal_editing() || !editor.buffer().read(cx).is_singleton() {
 79                return;
 80            }
 81
 82            cx.defer_in(window, |editor, window, cx| {
 83                let workspace = Workspace::for_window(window, cx);
 84                let project = workspace.map(|workspace| workspace.read(cx).project().clone());
 85
 86                let is_local_project = project
 87                    .as_ref()
 88                    .map(|project| project.read(cx).is_local())
 89                    .unwrap_or(false);
 90
 91                if !is_local_project {
 92                    return;
 93                }
 94
 95                let buffer = editor.buffer().read(cx).as_singleton();
 96
 97                let language = buffer
 98                    .as_ref()
 99                    .and_then(|buffer| buffer.read(cx).language());
100
101                let project_path = buffer.and_then(|buffer| buffer.read(cx).project_path(cx));
102
103                let editor_handle = cx.entity().downgrade();
104
105                if let Some(language) = language
106                    && language.name() == "Python".into()
107                        && let (Some(project_path), Some(project)) = (project_path, project) {
108                            let store = ReplStore::global(cx);
109                            store.update(cx, |store, cx| {
110                                store
111                                    .refresh_python_kernelspecs(
112                                        project_path.worktree_id,
113                                        &project,
114                                        cx,
115                                    )
116                                    .detach_and_log_err(cx);
117                            });
118                        }
119
120                editor
121                    .register_action({
122                        let editor_handle = editor_handle.clone();
123                        move |_: &Run, window, cx| {
124                            if !JupyterSettings::enabled(cx) {
125                                return;
126                            }
127
128                            crate::run(editor_handle.clone(), true, window, cx).log_err();
129                        }
130                    })
131                    .detach();
132
133                editor
134                    .register_action({
135                        let editor_handle = editor_handle.clone();
136                        move |_: &RunInPlace, window, cx| {
137                            if !JupyterSettings::enabled(cx) {
138                                return;
139                            }
140
141                            crate::run(editor_handle.clone(), false, window, cx).log_err();
142                        }
143                    })
144                    .detach();
145            });
146        },
147    )
148    .detach();
149}
150
151pub struct ReplSessionsPage {
152    focus_handle: FocusHandle,
153    _subscriptions: Vec<Subscription>,
154}
155
156impl ReplSessionsPage {
157    pub fn new(window: &mut Window, cx: &mut Context<Workspace>) -> Entity<Self> {
158        cx.new(|cx| {
159            let focus_handle = cx.focus_handle();
160
161            let subscriptions = vec![
162                cx.on_focus_in(&focus_handle, window, |_this, _window, cx| cx.notify()),
163                cx.on_focus_out(&focus_handle, window, |_this, _event, _window, cx| {
164                    cx.notify()
165                }),
166            ];
167
168            Self {
169                focus_handle,
170                _subscriptions: subscriptions,
171            }
172        })
173    }
174}
175
176impl EventEmitter<ItemEvent> for ReplSessionsPage {}
177
178impl Focusable for ReplSessionsPage {
179    fn focus_handle(&self, _cx: &App) -> FocusHandle {
180        self.focus_handle.clone()
181    }
182}
183
184impl Item for ReplSessionsPage {
185    type Event = ItemEvent;
186
187    fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
188        "REPL Sessions".into()
189    }
190
191    fn telemetry_event_text(&self) -> Option<&'static str> {
192        Some("REPL Session Started")
193    }
194
195    fn show_toolbar(&self) -> bool {
196        false
197    }
198
199    fn clone_on_split(
200        &self,
201        _workspace_id: Option<WorkspaceId>,
202        _window: &mut Window,
203        _: &mut Context<Self>,
204    ) -> Option<Entity<Self>> {
205        None
206    }
207
208    fn to_item_events(event: &Self::Event, mut f: impl FnMut(workspace::item::ItemEvent)) {
209        f(*event)
210    }
211}
212
213impl Render for ReplSessionsPage {
214    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
215        let store = ReplStore::global(cx);
216
217        let (kernel_specifications, sessions) = store.update(cx, |store, _cx| {
218            (
219                store
220                    .pure_jupyter_kernel_specifications()
221                    .cloned()
222                    .collect::<Vec<_>>(),
223                store.sessions().cloned().collect::<Vec<_>>(),
224            )
225        });
226
227        // When there are no kernel specifications, show a link to the Zed docs explaining how to
228        // install kernels. It can be assumed they don't have a running kernel if we have no
229        // specifications.
230        if kernel_specifications.is_empty() {
231            let instructions = "To start interactively running code in your editor, you need to install and configure Jupyter kernels.";
232
233            return ReplSessionsContainer::new("No Jupyter Kernels Available")
234                .child(Label::new(instructions))
235                .child(
236                    h_flex().w_full().p_4().justify_center().gap_2().child(
237                        ButtonLike::new("install-kernels")
238                            .style(ButtonStyle::Filled)
239                            .size(ButtonSize::Large)
240                            .layer(ElevationIndex::ModalSurface)
241                            .child(Label::new("Install Kernels"))
242                            .on_click(move |_, _, cx| {
243                                cx.open_url(
244                                    "https://zed.dev/docs/repl#language-specific-instructions",
245                                )
246                            }),
247                    ),
248                );
249        }
250
251        // When there are no sessions, show the command to run code in an editor
252        if sessions.is_empty() {
253            let instructions = "To run code in a Jupyter kernel, select some code and use the 'repl::Run' command.";
254
255            return ReplSessionsContainer::new("No Jupyter Kernel Sessions").child(
256                v_flex()
257                    .child(Label::new(instructions))
258                    .children(KeyBinding::for_action(&Run, window, cx)),
259            );
260        }
261
262        ReplSessionsContainer::new("Jupyter Kernel Sessions").children(sessions)
263    }
264}
265
266#[derive(IntoElement)]
267struct ReplSessionsContainer {
268    title: SharedString,
269    children: Vec<AnyElement>,
270}
271
272impl ReplSessionsContainer {
273    pub fn new(title: impl Into<SharedString>) -> Self {
274        Self {
275            title: title.into(),
276            children: Vec::new(),
277        }
278    }
279}
280
281impl ParentElement for ReplSessionsContainer {
282    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
283        self.children.extend(elements)
284    }
285}
286
287impl RenderOnce for ReplSessionsContainer {
288    fn render(self, _window: &mut Window, _cx: &mut App) -> impl IntoElement {
289        v_flex()
290            .p_4()
291            .gap_2()
292            .size_full()
293            .child(Label::new(self.title).size(LabelSize::Large))
294            .children(self.children)
295    }
296}