1use collections::HashMap;
2use editor::Editor;
3use gpui::{
4 actions, prelude::*, AnyElement, AppContext, EventEmitter, FocusHandle, FocusableView,
5 FontWeight, Subscription, View,
6};
7use ui::{prelude::*, ButtonLike, ElevationIndex, KeyBinding, ListItem, Tooltip};
8use util::ResultExt as _;
9use workspace::item::ItemEvent;
10use workspace::WorkspaceId;
11use workspace::{item::Item, Workspace};
12
13use crate::jupyter_settings::JupyterSettings;
14use crate::repl_store::ReplStore;
15use crate::KernelSpecification;
16
17actions!(
18 repl,
19 [
20 Run,
21 RunInPlace,
22 ClearOutputs,
23 Sessions,
24 Interrupt,
25 Shutdown,
26 Restart,
27 RefreshKernelspecs
28 ]
29);
30
31pub fn init(cx: &mut AppContext) {
32 cx.observe_new_views(
33 |workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
34 workspace.register_action(|workspace, _: &Sessions, cx| {
35 let existing = workspace
36 .active_pane()
37 .read(cx)
38 .items()
39 .find_map(|item| item.downcast::<ReplSessionsPage>());
40
41 if let Some(existing) = existing {
42 workspace.activate_item(&existing, true, true, cx);
43 } else {
44 let repl_sessions_page = ReplSessionsPage::new(cx);
45 workspace.add_item_to_active_pane(Box::new(repl_sessions_page), None, true, cx)
46 }
47 });
48
49 workspace.register_action(|_workspace, _: &RefreshKernelspecs, cx| {
50 let store = ReplStore::global(cx);
51 store.update(cx, |store, cx| {
52 store.refresh_kernelspecs(cx).detach();
53 });
54 });
55 },
56 )
57 .detach();
58
59 cx.observe_new_views(move |editor: &mut Editor, cx: &mut ViewContext<Editor>| {
60 if !editor.use_modal_editing() || !editor.buffer().read(cx).is_singleton() {
61 return;
62 }
63
64 cx.defer(|editor, cx| {
65 let workspace = Workspace::for_window(cx);
66
67 let is_local_project = workspace
68 .map(|workspace| workspace.read(cx).project().read(cx).is_local())
69 .unwrap_or(false);
70
71 if !is_local_project {
72 return;
73 }
74
75 let editor_handle = cx.view().downgrade();
76
77 editor
78 .register_action({
79 let editor_handle = editor_handle.clone();
80 move |_: &Run, cx| {
81 if !JupyterSettings::enabled(cx) {
82 return;
83 }
84
85 crate::run(editor_handle.clone(), true, cx).log_err();
86 }
87 })
88 .detach();
89
90 editor
91 .register_action({
92 let editor_handle = editor_handle.clone();
93 move |_: &RunInPlace, cx| {
94 if !JupyterSettings::enabled(cx) {
95 return;
96 }
97
98 crate::run(editor_handle.clone(), false, cx).log_err();
99 }
100 })
101 .detach();
102
103 editor
104 .register_action({
105 let editor_handle = editor_handle.clone();
106 move |_: &ClearOutputs, cx| {
107 if !JupyterSettings::enabled(cx) {
108 return;
109 }
110
111 crate::clear_outputs(editor_handle.clone(), cx);
112 }
113 })
114 .detach();
115
116 editor
117 .register_action({
118 let editor_handle = editor_handle.clone();
119 move |_: &Interrupt, cx| {
120 if !JupyterSettings::enabled(cx) {
121 return;
122 }
123
124 crate::interrupt(editor_handle.clone(), cx);
125 }
126 })
127 .detach();
128
129 editor
130 .register_action({
131 let editor_handle = editor_handle.clone();
132 move |_: &Shutdown, cx| {
133 if !JupyterSettings::enabled(cx) {
134 return;
135 }
136
137 crate::shutdown(editor_handle.clone(), cx);
138 }
139 })
140 .detach();
141
142 editor
143 .register_action({
144 let editor_handle = editor_handle.clone();
145 move |_: &Restart, cx| {
146 if !JupyterSettings::enabled(cx) {
147 return;
148 }
149
150 crate::restart(editor_handle.clone(), cx);
151 }
152 })
153 .detach();
154 });
155 })
156 .detach();
157}
158
159pub struct ReplSessionsPage {
160 focus_handle: FocusHandle,
161 _subscriptions: Vec<Subscription>,
162}
163
164impl ReplSessionsPage {
165 pub fn new(cx: &mut ViewContext<Workspace>) -> View<Self> {
166 cx.new_view(|cx: &mut ViewContext<Self>| {
167 let focus_handle = cx.focus_handle();
168
169 let subscriptions = vec![
170 cx.on_focus_in(&focus_handle, |_this, cx| cx.notify()),
171 cx.on_focus_out(&focus_handle, |_this, _event, cx| cx.notify()),
172 ];
173
174 Self {
175 focus_handle,
176 _subscriptions: subscriptions,
177 }
178 })
179 }
180}
181
182impl EventEmitter<ItemEvent> for ReplSessionsPage {}
183
184impl FocusableView for ReplSessionsPage {
185 fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
186 self.focus_handle.clone()
187 }
188}
189
190impl Item for ReplSessionsPage {
191 type Event = ItemEvent;
192
193 fn tab_content_text(&self, _cx: &WindowContext) -> Option<SharedString> {
194 Some("REPL Sessions".into())
195 }
196
197 fn telemetry_event_text(&self) -> Option<&'static str> {
198 Some("repl sessions")
199 }
200
201 fn show_toolbar(&self) -> bool {
202 false
203 }
204
205 fn clone_on_split(
206 &self,
207 _workspace_id: Option<WorkspaceId>,
208 _: &mut ViewContext<Self>,
209 ) -> Option<View<Self>> {
210 None
211 }
212
213 fn to_item_events(event: &Self::Event, mut f: impl FnMut(workspace::item::ItemEvent)) {
214 f(*event)
215 }
216}
217
218impl Render for ReplSessionsPage {
219 fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
220 let store = ReplStore::global(cx);
221
222 let (kernel_specifications, sessions) = store.update(cx, |store, _cx| {
223 (
224 store.kernel_specifications().cloned().collect::<Vec<_>>(),
225 store.sessions().cloned().collect::<Vec<_>>(),
226 )
227 });
228
229 // When there are no kernel specifications, show a link to the Zed docs explaining how to
230 // install kernels. It can be assumed they don't have a running kernel if we have no
231 // specifications.
232 if kernel_specifications.is_empty() {
233 let instructions = "To start interactively running code in your editor, you need to install and configure Jupyter kernels.";
234
235 return ReplSessionsContainer::new("No Jupyter Kernels Available")
236 .child(Label::new(instructions))
237 .child(
238 h_flex().w_full().p_4().justify_center().gap_2().child(
239 ButtonLike::new("install-kernels")
240 .style(ButtonStyle::Filled)
241 .size(ButtonSize::Large)
242 .layer(ElevationIndex::ModalSurface)
243 .child(Label::new("Install Kernels"))
244 .on_click(move |_, cx| {
245 cx.open_url(
246 "https://zed.dev/docs/repl#language-specific-instructions",
247 )
248 }),
249 ),
250 );
251 }
252
253 let mut kernels_by_language: HashMap<String, Vec<KernelSpecification>> = HashMap::default();
254 for spec in kernel_specifications {
255 kernels_by_language
256 .entry(spec.kernelspec.language.clone())
257 .or_default()
258 .push(spec);
259 }
260
261 let kernels_available = v_flex()
262 .child(Label::new("Kernels available").size(LabelSize::Large))
263 .gap_2()
264 .child(
265 h_flex()
266 .child(Label::new(
267 "Defaults indicated with a checkmark. Learn how to change your default kernel in the ",
268 ))
269 .child(
270 ButtonLike::new("configure-kernels")
271 .style(ButtonStyle::Filled)
272 // .size(ButtonSize::Compact)
273 .layer(ElevationIndex::Surface)
274 .child(Label::new("REPL documentation"))
275 .child(Icon::new(IconName::Link))
276 .on_click(move |_, cx| {
277 cx.open_url("https://zed.dev/docs/repl#changing-kernels")
278 }),
279 ),
280 )
281 .children(kernels_by_language.into_iter().map(|(language, specs)| {
282 let chosen_kernel = store.read(cx).kernelspec(&language, cx);
283
284 v_flex()
285 .gap_1()
286 .child(Label::new(language.clone()).weight(FontWeight::BOLD))
287 .children(specs.into_iter().map(|spec| {
288 let is_choice = if let Some(chosen_kernel) = &chosen_kernel {
289 chosen_kernel.name.to_lowercase() == spec.name.to_lowercase()
290 && chosen_kernel.path == spec.path
291 } else {
292 false
293 };
294
295 let path = SharedString::from(spec.path.to_string_lossy().to_string());
296
297 ListItem::new(path.clone())
298 .selectable(false)
299 .tooltip({
300 let path = path.clone();
301 move |cx| Tooltip::text(path.clone(), cx)})
302 .child(
303 h_flex()
304 .gap_1()
305 .child(div().id(path.clone()).child(Label::new(spec.name.clone())))
306 .when(is_choice, |el| {
307
308 let language = language.clone();
309
310 el.child(
311
312 div().id("check").tooltip(move |cx| Tooltip::text(format!("Default Kernel for {language}"), cx))
313 .child(Icon::new(IconName::Check)))}),
314 )
315
316 }))
317 }));
318
319 // When there are no sessions, show the command to run code in an editor
320 if sessions.is_empty() {
321 let instructions = "To run code in a Jupyter kernel, select some code and use the 'repl::Run' command.";
322
323 return ReplSessionsContainer::new("No Jupyter Kernel Sessions")
324 .child(
325 v_flex()
326 .child(Label::new(instructions))
327 .children(KeyBinding::for_action(&Run, cx)),
328 )
329 .child(div().pt_3().child(kernels_available));
330 }
331
332 ReplSessionsContainer::new("Jupyter Kernel Sessions")
333 .children(sessions)
334 .child(kernels_available)
335 }
336}
337
338#[derive(IntoElement)]
339struct ReplSessionsContainer {
340 title: SharedString,
341 children: Vec<AnyElement>,
342}
343
344impl ReplSessionsContainer {
345 pub fn new(title: impl Into<SharedString>) -> Self {
346 Self {
347 title: title.into(),
348 children: Vec::new(),
349 }
350 }
351}
352
353impl ParentElement for ReplSessionsContainer {
354 fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
355 self.children.extend(elements)
356 }
357}
358
359impl RenderOnce for ReplSessionsContainer {
360 fn render(self, _cx: &mut WindowContext) -> impl IntoElement {
361 v_flex()
362 .p_4()
363 .gap_2()
364 .size_full()
365 .child(Label::new(self.title).size(LabelSize::Large))
366 .children(self.children)
367 }
368}