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 editor::{Editor, MultiBuffer};
37use gpui::{AnyElement, ClipboardItem, Entity, EventEmitter, Render, WeakEntity};
38use language::Buffer;
39use runtimelib::{ExecutionState, JupyterMessageContent, MimeBundle, MimeType};
40use ui::{CommonAnimationExt, CopyButton, IconButton, Tooltip, prelude::*};
41
42mod image;
43use image::ImageView;
44
45mod markdown;
46use markdown::MarkdownView;
47
48mod table;
49use table::TableView;
50
51pub mod plain;
52use plain::TerminalOutput;
53
54pub(crate) mod user_error;
55use user_error::ErrorView;
56use workspace::Workspace;
57
58use crate::repl_settings::ReplSettings;
59use settings::Settings;
60
61/// When deciding what to render from a collection of mediatypes, we need to rank them in order of importance
62fn rank_mime_type(mimetype: &MimeType) -> usize {
63 match mimetype {
64 MimeType::DataTable(_) => 6,
65 MimeType::Png(_) => 4,
66 MimeType::Jpeg(_) => 3,
67 MimeType::Markdown(_) => 2,
68 MimeType::Plain(_) => 1,
69 // All other media types are not supported in Zed at this time
70 _ => 0,
71 }
72}
73
74pub(crate) trait OutputContent {
75 fn clipboard_content(&self, window: &Window, cx: &App) -> Option<ClipboardItem>;
76 fn has_clipboard_content(&self, _window: &Window, _cx: &App) -> bool {
77 false
78 }
79 fn has_buffer_content(&self, _window: &Window, _cx: &App) -> bool {
80 false
81 }
82 fn buffer_content(&mut self, _window: &mut Window, _cx: &mut App) -> Option<Entity<Buffer>> {
83 None
84 }
85}
86
87impl<V: OutputContent + 'static> OutputContent for Entity<V> {
88 fn clipboard_content(&self, window: &Window, cx: &App) -> Option<ClipboardItem> {
89 self.read(cx).clipboard_content(window, cx)
90 }
91
92 fn has_clipboard_content(&self, window: &Window, cx: &App) -> bool {
93 self.read(cx).has_clipboard_content(window, cx)
94 }
95
96 fn has_buffer_content(&self, window: &Window, cx: &App) -> bool {
97 self.read(cx).has_buffer_content(window, cx)
98 }
99
100 fn buffer_content(&mut self, window: &mut Window, cx: &mut App) -> Option<Entity<Buffer>> {
101 self.update(cx, |item, cx| item.buffer_content(window, cx))
102 }
103}
104
105pub enum Output {
106 Plain {
107 content: Entity<TerminalOutput>,
108 display_id: Option<String>,
109 },
110 Stream {
111 content: Entity<TerminalOutput>,
112 },
113 Image {
114 content: Entity<ImageView>,
115 display_id: Option<String>,
116 },
117 ErrorOutput(ErrorView),
118 Message(String),
119 Table {
120 content: Entity<TableView>,
121 display_id: Option<String>,
122 },
123 Markdown {
124 content: Entity<MarkdownView>,
125 display_id: Option<String>,
126 },
127 ClearOutputWaitMarker,
128}
129
130impl Output {
131 pub fn to_nbformat(&self, cx: &App) -> Option<nbformat::v4::Output> {
132 match self {
133 Output::Stream { content } => {
134 let text = content.read(cx).full_text();
135 Some(nbformat::v4::Output::Stream {
136 name: "stdout".to_string(),
137 text: nbformat::v4::MultilineString(text),
138 })
139 }
140 Output::Plain { content, .. } => {
141 let text = content.read(cx).full_text();
142 let mut data = jupyter_protocol::media::Media::default();
143 data.content.push(jupyter_protocol::MediaType::Plain(text));
144 Some(nbformat::v4::Output::DisplayData(
145 nbformat::v4::DisplayData {
146 data,
147 metadata: serde_json::Map::new(),
148 },
149 ))
150 }
151 Output::ErrorOutput(error_view) => {
152 let traceback_text = error_view.traceback.read(cx).full_text();
153 let traceback_lines: Vec<String> =
154 traceback_text.lines().map(|s| s.to_string()).collect();
155 Some(nbformat::v4::Output::Error(nbformat::v4::ErrorOutput {
156 ename: error_view.ename.clone(),
157 evalue: error_view.evalue.clone(),
158 traceback: traceback_lines,
159 }))
160 }
161 Output::Message(_) | Output::ClearOutputWaitMarker => None,
162 Output::Image { .. } | Output::Table { .. } | Output::Markdown { .. } => None,
163 }
164 }
165}
166
167impl Output {
168 fn render_output_controls<V: OutputContent + 'static>(
169 v: Entity<V>,
170 workspace: WeakEntity<Workspace>,
171 window: &mut Window,
172 cx: &mut Context<ExecutionView>,
173 ) -> Option<AnyElement> {
174 if !v.has_clipboard_content(window, cx) && !v.has_buffer_content(window, cx) {
175 return None;
176 }
177
178 Some(
179 h_flex()
180 .pl_1()
181 .when(v.has_clipboard_content(window, cx), |el| {
182 let v = v.clone();
183 el.child(
184 IconButton::new(ElementId::Name("copy-output".into()), IconName::Copy)
185 .style(ButtonStyle::Transparent)
186 .tooltip(Tooltip::text("Copy Output"))
187 .on_click(move |_, window, cx| {
188 let clipboard_content = v.clipboard_content(window, cx);
189
190 if let Some(clipboard_content) = clipboard_content.as_ref() {
191 cx.write_to_clipboard(clipboard_content.clone());
192 }
193 }),
194 )
195 })
196 .when(v.has_buffer_content(window, cx), |el| {
197 let v = v.clone();
198 el.child(
199 IconButton::new(
200 ElementId::Name("open-in-buffer".into()),
201 IconName::FileTextOutlined,
202 )
203 .style(ButtonStyle::Transparent)
204 .tooltip(Tooltip::text("Open in Buffer"))
205 .on_click({
206 let workspace = workspace.clone();
207 move |_, window, cx| {
208 let buffer_content =
209 v.update(cx, |item, cx| item.buffer_content(window, cx));
210
211 if let Some(buffer_content) = buffer_content.as_ref() {
212 let buffer = buffer_content.clone();
213 let editor = Box::new(cx.new(|cx| {
214 let multibuffer = cx.new(|cx| {
215 let mut multi_buffer =
216 MultiBuffer::singleton(buffer.clone(), cx);
217
218 multi_buffer.set_title("REPL Output".to_string(), cx);
219 multi_buffer
220 });
221
222 Editor::for_multibuffer(multibuffer, None, window, cx)
223 }));
224 workspace
225 .update(cx, |workspace, cx| {
226 workspace.add_item_to_active_pane(
227 editor, None, true, window, cx,
228 );
229 })
230 .ok();
231 }
232 }
233 }),
234 )
235 })
236 .into_any_element(),
237 )
238 }
239
240 pub fn render(
241 &self,
242 workspace: WeakEntity<Workspace>,
243 window: &mut Window,
244 cx: &mut Context<ExecutionView>,
245 ) -> impl IntoElement + use<> {
246 let content = match self {
247 Self::Plain { content, .. } => Some(content.clone().into_any_element()),
248 Self::Markdown { content, .. } => Some(content.clone().into_any_element()),
249 Self::Stream { content, .. } => Some(content.clone().into_any_element()),
250 Self::Image { content, .. } => Some(content.clone().into_any_element()),
251 Self::Message(message) => Some(div().child(message.clone()).into_any_element()),
252 Self::Table { content, .. } => Some(content.clone().into_any_element()),
253 Self::ErrorOutput(error_view) => error_view.render(window, cx),
254 Self::ClearOutputWaitMarker => None,
255 };
256
257 h_flex()
258 .id("output-content")
259 .w_full()
260 .overflow_x_scroll()
261 .items_start()
262 .child(div().flex_1().children(content))
263 .children(match self {
264 Self::Plain { content, .. } => {
265 Self::render_output_controls(content.clone(), workspace, window, cx)
266 }
267 Self::Markdown { content, .. } => {
268 Self::render_output_controls(content.clone(), workspace, window, cx)
269 }
270 Self::Stream { content, .. } => {
271 Self::render_output_controls(content.clone(), workspace, window, cx)
272 }
273 Self::Image { content, .. } => {
274 Self::render_output_controls(content.clone(), workspace, window, cx)
275 }
276 Self::ErrorOutput(err) => Some(
277 h_flex()
278 .pl_1()
279 .child({
280 let ename = err.ename.clone();
281 let evalue = err.evalue.clone();
282 let traceback = err.traceback.clone();
283 let traceback_text = traceback.read(cx).full_text();
284 let full_error = format!("{}: {}\n{}", ename, evalue, traceback_text);
285
286 CopyButton::new("copy-full-error", full_error)
287 .tooltip_label("Copy Full Error")
288 })
289 .child(
290 IconButton::new(
291 ElementId::Name("open-full-error-in-buffer-traceback".into()),
292 IconName::FileTextOutlined,
293 )
294 .style(ButtonStyle::Transparent)
295 .tooltip(Tooltip::text("Open Full Error in Buffer"))
296 .on_click({
297 let ename = err.ename.clone();
298 let evalue = err.evalue.clone();
299 let traceback = err.traceback.clone();
300 move |_, window, cx| {
301 if let Some(workspace) = workspace.upgrade() {
302 let traceback_text = traceback.read(cx).full_text();
303 let full_error =
304 format!("{}: {}\n{}", ename, evalue, traceback_text);
305 let buffer = cx.new(|cx| {
306 let mut buffer = Buffer::local(full_error, cx)
307 .with_language(language::PLAIN_TEXT.clone(), cx);
308 buffer
309 .set_capability(language::Capability::ReadOnly, cx);
310 buffer
311 });
312 let editor = Box::new(cx.new(|cx| {
313 let multibuffer = cx.new(|cx| {
314 let mut multi_buffer =
315 MultiBuffer::singleton(buffer.clone(), cx);
316 multi_buffer
317 .set_title("Full Error".to_string(), cx);
318 multi_buffer
319 });
320 Editor::for_multibuffer(multibuffer, None, window, cx)
321 }));
322 workspace.update(cx, |workspace, cx| {
323 workspace.add_item_to_active_pane(
324 editor, None, true, window, cx,
325 );
326 });
327 }
328 }
329 }),
330 )
331 .into_any_element(),
332 ),
333 Self::Message(_) => None,
334 Self::Table { content, .. } => {
335 Self::render_output_controls(content.clone(), workspace, window, cx)
336 }
337 Self::ClearOutputWaitMarker => None,
338 })
339 }
340
341 pub fn display_id(&self) -> Option<String> {
342 match self {
343 Output::Plain { display_id, .. } => display_id.clone(),
344 Output::Stream { .. } => None,
345 Output::Image { display_id, .. } => display_id.clone(),
346 Output::ErrorOutput(_) => None,
347 Output::Message(_) => None,
348 Output::Table { display_id, .. } => display_id.clone(),
349 Output::Markdown { display_id, .. } => display_id.clone(),
350 Output::ClearOutputWaitMarker => None,
351 }
352 }
353
354 pub fn new(
355 data: &MimeBundle,
356 display_id: Option<String>,
357 window: &mut Window,
358 cx: &mut App,
359 ) -> Self {
360 match data.richest(rank_mime_type) {
361 Some(MimeType::Plain(text)) => Output::Plain {
362 content: cx.new(|cx| TerminalOutput::from(text, window, cx)),
363 display_id,
364 },
365 Some(MimeType::Markdown(text)) => {
366 let content = cx.new(|cx| MarkdownView::from(text.clone(), cx));
367 Output::Markdown {
368 content,
369 display_id,
370 }
371 }
372 Some(MimeType::Png(data)) | Some(MimeType::Jpeg(data)) => match ImageView::from(data) {
373 Ok(view) => Output::Image {
374 content: cx.new(|_| view),
375 display_id,
376 },
377 Err(error) => Output::Message(format!("Failed to load image: {}", error)),
378 },
379 Some(MimeType::DataTable(data)) => Output::Table {
380 content: cx.new(|cx| TableView::new(data, window, cx)),
381 display_id,
382 },
383 // Any other media types are not supported
384 _ => Output::Message("Unsupported media type".to_string()),
385 }
386 }
387}
388
389#[derive(Default, Clone, Debug)]
390pub enum ExecutionStatus {
391 #[default]
392 Unknown,
393 ConnectingToKernel,
394 Queued,
395 Executing,
396 Finished,
397 ShuttingDown,
398 Shutdown,
399 KernelErrored(String),
400 Restarting,
401}
402
403pub struct ExecutionViewFinishedEmpty;
404pub struct ExecutionViewFinishedSmall(pub String);
405
406/// An ExecutionView shows the outputs of an execution.
407/// It can hold zero or more outputs, which the user
408/// sees as "the output" for a single execution.
409pub struct ExecutionView {
410 #[allow(unused)]
411 workspace: WeakEntity<Workspace>,
412 pub outputs: Vec<Output>,
413 pub status: ExecutionStatus,
414}
415
416impl EventEmitter<ExecutionViewFinishedEmpty> for ExecutionView {}
417impl EventEmitter<ExecutionViewFinishedSmall> for ExecutionView {}
418
419impl ExecutionView {
420 pub fn new(
421 status: ExecutionStatus,
422 workspace: WeakEntity<Workspace>,
423 _cx: &mut Context<Self>,
424 ) -> Self {
425 Self {
426 workspace,
427 outputs: Default::default(),
428 status,
429 }
430 }
431
432 /// Accept a Jupyter message belonging to this execution
433 pub fn push_message(
434 &mut self,
435 message: &JupyterMessageContent,
436 window: &mut Window,
437 cx: &mut Context<Self>,
438 ) {
439 let output: Output = match message {
440 JupyterMessageContent::ExecuteResult(result) => Output::new(
441 &result.data,
442 result.transient.as_ref().and_then(|t| t.display_id.clone()),
443 window,
444 cx,
445 ),
446 JupyterMessageContent::DisplayData(result) => Output::new(
447 &result.data,
448 result.transient.as_ref().and_then(|t| t.display_id.clone()),
449 window,
450 cx,
451 ),
452 JupyterMessageContent::StreamContent(result) => {
453 // Previous stream data will combine together, handling colors, carriage returns, etc
454 if let Some(new_terminal) = self.apply_terminal_text(&result.text, window, cx) {
455 new_terminal
456 } else {
457 return;
458 }
459 }
460 JupyterMessageContent::ErrorOutput(result) => {
461 let terminal =
462 cx.new(|cx| TerminalOutput::from(&result.traceback.join("\n"), window, cx));
463
464 Output::ErrorOutput(ErrorView {
465 ename: result.ename.clone(),
466 evalue: result.evalue.clone(),
467 traceback: terminal,
468 })
469 }
470 JupyterMessageContent::ExecuteReply(reply) => {
471 for payload in reply.payload.iter() {
472 if let runtimelib::Payload::Page { data, .. } = payload {
473 let output = Output::new(data, None, window, cx);
474 self.outputs.push(output);
475 }
476 }
477 cx.notify();
478 return;
479 }
480 JupyterMessageContent::ClearOutput(options) => {
481 if !options.wait {
482 self.outputs.clear();
483 cx.notify();
484 return;
485 }
486
487 // Create a marker to clear the output after we get in a new output
488 Output::ClearOutputWaitMarker
489 }
490 JupyterMessageContent::Status(status) => {
491 match status.execution_state {
492 ExecutionState::Busy => {
493 self.status = ExecutionStatus::Executing;
494 }
495 ExecutionState::Idle => {
496 self.status = ExecutionStatus::Finished;
497 if self.outputs.is_empty() {
498 cx.emit(ExecutionViewFinishedEmpty);
499 } else if ReplSettings::get_global(cx).inline_output {
500 if let Some(small_text) = self.get_small_inline_output(cx) {
501 cx.emit(ExecutionViewFinishedSmall(small_text));
502 }
503 }
504 }
505 ExecutionState::Unknown => self.status = ExecutionStatus::Unknown,
506 ExecutionState::Starting => self.status = ExecutionStatus::ConnectingToKernel,
507 ExecutionState::Restarting => self.status = ExecutionStatus::Restarting,
508 ExecutionState::Terminating => self.status = ExecutionStatus::ShuttingDown,
509 ExecutionState::AutoRestarting => self.status = ExecutionStatus::Restarting,
510 ExecutionState::Dead => self.status = ExecutionStatus::Shutdown,
511 ExecutionState::Other(_) => self.status = ExecutionStatus::Unknown,
512 }
513 cx.notify();
514 return;
515 }
516 _msg => {
517 return;
518 }
519 };
520
521 // Check for a clear output marker as the previous output, so we can clear it out
522 if let Some(output) = self.outputs.last()
523 && let Output::ClearOutputWaitMarker = output
524 {
525 self.outputs.clear();
526 }
527
528 self.outputs.push(output);
529
530 cx.notify();
531 }
532
533 pub fn update_display_data(
534 &mut self,
535 data: &MimeBundle,
536 display_id: &str,
537 window: &mut Window,
538 cx: &mut Context<Self>,
539 ) {
540 let mut any = false;
541
542 self.outputs.iter_mut().for_each(|output| {
543 if let Some(other_display_id) = output.display_id().as_ref()
544 && other_display_id == display_id
545 {
546 *output = Output::new(data, Some(display_id.to_owned()), window, cx);
547 any = true;
548 }
549 });
550
551 if any {
552 cx.notify();
553 }
554 }
555
556 /// Check if the output is a single small plain text that can be shown inline.
557 /// Returns the text if it's suitable for inline display (single line, short enough).
558 fn get_small_inline_output(&self, cx: &App) -> Option<String> {
559 // Only consider single outputs
560 if self.outputs.len() != 1 {
561 return None;
562 }
563
564 let output = self.outputs.first()?;
565
566 // Only Plain outputs can be inlined
567 let content = match output {
568 Output::Plain { content, .. } => content,
569 _ => return None,
570 };
571
572 let text = content.read(cx).full_text();
573 let trimmed = text.trim();
574
575 let max_length = ReplSettings::get_global(cx).inline_output_max_length;
576
577 // Must be a single line and within the configured max length
578 if trimmed.contains('\n') || trimmed.len() > max_length {
579 return None;
580 }
581
582 Some(trimmed.to_string())
583 }
584
585 fn apply_terminal_text(
586 &mut self,
587 text: &str,
588 window: &mut Window,
589 cx: &mut Context<Self>,
590 ) -> Option<Output> {
591 if let Some(last_output) = self.outputs.last_mut()
592 && let Output::Stream {
593 content: last_stream,
594 } = last_output
595 {
596 // Don't need to add a new output, we already have a terminal output
597 // and can just update the most recent terminal output
598 last_stream.update(cx, |last_stream, cx| {
599 last_stream.append_text(text, cx);
600 cx.notify();
601 });
602 return None;
603 }
604
605 Some(Output::Stream {
606 content: cx.new(|cx| TerminalOutput::from(text, window, cx)),
607 })
608 }
609}
610
611impl Render for ExecutionView {
612 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
613 let status = match &self.status {
614 ExecutionStatus::ConnectingToKernel => Label::new("Connecting to kernel...")
615 .color(Color::Muted)
616 .into_any_element(),
617 ExecutionStatus::Executing => h_flex()
618 .gap_2()
619 .child(
620 Icon::new(IconName::ArrowCircle)
621 .size(IconSize::Small)
622 .color(Color::Muted)
623 .with_rotate_animation(3),
624 )
625 .child(Label::new("Executing...").color(Color::Muted))
626 .into_any_element(),
627 ExecutionStatus::Finished => Icon::new(IconName::Check)
628 .size(IconSize::Small)
629 .into_any_element(),
630 ExecutionStatus::Unknown => Label::new("Unknown status")
631 .color(Color::Muted)
632 .into_any_element(),
633 ExecutionStatus::ShuttingDown => Label::new("Kernel shutting down...")
634 .color(Color::Muted)
635 .into_any_element(),
636 ExecutionStatus::Restarting => Label::new("Kernel restarting...")
637 .color(Color::Muted)
638 .into_any_element(),
639 ExecutionStatus::Shutdown => Label::new("Kernel shutdown")
640 .color(Color::Muted)
641 .into_any_element(),
642 ExecutionStatus::Queued => Label::new("Queued...")
643 .color(Color::Muted)
644 .into_any_element(),
645 ExecutionStatus::KernelErrored(error) => Label::new(format!("Kernel error: {}", error))
646 .color(Color::Error)
647 .into_any_element(),
648 };
649
650 if self.outputs.is_empty() {
651 return v_flex()
652 .min_h(window.line_height())
653 .justify_center()
654 .child(status)
655 .into_any_element();
656 }
657
658 div()
659 .w_full()
660 .children(
661 self.outputs
662 .iter()
663 .map(|output| output.render(self.workspace.clone(), window, cx)),
664 )
665 .children(match self.status {
666 ExecutionStatus::Executing => vec![status],
667 ExecutionStatus::Queued => vec![status],
668 _ => vec![],
669 })
670 .into_any_element()
671 }
672}