Eliminate GPUI View, ViewContext, and WindowContext types (#22632)

There's still a bit more work to do on this, but this PR is compiling
(with warnings) after eliminating the key types. When the tasks below
are complete, this will be the new narrative for GPUI:

- `Entity<T>` - This replaces `View<T>`/`Model<T>`. It represents a unit
of state, and if `T` implements `Render`, then `Entity<T>` implements
`Element`.
- `&mut App` This replaces `AppContext` and represents the app.
- `&mut Context<T>` This replaces `ModelContext` and derefs to `App`. It
is provided by the framework when updating an entity.
- `&mut Window` Broken out of `&mut WindowContext` which no longer
exists. Every method that once took `&mut WindowContext` now takes `&mut
Window, &mut App` and every method that took `&mut ViewContext<T>` now
takes `&mut Window, &mut Context<T>`

Not pictured here are the two other failed attempts. It's been quite a
month!

Tasks:

- [x] Remove `View`, `ViewContext`, `WindowContext` and thread through
`Window`
- [x] [@cole-miller @mikayla-maki] Redraw window when entities change
- [x] [@cole-miller @mikayla-maki] Get examples and Zed running
- [x] [@cole-miller @mikayla-maki] Fix Zed rendering
- [x] [@mikayla-maki] Fix todo! macros and comments
- [x] Fix a bug where the editor would not be redrawn because of view
caching
- [x] remove publicness window.notify() and replace with
`AppContext::notify`
- [x] remove `observe_new_window_models`, replace with
`observe_new_models` with an optional window
- [x] Fix a bug where the project panel would not be redrawn because of
the wrong refresh() call being used
- [x] Fix the tests
- [x] Fix warnings by eliminating `Window` params or using `_`
- [x] Fix conflicts
- [x] Simplify generic code where possible
- [x] Rename types
- [ ] Update docs

### issues post merge

- [x] Issues switching between normal and insert mode
- [x] Assistant re-rendering failure
- [x] Vim test failures
- [x] Mac build issue



Release Notes:

- N/A

---------

Co-authored-by: Antonio Scandurra <me@as-cii.com>
Co-authored-by: Cole Miller <cole@zed.dev>
Co-authored-by: Mikayla <mikayla@zed.dev>
Co-authored-by: Joseph <joseph@zed.dev>
Co-authored-by: max <max@zed.dev>
Co-authored-by: Michael Sloan <michael@zed.dev>
Co-authored-by: Mikayla Maki <mikaylamaki@Mikaylas-MacBook-Pro.local>
Co-authored-by: Mikayla <mikayla.c.maki@gmail.com>
Co-authored-by: joão <joao@zed.dev>
This commit is contained in:
Nathan Sobo 2025-01-25 20:02:45 -07:00 committed by GitHub
parent 21b4a0d50e
commit 6fca1d2b0b
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
648 changed files with 36248 additions and 28208 deletions

View file

@ -3,7 +3,7 @@ use std::sync::Arc;
use editor::{Editor, EditorMode, MultiBuffer};
use futures::future::Shared;
use gpui::{prelude::*, AppContext, Hsla, Task, TextStyleRefinement, View};
use gpui::{prelude::*, App, Entity, Hsla, Task, TextStyleRefinement};
use language::{Buffer, Language, LanguageRegistry};
use markdown_preview::{markdown_parser::parse_markdown, markdown_renderer::render_markdown_block};
use nbformat::v4::{CellId, CellMetadata, CellType};
@ -62,7 +62,10 @@ impl CellControl {
}
impl Clickable for CellControl {
fn on_click(self, handler: impl Fn(&gpui::ClickEvent, &mut WindowContext) + 'static) -> Self {
fn on_click(
self,
handler: impl Fn(&gpui::ClickEvent, &mut Window, &mut App) + 'static,
) -> Self {
let button = self.button.on_click(handler);
Self { button }
}
@ -75,28 +78,33 @@ impl Clickable for CellControl {
/// A notebook cell
#[derive(Clone)]
pub enum Cell {
Code(View<CodeCell>),
Markdown(View<MarkdownCell>),
Raw(View<RawCell>),
Code(Entity<CodeCell>),
Markdown(Entity<MarkdownCell>),
Raw(Entity<RawCell>),
}
fn convert_outputs(outputs: &Vec<nbformat::v4::Output>, cx: &mut WindowContext) -> Vec<Output> {
fn convert_outputs(
outputs: &Vec<nbformat::v4::Output>,
window: &mut Window,
cx: &mut App,
) -> Vec<Output> {
outputs
.into_iter()
.map(|output| match output {
nbformat::v4::Output::Stream { text, .. } => Output::Stream {
content: cx.new_view(|cx| TerminalOutput::from(&text.0, cx)),
content: cx.new(|cx| TerminalOutput::from(&text.0, window, cx)),
},
nbformat::v4::Output::DisplayData(display_data) => {
Output::new(&display_data.data, None, cx)
Output::new(&display_data.data, None, window, cx)
}
nbformat::v4::Output::ExecuteResult(execute_result) => {
Output::new(&execute_result.data, None, cx)
Output::new(&execute_result.data, None, window, cx)
}
nbformat::v4::Output::Error(error) => Output::ErrorOutput(ErrorView {
ename: error.ename.clone(),
evalue: error.evalue.clone(),
traceback: cx.new_view(|cx| TerminalOutput::from(&error.traceback.join("\n"), cx)),
traceback: cx
.new(|cx| TerminalOutput::from(&error.traceback.join("\n"), window, cx)),
}),
})
.collect()
@ -107,7 +115,8 @@ impl Cell {
cell: &nbformat::v4::Cell,
languages: &Arc<LanguageRegistry>,
notebook_language: Shared<Task<Option<Arc<Language>>>>,
cx: &mut WindowContext,
window: &mut Window,
cx: &mut App,
) -> Self {
match cell {
nbformat::v4::Cell::Markdown {
@ -118,12 +127,12 @@ impl Cell {
} => {
let source = source.join("");
let view = cx.new_view(|cx| {
let model = cx.new(|cx| {
let markdown_parsing_task = {
let languages = languages.clone();
let source = source.clone();
cx.spawn(|this, mut cx| async move {
cx.spawn_in(window, |this, mut cx| async move {
let parsed_markdown = cx
.background_executor()
.spawn(async move {
@ -150,7 +159,7 @@ impl Cell {
}
});
Cell::Markdown(view)
Cell::Markdown(model)
}
nbformat::v4::Cell::Code {
id,
@ -158,18 +167,19 @@ impl Cell {
execution_count,
source,
outputs,
} => Cell::Code(cx.new_view(|cx| {
} => Cell::Code(cx.new(|cx| {
let text = source.join("");
let buffer = cx.new_model(|cx| Buffer::local(text.clone(), cx));
let multi_buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer.clone(), cx));
let buffer = cx.new(|cx| Buffer::local(text.clone(), cx));
let multi_buffer = cx.new(|cx| MultiBuffer::singleton(buffer.clone(), cx));
let editor_view = cx.new_view(|cx| {
let editor_view = cx.new(|cx| {
let mut editor = Editor::new(
EditorMode::AutoHeight { max_lines: 1024 },
multi_buffer,
None,
false,
window,
cx,
);
@ -183,7 +193,7 @@ impl Cell {
..Default::default()
};
editor.set_text(text, cx);
editor.set_text(text, window, cx);
editor.set_show_gutter(false, cx);
editor.set_text_style_refinement(refinement);
@ -192,7 +202,7 @@ impl Cell {
});
let buffer = buffer.clone();
let language_task = cx.spawn(|this, mut cx| async move {
let language_task = cx.spawn_in(window, |this, mut cx| async move {
let language = notebook_language.await;
buffer.update(&mut cx, |buffer, cx| {
@ -206,7 +216,7 @@ impl Cell {
execution_count: *execution_count,
source: source.join(""),
editor: editor_view,
outputs: convert_outputs(outputs, cx),
outputs: convert_outputs(outputs, window, cx),
selected: false,
language_task,
cell_position: None,
@ -216,7 +226,7 @@ impl Cell {
id,
metadata,
source,
} => Cell::Raw(cx.new_view(|_| RawCell {
} => Cell::Raw(cx.new(|_| RawCell {
id: id.clone(),
metadata: metadata.clone(),
source: source.join(""),
@ -236,7 +246,7 @@ pub trait RenderableCell: Render {
fn source(&self) -> &String;
fn selected(&self) -> bool;
fn set_selected(&mut self, selected: bool) -> &mut Self;
fn selected_bg_color(&self, cx: &ViewContext<Self>) -> Hsla {
fn selected_bg_color(&self, window: &mut Window, cx: &mut Context<Self>) -> Hsla {
if self.selected() {
let mut color = cx.theme().colors().icon_accent;
color.fade_out(0.9);
@ -246,14 +256,15 @@ pub trait RenderableCell: Render {
cx.theme().colors().tab_bar_background
}
}
fn control(&self, _cx: &ViewContext<Self>) -> Option<CellControl> {
fn control(&self, _window: &mut Window, _cx: &mut Context<Self>) -> Option<CellControl> {
None
}
fn cell_position_spacer(
&self,
is_first: bool,
cx: &ViewContext<Self>,
window: &mut Window,
cx: &mut Context<Self>,
) -> Option<impl IntoElement> {
let cell_position = self.cell_position();
@ -266,7 +277,7 @@ pub trait RenderableCell: Render {
}
}
fn gutter(&self, cx: &ViewContext<Self>) -> impl IntoElement {
fn gutter(&self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let is_selected = self.selected();
div()
@ -289,7 +300,7 @@ pub trait RenderableCell: Render {
.when(!is_selected, |this| this.bg(cx.theme().colors().border)),
),
)
.when_some(self.control(cx), |this, control| {
.when_some(self.control(window, cx), |this, control| {
this.child(
div()
.absolute()
@ -314,7 +325,7 @@ pub trait RenderableCell: Render {
pub trait RunnableCell: RenderableCell {
fn execution_count(&self) -> Option<i32>;
fn set_execution_count(&mut self, count: i32) -> &mut Self;
fn run(&mut self, cx: &mut ViewContext<Self>) -> ();
fn run(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ();
}
pub struct MarkdownCell {
@ -356,7 +367,7 @@ impl RenderableCell for MarkdownCell {
self
}
fn control(&self, _: &ViewContext<Self>) -> Option<CellControl> {
fn control(&self, _window: &mut Window, _: &mut Context<Self>) -> Option<CellControl> {
None
}
@ -371,18 +382,18 @@ impl RenderableCell for MarkdownCell {
}
impl Render for MarkdownCell {
fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let Some(parsed) = self.parsed_markdown.as_ref() else {
return div();
};
let mut markdown_render_context =
markdown_preview::markdown_renderer::RenderContext::new(None, cx);
markdown_preview::markdown_renderer::RenderContext::new(None, window, cx);
v_flex()
.size_full()
// TODO: Move base cell render into trait impl so we don't have to repeat this
.children(self.cell_position_spacer(true, cx))
.children(self.cell_position_spacer(true, window, cx))
.child(
h_flex()
.w_full()
@ -390,8 +401,8 @@ impl Render for MarkdownCell {
.rounded_sm()
.items_start()
.gap(DynamicSpacing::Base08.rems(cx))
.bg(self.selected_bg_color(cx))
.child(self.gutter(cx))
.bg(self.selected_bg_color(window, cx))
.child(self.gutter(window, cx))
.child(
v_flex()
.size_full()
@ -408,7 +419,7 @@ impl Render for MarkdownCell {
),
)
// TODO: Move base cell render into trait impl so we don't have to repeat this
.children(self.cell_position_spacer(false, cx))
.children(self.cell_position_spacer(false, window, cx))
}
}
@ -417,7 +428,7 @@ pub struct CodeCell {
metadata: CellMetadata,
execution_count: Option<i32>,
source: String,
editor: View<editor::Editor>,
editor: Entity<editor::Editor>,
outputs: Vec<Output>,
selected: bool,
cell_position: Option<CellPosition>,
@ -425,7 +436,7 @@ pub struct CodeCell {
}
impl CodeCell {
pub fn is_dirty(&self, cx: &AppContext) -> bool {
pub fn is_dirty(&self, cx: &App) -> bool {
self.editor.read(cx).buffer().read(cx).is_dirty(cx)
}
pub fn has_outputs(&self) -> bool {
@ -444,7 +455,7 @@ impl CodeCell {
}
}
pub fn gutter_output(&self, cx: &ViewContext<Self>) -> impl IntoElement {
pub fn gutter_output(&self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let is_selected = self.selected();
div()
@ -505,12 +516,12 @@ impl RenderableCell for CodeCell {
&self.source
}
fn control(&self, cx: &ViewContext<Self>) -> Option<CellControl> {
fn control(&self, window: &mut Window, cx: &mut Context<Self>) -> Option<CellControl> {
let cell_control = if self.has_outputs() {
CellControl::new("rerun-cell", CellControlType::RerunCell)
} else {
CellControl::new("run-cell", CellControlType::RunCell)
.on_click(cx.listener(move |this, _, cx| this.run(cx)))
.on_click(cx.listener(move |this, _, window, cx| this.run(window, cx)))
};
Some(cell_control)
@ -536,7 +547,7 @@ impl RenderableCell for CodeCell {
}
impl RunnableCell for CodeCell {
fn run(&mut self, cx: &mut ViewContext<Self>) {
fn run(&mut self, window: &mut Window, cx: &mut Context<Self>) {
println!("Running code cell: {}", self.id);
}
@ -552,11 +563,11 @@ impl RunnableCell for CodeCell {
}
impl Render for CodeCell {
fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
v_flex()
.size_full()
// TODO: Move base cell render into trait impl so we don't have to repeat this
.children(self.cell_position_spacer(true, cx))
.children(self.cell_position_spacer(true, window, cx))
// Editor portion
.child(
h_flex()
@ -565,8 +576,8 @@ impl Render for CodeCell {
.rounded_sm()
.items_start()
.gap(DynamicSpacing::Base08.rems(cx))
.bg(self.selected_bg_color(cx))
.child(self.gutter(cx))
.bg(self.selected_bg_color(window, cx))
.child(self.gutter(window, cx))
.child(
div().py_1p5().w_full().child(
div()
@ -591,8 +602,8 @@ impl Render for CodeCell {
.rounded_sm()
.items_start()
.gap(DynamicSpacing::Base08.rems(cx))
.bg(self.selected_bg_color(cx))
.child(self.gutter_output(cx))
.bg(self.selected_bg_color(window, cx))
.child(self.gutter_output(window, cx))
.child(
div().py_1p5().w_full().child(
div()
@ -627,7 +638,7 @@ impl Render for CodeCell {
Some(content.clone().into_any_element())
}
Output::ErrorOutput(error_view) => {
error_view.render(cx)
error_view.render(window, cx)
}
Output::ClearOutputWaitMarker => None,
};
@ -648,7 +659,7 @@ impl Render for CodeCell {
),
)
// TODO: Move base cell render into trait impl so we don't have to repeat this
.children(self.cell_position_spacer(false, cx))
.children(self.cell_position_spacer(false, window, cx))
}
}
@ -699,11 +710,11 @@ impl RenderableCell for RawCell {
}
impl Render for RawCell {
fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
v_flex()
.size_full()
// TODO: Move base cell render into trait impl so we don't have to repeat this
.children(self.cell_position_spacer(true, cx))
.children(self.cell_position_spacer(true, window, cx))
.child(
h_flex()
.w_full()
@ -711,8 +722,8 @@ impl Render for RawCell {
.rounded_sm()
.items_start()
.gap(DynamicSpacing::Base08.rems(cx))
.bg(self.selected_bg_color(cx))
.child(self.gutter(cx))
.bg(self.selected_bg_color(window, cx))
.child(self.gutter(window, cx))
.child(
div()
.flex()
@ -725,6 +736,6 @@ impl Render for RawCell {
),
)
// TODO: Move base cell render into trait impl so we don't have to repeat this
.children(self.cell_position_spacer(false, cx))
.children(self.cell_position_spacer(false, window, cx))
}
}

View file

@ -9,8 +9,8 @@ use feature_flags::{FeatureFlagAppExt as _, NotebookFeatureFlag};
use futures::future::Shared;
use futures::FutureExt;
use gpui::{
actions, list, prelude::*, AnyElement, AppContext, EventEmitter, FocusHandle, FocusableView,
ListScrollEvent, ListState, Model, Point, Task, View,
actions, list, prelude::*, AnyElement, App, Entity, EventEmitter, FocusHandle, Focusable,
ListScrollEvent, ListState, Point, Task,
};
use language::{Language, LanguageRegistry};
use project::{Project, ProjectEntryId, ProjectPath};
@ -46,7 +46,7 @@ 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;
pub fn init(cx: &mut AppContext) {
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);
}
@ -66,10 +66,10 @@ pub fn init(cx: &mut AppContext) {
pub struct NotebookEditor {
languages: Arc<LanguageRegistry>,
project: Model<Project>,
project: Entity<Project>,
focus_handle: FocusHandle,
notebook_item: Model<NotebookItem>,
notebook_item: Entity<NotebookItem>,
remote_id: Option<ViewId>,
cell_list: ListState,
@ -81,9 +81,10 @@ pub struct NotebookEditor {
impl NotebookEditor {
pub fn new(
project: Model<Project>,
notebook_item: Model<NotebookItem>,
cx: &mut ViewContext<Self>,
project: Entity<Project>,
notebook_item: Entity<NotebookItem>,
window: &mut Window,
cx: &mut Context<Self>,
) -> Self {
let focus_handle = cx.focus_handle();
@ -91,7 +92,7 @@ impl NotebookEditor {
let language_name = notebook_item.read(cx).language_name();
let notebook_language = notebook_item.read(cx).notebook_language();
let notebook_language = cx.spawn(|_, _| notebook_language).shared();
let notebook_language = cx.spawn_in(window, |_, _| notebook_language).shared();
let mut cell_order = vec![]; // Vec<CellId>
let mut cell_map = HashMap::default(); // HashMap<CellId, Cell>
@ -108,27 +109,32 @@ impl NotebookEditor {
cell_order.push(cell_id.clone());
cell_map.insert(
cell_id.clone(),
Cell::load(cell, &languages, notebook_language.clone(), cx),
Cell::load(cell, &languages, notebook_language.clone(), window, cx),
);
}
let view = cx.view().downgrade();
let notebook_handle = cx.model().downgrade();
let cell_count = cell_order.len();
let this = cx.view();
let this = cx.model();
let cell_list = ListState::new(
cell_count,
gpui::ListAlignment::Top,
px(1000.),
move |ix, cx| {
view.upgrade()
move |ix, window, cx| {
notebook_handle
.upgrade()
.and_then(|notebook_handle| {
notebook_handle.update(cx, |notebook, cx| {
notebook
.cell_order
.get(ix)
.and_then(|cell_id| notebook.cell_map.get(cell_id))
.map(|cell| notebook.render_cell(ix, cell, cx).into_any_element())
.map(|cell| {
notebook
.render_cell(ix, cell, window, cx)
.into_any_element()
})
})
})
.unwrap_or_else(|| div().into_any())
@ -148,7 +154,7 @@ impl NotebookEditor {
}
}
fn has_outputs(&self, cx: &ViewContext<Self>) -> bool {
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()
@ -158,7 +164,7 @@ impl NotebookEditor {
})
}
fn clear_outputs(&mut self, cx: &mut ViewContext<Self>) {
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| {
@ -168,27 +174,27 @@ impl NotebookEditor {
}
}
fn run_cells(&mut self, cx: &mut ViewContext<Self>) {
fn run_cells(&mut self, window: &mut Window, cx: &mut Context<Self>) {
println!("Cells would all run here, if that was implemented!");
}
fn open_notebook(&mut self, _: &OpenNotebook, _cx: &mut ViewContext<Self>) {
fn open_notebook(&mut self, _: &OpenNotebook, _window: &mut Window, _cx: &mut Context<Self>) {
println!("Open notebook triggered");
}
fn move_cell_up(&mut self, cx: &mut ViewContext<Self>) {
fn move_cell_up(&mut self, window: &mut Window, cx: &mut Context<Self>) {
println!("Move cell up triggered");
}
fn move_cell_down(&mut self, cx: &mut ViewContext<Self>) {
fn move_cell_down(&mut self, window: &mut Window, cx: &mut Context<Self>) {
println!("Move cell down triggered");
}
fn add_markdown_block(&mut self, cx: &mut ViewContext<Self>) {
fn add_markdown_block(&mut self, window: &mut Window, cx: &mut Context<Self>) {
println!("Add markdown block triggered");
}
fn add_code_block(&mut self, cx: &mut ViewContext<Self>) {
fn add_code_block(&mut self, window: &mut Window, cx: &mut Context<Self>) {
println!("Add code block triggered");
}
@ -204,7 +210,8 @@ impl NotebookEditor {
&mut self,
index: usize,
jump_to_index: bool,
cx: &mut ViewContext<Self>,
window: &mut Window,
cx: &mut Context<Self>,
) {
// let previous_index = self.selected_cell_index;
self.selected_cell_index = index;
@ -213,11 +220,16 @@ impl NotebookEditor {
// 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, cx);
self.jump_to_cell(current_index, window, cx);
}
}
pub fn select_next(&mut self, _: &menu::SelectNext, cx: &mut ViewContext<Self>) {
pub fn select_next(
&mut self,
_: &menu::SelectNext,
window: &mut Window,
cx: &mut Context<Self>,
) {
let count = self.cell_count();
if count > 0 {
let index = self.selected_index();
@ -226,42 +238,57 @@ impl NotebookEditor {
} else {
index + 1
};
self.set_selected_index(ix, true, cx);
self.set_selected_index(ix, true, window, cx);
cx.notify();
}
}
pub fn select_previous(&mut self, _: &menu::SelectPrev, cx: &mut ViewContext<Self>) {
pub fn select_previous(
&mut self,
_: &menu::SelectPrev,
window: &mut Window,
cx: &mut Context<Self>,
) {
let count = self.cell_count();
if count > 0 {
let index = self.selected_index();
let ix = if index == 0 { 0 } else { index - 1 };
self.set_selected_index(ix, true, cx);
self.set_selected_index(ix, true, window, cx);
cx.notify();
}
}
pub fn select_first(&mut self, _: &menu::SelectFirst, cx: &mut ViewContext<Self>) {
pub fn select_first(
&mut self,
_: &menu::SelectFirst,
window: &mut Window,
cx: &mut Context<Self>,
) {
let count = self.cell_count();
if count > 0 {
self.set_selected_index(0, true, cx);
self.set_selected_index(0, true, window, cx);
cx.notify();
}
}
pub fn select_last(&mut self, _: &menu::SelectLast, cx: &mut ViewContext<Self>) {
pub fn select_last(
&mut self,
_: &menu::SelectLast,
window: &mut Window,
cx: &mut Context<Self>,
) {
let count = self.cell_count();
if count > 0 {
self.set_selected_index(count - 1, true, cx);
self.set_selected_index(count - 1, true, window, cx);
cx.notify();
}
}
fn jump_to_cell(&mut self, index: usize, _cx: &mut ViewContext<Self>) {
fn jump_to_cell(&mut self, index: usize, _window: &mut Window, _cx: &mut Context<Self>) {
self.cell_list.scroll_to_reveal_item(index);
}
fn button_group(cx: &ViewContext<Self>) -> Div {
fn button_group(window: &mut Window, cx: &mut Context<Self>) -> Div {
v_flex()
.gap(DynamicSpacing::Base04.rems(cx))
.items_center()
@ -277,14 +304,19 @@ impl NotebookEditor {
fn render_notebook_control(
id: impl Into<SharedString>,
icon: IconName,
_cx: &ViewContext<Self>,
_window: &mut Window,
_cx: &mut Context<Self>,
) -> IconButton {
let id: ElementId = ElementId::Name(id.into());
IconButton::new(id, icon).width(px(CONTROL_SIZE).into())
}
fn render_notebook_controls(&self, cx: &ViewContext<Self>) -> impl IntoElement {
let has_outputs = self.has_outputs(cx);
fn render_notebook_controls(
&self,
window: &mut Window,
cx: &mut Context<Self>,
) -> impl IntoElement {
let has_outputs = self.has_outputs(window, cx);
v_flex()
.max_w(px(CONTROL_SIZE + 4.0))
@ -298,83 +330,107 @@ impl NotebookEditor {
v_flex()
.gap(DynamicSpacing::Base08.rems(cx))
.child(
Self::button_group(cx)
Self::button_group(window, cx)
.child(
Self::render_notebook_control("run-all-cells", IconName::Play, cx)
.tooltip(move |cx| {
Tooltip::for_action("Execute all cells", &RunAll, cx)
})
.on_click(|_, cx| {
cx.dispatch_action(Box::new(RunAll));
}),
Self::render_notebook_control(
"run-all-cells",
IconName::Play,
window,
cx,
)
.tooltip(move |window, cx| {
Tooltip::for_action("Execute all cells", &RunAll, window, cx)
})
.on_click(|_, window, cx| {
window.dispatch_action(Box::new(RunAll), cx);
}),
)
.child(
Self::render_notebook_control(
"clear-all-outputs",
IconName::ListX,
window,
cx,
)
.disabled(!has_outputs)
.tooltip(move |cx| {
Tooltip::for_action("Clear all outputs", &ClearOutputs, cx)
.tooltip(move |window, cx| {
Tooltip::for_action(
"Clear all outputs",
&ClearOutputs,
window,
cx,
)
})
.on_click(|_, cx| {
cx.dispatch_action(Box::new(ClearOutputs));
.on_click(|_, window, cx| {
window.dispatch_action(Box::new(ClearOutputs), cx);
}),
),
)
.child(
Self::button_group(cx)
Self::button_group(window, cx)
.child(
Self::render_notebook_control(
"move-cell-up",
IconName::ArrowUp,
window,
cx,
)
.tooltip(move |cx| {
Tooltip::for_action("Move cell up", &MoveCellUp, cx)
.tooltip(move |window, cx| {
Tooltip::for_action("Move cell up", &MoveCellUp, window, cx)
})
.on_click(|_, cx| {
cx.dispatch_action(Box::new(MoveCellUp));
.on_click(|_, window, cx| {
window.dispatch_action(Box::new(MoveCellUp), cx);
}),
)
.child(
Self::render_notebook_control(
"move-cell-down",
IconName::ArrowDown,
window,
cx,
)
.tooltip(move |cx| {
Tooltip::for_action("Move cell down", &MoveCellDown, cx)
.tooltip(move |window, cx| {
Tooltip::for_action("Move cell down", &MoveCellDown, window, cx)
})
.on_click(|_, cx| {
cx.dispatch_action(Box::new(MoveCellDown));
.on_click(|_, window, cx| {
window.dispatch_action(Box::new(MoveCellDown), cx);
}),
),
)
.child(
Self::button_group(cx)
Self::button_group(window, cx)
.child(
Self::render_notebook_control(
"new-markdown-cell",
IconName::Plus,
window,
cx,
)
.tooltip(move |cx| {
Tooltip::for_action("Add markdown block", &AddMarkdownBlock, cx)
.tooltip(move |window, cx| {
Tooltip::for_action(
"Add markdown block",
&AddMarkdownBlock,
window,
cx,
)
})
.on_click(|_, cx| {
cx.dispatch_action(Box::new(AddMarkdownBlock));
.on_click(|_, window, cx| {
window.dispatch_action(Box::new(AddMarkdownBlock), cx);
}),
)
.child(
Self::render_notebook_control("new-code-cell", IconName::Code, cx)
.tooltip(move |cx| {
Tooltip::for_action("Add code block", &AddCodeBlock, cx)
})
.on_click(|_, cx| {
cx.dispatch_action(Box::new(AddCodeBlock));
}),
Self::render_notebook_control(
"new-code-cell",
IconName::Code,
window,
cx,
)
.tooltip(move |window, cx| {
Tooltip::for_action("Add code block", &AddCodeBlock, window, cx)
})
.on_click(|_, window, cx| {
window.dispatch_action(Box::new(AddCodeBlock), cx);
}),
),
),
)
@ -385,10 +441,11 @@ impl NotebookEditor {
.child(Self::render_notebook_control(
"more-menu",
IconName::Ellipsis,
window,
cx,
))
.child(
Self::button_group(cx)
Self::button_group(window, cx)
.child(IconButton::new("repl", IconName::ReplNeutral)),
),
)
@ -406,7 +463,8 @@ impl NotebookEditor {
&self,
index: usize,
cell: &Cell,
cx: &mut ViewContext<Self>,
window: &mut Window,
cx: &mut Context<Self>,
) -> impl IntoElement {
let cell_position = self.cell_position(index);
@ -439,17 +497,27 @@ impl NotebookEditor {
}
impl Render for NotebookEditor {
fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
div()
.key_context("notebook")
.track_focus(&self.focus_handle)
.on_action(cx.listener(|this, &OpenNotebook, cx| this.open_notebook(&OpenNotebook, cx)))
.on_action(cx.listener(|this, &ClearOutputs, cx| this.clear_outputs(cx)))
.on_action(cx.listener(|this, &RunAll, cx| this.run_cells(cx)))
.on_action(cx.listener(|this, &MoveCellUp, cx| this.move_cell_up(cx)))
.on_action(cx.listener(|this, &MoveCellDown, cx| this.move_cell_down(cx)))
.on_action(cx.listener(|this, &AddMarkdownBlock, cx| this.add_markdown_block(cx)))
.on_action(cx.listener(|this, &AddCodeBlock, cx| this.add_code_block(cx)))
.on_action(cx.listener(|this, &OpenNotebook, window, cx| {
this.open_notebook(&OpenNotebook, window, cx)
}))
.on_action(
cx.listener(|this, &ClearOutputs, window, cx| this.clear_outputs(window, cx)),
)
.on_action(cx.listener(|this, &RunAll, window, cx| this.run_cells(window, cx)))
.on_action(cx.listener(|this, &MoveCellUp, window, cx| this.move_cell_up(window, cx)))
.on_action(
cx.listener(|this, &MoveCellDown, window, cx| this.move_cell_down(window, cx)),
)
.on_action(cx.listener(|this, &AddMarkdownBlock, window, cx| {
this.add_markdown_block(window, cx)
}))
.on_action(
cx.listener(|this, &AddCodeBlock, window, cx| this.add_code_block(window, cx)),
)
.on_action(cx.listener(Self::select_next))
.on_action(cx.listener(Self::select_previous))
.on_action(cx.listener(Self::select_first))
@ -469,12 +537,12 @@ impl Render for NotebookEditor {
.overflow_y_scroll()
.child(list(self.cell_list.clone()).size_full()),
)
.child(self.render_notebook_controls(cx))
.child(self.render_notebook_controls(window, cx))
}
}
impl FocusableView for NotebookEditor {
fn focus_handle(&self, _: &AppContext) -> FocusHandle {
impl Focusable for NotebookEditor {
fn focus_handle(&self, _: &App) -> FocusHandle {
self.focus_handle.clone()
}
}
@ -492,10 +560,10 @@ pub struct NotebookItem {
impl project::ProjectItem for NotebookItem {
fn try_open(
project: &Model<Project>,
project: &Entity<Project>,
path: &ProjectPath,
cx: &mut AppContext,
) -> Option<Task<gpui::Result<Model<Self>>>> {
cx: &mut App,
) -> Option<Task<gpui::Result<Entity<Self>>>> {
let path = path.clone();
let project = project.clone();
let fs = project.read(cx).fs().clone();
@ -531,7 +599,7 @@ impl project::ProjectItem for NotebookItem {
.context("Entry not found")?
.id;
cx.new_model(|_| NotebookItem {
cx.new(|_| NotebookItem {
path: abs_path,
project_path: path,
languages,
@ -544,11 +612,11 @@ impl project::ProjectItem for NotebookItem {
}
}
fn entry_id(&self, _: &AppContext) -> Option<ProjectEntryId> {
fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
Some(self.id)
}
fn project_path(&self, _: &AppContext) -> Option<ProjectPath> {
fn project_path(&self, _: &App) -> Option<ProjectPath> {
Some(self.project_path.clone())
}
@ -607,7 +675,7 @@ impl EventEmitter<()> for NotebookEditor {}
// impl EventEmitter<ToolbarItemEvent> for NotebookControls {}
// impl Render for NotebookControls {
// fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
// fn render(&mut self, window: &mut Window, cx: &mut ModelContext<Self>) -> impl IntoElement {
// div().child("notebook controls")
// }
// }
@ -616,7 +684,7 @@ impl EventEmitter<()> for NotebookEditor {}
// fn set_active_pane_item(
// &mut self,
// active_pane_item: Option<&dyn workspace::ItemHandle>,
// cx: &mut ViewContext<Self>,
// window: &mut Window, cx: &mut ModelContext<Self>,
// ) -> workspace::ToolbarItemLocation {
// cx.notify();
// self.active_item = None;
@ -628,7 +696,7 @@ impl EventEmitter<()> for NotebookEditor {}
// ToolbarItemLocation::PrimaryLeft
// }
// fn pane_focus_update(&mut self, pane_focused: bool, _: &mut ViewContext<Self>) {
// fn pane_focus_update(&mut self, pane_focused: bool, _window: &mut Window, _cx: &mut ModelContext<Self>) {
// self.pane_focused = pane_focused;
// }
// }
@ -639,27 +707,28 @@ impl Item for NotebookEditor {
fn clone_on_split(
&self,
_workspace_id: Option<workspace::WorkspaceId>,
cx: &mut ViewContext<Self>,
) -> Option<gpui::View<Self>>
window: &mut Window,
cx: &mut Context<Self>,
) -> Option<Entity<Self>>
where
Self: Sized,
{
Some(cx.new_view(|cx| Self::new(self.project.clone(), self.notebook_item.clone(), cx)))
Some(cx.new(|cx| Self::new(self.project.clone(), self.notebook_item.clone(), window, cx)))
}
fn for_each_project_item(
&self,
cx: &AppContext,
cx: &App,
f: &mut dyn FnMut(gpui::EntityId, &dyn project::ProjectItem),
) {
f(self.notebook_item.entity_id(), self.notebook_item.read(cx))
}
fn is_singleton(&self, _cx: &AppContext) -> bool {
fn is_singleton(&self, _cx: &App) -> bool {
true
}
fn tab_content(&self, params: TabContentParams, cx: &WindowContext) -> AnyElement {
fn tab_content(&self, params: TabContentParams, window: &Window, cx: &App) -> AnyElement {
let path = &self.notebook_item.read(cx).path;
let title = path
.file_name()
@ -673,7 +742,7 @@ impl Item for NotebookEditor {
.into_any_element()
}
fn tab_icon(&self, _cx: &WindowContext) -> Option<Icon> {
fn tab_icon(&self, _window: &Window, _cx: &App) -> Option<Icon> {
Some(IconName::Book.into())
}
@ -682,29 +751,35 @@ impl Item for NotebookEditor {
}
// TODO
fn pixel_position_of_cursor(&self, _: &AppContext) -> Option<Point<Pixels>> {
fn pixel_position_of_cursor(&self, _: &App) -> Option<Point<Pixels>> {
None
}
// TODO
fn as_searchable(&self, _: &View<Self>) -> Option<Box<dyn SearchableItemHandle>> {
fn as_searchable(&self, _: &Entity<Self>) -> Option<Box<dyn SearchableItemHandle>> {
None
}
fn set_nav_history(&mut self, _: workspace::ItemNavHistory, _: &mut ViewContext<Self>) {
fn set_nav_history(
&mut self,
_: workspace::ItemNavHistory,
_window: &mut Window,
_: &mut Context<Self>,
) {
// TODO
}
// TODO
fn can_save(&self, _cx: &AppContext) -> bool {
fn can_save(&self, _cx: &App) -> bool {
false
}
// TODO
fn save(
&mut self,
_format: bool,
_project: Model<Project>,
_cx: &mut ViewContext<Self>,
_project: Entity<Project>,
_window: &mut Window,
_cx: &mut Context<Self>,
) -> Task<Result<()>> {
unimplemented!("save() must be implemented if can_save() returns true")
}
@ -712,22 +787,24 @@ impl Item for NotebookEditor {
// TODO
fn save_as(
&mut self,
_project: Model<Project>,
_project: Entity<Project>,
_path: ProjectPath,
_cx: &mut ViewContext<Self>,
_window: &mut Window,
_cx: &mut Context<Self>,
) -> Task<Result<()>> {
unimplemented!("save_as() must be implemented if can_save() returns true")
}
// TODO
fn reload(
&mut self,
_project: Model<Project>,
_cx: &mut ViewContext<Self>,
_project: Entity<Project>,
_window: &mut Window,
_cx: &mut Context<Self>,
) -> Task<Result<()>> {
unimplemented!("reload() must be implemented if can_save() returns true")
}
fn is_dirty(&self, cx: &AppContext) -> bool {
fn is_dirty(&self, cx: &App) -> bool {
self.cell_map.values().any(|cell| {
if let Cell::Code(code_cell) = cell {
code_cell.read(cx).is_dirty(cx)
@ -745,13 +822,14 @@ impl ProjectItem for NotebookEditor {
type Item = NotebookItem;
fn for_project_item(
project: Model<Project>,
item: Model<Self::Item>,
cx: &mut ViewContext<Self>,
project: Entity<Project>,
item: Entity<Self::Item>,
window: &mut Window,
cx: &mut Context<Self>,
) -> Self
where
Self: Sized,
{
Self::new(project, item, cx)
Self::new(project, item, window, cx)
}
}