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 {
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 clone_on_split(
196 &self,
197 _workspace_id: Option<WorkspaceId>,
198 _window: &mut Window,
199 _: &mut Context<Self>,
200 ) -> Option<Entity<Self>> {
201 None
202 }
203
204 fn to_item_events(event: &Self::Event, mut f: impl FnMut(workspace::item::ItemEvent)) {
205 f(*event)
206 }
207}
208
209impl Render for ReplSessionsPage {
210 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
211 let store = ReplStore::global(cx);
212
213 let (kernel_specifications, sessions) = store.update(cx, |store, _cx| {
214 (
215 store
216 .pure_jupyter_kernel_specifications()
217 .cloned()
218 .collect::<Vec<_>>(),
219 store.sessions().cloned().collect::<Vec<_>>(),
220 )
221 });
222
223 // When there are no kernel specifications, show a link to the Zed docs explaining how to
224 // install kernels. It can be assumed they don't have a running kernel if we have no
225 // specifications.
226 if kernel_specifications.is_empty() {
227 let instructions = "To start interactively running code in your editor, you need to install and configure Jupyter kernels.";
228
229 return ReplSessionsContainer::new("No Jupyter Kernels Available")
230 .child(Label::new(instructions))
231 .child(
232 h_flex().w_full().p_4().justify_center().gap_2().child(
233 ButtonLike::new("install-kernels")
234 .style(ButtonStyle::Filled)
235 .size(ButtonSize::Large)
236 .layer(ElevationIndex::ModalSurface)
237 .child(Label::new("Install Kernels"))
238 .on_click(move |_, _, cx| {
239 cx.open_url(
240 "https://zed.dev/docs/repl#language-specific-instructions",
241 )
242 }),
243 ),
244 );
245 }
246
247 // When there are no sessions, show the command to run code in an editor
248 if sessions.is_empty() {
249 let instructions = "To run code in a Jupyter kernel, select some code and use the 'repl::Run' command.";
250
251 return ReplSessionsContainer::new("No Jupyter Kernel Sessions").child(
252 v_flex()
253 .child(Label::new(instructions))
254 .children(KeyBinding::for_action(&Run, window, cx)),
255 );
256 }
257
258 ReplSessionsContainer::new("Jupyter Kernel Sessions").children(sessions)
259 }
260}
261
262#[derive(IntoElement)]
263struct ReplSessionsContainer {
264 title: SharedString,
265 children: Vec<AnyElement>,
266}
267
268impl ReplSessionsContainer {
269 pub fn new(title: impl Into<SharedString>) -> Self {
270 Self {
271 title: title.into(),
272 children: Vec::new(),
273 }
274 }
275}
276
277impl ParentElement for ReplSessionsContainer {
278 fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
279 self.children.extend(elements)
280 }
281}
282
283impl RenderOnce for ReplSessionsContainer {
284 fn render(self, _window: &mut Window, _cx: &mut App) -> impl IntoElement {
285 v_flex()
286 .p_4()
287 .gap_2()
288 .size_full()
289 .child(Label::new(self.title).size(LabelSize::Large))
290 .children(self.children)
291 }
292}