-
-
Notifications
You must be signed in to change notification settings - Fork 10.1k
Expand file tree
/
Copy pathnotebook_ui.rs
More file actions
2302 lines (2072 loc) · 83.6 KB
/
Copy pathnotebook_ui.rs
File metadata and controls
2302 lines (2072 loc) · 83.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#![allow(unused, dead_code)]
use std::future::Future;
use std::{path::PathBuf, sync::Arc};
use anyhow::{Context as _, Result};
use client::proto::ViewId;
use collections::HashMap;
use editor::DisplayPoint;
use feature_flags::{FeatureFlagAppExt as _, NotebookFeatureFlag};
use futures::FutureExt;
use futures::future::Shared;
use gpui::{
AnyElement, App, Entity, EventEmitter, FocusHandle, Focusable, KeyContext, ListScrollEvent,
ListState, Point, PromptLevel, Task, TaskExt, actions, list, prelude::*,
};
use jupyter_protocol::JupyterKernelspec;
use language::{Language, LanguageRegistry};
use log;
use project::{Project, ProjectEntryId, ProjectPath};
use settings::Settings as _;
use ui::{CommonAnimationExt, KeyBinding, Tooltip, prelude::*};
use workspace::item::{ItemEvent, SaveOptions, TabContentParams};
use workspace::notifications::DetachAndPromptErr;
use workspace::searchable::SearchableItemHandle;
use workspace::{Item, ItemHandle, Pane, ProjectItem, ToolbarItemLocation};
use super::{Cell, CellEvent, CellPosition, MarkdownCellEvent, RenderableCell};
use nbformat::v4::CellId;
use nbformat::v4::Metadata as NotebookMetadata;
use serde_json;
use uuid::Uuid;
use crate::components::{KernelPickerDelegate, KernelSelector};
use crate::kernels::{
Kernel, KernelSession, KernelSpecification, KernelStatus, LocalKernelSpecification,
NativeRunningKernel, RemoteRunningKernel, SshRunningKernel, WslRunningKernel,
};
use crate::notebook::MovementDirection;
use crate::repl_store::ReplStore;
use picker::Picker;
use runtimelib::{ExecuteRequest, JupyterMessage, JupyterMessageContent};
use ui::PopoverMenuHandle;
use zed_actions::editor::{MoveDown, MoveUp};
use zed_actions::notebook::{
AddCodeBlock, AddMarkdownBlock, ClearOutputs, DeleteCell, DeleteCurrentCell, EnterCommandMode,
EnterEditMode, InterruptKernel, MoveCellDown, MoveCellUp, NotebookMoveDown, NotebookMoveUp,
OpenNotebook, RestartKernel, Run, RunAll, RunAndAdvance,
};
/// Whether the notebook is in command mode (navigating cells) or edit mode (editing a cell).
#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) enum NotebookMode {
Command,
Edit,
}
#[derive(PartialEq, Eq)]
enum SelectionMode {
SelectOnly,
SelectAndMove,
}
pub(crate) const MAX_TEXT_BLOCK_WIDTH: f32 = 9999.0;
pub(crate) const SMALL_SPACING_SIZE: f32 = 8.0;
pub(crate) const MEDIUM_SPACING_SIZE: f32 = 12.0;
pub(crate) const LARGE_SPACING_SIZE: f32 = 16.0;
pub(crate) const GUTTER_WIDTH: f32 = 19.0;
pub(crate) const CODE_BLOCK_INSET: f32 = MEDIUM_SPACING_SIZE;
pub(crate) const CONTROL_SIZE: f32 = 20.0;
const NOTEBOOK_EXTENSION: &str = "ipynb";
pub fn init(cx: &mut App) {
if cx.has_flag::<NotebookFeatureFlag>() || std::env::var("LOCAL_NOTEBOOK_DEV").is_ok() {
workspace::register_project_item::<NotebookEditor>(cx);
}
cx.observe_flag::<NotebookFeatureFlag, _>({
move |flag, cx| {
if *flag {
workspace::register_project_item::<NotebookEditor>(cx);
} else {
// todo: there is no way to unregister a project item, so if the feature flag
// gets turned off they need to restart Zed.
}
}
})
.detach();
}
pub struct NotebookEditor {
languages: Arc<LanguageRegistry>,
project: Entity<Project>,
worktree_id: project::WorktreeId,
focus_handle: FocusHandle,
notebook_item: Entity<NotebookItem>,
notebook_language: Shared<Task<Option<Arc<Language>>>>,
remote_id: Option<ViewId>,
cell_list: ListState,
notebook_mode: NotebookMode,
selected_cell_index: usize,
cell_order: Vec<CellId>,
original_cell_order: Vec<CellId>,
cell_map: HashMap<CellId, Cell>,
kernel: Kernel,
kernel_specification: Option<KernelSpecification>,
execution_requests: HashMap<String, CellId>,
kernel_picker_handle: PopoverMenuHandle<Picker<KernelPickerDelegate>>,
}
impl NotebookEditor {
pub fn new(
project: Entity<Project>,
notebook_item: Entity<NotebookItem>,
window: &mut Window,
cx: &mut Context<Self>,
) -> Self {
let focus_handle = cx.focus_handle();
let languages = project.read(cx).languages().clone();
let language_name = notebook_item.read(cx).language_name();
let worktree_id = notebook_item.read(cx).project_path.worktree_id;
let notebook_language = notebook_item.read(cx).notebook_language();
let notebook_language = cx
.spawn_in(window, async move |_, _| notebook_language.await)
.shared();
let mut cell_order = vec![]; // Vec<CellId>
let mut cell_map = HashMap::default(); // HashMap<CellId, Cell>
let cell_count = notebook_item.read(cx).notebook.cells.len();
for index in 0..cell_count {
let cell = notebook_item.read(cx).notebook.cells[index].clone();
let cell_id = cell.id();
cell_order.push(cell_id.clone());
let cell_entity = Cell::load(&cell, &languages, notebook_language.clone(), window, cx);
match &cell_entity {
Cell::Code(code_cell) => {
let cell_id_for_focus = cell_id.clone();
cx.subscribe_in(code_cell, window, move |this, _cell, event, window, cx| {
match event {
CellEvent::Run(cell_id) => {
this.execute_cell(cell_id.clone(), window, cx)
}
CellEvent::FocusedIn(_) => {
this.select_cell_by_id(&cell_id_for_focus, cx)
}
}
})
.detach();
let cell_id_for_editor = cell_id.clone();
let editor = code_cell.read(cx).editor().clone();
cx.subscribe(&editor, move |this, _editor, event, cx| {
if let editor::EditorEvent::Focused = event {
this.select_cell_by_id(&cell_id_for_editor, cx);
}
})
.detach();
}
Cell::Markdown(markdown_cell) => {
cx.subscribe(
markdown_cell,
move |_this, cell, event: &MarkdownCellEvent, cx| {
match event {
MarkdownCellEvent::FinishedEditing => {
cell.update(cx, |cell, cx| {
cell.reparse_markdown(cx);
});
}
MarkdownCellEvent::Run(_cell_id) => {
// run is handled separately by move_to_next_cell
// Just reparse here
cell.update(cx, |cell, cx| {
cell.reparse_markdown(cx);
});
}
}
},
)
.detach();
let cell_id_for_editor = cell_id.clone();
let editor = markdown_cell.read(cx).editor().clone();
cx.subscribe(&editor, move |this, _editor, event, cx| {
if let editor::EditorEvent::Focused = event {
this.select_cell_by_id(&cell_id_for_editor, cx);
}
})
.detach();
}
Cell::Raw(_) => {}
}
cell_map.insert(cell_id.clone(), cell_entity);
}
let notebook_handle = cx.entity().downgrade();
let cell_count = cell_order.len();
let this = cx.entity();
let cell_list = ListState::new(cell_count, gpui::ListAlignment::Top, px(1000.));
let mut editor = Self {
project,
languages: languages.clone(),
worktree_id,
focus_handle,
notebook_item: notebook_item.clone(),
notebook_language,
remote_id: None,
cell_list,
notebook_mode: NotebookMode::Command,
selected_cell_index: 0,
cell_order: cell_order.clone(),
original_cell_order: cell_order.clone(),
cell_map: cell_map.clone(),
kernel: Kernel::Shutdown,
kernel_specification: None,
execution_requests: HashMap::default(),
kernel_picker_handle: PopoverMenuHandle::default(),
};
editor.launch_kernel(window, cx);
editor.refresh_language(cx);
editor.refresh_kernelspecs(cx);
cx.subscribe(¬ebook_item, |this, _item, _event, cx| {
this.refresh_language(cx);
})
.detach();
editor
}
fn refresh_kernelspecs(&mut self, cx: &mut Context<Self>) {
let store = ReplStore::global(cx);
let project = self.project.clone();
let worktree_id = self.worktree_id;
let refresh_task = store.update(cx, |store, cx| {
store.refresh_python_kernelspecs(worktree_id, &project, cx)
});
cx.background_spawn(refresh_task).detach_and_log_err(cx);
}
fn refresh_language(&mut self, cx: &mut Context<Self>) {
let notebook_language = self.notebook_item.read(cx).notebook_language();
let task = cx.spawn(async move |this, cx| {
let language = notebook_language.await;
if let Some(this) = this.upgrade() {
this.update(cx, |this, cx| {
for cell in this.cell_map.values() {
if let Cell::Code(code_cell) = cell {
code_cell.update(cx, |cell, cx| {
cell.set_language(language.clone(), cx);
});
}
}
});
}
language
});
self.notebook_language = task.shared();
}
fn has_structural_changes(&self) -> bool {
self.cell_order != self.original_cell_order
}
fn has_content_changes(&self, cx: &App) -> bool {
self.cell_map.values().any(|cell| cell.is_dirty(cx))
}
pub fn to_notebook(&self, cx: &App) -> nbformat::v4::Notebook {
let cells: Vec<nbformat::v4::Cell> = self
.cell_order
.iter()
.filter_map(|cell_id| {
self.cell_map
.get(cell_id)
.map(|cell| cell.to_nbformat_cell(cx))
})
.collect();
let metadata = self.notebook_item.read(cx).notebook.metadata.clone();
nbformat::v4::Notebook {
metadata,
nbformat: 4,
nbformat_minor: 5,
cells,
}
}
pub fn mark_as_saved(&mut self, cx: &mut Context<Self>) {
self.original_cell_order = self.cell_order.clone();
for cell in self.cell_map.values() {
match cell {
Cell::Code(code_cell) => {
code_cell.update(cx, |code_cell, cx| {
let editor = code_cell.editor();
editor.update(cx, |editor, cx| {
editor.buffer().update(cx, |buffer, cx| {
if let Some(buf) = buffer.as_singleton() {
buf.update(cx, |b, cx| {
let version = b.version();
b.did_save(version, None, cx);
});
}
});
});
});
}
Cell::Markdown(markdown_cell) => {
markdown_cell.update(cx, |markdown_cell, cx| {
let editor = markdown_cell.editor();
editor.update(cx, |editor, cx| {
editor.buffer().update(cx, |buffer, cx| {
if let Some(buf) = buffer.as_singleton() {
buf.update(cx, |b, cx| {
let version = b.version();
b.did_save(version, None, cx);
});
}
});
});
});
}
Cell::Raw(_) => {}
}
}
cx.notify();
}
fn launch_kernel(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let spec = self.kernel_specification.clone().or_else(|| {
ReplStore::global(cx)
.read(cx)
.active_kernelspec(self.worktree_id, None, cx)
});
let spec = spec.unwrap_or_else(|| {
KernelSpecification::Jupyter(LocalKernelSpecification {
name: "python3".to_string(),
path: PathBuf::from("python3"),
kernelspec: JupyterKernelspec {
argv: vec![
"python3".to_string(),
"-m".to_string(),
"ipykernel_launcher".to_string(),
"-f".to_string(),
"{connection_file}".to_string(),
],
display_name: "Python 3".to_string(),
language: "python".to_string(),
interrupt_mode: None,
metadata: None,
env: None,
},
})
});
self.launch_kernel_with_spec(spec, window, cx);
}
fn launch_kernel_with_spec(
&mut self,
spec: KernelSpecification,
window: &mut Window,
cx: &mut Context<Self>,
) {
let entity_id = cx.entity_id();
let working_directory = self
.project
.read(cx)
.worktree_for_id(self.worktree_id, cx)
.map(|worktree| worktree.read(cx).abs_path().to_path_buf())
.unwrap_or_else(std::env::temp_dir);
let fs = self.project.read(cx).fs().clone();
let view = cx.entity();
self.kernel_specification = Some(spec.clone());
self.notebook_item.update(cx, |item, cx| {
let kernel_name = spec.name().to_string();
let language = spec.language().to_string();
let display_name = match &spec {
KernelSpecification::Jupyter(s) => s.kernelspec.display_name.clone(),
KernelSpecification::PythonEnv(s) => s.kernelspec.display_name.clone(),
KernelSpecification::JupyterServer(s) => s.kernelspec.display_name.clone(),
KernelSpecification::SshRemote(s) => s.kernelspec.display_name.clone(),
KernelSpecification::WslRemote(s) => s.kernelspec.display_name.clone(),
};
let kernelspec_json = serde_json::json!({
"display_name": display_name,
"name": kernel_name,
"language": language
});
if let Ok(k) = serde_json::from_value(kernelspec_json) {
item.notebook.metadata.kernelspec = Some(k);
cx.emit(());
}
});
let kernel_task = match spec {
KernelSpecification::Jupyter(local_spec) => NativeRunningKernel::new(
local_spec,
entity_id,
working_directory,
fs,
view,
window,
cx,
),
KernelSpecification::PythonEnv(env_spec) => NativeRunningKernel::new(
env_spec.as_local_spec(),
entity_id,
working_directory,
fs,
view,
window,
cx,
),
KernelSpecification::JupyterServer(remote_spec) => {
RemoteRunningKernel::new(remote_spec, working_directory, view, window, cx)
}
KernelSpecification::SshRemote(spec) => {
let project = self.project.clone();
SshRunningKernel::new(spec, working_directory, project, view, window, cx)
}
KernelSpecification::WslRemote(spec) => {
WslRunningKernel::new(spec, entity_id, working_directory, fs, view, window, cx)
}
};
let pending_kernel = cx
.spawn(async move |this, cx| {
let kernel = kernel_task.await;
match kernel {
Ok(kernel) => {
this.update(cx, |editor, cx| {
editor.kernel = Kernel::RunningKernel(kernel);
cx.notify();
})
.ok();
}
Err(err) => {
log::error!("Kernel failed to start: {:?}", err);
this.update(cx, |editor, cx| {
editor.kernel = Kernel::ErroredLaunch(err.to_string());
cx.notify();
})
.ok();
}
}
})
.shared();
self.kernel = Kernel::StartingKernel(pending_kernel);
cx.notify();
}
// Note: Python environments are only detected as kernels if ipykernel is installed.
// Users need to run `pip install ipykernel` (or `uv pip install ipykernel`) in their
// virtual environment for it to appear in the kernel selector.
// This happens because we have an ipykernel check inside the function python_env_kernel_specification in mod.rs L:121
fn change_kernel(
&mut self,
spec: KernelSpecification,
window: &mut Window,
cx: &mut Context<Self>,
) {
if let Kernel::RunningKernel(kernel) = &mut self.kernel {
kernel.force_shutdown(window, cx).detach();
}
self.execution_requests.clear();
self.launch_kernel_with_spec(spec, window, cx);
}
fn restart_kernel(&mut self, _: &RestartKernel, window: &mut Window, cx: &mut Context<Self>) {
if let Some(spec) = self.kernel_specification.clone() {
if let Kernel::RunningKernel(kernel) = &mut self.kernel {
kernel.force_shutdown(window, cx).detach();
}
self.kernel = Kernel::Restarting;
cx.notify();
self.launch_kernel_with_spec(spec, window, cx);
}
}
fn interrupt_kernel(
&mut self,
_: &InterruptKernel,
_window: &mut Window,
cx: &mut Context<Self>,
) {
if let Kernel::RunningKernel(kernel) = &self.kernel {
let interrupt_request = runtimelib::InterruptRequest {};
let message: JupyterMessage = interrupt_request.into();
kernel.request_tx().try_send(message).ok();
cx.notify();
}
}
fn execute_cell(&mut self, cell_id: CellId, window: &mut Window, cx: &mut Context<Self>) {
let code = if let Some(Cell::Code(cell)) = self.cell_map.get(&cell_id) {
let editor = cell.read(cx).editor().clone();
let buffer = editor.read(cx).buffer().read(cx);
buffer
.as_singleton()
.map(|b| b.read(cx).text())
.unwrap_or_default()
} else {
return;
};
let request = ExecuteRequest {
code,
..Default::default()
};
let message: JupyterMessage = request.into();
let msg_id = message.header.msg_id.clone();
let send_result = match &mut self.kernel {
Kernel::RunningKernel(kernel) => kernel
.request_tx()
.try_send(message)
.map_err(|err| format!("failed to send execute request to kernel (the kernel process may have died): {err}")),
Kernel::StartingKernel(_) => Err("the kernel is still starting".to_string()),
Kernel::ErroredLaunch(error) => Err(format!("the kernel failed to launch: {error}")),
Kernel::ShuttingDown | Kernel::Shutdown => Err("the kernel is shut down".to_string()),
Kernel::Restarting => Err("the kernel is restarting".to_string()),
};
if let Some(Cell::Code(cell)) = self.cell_map.get(&cell_id) {
cell.update(cx, |cell, cx| {
if cell.has_outputs() {
cell.clear_outputs();
}
if let Err(error) = &send_result {
cell.show_kernel_error(error, window, cx);
} else {
cell.start_execution();
}
cx.notify();
});
}
if let Err(error) = send_result {
log::error!("notebook: cannot execute cell: {error}");
} else {
self.execution_requests.insert(msg_id, cell_id.clone());
}
}
fn get_selected_cell(&self) -> Option<&Cell> {
self.cell_order
.get(self.selected_cell_index)
.and_then(|cell_id| self.cell_map.get(cell_id))
}
fn has_outputs(&self, window: &mut Window, cx: &mut Context<Self>) -> bool {
self.cell_map.values().any(|cell| {
if let Cell::Code(code_cell) = cell {
code_cell.read(cx).has_outputs()
} else {
false
}
})
}
fn clear_outputs(&mut self, window: &mut Window, cx: &mut Context<Self>) {
for cell in self.cell_map.values() {
if let Cell::Code(code_cell) = cell {
code_cell.update(cx, |cell, cx| {
cell.clear_outputs();
cx.notify();
});
}
}
cx.notify();
}
fn run_cells(&mut self, window: &mut Window, cx: &mut Context<Self>) {
for cell_id in self.cell_order.clone() {
self.execute_cell(cell_id, window, cx);
}
}
fn run_current_cell(&mut self, _: &Run, window: &mut Window, cx: &mut Context<Self>) {
let Some(cell_id) = self.cell_order.get(self.selected_cell_index).cloned() else {
return;
};
let Some(cell) = self.cell_map.get(&cell_id) else {
return;
};
match cell {
Cell::Code(_) => {
self.execute_cell(cell_id, window, cx);
}
Cell::Markdown(markdown_cell) => {
// for markdown, finish editing and move to next cell
let is_editing = markdown_cell.read(cx).is_editing();
if is_editing {
markdown_cell.update(cx, |cell, cx| {
cell.run(cx);
});
self.enter_command_mode(window, cx);
}
}
Cell::Raw(_) => {}
}
}
fn run_and_advance(&mut self, _: &RunAndAdvance, window: &mut Window, cx: &mut Context<Self>) {
if let Some(cell_id) = self.cell_order.get(self.selected_cell_index).cloned() {
if let Some(cell) = self.cell_map.get(&cell_id) {
match cell {
Cell::Code(_) => {
self.execute_cell(cell_id, window, cx);
}
Cell::Markdown(markdown_cell) => {
if markdown_cell.read(cx).is_editing() {
markdown_cell.update(cx, |cell, cx| {
cell.run(cx);
});
}
}
Cell::Raw(_) => {}
}
}
}
let is_last_cell = self.selected_cell_index == self.cell_count().saturating_sub(1);
if is_last_cell {
self.add_code_block(window, cx);
self.enter_command_mode(window, cx);
} else {
self.advance_in_command_mode(window, cx);
}
}
fn enter_edit_mode(&mut self, _: &EnterEditMode, window: &mut Window, cx: &mut Context<Self>) {
self.notebook_mode = NotebookMode::Edit;
if let Some(cell_id) = self.cell_order.get(self.selected_cell_index) {
if let Some(cell) = self.cell_map.get(cell_id) {
match cell {
Cell::Code(code_cell) => {
let editor = code_cell.read(cx).editor().clone();
window.focus(&editor.focus_handle(cx), cx);
}
Cell::Markdown(markdown_cell) => {
markdown_cell.update(cx, |cell, cx| {
cell.set_editing(true);
cx.notify();
});
let editor = markdown_cell.read(cx).editor().clone();
window.focus(&editor.focus_handle(cx), cx);
}
Cell::Raw(_) => {}
}
}
}
cx.notify();
}
fn enter_command_mode(&mut self, window: &mut Window, cx: &mut Context<Self>) {
self.notebook_mode = NotebookMode::Command;
self.focus_handle.focus(window, cx);
cx.notify();
}
fn handle_enter_command_mode(
&mut self,
_: &EnterCommandMode,
window: &mut Window,
cx: &mut Context<Self>,
) {
self.enter_command_mode(window, cx);
}
/// Advances to the next cell while staying in command mode (used by RunAndAdvance and shift-enter).
fn advance_in_command_mode(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let count = self.cell_count();
if count == 0 {
return;
}
if self.selected_cell_index < count - 1 {
self.selected_cell_index += 1;
self.cell_list
.scroll_to_reveal_item(self.selected_cell_index);
}
self.notebook_mode = NotebookMode::Command;
self.focus_handle.focus(window, cx);
cx.notify();
}
// Discussion can be done on this default implementation
/// Moves focus to the next cell editor (used when already in edit mode).
fn move_to_next_cell(&mut self, window: &mut Window, cx: &mut Context<Self>) {
if !self.cell_order.is_empty() && self.selected_cell_index < self.cell_order.len() - 1 {
self.selected_cell_index += 1;
// focus the new cell's editor
if let Some(cell_id) = self.cell_order.get(self.selected_cell_index) {
if let Some(cell) = self.cell_map.get(cell_id) {
match cell {
Cell::Code(code_cell) => {
let editor = code_cell.read(cx).editor();
window.focus(&editor.focus_handle(cx), cx);
}
Cell::Markdown(markdown_cell) => {
// Don't auto-enter edit mode for next markdown cell
// Just select it
}
Cell::Raw(_) => {}
}
}
}
cx.notify();
} else {
// in the end, could optionally create a new cell
// For now, just stay on the current cell
}
}
fn open_notebook(&mut self, _: &OpenNotebook, _window: &mut Window, _cx: &mut Context<Self>) {
println!("Open notebook triggered");
}
fn move_cell_up(&mut self, window: &mut Window, cx: &mut Context<Self>) {
println!("Move cell up triggered");
if self.selected_cell_index > 0 {
self.cell_order
.swap(self.selected_cell_index, self.selected_cell_index - 1);
self.selected_cell_index -= 1;
cx.notify();
}
}
fn move_cell_down(&mut self, window: &mut Window, cx: &mut Context<Self>) {
println!("Move cell down triggered");
if !self.cell_order.is_empty() && self.selected_cell_index < self.cell_order.len() - 1 {
self.cell_order
.swap(self.selected_cell_index, self.selected_cell_index + 1);
self.selected_cell_index += 1;
cx.notify();
}
}
fn delete_cell(&mut self, window: &mut Window, cx: &mut Context<Self>) {
if self.cell_order.is_empty() {
return;
}
let index = self.selected_cell_index.min(self.cell_order.len() - 1);
let cell_id = self.cell_order.remove(index);
self.cell_map.remove(&cell_id);
self.cell_list.splice(index..index + 1, 0);
if self.cell_order.is_empty() {
self.selected_cell_index = 0;
} else {
self.selected_cell_index = index.min(self.cell_order.len() - 1);
self.cell_list
.scroll_to_reveal_item(self.selected_cell_index);
}
self.notebook_mode = NotebookMode::Command;
window.focus(&self.focus_handle, cx);
cx.notify();
}
fn delete_current_cell(&mut self, window: &mut Window, cx: &mut Context<Self>) {
if self.cell_order.is_empty() {
return;
}
let prompt = window.prompt(
PromptLevel::Warning,
"Delete current cell?",
None,
&["Delete", "Cancel"],
cx,
);
cx.spawn_in(window, async move |this, cx| {
let answer = prompt.await?;
if answer != 0 {
return Ok(());
}
this.update_in(cx, |this, window, cx| {
this.delete_current_cell_confirmed(window, cx);
})?;
Ok(())
})
.detach_and_prompt_err("Failed to delete cell", window, cx, |e, _, _| {
Some(format!("{e}"))
});
}
fn delete_current_cell_confirmed(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
if self.cell_order.is_empty() {
return;
}
let cell_id = self.cell_order.remove(self.selected_cell_index);
self.cell_map.remove(&cell_id);
if !self.cell_order.is_empty() {
self.selected_cell_index = self.selected_cell_index.min(self.cell_order.len() - 1);
} else {
self.selected_cell_index = 0;
}
self.cell_list.reset(self.cell_order.len());
cx.notify();
}
fn insert_cell_at_current_position(&mut self, cell_id: CellId, cell: Cell) {
let insert_index = if self.cell_order.is_empty() {
0
} else {
self.selected_cell_index + 1
};
self.cell_order.insert(insert_index, cell_id.clone());
self.cell_map.insert(cell_id, cell);
self.selected_cell_index = insert_index;
self.cell_list.splice(insert_index..insert_index, 1);
self.cell_list.scroll_to_reveal_item(insert_index);
}
fn add_markdown_block(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let new_cell_id: CellId = Uuid::new_v4().into();
let languages = self.languages.clone();
let metadata: nbformat::v4::CellMetadata =
serde_json::from_str("{}").expect("empty object should parse");
let markdown_cell = cx.new(|cx| {
super::MarkdownCell::new(
new_cell_id.clone(),
metadata,
String::new(),
languages,
window,
cx,
)
});
cx.subscribe(
&markdown_cell,
move |_this, cell, event: &MarkdownCellEvent, cx| match event {
MarkdownCellEvent::FinishedEditing | MarkdownCellEvent::Run(_) => {
cell.update(cx, |cell, cx| {
cell.reparse_markdown(cx);
});
}
},
)
.detach();
let cell_id_for_editor = new_cell_id.clone();
let editor = markdown_cell.read(cx).editor().clone();
cx.subscribe(&editor, move |this, _editor, event, cx| {
if let editor::EditorEvent::Focused = event {
this.select_cell_by_id(&cell_id_for_editor, cx);
}
})
.detach();
self.insert_cell_at_current_position(new_cell_id, Cell::Markdown(markdown_cell.clone()));
markdown_cell.update(cx, |cell, cx| {
cell.set_editing(true);
cx.notify();
});
let editor = markdown_cell.read(cx).editor().clone();
window.focus(&editor.focus_handle(cx), cx);
self.notebook_mode = NotebookMode::Edit;
cx.notify();
}
fn add_code_block(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let new_cell_id: CellId = Uuid::new_v4().into();
let notebook_language = self.notebook_language.clone();
let metadata: nbformat::v4::CellMetadata =
serde_json::from_str("{}").expect("empty object should parse");
let code_cell = cx.new(|cx| {
super::CodeCell::new(
super::CellSource::None,
new_cell_id.clone(),
metadata,
String::new(),
notebook_language,
window,
cx,
)
});
let cell_id_for_run = new_cell_id.clone();
cx.subscribe_in(
&code_cell,
window,
move |this, _cell, event, window, cx| match event {
CellEvent::Run(cell_id) => this.execute_cell(cell_id.clone(), window, cx),
CellEvent::FocusedIn(_) => this.select_cell_by_id(&cell_id_for_run, cx),
},
)
.detach();
let cell_id_for_editor = new_cell_id.clone();
let editor = code_cell.read(cx).editor().clone();
cx.subscribe(&editor, move |this, _editor, event, cx| {
if let editor::EditorEvent::Focused = event {
this.select_cell_by_id(&cell_id_for_editor, cx);
}
})
.detach();
self.insert_cell_at_current_position(new_cell_id, Cell::Code(code_cell.clone()));
let editor = code_cell.read(cx).editor().clone();
window.focus(&editor.focus_handle(cx), cx);
self.notebook_mode = NotebookMode::Edit;
cx.notify();
}
fn cell_count(&self) -> usize {
self.cell_map.len()
}
fn selected_index(&self) -> usize {
self.selected_cell_index
}
fn select_cell_by_id(&mut self, cell_id: &CellId, cx: &mut Context<Self>) {
if let Some(index) = self.cell_order.iter().position(|id| id == cell_id) {
self.selected_cell_index = index;
self.notebook_mode = NotebookMode::Edit;
cx.notify();
}
}
pub fn set_selected_index(
&mut self,
index: usize,
jump_to_index: bool,
window: &mut Window,
cx: &mut Context<Self>,
) {
// let previous_index = self.selected_cell_index;
self.selected_cell_index = index;
let current_index = self.selected_cell_index;
// in the future we may have some `on_cell_change` event that we want to fire here
if jump_to_index {
self.jump_to_cell(current_index, window, cx);
}
}
fn select_next(
&mut self,
_: &menu::SelectNext,
selection_mode: SelectionMode,
window: &mut Window,
cx: &mut Context<Self>,
) {
let count = self.cell_count();
if count > 0 {
let index = self.selected_index();
let ix = if index == count - 1 {
count - 1
} else {
index + 1
};
self.set_selected_index(ix, true, window, cx);
if selection_mode == SelectionMode::SelectAndMove
&& let Some(cell) = self.get_selected_cell()
{
cell.move_to(MovementDirection::Start, window, cx);
}
cx.notify();
}