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 let editor_handle = editor_handle.clone();
133 move |_: &RunInPlace, window, cx| {
134 if !JupyterSettings::enabled(cx) {
135 return;
136 }
137
138 crate::run(editor_handle.clone(), false, window, cx).log_err();
139 }
140 })
141 .detach();
142 });
143 },
144 )
145 .detach();
146}
147
148pub struct ReplSessionsPage {
149 focus_handle: FocusHandle,
150 _subscriptions: Vec<Subscription>,
151}
152
153impl ReplSessionsPage {
154 pub fn new(window: &mut Window, cx: &mut Context<Workspace>) -> Entity<Self> {
155 cx.new(|cx| {
156 let focus_handle = cx.focus_handle();
157
158 let subscriptions = vec![
159 cx.on_focus_in(&focus_handle, window, |_this, _window, cx| cx.notify()),
160 cx.on_focus_out(&focus_handle, window, |_this, _event, _window, cx| {
161 cx.notify()
162 }),
163 ];
164
165 Self {
166 focus_handle,
167 _subscriptions: subscriptions,
168 }
169 })
170 }
171}
172
173impl EventEmitter<ItemEvent> for ReplSessionsPage {}
174
175impl Focusable for ReplSessionsPage {
176 fn focus_handle(&self, _cx: &App) -> FocusHandle {
177 self.focus_handle.clone()
178 }
179}
180
181impl Item for ReplSessionsPage {
182 type Event = ItemEvent;
183
184 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
185 "REPL Sessions".into()
186 }
187
188 fn telemetry_event_text(&self) -> Option<&'static str> {
189 Some("REPL Session Started")
190 }
191
192 fn show_toolbar(&self) -> bool {
193 false
194 }
195
196 fn clone_on_split(
197 &self,
198 _workspace_id: Option<WorkspaceId>,
199 _window: &mut Window,
200 _: &mut Context<Self>,
201 ) -> Option<Entity<Self>> {
202 None
203 }
204
205 fn to_item_events(event: &Self::Event, mut f: impl FnMut(workspace::item::ItemEvent)) {
206 f(*event)
207 }
208}
209
210impl Render for ReplSessionsPage {
211 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
212 let store = ReplStore::global(cx);
213
214 let (kernel_specifications, sessions) = store.update(cx, |store, _cx| {
215 (
216 store
217 .pure_jupyter_kernel_specifications()
218 .cloned()
219 .collect::<Vec<_>>(),
220 store.sessions().cloned().collect::<Vec<_>>(),
221 )
222 });
223
224 // When there are no kernel specifications, show a link to the Zed docs explaining how to
225 // install kernels. It can be assumed they don't have a running kernel if we have no
226 // specifications.
227 if kernel_specifications.is_empty() {
228 let instructions = "To start interactively running code in your editor, you need to install and configure Jupyter kernels.";
229
230 return ReplSessionsContainer::new("No Jupyter Kernels Available")
231 .child(Label::new(instructions))
232 .child(
233 h_flex().w_full().p_4().justify_center().gap_2().child(
234 ButtonLike::new("install-kernels")
235 .style(ButtonStyle::Filled)
236 .size(ButtonSize::Large)
237 .layer(ElevationIndex::ModalSurface)
238 .child(Label::new("Install Kernels"))
239 .on_click(move |_, _, cx| {
240 cx.open_url(
241 "https://zed.dev/docs/repl#language-specific-instructions",
242 )
243 }),
244 ),
245 );
246 }
247
248 // When there are no sessions, show the command to run code in an editor
249 if sessions.is_empty() {
250 let instructions = "To run code in a Jupyter kernel, select some code and use the 'repl::Run' command.";
251
252 return ReplSessionsContainer::new("No Jupyter Kernel Sessions").child(
253 v_flex()
254 .child(Label::new(instructions))
255 .children(KeyBinding::for_action(&Run, window, cx)),
256 );
257 }
258
259 ReplSessionsContainer::new("Jupyter Kernel Sessions").children(sessions)
260 }
261}
262
263#[derive(IntoElement)]
264struct ReplSessionsContainer {
265 title: SharedString,
266 children: Vec<AnyElement>,
267}
268
269impl ReplSessionsContainer {
270 pub fn new(title: impl Into<SharedString>) -> Self {
271 Self {
272 title: title.into(),
273 children: Vec::new(),
274 }
275 }
276}
277
278impl ParentElement for ReplSessionsContainer {
279 fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
280 self.children.extend(elements)
281 }
282}
283
284impl RenderOnce for ReplSessionsContainer {
285 fn render(self, _window: &mut Window, _cx: &mut App) -> impl IntoElement {
286 v_flex()
287 .p_4()
288 .gap_2()
289 .size_full()
290 .child(Label::new(self.title).size(LabelSize::Large))
291 .children(self.children)
292 }
293}