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