1//! # REPL Output Module
2//!
3//! This module provides the core functionality for handling and displaying
4//! various types of output from Jupyter kernels.
5//!
6//! ## Key Components
7//!
8//! - `OutputContent`: An enum that encapsulates different types of output content.
9//! - `ExecutionView`: Manages the display of outputs for a single execution.
10//! - `ExecutionStatus`: Represents the current status of an execution.
11//!
12//! ## Output Types
13//!
14//! The module supports several output types, including:
15//! - Plain text
16//! - Markdown
17//! - Images (PNG and JPEG)
18//! - Tables
19//! - Error messages
20//!
21//! ## Clipboard Support
22//!
23//! Most output types implement the `SupportsClipboard` trait, allowing
24//! users to easily copy output content to the system clipboard.
25//!
26//! ## Rendering
27//!
28//! The module provides rendering capabilities for each output type,
29//! ensuring proper display within the REPL interface.
30//!
31//! ## Jupyter Integration
32//!
33//! This module is designed to work with Jupyter message protocols,
34//! interpreting and displaying various types of Jupyter output.
35
36use std::time::Duration;
37
38use editor::{Editor, MultiBuffer};
39use gpui::{
40 Animation, AnimationExt, AnyElement, ClipboardItem, Entity, Render, Transformation, WeakEntity,
41 percentage,
42};
43use language::Buffer;
44use runtimelib::{ExecutionState, JupyterMessageContent, MimeBundle, MimeType};
45use ui::{Context, IntoElement, Styled, Tooltip, Window, div, prelude::*, v_flex};
46
47mod image;
48use image::ImageView;
49
50mod markdown;
51use markdown::MarkdownView;
52
53mod table;
54use table::TableView;
55
56pub mod plain;
57use plain::TerminalOutput;
58
59pub(crate) mod user_error;
60use user_error::ErrorView;
61use workspace::Workspace;
62
63/// When deciding what to render from a collection of mediatypes, we need to rank them in order of importance
64fn rank_mime_type(mimetype: &MimeType) -> usize {
65 match mimetype {
66 MimeType::DataTable(_) => 6,
67 MimeType::Png(_) => 4,
68 MimeType::Jpeg(_) => 3,
69 MimeType::Markdown(_) => 2,
70 MimeType::Plain(_) => 1,
71 // All other media types are not supported in Zed at this time
72 _ => 0,
73 }
74}
75
76pub(crate) trait OutputContent {
77 fn clipboard_content(&self, window: &Window, cx: &App) -> Option<ClipboardItem>;
78 fn has_clipboard_content(&self, _window: &Window, _cx: &App) -> bool {
79 false
80 }
81 fn has_buffer_content(&self, _window: &Window, _cx: &App) -> bool {
82 false
83 }
84 fn buffer_content(&mut self, _window: &mut Window, _cx: &mut App) -> Option<Entity<Buffer>> {
85 None
86 }
87}
88
89impl<V: OutputContent + 'static> OutputContent for Entity<V> {
90 fn clipboard_content(&self, window: &Window, cx: &App) -> Option<ClipboardItem> {
91 self.read(cx).clipboard_content(window, cx)
92 }
93
94 fn has_clipboard_content(&self, window: &Window, cx: &App) -> bool {
95 self.read(cx).has_clipboard_content(window, cx)
96 }
97
98 fn has_buffer_content(&self, window: &Window, cx: &App) -> bool {
99 self.read(cx).has_buffer_content(window, cx)
100 }
101
102 fn buffer_content(&mut self, window: &mut Window, cx: &mut App) -> Option<Entity<Buffer>> {
103 self.update(cx, |item, cx| item.buffer_content(window, cx))
104 }
105}
106
107pub enum Output {
108 Plain {
109 content: Entity<TerminalOutput>,
110 display_id: Option<String>,
111 },
112 Stream {
113 content: Entity<TerminalOutput>,
114 },
115 Image {
116 content: Entity<ImageView>,
117 display_id: Option<String>,
118 },
119 ErrorOutput(ErrorView),
120 Message(String),
121 Table {
122 content: Entity<TableView>,
123 display_id: Option<String>,
124 },
125 Markdown {
126 content: Entity<MarkdownView>,
127 display_id: Option<String>,
128 },
129 ClearOutputWaitMarker,
130}
131
132impl Output {
133 fn render_output_controls<V: OutputContent + 'static>(
134 v: Entity<V>,
135 workspace: WeakEntity<Workspace>,
136 window: &mut Window,
137 cx: &mut Context<ExecutionView>,
138 ) -> Option<AnyElement> {
139 if !v.has_clipboard_content(window, cx) && !v.has_buffer_content(window, cx) {
140 return None;
141 }
142
143 Some(
144 h_flex()
145 .pl_1()
146 .when(v.has_clipboard_content(window, cx), |el| {
147 let v = v.clone();
148 el.child(
149 IconButton::new(ElementId::Name("copy-output".into()), IconName::Copy)
150 .style(ButtonStyle::Transparent)
151 .tooltip(Tooltip::text("Copy Output"))
152 .on_click(cx.listener(move |_, _, window, cx| {
153 let clipboard_content = v.clipboard_content(window, cx);
154
155 if let Some(clipboard_content) = clipboard_content.as_ref() {
156 cx.write_to_clipboard(clipboard_content.clone());
157 }
158 })),
159 )
160 })
161 .when(v.has_buffer_content(window, cx), |el| {
162 let v = v.clone();
163 el.child(
164 IconButton::new(
165 ElementId::Name("open-in-buffer".into()),
166 IconName::FileTextOutlined,
167 )
168 .style(ButtonStyle::Transparent)
169 .tooltip(Tooltip::text("Open in Buffer"))
170 .on_click(cx.listener({
171 let workspace = workspace.clone();
172
173 move |_, _, window, cx| {
174 let buffer_content =
175 v.update(cx, |item, cx| item.buffer_content(window, cx));
176
177 if let Some(buffer_content) = buffer_content.as_ref() {
178 let buffer = buffer_content.clone();
179 let editor = Box::new(cx.new(|cx| {
180 let multibuffer = cx.new(|cx| {
181 let mut multi_buffer =
182 MultiBuffer::singleton(buffer.clone(), cx);
183
184 multi_buffer.set_title("REPL Output".to_string(), cx);
185 multi_buffer
186 });
187
188 Editor::for_multibuffer(multibuffer, None, window, cx)
189 }));
190 workspace
191 .update(cx, |workspace, cx| {
192 workspace.add_item_to_active_pane(
193 editor, None, true, window, cx,
194 );
195 })
196 .ok();
197 }
198 }
199 })),
200 )
201 })
202 .into_any_element(),
203 )
204 }
205
206 pub fn render(
207 &self,
208 workspace: WeakEntity<Workspace>,
209 window: &mut Window,
210 cx: &mut Context<ExecutionView>,
211 ) -> impl IntoElement + use<> {
212 let content = match self {
213 Self::Plain { content, .. } => Some(content.clone().into_any_element()),
214 Self::Markdown { content, .. } => Some(content.clone().into_any_element()),
215 Self::Stream { content, .. } => Some(content.clone().into_any_element()),
216 Self::Image { content, .. } => Some(content.clone().into_any_element()),
217 Self::Message(message) => Some(div().child(message.clone()).into_any_element()),
218 Self::Table { content, .. } => Some(content.clone().into_any_element()),
219 Self::ErrorOutput(error_view) => error_view.render(window, cx),
220 Self::ClearOutputWaitMarker => None,
221 };
222
223 h_flex()
224 .id("output-content")
225 .w_full()
226 .overflow_x_scroll()
227 .items_start()
228 .child(div().flex_1().children(content))
229 .children(match self {
230 Self::Plain { content, .. } => {
231 Self::render_output_controls(content.clone(), workspace, window, cx)
232 }
233 Self::Markdown { content, .. } => {
234 Self::render_output_controls(content.clone(), workspace, window, cx)
235 }
236 Self::Stream { content, .. } => {
237 Self::render_output_controls(content.clone(), workspace, window, cx)
238 }
239 Self::Image { content, .. } => {
240 Self::render_output_controls(content.clone(), workspace, window, cx)
241 }
242 Self::ErrorOutput(err) => {
243 Self::render_output_controls(err.traceback.clone(), workspace, window, cx)
244 }
245 Self::Message(_) => None,
246 Self::Table { content, .. } => {
247 Self::render_output_controls(content.clone(), workspace, window, cx)
248 }
249 Self::ClearOutputWaitMarker => None,
250 })
251 }
252
253 pub fn display_id(&self) -> Option<String> {
254 match self {
255 Output::Plain { display_id, .. } => display_id.clone(),
256 Output::Stream { .. } => None,
257 Output::Image { display_id, .. } => display_id.clone(),
258 Output::ErrorOutput(_) => None,
259 Output::Message(_) => None,
260 Output::Table { display_id, .. } => display_id.clone(),
261 Output::Markdown { display_id, .. } => display_id.clone(),
262 Output::ClearOutputWaitMarker => None,
263 }
264 }
265
266 pub fn new(
267 data: &MimeBundle,
268 display_id: Option<String>,
269 window: &mut Window,
270 cx: &mut App,
271 ) -> Self {
272 match data.richest(rank_mime_type) {
273 Some(MimeType::Plain(text)) => Output::Plain {
274 content: cx.new(|cx| TerminalOutput::from(text, window, cx)),
275 display_id,
276 },
277 Some(MimeType::Markdown(text)) => {
278 let content = cx.new(|cx| MarkdownView::from(text.clone(), cx));
279 Output::Markdown {
280 content,
281 display_id,
282 }
283 }
284 Some(MimeType::Png(data)) | Some(MimeType::Jpeg(data)) => match ImageView::from(data) {
285 Ok(view) => Output::Image {
286 content: cx.new(|_| view),
287 display_id,
288 },
289 Err(error) => Output::Message(format!("Failed to load image: {}", error)),
290 },
291 Some(MimeType::DataTable(data)) => Output::Table {
292 content: cx.new(|cx| TableView::new(data, window, cx)),
293 display_id,
294 },
295 // Any other media types are not supported
296 _ => Output::Message("Unsupported media type".to_string()),
297 }
298 }
299}
300
301#[derive(Default, Clone, Debug)]
302pub enum ExecutionStatus {
303 #[default]
304 Unknown,
305 ConnectingToKernel,
306 Queued,
307 Executing,
308 Finished,
309 ShuttingDown,
310 Shutdown,
311 KernelErrored(String),
312 Restarting,
313}
314
315/// An ExecutionView shows the outputs of an execution.
316/// It can hold zero or more outputs, which the user
317/// sees as "the output" for a single execution.
318pub struct ExecutionView {
319 #[allow(unused)]
320 workspace: WeakEntity<Workspace>,
321 pub outputs: Vec<Output>,
322 pub status: ExecutionStatus,
323}
324
325impl ExecutionView {
326 pub fn new(
327 status: ExecutionStatus,
328 workspace: WeakEntity<Workspace>,
329 _cx: &mut Context<Self>,
330 ) -> Self {
331 Self {
332 workspace,
333 outputs: Default::default(),
334 status,
335 }
336 }
337
338 /// Accept a Jupyter message belonging to this execution
339 pub fn push_message(
340 &mut self,
341 message: &JupyterMessageContent,
342 window: &mut Window,
343 cx: &mut Context<Self>,
344 ) {
345 let output: Output = match message {
346 JupyterMessageContent::ExecuteResult(result) => Output::new(
347 &result.data,
348 result.transient.as_ref().and_then(|t| t.display_id.clone()),
349 window,
350 cx,
351 ),
352 JupyterMessageContent::DisplayData(result) => Output::new(
353 &result.data,
354 result.transient.as_ref().and_then(|t| t.display_id.clone()),
355 window,
356 cx,
357 ),
358 JupyterMessageContent::StreamContent(result) => {
359 // Previous stream data will combine together, handling colors, carriage returns, etc
360 if let Some(new_terminal) = self.apply_terminal_text(&result.text, window, cx) {
361 new_terminal
362 } else {
363 return;
364 }
365 }
366 JupyterMessageContent::ErrorOutput(result) => {
367 let terminal =
368 cx.new(|cx| TerminalOutput::from(&result.traceback.join("\n"), window, cx));
369
370 Output::ErrorOutput(ErrorView {
371 ename: result.ename.clone(),
372 evalue: result.evalue.clone(),
373 traceback: terminal,
374 })
375 }
376 JupyterMessageContent::ExecuteReply(reply) => {
377 for payload in reply.payload.iter() {
378 if let runtimelib::Payload::Page { data, .. } = payload {
379 let output = Output::new(data, None, window, cx);
380 self.outputs.push(output);
381 }
382 }
383 cx.notify();
384 return;
385 }
386 JupyterMessageContent::ClearOutput(options) => {
387 if !options.wait {
388 self.outputs.clear();
389 cx.notify();
390 return;
391 }
392
393 // Create a marker to clear the output after we get in a new output
394 Output::ClearOutputWaitMarker
395 }
396 JupyterMessageContent::Status(status) => {
397 match status.execution_state {
398 ExecutionState::Busy => {
399 self.status = ExecutionStatus::Executing;
400 }
401 ExecutionState::Idle => self.status = ExecutionStatus::Finished,
402 }
403 cx.notify();
404 return;
405 }
406 _msg => {
407 return;
408 }
409 };
410
411 // Check for a clear output marker as the previous output, so we can clear it out
412 if let Some(output) = self.outputs.last()
413 && let Output::ClearOutputWaitMarker = output
414 {
415 self.outputs.clear();
416 }
417
418 self.outputs.push(output);
419
420 cx.notify();
421 }
422
423 pub fn update_display_data(
424 &mut self,
425 data: &MimeBundle,
426 display_id: &str,
427 window: &mut Window,
428 cx: &mut Context<Self>,
429 ) {
430 let mut any = false;
431
432 self.outputs.iter_mut().for_each(|output| {
433 if let Some(other_display_id) = output.display_id().as_ref()
434 && other_display_id == display_id
435 {
436 *output = Output::new(data, Some(display_id.to_owned()), window, cx);
437 any = true;
438 }
439 });
440
441 if any {
442 cx.notify();
443 }
444 }
445
446 fn apply_terminal_text(
447 &mut self,
448 text: &str,
449 window: &mut Window,
450 cx: &mut Context<Self>,
451 ) -> Option<Output> {
452 if let Some(last_output) = self.outputs.last_mut()
453 && let Output::Stream {
454 content: last_stream,
455 } = last_output
456 {
457 // Don't need to add a new output, we already have a terminal output
458 // and can just update the most recent terminal output
459 last_stream.update(cx, |last_stream, cx| {
460 last_stream.append_text(text, cx);
461 cx.notify();
462 });
463 return None;
464 }
465
466 Some(Output::Stream {
467 content: cx.new(|cx| TerminalOutput::from(text, window, cx)),
468 })
469 }
470}
471
472impl Render for ExecutionView {
473 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
474 let status = match &self.status {
475 ExecutionStatus::ConnectingToKernel => Label::new("Connecting to kernel...")
476 .color(Color::Muted)
477 .into_any_element(),
478 ExecutionStatus::Executing => h_flex()
479 .gap_2()
480 .child(
481 Icon::new(IconName::ArrowCircle)
482 .size(IconSize::Small)
483 .color(Color::Muted)
484 .with_animation(
485 "arrow-circle",
486 Animation::new(Duration::from_secs(3)).repeat(),
487 |icon, delta| icon.transform(Transformation::rotate(percentage(delta))),
488 ),
489 )
490 .child(Label::new("Executing...").color(Color::Muted))
491 .into_any_element(),
492 ExecutionStatus::Finished => Icon::new(IconName::Check)
493 .size(IconSize::Small)
494 .into_any_element(),
495 ExecutionStatus::Unknown => Label::new("Unknown status")
496 .color(Color::Muted)
497 .into_any_element(),
498 ExecutionStatus::ShuttingDown => Label::new("Kernel shutting down...")
499 .color(Color::Muted)
500 .into_any_element(),
501 ExecutionStatus::Restarting => Label::new("Kernel restarting...")
502 .color(Color::Muted)
503 .into_any_element(),
504 ExecutionStatus::Shutdown => Label::new("Kernel shutdown")
505 .color(Color::Muted)
506 .into_any_element(),
507 ExecutionStatus::Queued => Label::new("Queued...")
508 .color(Color::Muted)
509 .into_any_element(),
510 ExecutionStatus::KernelErrored(error) => Label::new(format!("Kernel error: {}", error))
511 .color(Color::Error)
512 .into_any_element(),
513 };
514
515 if self.outputs.is_empty() {
516 return v_flex()
517 .min_h(window.line_height())
518 .justify_center()
519 .child(status)
520 .into_any_element();
521 }
522
523 div()
524 .w_full()
525 .children(
526 self.outputs
527 .iter()
528 .map(|output| output.render(self.workspace.clone(), window, cx)),
529 )
530 .children(match self.status {
531 ExecutionStatus::Executing => vec![status],
532 ExecutionStatus::Queued => vec![status],
533 _ => vec![],
534 })
535 .into_any_element()
536 }
537}