From 0e19da3107657fcdda07aa7145611a1f762dd126 Mon Sep 17 00:00:00 2001 From: Piotr Osiewicz <24362066+osiewicz@users.noreply.github.com> Date: Wed, 13 Dec 2023 12:53:53 +0100 Subject: [PATCH 01/21] Bring back semantic search UI --- crates/search2/src/project_search.rs | 340 ++++++++++----------------- 1 file changed, 128 insertions(+), 212 deletions(-) diff --git a/crates/search2/src/project_search.rs b/crates/search2/src/project_search.rs index 34cd2b98149d74d6064b0abc50c7e938ed1c82a4..875d2fe095a73495144182e14e5e4e4dd9959582 100644 --- a/crates/search2/src/project_search.rs +++ b/crates/search2/src/project_search.rs @@ -1,7 +1,8 @@ use crate::{ - history::SearchHistory, mode::SearchMode, ActivateRegexMode, ActivateTextMode, CycleMode, - NextHistoryQuery, PreviousHistoryQuery, ReplaceAll, ReplaceNext, SearchOptions, - SelectNextMatch, SelectPrevMatch, ToggleCaseSensitive, ToggleReplace, ToggleWholeWord, + history::SearchHistory, mode::SearchMode, ActivateRegexMode, ActivateSemanticMode, + ActivateTextMode, CycleMode, NextHistoryQuery, PreviousHistoryQuery, ReplaceAll, ReplaceNext, + SearchOptions, SelectNextMatch, SelectPrevMatch, ToggleCaseSensitive, ToggleReplace, + ToggleWholeWord, }; use anyhow::{Context as _, Result}; use collections::HashMap; @@ -29,7 +30,7 @@ use std::{ mem, ops::{Not, Range}, path::PathBuf, - time::Duration, + time::{Duration, Instant}, }; use ui::{ @@ -283,196 +284,86 @@ impl Render for ProjectSearchView { let model = self.model.read(cx); let has_no_results = model.no_results.unwrap_or(false); let is_search_underway = model.pending_search.is_some(); - let major_text = if is_search_underway { + let mut major_text = if is_search_underway { Label::new("Searching...") } else if has_no_results { - Label::new("No results for a given query") + Label::new("No results") } else { Label::new(format!("{} search all files", self.current_mode.label())) }; + + let mut show_minor_text = true; + let semantic_status = self.semantic_state.as_ref().and_then(|semantic| { + let status = semantic.index_status; + match status { + SemanticIndexStatus::NotAuthenticated => { + major_text = Label::new("Not Authenticated"); + show_minor_text = false; + Some( + "API Key Missing: Please set 'OPENAI_API_KEY' in Environment Variables. If you authenticated using the Assistant Panel, please restart Zed to Authenticate.".to_string()) + } + SemanticIndexStatus::Indexed => Some("Indexing complete".to_string()), + SemanticIndexStatus::Indexing { + remaining_files, + rate_limit_expiry, + } => { + if remaining_files == 0 { + Some("Indexing...".to_string()) + } else { + if let Some(rate_limit_expiry) = rate_limit_expiry { + let remaining_seconds = + rate_limit_expiry.duration_since(Instant::now()); + if remaining_seconds > Duration::from_secs(0) { + Some(format!( + "Remaining files to index (rate limit resets in {}s): {}", + remaining_seconds.as_secs(), + remaining_files + )) + } else { + Some(format!("Remaining files to index: {}", remaining_files)) + } + } else { + Some(format!("Remaining files to index: {}", remaining_files)) + } + } + } + SemanticIndexStatus::NotIndexed => None, + } + }); let major_text = div().justify_center().max_w_96().child(major_text); - let middle_text = div() - .items_center() - .max_w_96() - .child(Label::new(self.landing_text_minor()).size(LabelSize::Small)); + + let minor_text: Option = if let Some(no_results) = model.no_results { + if model.pending_search.is_none() && no_results { + Some("No results found in this project for the provided query".into()) + } else { + None + } + } else { + if let Some(mut semantic_status) = semantic_status { + semantic_status.extend(self.landing_text_minor().chars()); + Some(semantic_status.into()) + } else { + Some(self.landing_text_minor()) + } + }; + let minor_text = minor_text.map(|text| { + div() + .items_center() + .max_w_96() + .child(Label::new(text).size(LabelSize::Small)) + }); v_stack().flex_1().size_full().justify_center().child( h_stack() .size_full() .justify_center() .child(h_stack().flex_1()) - .child(v_stack().child(major_text).child(middle_text)) + .child(v_stack().child(major_text).children(minor_text)) .child(h_stack().flex_1()), ) } } } -// impl Entity for ProjectSearchView { -// type Event = ViewEvent; -// } - -// impl View for ProjectSearchView { -// fn ui_name() -> &'static str { -// "ProjectSearchView" -// } - -// fn render(&mut self, cx: &mut ViewContext) -> AnyElement { -// let model = &self.model.read(cx); -// if model.match_ranges.is_empty() { -// enum Status {} - -// let theme = theme::current(cx).clone(); - -// // If Search is Active -> Major: Searching..., Minor: None -// // If Semantic -> Major: "Search using Natural Language", Minor: {Status}/n{ex...}/n{ex...} -// // If Regex -> Major: "Search using Regex", Minor: {ex...} -// // If Text -> Major: "Text search all files and folders", Minor: {...} - -// let current_mode = self.current_mode; -// let mut major_text = if model.pending_search.is_some() { -// Cow::Borrowed("Searching...") -// } else if model.no_results.is_some_and(|v| v) { -// Cow::Borrowed("No Results") -// } else { -// match current_mode { -// SearchMode::Text => Cow::Borrowed("Text search all files and folders"), -// SearchMode::Semantic => { -// Cow::Borrowed("Search all code objects using Natural Language") -// } -// SearchMode::Regex => Cow::Borrowed("Regex search all files and folders"), -// } -// }; - -// let mut show_minor_text = true; -// let semantic_status = self.semantic_state.as_ref().and_then(|semantic| { -// let status = semantic.index_status; -// match status { -// SemanticIndexStatus::NotAuthenticated => { -// major_text = Cow::Borrowed("Not Authenticated"); -// show_minor_text = false; -// Some(vec![ -// "API Key Missing: Please set 'OPENAI_API_KEY' in Environment Variables." -// .to_string(), "If you authenticated using the Assistant Panel, please restart Zed to Authenticate.".to_string()]) -// } -// SemanticIndexStatus::Indexed => Some(vec!["Indexing complete".to_string()]), -// SemanticIndexStatus::Indexing { -// remaining_files, -// rate_limit_expiry, -// } => { -// if remaining_files == 0 { -// Some(vec![format!("Indexing...")]) -// } else { -// if let Some(rate_limit_expiry) = rate_limit_expiry { -// let remaining_seconds = -// rate_limit_expiry.duration_since(Instant::now()); -// if remaining_seconds > Duration::from_secs(0) { -// Some(vec![format!( -// "Remaining files to index (rate limit resets in {}s): {}", -// remaining_seconds.as_secs(), -// remaining_files -// )]) -// } else { -// Some(vec![format!("Remaining files to index: {}", remaining_files)]) -// } -// } else { -// Some(vec![format!("Remaining files to index: {}", remaining_files)]) -// } -// } -// } -// SemanticIndexStatus::NotIndexed => None, -// } -// }); - -// let minor_text = if let Some(no_results) = model.no_results { -// if model.pending_search.is_none() && no_results { -// vec!["No results found in this project for the provided query".to_owned()] -// } else { -// vec![] -// } -// } else { -// match current_mode { -// SearchMode::Semantic => { -// let mut minor_text: Vec = Vec::new(); -// minor_text.push("".into()); -// if let Some(semantic_status) = semantic_status { -// minor_text.extend(semantic_status); -// } -// if show_minor_text { -// minor_text -// .push("Simply explain the code you are looking to find.".into()); -// minor_text.push( -// "ex. 'prompt user for permissions to index their project'".into(), -// ); -// } -// minor_text -// } -// _ => vec![ -// "".to_owned(), -// "Include/exclude specific paths with the filter option.".to_owned(), -// "Matching exact word and/or casing is available too.".to_owned(), -// ], -// } -// }; - -// MouseEventHandler::new::(0, cx, |_, _| { -// Flex::column() -// .with_child(Flex::column().contained().flex(1., true)) -// .with_child( -// Flex::column() -// .align_children_center() -// .with_child(Label::new( -// major_text, -// theme.search.major_results_status.clone(), -// )) -// .with_children( -// minor_text.into_iter().map(|x| { -// Label::new(x, theme.search.minor_results_status.clone()) -// }), -// ) -// .aligned() -// .top() -// .contained() -// .flex(7., true), -// ) -// .contained() -// .with_background_color(theme.editor.background) -// }) -// .on_down(MouseButton::Left, |_, _, cx| { -// cx.focus_parent(); -// }) -// .into_any_named("project search view") -// } else { -// ChildView::new(&self.results_editor, cx) -// .flex(1., true) -// .into_any_named("project search view") -// } -// } - -// fn focus_in(&mut self, _: AnyView, cx: &mut ViewContext) { -// let handle = cx.weak_handle(); -// cx.update_global(|state: &mut ActiveSearches, cx| { -// state -// .0 -// .insert(self.model.read(cx).project.downgrade(), handle) -// }); - -// cx.update_global(|state: &mut ActiveSettings, cx| { -// state.0.insert( -// self.model.read(cx).project.downgrade(), -// self.current_settings(), -// ); -// }); - -// if cx.is_self_focused() { -// if self.query_editor_was_focused { -// cx.focus(&self.query_editor); -// } else { -// cx.focus(&self.results_editor); -// } -// } -// } -// } - impl FocusableView for ProjectSearchView { fn focus_handle(&self, cx: &AppContext) -> gpui::FocusHandle { self.results_editor.focus_handle(cx) @@ -1256,7 +1147,7 @@ impl ProjectSearchView { fn landing_text_minor(&self) -> SharedString { match self.current_mode { SearchMode::Text | SearchMode::Regex => "Include/exclude specific paths with the filter option. Matching exact word and/or casing is available too.".into(), - SearchMode::Semantic => ".Simply explain the code you are looking to find. ex. 'prompt user for permissions to index their project'".into() + SearchMode::Semantic => "\nSimply explain the code you are looking to find. ex. 'prompt user for permissions to index their project'".into() } } } @@ -1277,8 +1168,8 @@ impl ProjectSearchBar { fn cycle_mode(&self, _: &CycleMode, cx: &mut ViewContext) { if let Some(view) = self.active_project_search.as_ref() { view.update(cx, |this, cx| { - // todo: po: 2nd argument of `next_mode` should be `SemanticIndex::enabled(cx))`, but we need to flesh out port of semantic_index first. - let new_mode = crate::mode::next_mode(&this.current_mode, false); + let new_mode = + crate::mode::next_mode(&this.current_mode, SemanticIndex::enabled(cx)); this.activate_search_mode(new_mode, cx); let editor_handle = this.query_editor.focus_handle(cx); cx.focus(&editor_handle); @@ -1548,7 +1439,7 @@ impl Render for ProjectSearchBar { }); } let search = search.read(cx); - + let semantic_is_available = SemanticIndex::enabled(cx); let query_column = v_stack() //.flex_1() .child( @@ -1578,42 +1469,51 @@ impl Render for ProjectSearchBar { .unwrap_or_default(), ), ) - .child( - IconButton::new( - "project-search-case-sensitive", - Icon::CaseSensitive, - ) - .tooltip(|cx| { - Tooltip::for_action( - "Toggle case sensitive", - &ToggleCaseSensitive, - cx, + .when(search.current_mode != SearchMode::Semantic, |this| { + this.child( + IconButton::new( + "project-search-case-sensitive", + Icon::CaseSensitive, ) - }) - .selected(self.is_option_enabled(SearchOptions::CASE_SENSITIVE, cx)) - .on_click(cx.listener( - |this, _, cx| { - this.toggle_search_option( - SearchOptions::CASE_SENSITIVE, - cx, - ); - }, - )), - ) - .child( - IconButton::new("project-search-whole-word", Icon::WholeWord) .tooltip(|cx| { Tooltip::for_action( - "Toggle whole word", - &ToggleWholeWord, + "Toggle case sensitive", + &ToggleCaseSensitive, cx, ) }) - .selected(self.is_option_enabled(SearchOptions::WHOLE_WORD, cx)) - .on_click(cx.listener(|this, _, cx| { - this.toggle_search_option(SearchOptions::WHOLE_WORD, cx); - })), - ), + .selected( + self.is_option_enabled(SearchOptions::CASE_SENSITIVE, cx), + ) + .on_click(cx.listener( + |this, _, cx| { + this.toggle_search_option( + SearchOptions::CASE_SENSITIVE, + cx, + ); + }, + )), + ) + .child( + IconButton::new("project-search-whole-word", Icon::WholeWord) + .tooltip(|cx| { + Tooltip::for_action( + "Toggle whole word", + &ToggleWholeWord, + cx, + ) + }) + .selected( + self.is_option_enabled(SearchOptions::WHOLE_WORD, cx), + ) + .on_click(cx.listener(|this, _, cx| { + this.toggle_search_option( + SearchOptions::WHOLE_WORD, + cx, + ); + })), + ) + }), ) .border_2() .bg(white()) @@ -1668,7 +1568,23 @@ impl Render for ProjectSearchBar { cx, ) }), - ), + ) + .when(semantic_is_available, |this| { + this.child( + Button::new("project-search-semantic-button", "Semantic") + .selected(search.current_mode == SearchMode::Semantic) + .on_click(cx.listener(|this, _, cx| { + this.activate_search_mode(SearchMode::Semantic, cx) + })) + .tooltip(|cx| { + Tooltip::for_action( + "Toggle semantic search", + &ActivateSemanticMode, + cx, + ) + }), + ) + }), ) .child( IconButton::new("project-search-toggle-replace", Icon::Replace) From ce1489f5dcb6471216d7a66924f880333afdddf4 Mon Sep 17 00:00:00 2001 From: Piotr Osiewicz <24362066+osiewicz@users.noreply.github.com> Date: Wed, 13 Dec 2023 14:22:29 +0100 Subject: [PATCH 02/21] Add inclusion of ignored files --- crates/search2/src/project_search.rs | 75 ++++++++++++++++++---------- crates/search2/src/search.rs | 5 ++ 2 files changed, 55 insertions(+), 25 deletions(-) diff --git a/crates/search2/src/project_search.rs b/crates/search2/src/project_search.rs index 875d2fe095a73495144182e14e5e4e4dd9959582..f1b0c16d5708241cd4421e9c7b88d762383ff532 100644 --- a/crates/search2/src/project_search.rs +++ b/crates/search2/src/project_search.rs @@ -1,8 +1,8 @@ use crate::{ history::SearchHistory, mode::SearchMode, ActivateRegexMode, ActivateSemanticMode, ActivateTextMode, CycleMode, NextHistoryQuery, PreviousHistoryQuery, ReplaceAll, ReplaceNext, - SearchOptions, SelectNextMatch, SelectPrevMatch, ToggleCaseSensitive, ToggleReplace, - ToggleWholeWord, + SearchOptions, SelectNextMatch, SelectPrevMatch, ToggleCaseSensitive, ToggleIncludeIgnored, + ToggleReplace, ToggleWholeWord, }; use anyhow::{Context as _, Result}; use collections::HashMap; @@ -1530,7 +1530,22 @@ impl Render for ProjectSearchBar { .flex_1() .border_1() .mr_2() - .child(search.included_files_editor.clone()), + .child(search.included_files_editor.clone()) + .when(search.current_mode != SearchMode::Semantic, |this| { + this.child( + SearchOptions::INCLUDE_IGNORED.as_button( + search + .search_options + .contains(SearchOptions::INCLUDE_IGNORED), + cx.listener(|this, _, cx| { + this.toggle_search_option( + SearchOptions::INCLUDE_IGNORED, + cx, + ); + }), + ), + ) + }), ) .child( h_stack() @@ -1671,34 +1686,14 @@ impl Render for ProjectSearchBar { .on_action(cx.listener(|this, _: &ToggleFilters, cx| { this.toggle_filters(cx); })) - .on_action(cx.listener(|this, _: &ToggleWholeWord, cx| { - this.toggle_search_option(SearchOptions::WHOLE_WORD, cx); - })) - .on_action(cx.listener(|this, _: &ToggleCaseSensitive, cx| { - this.toggle_search_option(SearchOptions::CASE_SENSITIVE, cx); - })) - .on_action(cx.listener(|this, action, cx| { - this.toggle_replace(action, cx); - })) .on_action(cx.listener(|this, _: &ActivateTextMode, cx| { this.activate_search_mode(SearchMode::Text, cx) })) .on_action(cx.listener(|this, _: &ActivateRegexMode, cx| { this.activate_search_mode(SearchMode::Regex, cx) })) - .on_action(cx.listener(|this, action, cx| { - if let Some(search) = this.active_project_search.as_ref() { - search.update(cx, |this, cx| { - this.replace_next(action, cx); - }) - } - })) - .on_action(cx.listener(|this, action, cx| { - if let Some(search) = this.active_project_search.as_ref() { - search.update(cx, |this, cx| { - this.replace_all(action, cx); - }) - } + .on_action(cx.listener(|this, _: &ActivateSemanticMode, cx| { + this.activate_search_mode(SearchMode::Semantic, cx) })) .on_action(cx.listener(|this, action, cx| { this.tab(action, cx); @@ -1709,6 +1704,36 @@ impl Render for ProjectSearchBar { .on_action(cx.listener(|this, action, cx| { this.cycle_mode(action, cx); })) + .when(search.current_mode != SearchMode::Semantic, |this| { + this.on_action(cx.listener(|this, action, cx| { + this.toggle_replace(action, cx); + })) + .on_action(cx.listener(|this, _: &ToggleWholeWord, cx| { + this.toggle_search_option(SearchOptions::WHOLE_WORD, cx); + })) + .on_action(cx.listener(|this, _: &ToggleCaseSensitive, cx| { + this.toggle_search_option(SearchOptions::CASE_SENSITIVE, cx); + })) + .on_action(cx.listener(|this, action, cx| { + if let Some(search) = this.active_project_search.as_ref() { + search.update(cx, |this, cx| { + this.replace_next(action, cx); + }) + } + })) + .on_action(cx.listener(|this, action, cx| { + if let Some(search) = this.active_project_search.as_ref() { + search.update(cx, |this, cx| { + this.replace_all(action, cx); + }) + } + })) + .when(search.filters_enabled, |this| { + this.on_action(cx.listener(|this, _: &ToggleIncludeIgnored, cx| { + this.toggle_search_option(SearchOptions::INCLUDE_IGNORED, cx); + })) + }) + }) .child(query_column) .child(mode_column) .child(replace_column) diff --git a/crates/search2/src/search.rs b/crates/search2/src/search.rs index 015c126aa1ef5abd37e67f6c169a3c7787ccf4b6..18fcc258f44497c8863f9000201238cebc1520ab 100644 --- a/crates/search2/src/search.rs +++ b/crates/search2/src/search.rs @@ -28,6 +28,7 @@ actions!( CycleMode, ToggleWholeWord, ToggleCaseSensitive, + ToggleIncludeIgnored, ToggleReplace, SelectNextMatch, SelectPrevMatch, @@ -57,6 +58,7 @@ impl SearchOptions { match *self { SearchOptions::WHOLE_WORD => "Match Whole Word", SearchOptions::CASE_SENSITIVE => "Match Case", + SearchOptions::INCLUDE_IGNORED => "Include ignored", _ => panic!("{:?} is not a named SearchOption", self), } } @@ -65,6 +67,7 @@ impl SearchOptions { match *self { SearchOptions::WHOLE_WORD => ui::Icon::WholeWord, SearchOptions::CASE_SENSITIVE => ui::Icon::CaseSensitive, + SearchOptions::INCLUDE_IGNORED => ui::Icon::FileGit, _ => panic!("{:?} is not a named SearchOption", self), } } @@ -73,6 +76,7 @@ impl SearchOptions { match *self { SearchOptions::WHOLE_WORD => Box::new(ToggleWholeWord), SearchOptions::CASE_SENSITIVE => Box::new(ToggleCaseSensitive), + SearchOptions::INCLUDE_IGNORED => Box::new(ToggleIncludeIgnored), _ => panic!("{:?} is not a named SearchOption", self), } } @@ -85,6 +89,7 @@ impl SearchOptions { let mut options = SearchOptions::NONE; options.set(SearchOptions::WHOLE_WORD, query.whole_word()); options.set(SearchOptions::CASE_SENSITIVE, query.case_sensitive()); + options.set(SearchOptions::INCLUDE_IGNORED, query.include_ignored()); options } From 85a1a8f777f4a8586d7adcd88863f6afeb086b2c Mon Sep 17 00:00:00 2001 From: Nate Butler Date: Mon, 11 Dec 2023 19:17:13 -0500 Subject: [PATCH 03/21] WIP --- docs/.gitignore | 2 + docs/book.toml | 6 + docs/src/CODE_OF_CONDUCT.md | 128 ++ docs/src/CONTRIBUTING.md | 3 + docs/src/SUMMARY.md | 18 + docs/src/configuring_zed.md | 1035 +++++++++++++++++ docs/src/configuring_zed__configuring_vim.md | 170 +++ docs/src/developing_zed__adding_languages.md | 83 ++ docs/src/developing_zed__building_zed.md | 107 ++ .../developing_zed__local_collaboration.md} | 0 docs/src/feedback.md | 29 + docs/src/getting_started.md | 15 + docs/src/system_requirements.md | 13 + docs/src/telemetry.md | 147 +++ {docs => docs_old}/backend-development.md | 0 {docs => docs_old}/building-zed.md | 0 {docs => docs_old}/company-and-vision.md | 0 {docs => docs_old}/design-tools.md | 0 {docs => docs_old}/index.md | 0 docs_old/local-collaboration.md | 22 + {docs => docs_old}/release-process.md | 0 .../theme/generating-theme-types.md | 0 {docs => docs_old}/tools.md | 0 {docs => docs_old}/zed/syntax-highlighting.md | 0 24 files changed, 1778 insertions(+) create mode 100644 docs/.gitignore create mode 100644 docs/book.toml create mode 100644 docs/src/CODE_OF_CONDUCT.md create mode 100644 docs/src/CONTRIBUTING.md create mode 100644 docs/src/SUMMARY.md create mode 100644 docs/src/configuring_zed.md create mode 100644 docs/src/configuring_zed__configuring_vim.md create mode 100644 docs/src/developing_zed__adding_languages.md create mode 100644 docs/src/developing_zed__building_zed.md rename docs/{local-collaboration.md => src/developing_zed__local_collaboration.md} (100%) create mode 100644 docs/src/feedback.md create mode 100644 docs/src/getting_started.md create mode 100644 docs/src/system_requirements.md create mode 100644 docs/src/telemetry.md rename {docs => docs_old}/backend-development.md (100%) rename {docs => docs_old}/building-zed.md (100%) rename {docs => docs_old}/company-and-vision.md (100%) rename {docs => docs_old}/design-tools.md (100%) rename {docs => docs_old}/index.md (100%) create mode 100644 docs_old/local-collaboration.md rename {docs => docs_old}/release-process.md (100%) rename {docs => docs_old}/theme/generating-theme-types.md (100%) rename {docs => docs_old}/tools.md (100%) rename {docs => docs_old}/zed/syntax-highlighting.md (100%) diff --git a/docs/.gitignore b/docs/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..eed3a3e0462ad6c1a85505fbedae8c76112571ba --- /dev/null +++ b/docs/.gitignore @@ -0,0 +1,2 @@ +book +.vercel diff --git a/docs/book.toml b/docs/book.toml new file mode 100644 index 0000000000000000000000000000000000000000..8062a76a4216ca248c786283bef9acf725fdee9d --- /dev/null +++ b/docs/book.toml @@ -0,0 +1,6 @@ +[book] +authors = ["Nate Butler"] +language = "en" +multilingual = false +src = "src" +title = "Zed App Docs" diff --git a/docs/src/CODE_OF_CONDUCT.md b/docs/src/CODE_OF_CONDUCT.md new file mode 100644 index 0000000000000000000000000000000000000000..bc1d5522a0af5502dd8a428f8f3d28a9965b52be --- /dev/null +++ b/docs/src/CODE_OF_CONDUCT.md @@ -0,0 +1,128 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +We as members, contributors, and leaders pledge to make participation in our +community a harassment-free experience for everyone, regardless of age, body +size, visible or invisible disability, ethnicity, sex characteristics, gender +identity and expression, level of experience, education, socio-economic status, +nationality, personal appearance, race, religion, or sexual identity +and orientation. + +We pledge to act and interact in ways that contribute to an open, welcoming, +diverse, inclusive, and healthy community. + +## Our Standards + +Examples of behavior that contributes to a positive environment for our +community include: + +* Demonstrating empathy and kindness toward other people +* Being respectful of differing opinions, viewpoints, and experiences +* Giving and gracefully accepting constructive feedback +* Accepting responsibility and apologizing to those affected by our mistakes, + and learning from the experience +* Focusing on what is best not just for us as individuals, but for the + overall community + +Examples of unacceptable behavior include: + +* The use of sexualized language or imagery, and sexual attention or + advances of any kind +* Trolling, insulting or derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or email + address, without their explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Enforcement Responsibilities + +Community leaders are responsible for clarifying and enforcing our standards of +acceptable behavior and will take appropriate and fair corrective action in +response to any behavior that they deem inappropriate, threatening, offensive, +or harmful. + +Community leaders have the right and responsibility to remove, edit, or reject +comments, commits, code, wiki edits, issues, and other contributions that are +not aligned to this Code of Conduct, and will communicate reasons for moderation +decisions when appropriate. + +## Scope + +This Code of Conduct applies within all community spaces, and also applies when +an individual is officially representing the community in public spaces. +Examples of representing our community include using an official e-mail address, +posting via an official social media account, or acting as an appointed +representative at an online or offline event. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported to the community leaders responsible for enforcement at +hi@zed.dev. +All complaints will be reviewed and investigated promptly and fairly. + +All community leaders are obligated to respect the privacy and security of the +reporter of any incident. + +## Enforcement Guidelines + +Community leaders will follow these Community Impact Guidelines in determining +the consequences for any action they deem in violation of this Code of Conduct: + +### 1. Correction + +**Community Impact**: Use of inappropriate language or other behavior deemed +unprofessional or unwelcome in the community. + +**Consequence**: A private, written warning from community leaders, providing +clarity around the nature of the violation and an explanation of why the +behavior was inappropriate. A public apology may be requested. + +### 2. Warning + +**Community Impact**: A violation through a single incident or series +of actions. + +**Consequence**: A warning with consequences for continued behavior. No +interaction with the people involved, including unsolicited interaction with +those enforcing the Code of Conduct, for a specified period of time. This +includes avoiding interactions in community spaces as well as external channels +like social media. Violating these terms may lead to a temporary or +permanent ban. + +### 3. Temporary Ban + +**Community Impact**: A serious violation of community standards, including +sustained inappropriate behavior. + +**Consequence**: A temporary ban from any sort of interaction or public +communication with the community for a specified period of time. No public or +private interaction with the people involved, including unsolicited interaction +with those enforcing the Code of Conduct, is allowed during this period. +Violating these terms may lead to a permanent ban. + +### 4. Permanent Ban + +**Community Impact**: Demonstrating a pattern of violation of community +standards, including sustained inappropriate behavior, harassment of an +individual, or aggression toward or disparagement of classes of individuals. + +**Consequence**: A permanent ban from any sort of public interaction within +the community. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], +version 2.0, available at +https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. + +Community Impact Guidelines were inspired by [Mozilla's code of conduct +enforcement ladder](https://github.com/mozilla/diversity). + +[homepage]: https://www.contributor-covenant.org + +For answers to common questions about this code of conduct, see the FAQ at +https://www.contributor-covenant.org/faq. Translations are available at +https://www.contributor-covenant.org/translations. diff --git a/docs/src/CONTRIBUTING.md b/docs/src/CONTRIBUTING.md new file mode 100644 index 0000000000000000000000000000000000000000..d48c26844f2ee079fedcbdda70ac83704abb9747 --- /dev/null +++ b/docs/src/CONTRIBUTING.md @@ -0,0 +1,3 @@ +# Contributing + +TBD diff --git a/docs/src/SUMMARY.md b/docs/src/SUMMARY.md new file mode 100644 index 0000000000000000000000000000000000000000..4c6f5f9421dcb7e6b8517085e0c30374a216632b --- /dev/null +++ b/docs/src/SUMMARY.md @@ -0,0 +1,18 @@ +# Summary + +[Getting Started](./getting_started.md) +[Feedback](./feedback.md) + +# Configuring Zed +- [Settings](./configuring_zed.md) +- [Vim Mode](./configuring_zed__configuring_vim.md) + +# Developing Zed +- [Building from Source](./developing_zed__building_zed.md) +- [Local Collaboration](./developing_zed__local_collaboration.md) +- [Adding Languages](./developing_zed__adding_languages.md) + +# Other +- [Code of Conduct](./CODE_OF_CONDUCT.md) +- [Telemetry](./telemetry.md) +- [Contributing](./CONTRIBUTING.md) diff --git a/docs/src/configuring_zed.md b/docs/src/configuring_zed.md new file mode 100644 index 0000000000000000000000000000000000000000..9b9205f70ca7cac1cb587a2800de6af3f7bed956 --- /dev/null +++ b/docs/src/configuring_zed.md @@ -0,0 +1,1035 @@ +# Configuring Zed + +## Folder-specific settings + +Folder-specific settings are used to override Zed's global settings for files within a specific directory in the project panel. To get started, create a `.zed` subdirectory and add a `settings.json` within it. It should be noted that folder-specific settings don't need to live only a project's root, but can be defined at multiple levels in the project hierarchy. In setups like this, Zed will find the configuration nearest to the file you are working in and apply those settings to it. In most cases, this level of flexibility won't be needed and a single configuration for all files in a project is all that is required; the `Zed > Settings > Open Local Settings` menu action is built for this case. Running this action will look for a `.zed/settings.json` file at the root of the first top-level directory in your project panel. If it does not exist, it will create it. + +The following global settings can be overriden with a folder-specific configuration: + +- `copilot` +- `enable_language_server` +- `ensure_final_newline_on_save` +- `format_on_save` +- `formatter` +- `hard_tabs` +- `language_overrides` +- `preferred_line_length` +- `remove_trailing_whitespace_on_save` +- `soft_wrap` +- `tab_size` +- `show_copilot_suggestions` +- `show_whitespaces` + +*See the Global settings section for details about these settings* + +## Global settings + +To get started with editing Zed's global settings, open `~/.config/zed/settings.json` via `cmd-,`, the command palette (`zed: open settings`), or the `Zed > Settings > Open Settings` application menu item. + +Here are all the currently available settings. + +## Active Pane Magnification + +- Description: Scale by which to zoom the active pane. When set to `1.0`, the active pane has the same size as others, but when set to a larger value, the active pane takes up more space. +- Setting: `active_pane_magnification` +- Default: `1.0` + +**Options** + +`float` values + +## Autosave + +- Description: When to automatically save edited buffers. +- Setting: `autosave` +- Default: `off` + +**Options** + +1. To disable autosave, set it to `off` + +```json +{ + "autosave": "off" +} +``` + +2. To autosave when focus changes, use `on_focus_change`: + +```json +{ + "autosave": "on_focus_change" +} +``` + +3. To autosave when the active window changes, use `on_window_change`: + +```json +{ + "autosave": "on_window_change" +} +``` + +4. To autosave after an inactivity period, use `after_delay`: + +```json +{ + "autosave": { + "after_delay": { + "milliseconds": 1000 + } + } +} +``` + +## Auto Update + +- Description: Whether or not to automatically check for updates. +- Setting: `auto_update` +- Default: `true` + +**Options** + +`boolean` values + +## Buffer Font Family + +- Description: The name of a font to use for rendering text in the editor. +- Setting: `buffer_font_family` +- Default: `Zed Mono` + +**Options** + +The name of any font family installed on the user's system + +## Buffer Font Features + +- Description: The OpenType features to enable for text in the editor. +- Setting: `buffer_font_features` +- Default: `null` + +**Options** + +Zed supports a subset of OpenType features that can be enabled or disabled for a given buffer or terminal font. The following [OpenType features](https://en.wikipedia.org/wiki/List_of_typographic_features) can be enabled or disabled too: `calt`, `case`, `cpsp`, `frac`, `liga`, `onum`, `ordn`, `pnum`, `ss01`, `ss02`, `ss03`, `ss04`, `ss05`, `ss06`, `ss07`, `ss08`, `ss09`, `ss10`, `ss11`, `ss12`, `ss13`, `ss14`, `ss15`, `ss16`, `ss17`, `ss18`, `ss19`, `ss20`, `subs`, `sups`, `swsh`, `titl`, `tnum`, `zero`. + +For example, to disable ligatures for a given font you can add the following to your settings: + +```json +{ + "buffer_font_features": { + "calt": false + } +} +``` + +## Buffer Font Size + +- Description: The default font size for text in the editor. +- Setting: `buffer_font_size` +- Default: `15` + +**Options** + +`integer` values + +## Confirm Quit + +- Description: Whether or not to prompt the user to confirm before closing the application. +- Setting: `confirm_quit` +- Default: `false` + +**Options** + +`boolean` values + +## Copilot + +- Description: Copilot-specific settings. +- Setting: `copilot` +- Default: + +```json +"copilot": { + "disabled_globs": [ + ".env" + ] +} +``` + +**Options** + +### Disabled Globs + +- Description: The set of glob patterns for which Copilot should be disabled in any matching file. +- Setting: `disabled_globs` +- Default: [".env"] + +**Options** + +List of `string` values + +## Cursor Blink + +- Description: Whether or not the cursor blinks. +- Setting: `cursor_blink` +- Default: `true` + +**Options** + +`boolean` values + +## Default Dock Anchor + +- Description: The default anchor for new docks. +- Setting: `default_dock_anchor` +- Default: `bottom` + +**Options** + +1. Position the dock attached to the bottom of the workspace: `bottom` +2. Position the dock to the right of the workspace like a side panel: `right` +3. Position the dock full screen over the entire workspace: `expanded` + +## Enable Language Server + +- Description: Whether or not to use language servers to provide code intelligence. +- Setting: `enable_language_server` +- Default: `true` + +**Options** + +`boolean` values + +## Ensure Final Newline On Save + +- Description: Whether or not to ensure there's a single newline at the end of a buffer when saving it. +- Setting: `ensure_final_newline_on_save` +- Default: `true` + +**Options** + +`boolean` values + +## LSP + +- Description: Configuration for language servers. +- Setting: `lsp` +- Default: `null` + +**Options** + +The following settings can be overridden for specific language servers: + +- `initialization_options` + +To override settings for a language, add an entry for that language server's name to the `lsp` value. Example: + +```json +"lsp": { + "rust-analyzer": { + "initialization_options": { + "checkOnSave": { + "command": "clippy" // rust-analyzer.checkOnSave.command + } + } + } +} +``` + +## Format On Save + +- Description: Whether or not to perform a buffer format before saving. +- Setting: `format_on_save` +- Default: `on` + +**Options** + +1. `on`, enables format on save obeying `formatter` setting: + +```json +{ + "format_on_save": "on" +} +``` + +2. `off`, disables format on save: + +```json +{ + "format_on_save": "off" +} +``` + +## Formatter + +- Description: How to perform a buffer format. +- Setting: `formatter` +- Default: `language_server` + +**Options** + +1. To use the current language server, use `"language_server"`: + +```json +{ + "formatter": "language_server" +} +``` + +2. Or to use an external command, use `"external"`. Specify the name of the formatting program to run, and an array of arguments to pass to the program. The buffer's text will be passed to the program on stdin, and the formatted output should be written to stdout. For example, the following command would strip trailing spaces using [`sed(1)`](https://linux.die.net/man/1/sed): + +```json +{ + "formatter": { + "external": { + "command": "sed", + "arguments": ["-e", "s/ *$//"] + } + } +} +``` + +## Git + +- Description: Configuration for git-related features. +- Setting: `git` +- Default: + +```json +"git": { + "git_gutter": "tracked_files" +}, +``` + +### Git Gutter + +- Description: Whether or not to show the git gutter. +- Setting: `git_gutter` +- Default: `tracked_files` + +**Options** + +1. Show git gutter in tracked files + +```json +{ + "git_gutter": "tracked_files" +} +``` + +2. Hide git gutter + +```json +{ + "git_gutter": "hide" +} +``` + +## Hard Tabs + +- Description: Whether to indent lines using tab characters or multiple spaces. +- Setting: `hard_tabs` +- Default: `false` + +**Options** + +`boolean` values + +## Hover Popover Enabled + +- Description: Whether or not to show the informational hover box when moving the mouse over symbols in the editor. +- Setting: `hover_popover_enabled` +- Default: `true` + +**Options** + +`boolean` values + +## Inlay hints + +- Description: Configuration for displaying extra text with hints in the editor. +- Setting: `inlay_hints` +- Default: + +```json +"inlay_hints": { + "enabled": false, + "show_type_hints": true, + "show_parameter_hints": true, + "show_other_hints": true +} +``` + +**Options** + +Inlay hints querying consists of two parts: editor (client) and LSP server. +With the inlay settings above are changed to enable the hints, editor will start to query certain types of hints and react on LSP hint refresh request from the server. +At this point, the server may or may not return hints depending on its implementation, further configuration might be needed, refer to the corresponding LSP server documentation. + +Use `lsp` section for the server configuration, below are some examples for well known servers: + +### Rust + +```json +"lsp": { + "rust-analyzer": { + "initialization_options": { + "inlayHints": { + "maxLength": null, + "lifetimeElisionHints": { + "useParameterNames": true, + "enable": "skip_trivial" + }, + "closureReturnTypeHints": { + "enable": "always" + } + } + } + } +} +``` + +### Typescript + +```json +"lsp": { + "typescript-language-server": { + "initialization_options": { + "preferences": { + "includeInlayParameterNameHints": "all", + "includeInlayParameterNameHintsWhenArgumentMatchesName": true, + "includeInlayFunctionParameterTypeHints": true, + "includeInlayVariableTypeHints": true, + "includeInlayVariableTypeHintsWhenTypeMatchesName": false, + "includeInlayPropertyDeclarationTypeHints": true, + "includeInlayFunctionLikeReturnTypeHints": true, + "includeInlayEnumMemberValueHints": true + } + } + } +} +``` + +### Go + +```json +"lsp": { + "gopls": { + "initialization_options": { + "hints": { + "assignVariableTypes": true, + "compositeLiteralFields": true, + "compositeLiteralTypes": true, + "constantValues": true, + "functionTypeParameters": true, + "parameterNames": true, + "rangeVariableTypes": true + } + } + } +} +``` + +### Svelte + +```json +{ + "lsp": { + "typescript-language-server": { + "initialization_options": { + "preferences": { + "includeInlayParameterNameHints": "all", + "includeInlayParameterNameHintsWhenArgumentMatchesName": true, + "includeInlayFunctionParameterTypeHints": true, + "includeInlayVariableTypeHints": true, + "includeInlayVariableTypeHintsWhenTypeMatchesName": false, + "includeInlayPropertyDeclarationTypeHints": true, + "includeInlayFunctionLikeReturnTypeHints": true, + "includeInlayEnumMemberValueHints": true, + "includeInlayEnumMemberDeclarationTypes": true + } + } + } + } +} +``` + +## Journal + +- Description: Configuration for the journal. +- Setting: `journal` +- Default: + +```json +"journal": { + "path": "~", + "hour_format": "hour12" +} +``` + +### Path + +- Description: The path of the directory where journal entries are stored. +- Setting: `path` +- Default: `~` + +**Options** + +`string` values + +### Hour Format + +- Description: The format to use for displaying hours in the journal. +- Setting: `hour_format` +- Default: `hour12` + +**Options** + +1. 12-hour format: + +```json +{ + "hour_format": "hour12" +} +``` + +2. 24-hour format: + +```json +{ + "hour_format": "hour24" +} +``` + +## Language Overrides + +- Description: Configuration overrides for specific languages. +- Setting: `language_overrides` +- Default: `null` + +**Options** + +To override settings for a language, add an entry for that languages name to the `language_overrides` value. Example: + +```json +"language_overrides": { + "C": { + "format_on_save": "off", + "preferred_line_length": 64, + "soft_wrap": "preferred_line_length" + }, + "JSON": { + "tab_size": 4 + } +} +``` + +The following settings can be overridden for each specific language: + +- `enable_language_server` +- `ensure_final_newline_on_save` +- `format_on_save` +- `formatter` +- `hard_tabs` +- `preferred_line_length` +- `remove_trailing_whitespace_on_save` +- `show_copilot_suggestions` +- `show_whitespaces` +- `soft_wrap` +- `tab_size` + +These values take in the same options as the root-level settings with the same name. + +## Preferred Line Length + +- Description: The column at which to soft-wrap lines, for buffers where soft-wrap is enabled. +- Setting: `preferred_line_length` +- Default: `80` + +**Options** + +`integer` values + +## Projects Online By Default + +- Description: Whether or not to show the online projects view by default. +- Setting: `projects_online_by_default` +- Default: `true` + +**Options** + +`boolean` values + +## Remove Trailing Whitespace On Save + +- Description: Whether or not to remove any trailing whitespace from lines of a buffer before saving it. +- Setting: `remove_trailing_whitespace_on_save` +- Default: `true` + +**Options** + +`boolean` values + +## Semantic Index + +- Description: Settings related to semantic index. +- Setting: `semantic_index` +- Default: + +```json +"semantic_index": { + "enabled": false +}, +``` + +### Enabled + +- Description: Whether or not to display the `Semantic` mode in project search. +- Setting: `enabled` +- Default: `true` + +**Options** + +`boolean` values + +## Show Call Status Icon + +- Description: Whether or not to show the call status icon in the status bar. +- Setting: `show_call_status_icon` +- Default: `true` + +**Options** + +`boolean` values + +## Show Completions On Input + +- Description: Whether or not to show completions as you type. +- Setting: `show_completions_on_input` +- Default: `true` + +**Options** + +`boolean` values + +## Show Completion Documentation + +- Description: Whether to display inline and alongside documentation for items in the completions menu. +- Setting: `show_completion_documentation` +- Default: `true` + +**Options** + +`boolean` values + +## Show Copilot Suggestions + +- Description: Whether or not to show Copilot suggestions as you type or wait for a `copilot::Toggle`. +- Setting: `show_copilot_suggestions` +- Default: `true` + +**Options** + +`boolean` values + +## Show Whitespaces + +- Description: Whether or not to show render whitespace characters in the editor. +- Setting: `show_whitespaces` +- Default: `selection` + +**Options** + +1. `all` +2. `selection` +3. `none` + +## Soft Wrap + +- Description: Whether or not to automatically wrap lines of text to fit editor / preferred width. +- Setting: `soft_wrap` +- Default: `none` + +**Options** + +1. `editor_width` +2. `preferred_line_length` +3. `none` + +## Tab Size + +- Description: The number of spaces to use for each tab character. +- Setting: `tab_size` +- Default: `4` + +**Options** + +`integer` values + +## Telemetry + +- Description: Control what info is collected by Zed. +- Setting: `telemetry` +- Default: + +```json +"telemetry": { + "diagnostics": true, + "metrics": true +}, +``` + +**Options** + +### Diagnostics + +- Description: Setting for sending debug-related data, such as crash reports. +- Setting: `diagnostics` +- Default: `true` + +**Options** + +`boolean` values + +### Metrics + +- Description: Setting for sending anonymized usage data, such what languages you're using Zed with. +- Setting: `metrics` +- Default: `true` + +**Options** + +`boolean` values + +## Terminal + +- Description: Configuration for the terminal. +- Setting: `terminal` +- Default: + +```json +"terminal": { + "alternate_scroll": "off", + "blinking": "terminal_controlled", + "copy_on_select": false, + "env": {}, + "font_family": null, + "font_features": null, + "font_size": null, + "option_as_meta": false, + "shell": {}, + "working_directory": "current_project_directory" +} +``` + +### Alternate Scroll + +- Description: Set whether Alternate Scroll mode (DECSET code: `?1007`) is active by default. Alternate Scroll mode converts mouse scroll events into up / down key presses when in the alternate screen (e.g. when running applications like vim or less). The terminal can still set and unset this mode with ANSI escape codes. +- Setting: `alternate_scroll` +- Default: `off` + +**Options** + +1. Default alternate scroll mode to on + +```json +{ + "alternate_scroll": "on" +} +``` + +2. Default alternate scroll mode to off + +```json +{ + "alternate_scroll": "off" +} +``` + +### Blinking + +- Description: Set the cursor blinking behavior in the terminal +- Setting: `blinking` +- Default: `terminal_controlled` + +**Options** + +1. Never blink the cursor, ignore the terminal mode + +```json +{ + "blinking": "off" +} +``` + +2. Default the cursor blink to off, but allow the terminal to turn blinking on + +```json +{ + "blinking": "terminal_controlled" +} +``` + +3. Always blink the cursor, ignore the terminal mode + +```json +"blinking": "on", +``` + +### Copy On Select + +- Description: Whether or not selecting text in the terminal will automatically copy to the system clipboard. +- Setting: `copy_on_select` +- Default: `false` + +**Options** + +`boolean` values + +### Env + +- Description: Any key-value pairs added to this object will be added to the terminal's environment. Keys must be unique, use `:` to separate multiple values in a single variable +- Setting: `env` +- Default: `{}` + +**Example** + +```json +"env": { + "ZED": "1", + "KEY": "value1:value2" +} +``` + +### Font Size + +- Description: What font size to use for the terminal. When not set defaults to matching the editor's font size +- Setting: `font_size` +- Default: `null` + +**Options** + +`integer` values + +### Font Family + +- Description: What font to use for the terminal. When not set, defaults to matching the editor's font. +- Setting: `font_family` +- Default: `null` + +**Options** + +The name of any font family installed on the user's system + +### Font Features + +- Description: What font features to use for the terminal. When not set, defaults to matching the editor's font features. +- Setting: `font_features` +- Default: `null` + +**Options** + +See Buffer Font Features + +### Option As Meta + +- Description: Re-interprets the option keys to act like a 'meta' key, like in Emacs. +- Setting: `option_as_meta` +- Default: `true` + +**Options** + +`boolean` values + +### Shell + +- Description: What shell to use when launching the terminal. +- Setting: `shell` +- Default: `system` + +**Options** + +1. Use the system's default terminal configuration (usually the `/etc/passwd` file). + +```json +{ + "shell": "system" +} +``` + +2. A program to launch: + +```json +"shell": { + "program": "sh" +} +``` + +3. A program with arguments: + +```json +"shell": { + "with_arguments": { + "program": "/bin/bash", + "args": ["--login"] + } +} +``` + +### Working Directory + +- Description: What working directory to use when launching the terminal. +- Setting: `working_directory` +- Default: `"current_project_directory"` + +**Options** + +1. Use the current file's project directory. Will Fallback to the first project directory strategy if unsuccessful + +```json +{ + "working_directory": "current_project_directory" +} +``` + +2. Use the first project in this workspace's directory. Will fallback to using this platform's home directory. + +```json +{ + "working_directory": "first_project_directory" +} +``` + +3. Always use this platform's home directory (if we can find it) + +```json +{ + "working_directory": "always_home" +} +``` + +4. Always use a specific directory. This value will be shell expanded. If this path is not a valid directory the terminal will default to this platform's home directory. + +```json +"working_directory": { + "always": { + "directory": "~/zed/projects/" + } +} +``` + +## Theme + +- Description: The name of the Zed theme to use for the UI. +- Setting: `theme` +- Default: `One Dark` + +**Options** + +Run the `theme selector: toggle` action in the command palette to see a current list of valid themes names. + +## Vim + +- Description: Whether or not to enable vim mode (work in progress). +- Setting: `vim_mode` +- Default: `false` + +## Project Panel + +- Description: Customise project panel +- Setting: `project_panel` +- Default: + +```json +"project_panel": { + "dock": "left", + "git_status": true, + "default_width": "N/A - width in pixels" +}, +``` + +### Dock + +- Description: Control the position of the dock +- Setting: `dock` +- Default: `left` + +**Options** + +1. Default dock position to left + +```json +{ + "dock": "left" +} +``` + +2. Default dock position to right + +```json +{ + "dock": "right" +} +``` + +### Git Status + +- Description: Indicates newly created and updated files +- Setting: `git_status` +- Default: `true` + +1. Default enable git status + +```json +{ + "git_status": true +} +``` + +2. Default disable git status + +```json +{ + "git_status": false +} +``` + +### Default Width +- Description: Customise default width taken by project panel +- Setting: `default_width` +- Default: N/A width in pixels (eg: 420) + +**Options** + +`boolean` values + +## An example configuration: + +```json +// ~/.config/zed/settings.json +{ + "theme": "cave-light", + "tab_size": 2, + "preferred_line_length": 80, + "soft_wrap": "none", + + "buffer_font_size": 18, + "buffer_font_family": "Zed Mono", + + "autosave": "on_focus_change", + "format_on_save": "off", + "vim_mode": false, + "projects_online_by_default": true, + "terminal": { + "font_family": "FiraCode Nerd Font Mono", + "blinking": "off" + }, + "language_overrides": { + "C": { + "format_on_save": "language_server", + "preferred_line_length": 64, + "soft_wrap": "preferred_line_length" + } + } +} +``` diff --git a/docs/src/configuring_zed__configuring_vim.md b/docs/src/configuring_zed__configuring_vim.md new file mode 100644 index 0000000000000000000000000000000000000000..ddef07e3c28f8e2d2e3452d1e586f57656fbff91 --- /dev/null +++ b/docs/src/configuring_zed__configuring_vim.md @@ -0,0 +1,170 @@ +# Vim Mode + +Zed includes a vim emulation layer known as “vim mode”. This document aims to describe how it works, and how to make the most out of it. + +### Philosophy +Vim mode in Zed is supposed to primarily "do what you expect": it mostly tries to copy vim exactly, but will use Zed-specific functionality when available to make things smoother. + +This means Zed will never be 100% vim compatible, but should be 100% vim familiar! We expect that our vim mode already copes with 90% of your workflow, and we'd like to keep improving it. If you find things that you can’t yet do in vim mode, but which you rely on in your current workflow, please leave feedback in the editor itself (`:feedback`), or [file an issue](https://github.com/zed-industries/community). + +### Zed-specific features +Zed is built on a modern foundation that (among other things) uses tree-sitter to understand the content of the file you're editing, and supports multiple cursors out of the box. + +Vim mode has several "core Zed" key bindings, that will help you make the most of Zed's specific feature set. +``` +# Normal mode +g d Go to definition +g D Go to type definition +c d Rename (change definition) +g A Go to All references to the current word + +g Open the current search excerpt in its own tab + +g s Find symbol in current file +g S Find symbol in entire project + +g n Add a visual selection for the next copy of the current word +g N The same, but backwards +g > Skip latest word selection, and add next. +g < The same, but backwards +g a Add a visual selection for every copy of the current word + +g h Show inline error (hover) + +# Insert mode +ctrl-x ctrl-o Open the completion menu +ctrl-x ctrl-c Request Github Copilot suggestion (if configured) +ctrl-x ctrl-a Open the inline AI assistant (if configured) +ctrl-x ctrl-l Open the LSP code actions +ctrl-x ctrl-z Hides all suggestions +``` + +Vim mode uses Zed to define concepts like "brackets" (for the `%` key) and "words" (for motions like `w` and `e`). This does lead to some differences, but they are mostly positive. For example `%` considers `|` to be a bracket in languages like Rust; and `w` considers `$` to be a word-character in languages like Javascript. + +Vim mode emulates visual block mode using Zed's multiple cursor support. This again leads to some differences, but is much more powerful. + +Finally, Vim mode's search and replace functionality is backed by Zed's. This means that the pattern syntax is slightly different, see the section on [Regex differences](#regex-differences) for details. + +### Custom key bindings +Zed does not yet have an equivalent to vim’s `map` command to convert one set of keystrokes into another, however you can bind any sequence of keys to fire any Action documented in the [Key bindings documentation](https://docs.zed.dev/configuration/key-bindings). + +You can edit your personal key bindings with `:keymap`. +For vim-specific shortcuts, you may find the following template a good place to start: + +```json +[ + { + "context": "Editor && VimControl && !VimWaiting && !menu", + "bindings": { + // put key-bindings here if you want them to work in normal & visual mode + } + }, + { + "context": "Editor && vim_mode == normal && !VimWaiting && !menu", + "bindings": { + // put key-bindings here if you want them to work only in normal mode + } + }, + { + "context": "Editor && vim_mode == visual && !VimWaiting && !menu", + "bindings": { + // visual, visual line & visual block modes + } + }, + { + "context": "Editor && vim_mode == insert && !menu", + "bindings": { + // put key-bindings here if you want them to work in insert mode + } + } +] +``` + +You can see the bindings that are enabled by default in vim mode [here](https://zed.dev/ref/vim.json). + +The details of the context are a little out of scope for this doc, but suffice to say that `menu` is true when a menu is open (e.g. the completions menu), `VimWaiting` is true after you type `f` or `t` when we’re waiting for a new key (and you probably don’t want bindings to happen). Please reach out on [Github](https://github.com/zed-industries/community) if you want help making a key bindings work. + +### Command palette + +Vim mode allows you to enable Zed’s command palette with `:`. This means that you can use vim's command palette to run any action that Zed supports. + +Additionally vim mode contains a number of aliases for popular vim commands to ensure that muscle memory works. For example `:w` will save the file. + +We do not (yet) emulate the full power of vim’s command line, in particular we special case specific patterns instead of using vim's range selection syntax, and we do not support arguments to commands yet. Please reach out on [Github](https://github.com/zed-industries/community) as you find things that are missing from the command palette. + +As mentioned above, one thing to be aware of is that the regex engine is slightly different from vim's in `:%s/a/b`. + +Currently supported vim-specific commands (as of Zed 0.106): +``` +# window management +:w[rite][!], :wq[!], :q[uit][!], :wa[ll][!], :wqa[ll][!], :qa[ll][!], :[e]x[it][!], :up[date] + to save/close tab(s) and pane(s) (no filename is supported yet) +:cq + to quit completely. +:vs[plit], :sp[lit] + to split vertically/horizontally (no filename is supported yet) +:new, :vne[w] + to create a new file in a new pane above or to the left +:tabedit, :tabnew + to create a new file in a new tab. +:tabn[ext], :tabp[rev] + to go to previous/next tabs +:tabc[lose] + to close the current tab + +# navigating diagnostics +:cn[ext], :cp[rev], :ln[ext], :lp[rev] + to go to the next/prev diagnostics +:cc, :ll + to open the errors page + +# jump to position +: + to jump to a line number +:$ + to jump to the end of the file +:/foo and :?foo + to jump to next/prev line matching foo + +# replacement +:%s/foo/bar/ + to replace instances of foo with bar (/g is always assumed, the range must always be %, and Zed uses different regex syntax to vim) + +# editing +:j[oin] + to join the current line (no range is yet supported) +:d[elete][l][p] + to delete the current line (no range is yet supported) +:s[ort] [i] + to sort the current selection (with i, case-insensitively) +``` + + +### Related settings +There are a few Zed settings that you may also enjoy if you use vim mode: +``` +{ + // disable cursor blink + "cursor_blink": false + // use relative line numbers + "relative_line_numbers": true, + // hide the scroll bar + "scrollbar": {"show": "never"}, +} +``` + +### Regex differences + +Zed uses a different regular expression engine from Vim. This means that you will have to use a different syntax for some things. + +Notably: +* Vim uses `\(` and `\)` to represent capture groups, in Zed these are `(` and `)`. +* On the flip side, `(` and `)` represent literal parentheses, but in Zed these must be escaped to `\(` and `\)`. +* When replacing, Vim uses `\0` to represent the entire match, in Zed this is `$0`, same for numbered capture groups `\1` -> `$1`. +* Vim uses `\<` and `\>` to represent word boundaries, in Zed these are both handled by `\b` +* Vim uses `/g` to indicate "all matches on one line", in Zed this is implied +* Vim uses `/i` to indicate "case-insensitive", in Zed you can either use `(?i)` at the start of the pattern or toggle case-sensitivity with `cmd-option-c`. + +To help with the transition, the command palette will fix parentheses and replace groups for you when you run `:%s//`. So `%s:/\(a\)(b)/\1/` will be converted into a search for "(a)\(b\)" and a replacement of "$1". + +For the full syntax supported by Zed's regex engine see the [regex crate documentation](https://docs.rs/regex/latest/regex/#syntax). diff --git a/docs/src/developing_zed__adding_languages.md b/docs/src/developing_zed__adding_languages.md new file mode 100644 index 0000000000000000000000000000000000000000..2917b08422c1e2153a38f5c857a9318a9228c031 --- /dev/null +++ b/docs/src/developing_zed__adding_languages.md @@ -0,0 +1,83 @@ +# Adding New Languages to Zed + +## LSP + +Zed uses the [Language Server Protocol](https://microsoft.github.io/language-server-protocol/) to provide language support. This means, in theory, we can support any language that has an LSP server. + +## Syntax Highlighting + +### Defining syntax highlighting rules + +We use tree-sitter queries to match certian properties to highlight. + +#### Simple Example: + +```scheme +(property_identifier) @property +``` + +```ts +const font: FontFamily = { + weight: "normal", + underline: false, + italic: false, +} +``` + +Match a property identifier and highlight it using the identifier `@property`. In the above example, `weight`, `underline`, and `italic` would be highlighted. + +#### Complex example: + +```scheme +(_ + return_type: (type_annotation + [ + (type_identifier) @type.return + (generic_type + name: (type_identifier) @type.return) + ])) +``` + +```ts +function buildDefaultSyntax(colorScheme: Theme): Partial { + // ... +} +``` + +Match a function return type, and highlight the type using the identifier `@type.return`. In the above example, `Partial` would be highlighted. + +#### Example - Typescript + +Here is an example portion of our `highlights.scm` for TypeScript: + +```scheme +; crates/zed/src/languages/typescript/highlights.scm + +; Variables + +(identifier) @variable + +; Properties + +(property_identifier) @property + +; Function and method calls + +(call_expression + function: (identifier) @function) + +(call_expression + function: (member_expression + property: (property_identifier) @function.method)) + +; Function and method definitions + +(function + name: (identifier) @function) +(function_declaration + name: (identifier) @function) +(method_definition + name: (property_identifier) @function.method) + +; ... +``` diff --git a/docs/src/developing_zed__building_zed.md b/docs/src/developing_zed__building_zed.md new file mode 100644 index 0000000000000000000000000000000000000000..cb30051ffa19f551b46d6ddefdbf981077cb9fed --- /dev/null +++ b/docs/src/developing_zed__building_zed.md @@ -0,0 +1,107 @@ +# Building Zed + +🚧 TODO: +- [ ] Tidy up & update instructions +- [ ] Remove ZI-specific things +- [ ] Rework any steps that currently require a ZI-specific account + +How to build Zed from source for the first time. + +## Prerequisites + +- Be added to the GitHub organization +- Be added to the Vercel team + +## Process + +Expect this to take 30min to an hour! Some of these steps will take quite a while based on your connection speed, and how long your first build will be. + +1. Install the [GitHub CLI](https://cli.github.com/): + - `brew install gh` +1. Clone the `zed` repo + - `gh repo clone zed-industries/zed` +1. Install Xcode from the macOS App Store +1. Install Xcode command line tools + - `xcode-select --install` + - If xcode-select --print-path prints /Library/Developer/CommandLineTools… run `sudo xcode-select --switch /Applications/Xcode.app/Contents/Developer.` +1. Install [Postgres](https://postgresapp.com) +1. Install rust/rustup + - `curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh` +1. Install the wasm toolchain + - `rustup target add wasm32-wasi` +1. Install Livekit & Foreman + - `brew install livekit` + - `brew install foreman` +1. Generate an GitHub API Key + - Go to https://github.com/settings/tokens and Generate new token + - GitHub currently provides two kinds of tokens: + - Classic Tokens, where only `repo` (Full control of private repositories) OAuth scope has to be selected + Unfortunately, unselecting `repo` scope and selecting every its inner scope instead does not allow the token users to read from private repositories + - (not applicable) Fine-grained Tokens, at the moment of writing, did not allow any kind of access of non-owned private repos + - Keep the token in the browser tab/editor for the next two steps +1. (Optional but reccomended) Add your GITHUB_TOKEN to your `.zshrc` or `.bashrc` like this: `export GITHUB_TOKEN=yourGithubAPIToken` +1. Ensure the Zed.dev website is checked out in a sibling directory and install it's dependencies: + ``` + cd .. + git clone https://github.com/zed-industries/zed.dev + cd zed.dev && npm install + npm install -g vercel + ``` +1. Link your zed.dev project to Vercel + - `vercel link` + - Select the `zed-industries` team. If you don't have this get someone on the team to add you to it. + - Select the `zed.dev` project +1. Run `vercel pull` to pull down the environment variables and project info from Vercel +1. Open Postgres.app +1. From `./path/to/zed/`: + - Run: + - `GITHUB_TOKEN={yourGithubAPIToken} script/bootstrap` + - Replace `{yourGithubAPIToken}` with the API token you generated above. + - You don't need to include the GITHUB_TOKEN if you exported it above. + - Consider removing the token (if it's fine for you to recreate such tokens during occasional migrations) or store this token somewhere safe (like your Zed 1Password vault). + - If you get: + - ```bash + Error: Cannot install in Homebrew on ARM processor in Intel default prefix (/usr/local)! + Please create a new installation in /opt/homebrew using one of the + "Alternative Installs" from: + https://docs.brew.sh/Installation + ``` + - In that case try: + - `/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"` + - If Homebrew is not in your PATH: + - Replace `{username}` with your home folder name (usually your login name) + - `echo 'eval "$(/opt/homebrew/bin/brew shellenv)"' >> /Users/{username}/.zprofile` + - `eval "$(/opt/homebrew/bin/brew shellenv)"` +1. To run the Zed app: + - If you are working on zed: + - `cargo run` + - If you are just using the latest version, but not working on zed: + - `cargo run --release` + - If you need to run the collaboration server locally: + - `script/zed-local` + +## Troubleshooting + +### `error: failed to run custom build command for gpui v0.1.0 (/Users/path/to/zed)` + +- Try `xcode-select --switch /Applications/Xcode.app/Contents/Developer` + +### `xcrun: error: unable to find utility "metal", not a developer tool or in PATH` + +### Seeding errors during `script/bootstrap` runs + +``` +seeding database... +thread 'main' panicked at 'failed to deserialize github user from 'https://api.github.com/orgs/zed-industries/teams/staff/members': reqwest::Error { kind: Decode, source: Error("invalid type: map, expected a sequence", line: 1, column: 0) }', crates/collab/src/bin/seed.rs:111:10 +``` + +Wrong permissions for `GITHUB_TOKEN` token used, the token needs to be able to read from private repos. +For Classic GitHub Tokens, that required OAuth scope `repo` (seacrh the scope name above for more details) + +Same command + +`sudo xcode-select --switch /Applications/Xcode.app/Contents/Developer` + +### If you experience errors that mention some dependency is using unstable features + +Try `cargo clean` and `cargo build` diff --git a/docs/local-collaboration.md b/docs/src/developing_zed__local_collaboration.md similarity index 100% rename from docs/local-collaboration.md rename to docs/src/developing_zed__local_collaboration.md diff --git a/docs/src/feedback.md b/docs/src/feedback.md new file mode 100644 index 0000000000000000000000000000000000000000..11ae444079c05d9b2573e4c691ef88848ddd2fd7 --- /dev/null +++ b/docs/src/feedback.md @@ -0,0 +1,29 @@ +# Giving feedback + +### Community repository + +We track our issues at [`zed-industries/community`](https://github.com/zed-industries/community/issues). + +#### Feature requests + +Try to focus on the things that are most critical to you rather than exhaustively listing all features another editor you have used has. + +Command palette: `request feature` + +#### Bug reports + +Try to add as much detail as possible, if it is not obvious to reproduce. Let us know how severe the problem is for you; is the issue more of a minor inconvenience or something that would prevent you from using Zed? + +Command palette: `file bug report` + +### In-app feedback + +Anonymous feedback can be submitted from within Zed via the feedback editor (command palette: `give feedback`). + +### Zed forum + +Use the [community forum](https://github.com/zed-industries/community/discussions) to ask questions and learn from one another. We will be present in the forum and answering questions as well. + +### Email + +If you prefer to write up your thoughts as an email, you can send them to [hi@zed.dev](mailto:hi@zed.dev). diff --git a/docs/src/getting_started.md b/docs/src/getting_started.md new file mode 100644 index 0000000000000000000000000000000000000000..236249d00abf339e0cd291e1b0ec82b5447f8419 --- /dev/null +++ b/docs/src/getting_started.md @@ -0,0 +1,15 @@ +# Getting Started + +Welcome to Zed! We are excited to have you. Here is a jumping-off point to getting started. + +### Download Zed + +You can obtain the release build via the [download page](https://zed.dev/download). After the first manual installation, Zed will periodically check for and install updates automatically for you. + +### Configure Zed + +Use `CMD + ,` to open your custom settings to set things like fonts, formatting settings, per-language settings and more. You can access the default configuration using the `Zed > Settings > Open Default Settings` menu item. See Configuring Zed for all available settings. + +### Set up your key bindings + +You can access the default key binding set using the `Zed > Settings > Open Default Key Bindings` menu item. Use `CMD + K`,`CMD + S` to open your custom keymap to add your own key bindings. See Key Bindings for more info., diff --git a/docs/src/system_requirements.md b/docs/src/system_requirements.md new file mode 100644 index 0000000000000000000000000000000000000000..debf7fa2998b262e9ad07746e3732e433b448fe6 --- /dev/null +++ b/docs/src/system_requirements.md @@ -0,0 +1,13 @@ +# System Requirements + +## macOS + +Supported versions: Catalina (10.15) - Ventura (13.x). + +{% hint style="info" %} +The implementation of our screen sharing feature makes use of [LiveKit](https://livekit.io). The LiveKit SDK requires macOS Catalina (10.15); consequently, in v0.62.4, we dropped support for earlier macOS versions that we were initially supporting. +{% endhint %} + +## Linux, Windows, and Web + +_Not supported at this time. See our_ [_Platform Support_](https://github.com/zed-industries/community/issues/174) _issue._ diff --git a/docs/src/telemetry.md b/docs/src/telemetry.md new file mode 100644 index 0000000000000000000000000000000000000000..834e02770aee030dcbf33c419ba6a8848de65024 --- /dev/null +++ b/docs/src/telemetry.md @@ -0,0 +1,147 @@ +# Telemetry in Zed + +**Up to date with v0.112.0** + +Zed collects anonymous telemetry data to help the team understand how people are using the application and to see what sort of issues they are experiencing. + +## Dataflow + +Telemetry is sent from the application to zed.dev. Data is proxied through our servers to enable us to easily switch analytics services; we never store this data. The data is then sent off to various services: + +- [Datadog](https://www.datadoghq.com): Cloud-monitoring service - stores diagnostic events +- [Clickhouse](https://clickhouse.com): Business Intelligence platform - stores both diagnostic and metric events +- [Metabase](https://www.metabase.com): Dashboards - dashboards built around data pulled from Clickhouse + +## Types of Telemetry + +### Diagnostics + +Diagnostic events include debug information (stack traces) from crash reports. Reports are sent on the first application launch after the crash occurred. We've built dashboards that allow us to visualize the frequency and severity of issues experienced by users. Having these reports sent automatically allows us to begin implementing fixes without the user needing to file a report in our issue tracker. The plots in the dashboards also give us an informal measurement of the stability of Zed. + +When a panic occurs, the following data is sent: + +#### PanicRequest + +- `panic`: The panic data +- `token`: An identifier that is used to authenticate the request on zed.dev + +#### Panic + +- `thread`: The name of the thread that panicked +- `payload`: The panic message +- `location_data`: The location of the panic + - `file` + - `line` +- `backtrace`: The backtrace of the panic +- `app_version`: Zed's app version +- `release_channel`: Zed's release channel + - `stable` + - `preview` + - `dev` +- `os_name`: The name of your operating system +- `os_version`: The version of your operating system +- `architecture`: The architecture of your CPU +- `panicked_on`: The time that the panic occurred +- `installation_id`: An identifier that is unique to each installation of Zed (this differs for stable, preview, and dev builds) +- `session_id`: An identifier that is unique to each Zed session (this differs for each time you open Zed) + +### Metrics + +Zed also collects metric information based on user actions. Metric events are reported over HTTPS, and requests are rate-limited to avoid using significant network bandwidth. All data remains anonymous, and can't be related to specific Zed users. + +The following data is sent: + +#### ClickhouseEventRequestBody + +- `token`: An identifier that is used to authenticate the request on zed.dev +- `installation_id`: An identifier that is unique to each installation of Zed (this differs for stable, preview, and dev builds) +- `session_id`: An identifier that is unique to each Zed session (this differs for each time you open Zed) +- `is_staff`: A boolean that indicates whether the user is a member of the Zed team or not +- `app_version`: Zed's app version +- `os_name`: The name of your operating system +- `os_version`: The version of your operating system +- `architecture`: The architecture of your CPU +- `release_channel`: Zed's release channel + - `stable` + - `preview` + - `dev` +- `events`: A vector of `ClickhouseEventWrapper`s + +#### ClickhouseEventWrapper + +- `signed_in`: A boolean that indicates whether the user is signed in or not +- `event`: An enum, where each variant can be one of the following `ClickhouseEvent` variants: + +#### ClickhouseEvent + +- `editor` + - `operation`: The editor operation that was performed + - `open` + - `save` + - `file_extension`: The extension of the file that was opened or saved + - `vim_mode`: A boolean that indicates whether the user is in vim mode or not + - `copilot_enabled`: A boolean that indicates whether the user has copilot enabled or not + - `copilot_enabled_for_language`: A boolean that indicates whether the user has copilot enabled for the language of the file that was opened or saved + - `milliseconds_since_first_event`: Duration of time between this event's timestamp and the timestamp of the first event in the current batch +- `copilot` + - `suggestion_id`: The ID of the suggestion + - `suggestion_accepted`: A boolean that indicates whether the suggestion was accepted or not + - `file_extension`: The file extension of the file that was opened or saved + - `milliseconds_since_first_event`: Same as above +- `call` + - `operation`: The call operation that was performed + - `accept incoming` + - `decline incoming` + - `disable microphone` + - `disable screen share` + - `enable microphone` + - `enable screen share` + - `hang up` + - `invite` + - `join channel` + - `open channel notes` + - `share project` + - `unshare project` + - `room_id`: The ID of the room + - `channel_id`: The ID of the channel + - `milliseconds_since_first_event`: Same as above +- `assistant` + - `conversation_id`: The ID of the conversation (for panel events only) + - `kind`: An enum with the following variants: + - `panel` + - `inline` + - `model`: The model that was used + - `milliseconds_since_first_event`: Same as above +- `cpu` + - `usage_as_percentage`: The CPU usage + - `core_count`: The number of cores on the CPU + - `milliseconds_since_first_event`: Same as above +- `memory` + - `memory_in_bytes`: The amount of memory used in bytes + - `virtual_memory_in_bytes`: The amount of virtual memory used in bytes + - `milliseconds_since_first_event`: Same as above +- `app` + - `operation`: The app operation that was performed + - `first open` + - `open` + - `close (only in GPUI2-powered Zed)` + - `milliseconds_since_first_event`: Same as above + +You can audit the metrics data that Zed has reported by running the command `zed: open telemetry log` from the command palette, or clicking `Help > View Telemetry Log` in the application menu. + +### Configuring Telemetry Settings + +You have full control over what data is sent out by Zed. To enable or disable some or all telemetry types, open your `settings.json` file via `zed: open settings` from the command palette. Insert and tweak the following: + +```json +"telemetry": { + "diagnostics": false, + "metrics": false +}, +``` + +The telemetry settings can also be configured via the `welcome` screen, which can be invoked via the `workspace: welcome` action in the command palette. + +### Concerns and Questions + +If you have concerns about telemetry, please feel free to open issues in our [community repository](https://github.com/zed-industries/community/issues/new/choose). diff --git a/docs/backend-development.md b/docs_old/backend-development.md similarity index 100% rename from docs/backend-development.md rename to docs_old/backend-development.md diff --git a/docs/building-zed.md b/docs_old/building-zed.md similarity index 100% rename from docs/building-zed.md rename to docs_old/building-zed.md diff --git a/docs/company-and-vision.md b/docs_old/company-and-vision.md similarity index 100% rename from docs/company-and-vision.md rename to docs_old/company-and-vision.md diff --git a/docs/design-tools.md b/docs_old/design-tools.md similarity index 100% rename from docs/design-tools.md rename to docs_old/design-tools.md diff --git a/docs/index.md b/docs_old/index.md similarity index 100% rename from docs/index.md rename to docs_old/index.md diff --git a/docs_old/local-collaboration.md b/docs_old/local-collaboration.md new file mode 100644 index 0000000000000000000000000000000000000000..4c059c0878b4df38a3450a5e4d44787ee10aaf0f --- /dev/null +++ b/docs_old/local-collaboration.md @@ -0,0 +1,22 @@ +# Local Collaboration + +## Setting up the local collaboration server + +### Setting up for the first time? + +1. Make sure you have livekit installed (`brew install livekit`) +1. Install [Postgres](https://postgresapp.com) and run it. +1. Then, from the root of the repo, run `script/bootstrap`. + +### Have a db that is out of date? / Need to migrate? + +1. Make sure you have livekit installed (`brew install livekit`) +1. Try `cd crates/collab && cargo run -- migrate` from the root of the repo. +1. Run `script/seed-db` + +## Testing collab locally + +1. Run `foreman start` from the root of the repo. +1. In another terminal run `script/zed-local -2`. +1. Two copies of Zed will open. Add yourself as a contact in the one that is not you. +1. Start a collaboration session as normal with any open project. diff --git a/docs/release-process.md b/docs_old/release-process.md similarity index 100% rename from docs/release-process.md rename to docs_old/release-process.md diff --git a/docs/theme/generating-theme-types.md b/docs_old/theme/generating-theme-types.md similarity index 100% rename from docs/theme/generating-theme-types.md rename to docs_old/theme/generating-theme-types.md diff --git a/docs/tools.md b/docs_old/tools.md similarity index 100% rename from docs/tools.md rename to docs_old/tools.md diff --git a/docs/zed/syntax-highlighting.md b/docs_old/zed/syntax-highlighting.md similarity index 100% rename from docs/zed/syntax-highlighting.md rename to docs_old/zed/syntax-highlighting.md From 5b3b15e95cb97553377e7cc0661fec145f9dd5a3 Mon Sep 17 00:00:00 2001 From: Nate Butler Date: Tue, 12 Dec 2023 09:10:12 -0500 Subject: [PATCH 04/21] Futher outline --- docs/src/CONTRIBUTING.md | 3 --- docs/src/SUMMARY.md | 17 ++++++++++++----- 2 files changed, 12 insertions(+), 8 deletions(-) delete mode 100644 docs/src/CONTRIBUTING.md diff --git a/docs/src/CONTRIBUTING.md b/docs/src/CONTRIBUTING.md deleted file mode 100644 index d48c26844f2ee079fedcbdda70ac83704abb9747..0000000000000000000000000000000000000000 --- a/docs/src/CONTRIBUTING.md +++ /dev/null @@ -1,3 +0,0 @@ -# Contributing - -TBD diff --git a/docs/src/SUMMARY.md b/docs/src/SUMMARY.md index 4c6f5f9421dcb7e6b8517085e0c30374a216632b..ad1cd6332c4a5200a66ff5767db3673abc88f921 100644 --- a/docs/src/SUMMARY.md +++ b/docs/src/SUMMARY.md @@ -7,12 +7,19 @@ - [Settings](./configuring_zed.md) - [Vim Mode](./configuring_zed__configuring_vim.md) -# Developing Zed +# Using Zed +- [Workflows]() +- [Collaboration]() +- [Using AI]() + +# Contributing to Zed +- [How to Contribute]() - [Building from Source](./developing_zed__building_zed.md) - [Local Collaboration](./developing_zed__local_collaboration.md) - [Adding Languages](./developing_zed__adding_languages.md) +- [Adding UI]() + +--- -# Other -- [Code of Conduct](./CODE_OF_CONDUCT.md) -- [Telemetry](./telemetry.md) -- [Contributing](./CONTRIBUTING.md) +[Telemetry](./telemetry.md) +[Code of Conduct](./CODE_OF_CONDUCT.md) From f9e7c796720834ec7c7da0622b5b8a4da34d8afe Mon Sep 17 00:00:00 2001 From: Nate Butler Date: Wed, 13 Dec 2023 10:35:03 -0500 Subject: [PATCH 05/21] Add deploy note --- docs/how-to-deploy.md | 8 ++++++++ {docs_old => docs/old}/backend-development.md | 0 {docs_old => docs/old}/building-zed.md | 0 {docs_old => docs/old}/company-and-vision.md | 0 {docs_old => docs/old}/design-tools.md | 0 {docs_old => docs/old}/index.md | 0 {docs_old => docs/old}/local-collaboration.md | 0 {docs_old => docs/old}/release-process.md | 0 {docs_old => docs/old}/theme/generating-theme-types.md | 0 {docs_old => docs/old}/tools.md | 0 {docs_old => docs/old}/zed/syntax-highlighting.md | 0 11 files changed, 8 insertions(+) create mode 100644 docs/how-to-deploy.md rename {docs_old => docs/old}/backend-development.md (100%) rename {docs_old => docs/old}/building-zed.md (100%) rename {docs_old => docs/old}/company-and-vision.md (100%) rename {docs_old => docs/old}/design-tools.md (100%) rename {docs_old => docs/old}/index.md (100%) rename {docs_old => docs/old}/local-collaboration.md (100%) rename {docs_old => docs/old}/release-process.md (100%) rename {docs_old => docs/old}/theme/generating-theme-types.md (100%) rename {docs_old => docs/old}/tools.md (100%) rename {docs_old => docs/old}/zed/syntax-highlighting.md (100%) diff --git a/docs/how-to-deploy.md b/docs/how-to-deploy.md new file mode 100644 index 0000000000000000000000000000000000000000..b1222aac5cddc196add7ea8020f59641df3b39eb --- /dev/null +++ b/docs/how-to-deploy.md @@ -0,0 +1,8 @@ +1. `cd docs` from repo root +1. Install the vercel cli if you haven't already + - `pnpm i -g vercel` +1. `vercel` to deploy if you already have the project linked +1. Otherwise, `vercel login` and `vercel` to link + - Choose Zed Industries as the team, then `zed-app-docs` as the project + +Someone can write a script for this when they have time. diff --git a/docs_old/backend-development.md b/docs/old/backend-development.md similarity index 100% rename from docs_old/backend-development.md rename to docs/old/backend-development.md diff --git a/docs_old/building-zed.md b/docs/old/building-zed.md similarity index 100% rename from docs_old/building-zed.md rename to docs/old/building-zed.md diff --git a/docs_old/company-and-vision.md b/docs/old/company-and-vision.md similarity index 100% rename from docs_old/company-and-vision.md rename to docs/old/company-and-vision.md diff --git a/docs_old/design-tools.md b/docs/old/design-tools.md similarity index 100% rename from docs_old/design-tools.md rename to docs/old/design-tools.md diff --git a/docs_old/index.md b/docs/old/index.md similarity index 100% rename from docs_old/index.md rename to docs/old/index.md diff --git a/docs_old/local-collaboration.md b/docs/old/local-collaboration.md similarity index 100% rename from docs_old/local-collaboration.md rename to docs/old/local-collaboration.md diff --git a/docs_old/release-process.md b/docs/old/release-process.md similarity index 100% rename from docs_old/release-process.md rename to docs/old/release-process.md diff --git a/docs_old/theme/generating-theme-types.md b/docs/old/theme/generating-theme-types.md similarity index 100% rename from docs_old/theme/generating-theme-types.md rename to docs/old/theme/generating-theme-types.md diff --git a/docs_old/tools.md b/docs/old/tools.md similarity index 100% rename from docs_old/tools.md rename to docs/old/tools.md diff --git a/docs_old/zed/syntax-highlighting.md b/docs/old/zed/syntax-highlighting.md similarity index 100% rename from docs_old/zed/syntax-highlighting.md rename to docs/old/zed/syntax-highlighting.md From 70c6660ae4f7d0c2a70218022509bc4c1d77e4f1 Mon Sep 17 00:00:00 2001 From: Nate Butler Date: Wed, 13 Dec 2023 10:35:54 -0500 Subject: [PATCH 06/21] Add note --- docs/how-to-deploy.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/how-to-deploy.md b/docs/how-to-deploy.md index b1222aac5cddc196add7ea8020f59641df3b39eb..c32d3619a6d12657843b43ee9083291faed1c4e1 100644 --- a/docs/how-to-deploy.md +++ b/docs/how-to-deploy.md @@ -1,3 +1,5 @@ +These docs are intendended to replace both docs.zed.dev and introduce people to how to build Zed from source. + 1. `cd docs` from repo root 1. Install the vercel cli if you haven't already - `pnpm i -g vercel` From a874a96e76b8cced2bc0fe5e108f35b813814c7c Mon Sep 17 00:00:00 2001 From: Marshall Bowers Date: Wed, 13 Dec 2023 11:44:51 -0500 Subject: [PATCH 07/21] Fix tab bar drop target sizing (#3627) This PR fixes an issue where the tab bar drop target was not receiving any size. The styling isn't 100% correct yet, as the updated background color has a gap around it. Release Notes: - N/A --- crates/workspace2/src/pane.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/crates/workspace2/src/pane.rs b/crates/workspace2/src/pane.rs index 20682451596f986e09665882014db6972ed68b19..afd7e665c4503e8492921206964d6a37b795b6f2 100644 --- a/crates/workspace2/src/pane.rs +++ b/crates/workspace2/src/pane.rs @@ -1664,6 +1664,10 @@ impl Pane { ) .child( div() + .min_w_6() + // HACK: This empty child is currently necessary to force the drop traget to appear + // despite us setting a min width above. + .child("") .h_full() .flex_grow() .drag_over::(|bar| { From ab8d0abbc142052779a9968c4d64c2c26d335cab Mon Sep 17 00:00:00 2001 From: Marshall Bowers Date: Wed, 13 Dec 2023 12:11:33 -0500 Subject: [PATCH 08/21] Wire up tooltips on tab bar actions (#3629) This PR wires up the tooltips on the actions in the tab bar. Release Notes: - N/A --- crates/workspace2/src/pane.rs | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/crates/workspace2/src/pane.rs b/crates/workspace2/src/pane.rs index afd7e665c4503e8492921206964d6a37b795b6f2..bcbadc4e532bcde153d4d70fc7044d51a490d44d 100644 --- a/crates/workspace2/src/pane.rs +++ b/crates/workspace2/src/pane.rs @@ -1597,7 +1597,8 @@ impl Pane { let view = cx.view().clone(); move |_, cx| view.update(cx, Self::navigate_backward) }) - .disabled(!self.can_navigate_backward()), + .disabled(!self.can_navigate_backward()) + .tooltip(|cx| Tooltip::for_action("Go Back", &GoBack, cx)), ) .start_child( IconButton::new("navigate_forward", Icon::ArrowRight) @@ -1606,7 +1607,8 @@ impl Pane { let view = cx.view().clone(); move |_, cx| view.update(cx, Self::navigate_backward) }) - .disabled(!self.can_navigate_forward()), + .disabled(!self.can_navigate_forward()) + .tooltip(|cx| Tooltip::for_action("Go Forward", &GoForward, cx)), ) .end_child( div() @@ -1625,7 +1627,8 @@ impl Pane { }) .detach(); this.new_item_menu = Some(menu); - })), + })) + .tooltip(|cx| Tooltip::text("New...", cx)), ) .when_some(self.new_item_menu.as_ref(), |el, new_item_menu| { el.child(Self::render_menu_overlay(new_item_menu)) @@ -1649,7 +1652,8 @@ impl Pane { }) .detach(); this.split_item_menu = Some(menu); - })), + })) + .tooltip(|cx| Tooltip::text("Split Pane", cx)), ) .when_some(self.split_item_menu.as_ref(), |el, split_item_menu| { el.child(Self::render_menu_overlay(split_item_menu)) From 48faa171b53e252a07e1f95c10603c9d6dd196e6 Mon Sep 17 00:00:00 2001 From: "Joseph T. Lyons" Date: Wed, 13 Dec 2023 12:24:10 -0500 Subject: [PATCH 09/21] v0.118.x dev --- Cargo.lock | 2 +- crates/zed/Cargo.toml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 033ff8b69c542ea96e5d3cac6d7d8320c4383946..cc4393bffa9e541330e6cf34c19b50b2e64e2a1c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -11882,7 +11882,7 @@ dependencies = [ [[package]] name = "zed" -version = "0.117.0" +version = "0.118.0" dependencies = [ "activity_indicator", "ai", diff --git a/crates/zed/Cargo.toml b/crates/zed/Cargo.toml index f665cc36dbdc8f4b0fa8576768efb32388d07374..0c115fb2850a07afc1d26b348c80d9816418c232 100644 --- a/crates/zed/Cargo.toml +++ b/crates/zed/Cargo.toml @@ -3,7 +3,7 @@ authors = ["Nathan Sobo "] description = "The fast, collaborative code editor." edition = "2021" name = "zed" -version = "0.117.0" +version = "0.118.0" publish = false [lib] From a91a42763f8abd5426059dfb1206e0239deba099 Mon Sep 17 00:00:00 2001 From: Piotr Osiewicz <24362066+osiewicz@users.noreply.github.com> Date: Wed, 13 Dec 2023 17:56:49 +0100 Subject: [PATCH 10/21] collab_ui: Wire up project picker Co-authored-by: Conrad --- crates/collab_ui2/src/collab_titlebar_item.rs | 111 ++++++++++-------- crates/picker2/src/picker2.rs | 23 ++-- .../recent_projects2/src/recent_projects.rs | 21 +++- 3 files changed, 95 insertions(+), 60 deletions(-) diff --git a/crates/collab_ui2/src/collab_titlebar_item.rs b/crates/collab_ui2/src/collab_titlebar_item.rs index 2b931f7085b55d868a428453040e6a905b1628dd..f48a78fb1d87dd1d69db7011c70e3c726f48d733 100644 --- a/crates/collab_ui2/src/collab_titlebar_item.rs +++ b/crates/collab_ui2/src/collab_titlebar_item.rs @@ -2,11 +2,13 @@ use crate::face_pile::FacePile; use call::{ActiveCall, ParticipantLocation, Room}; use client::{proto::PeerId, Client, ParticipantIndex, User, UserStore}; use gpui::{ - actions, canvas, div, point, px, rems, AppContext, Div, Element, Hsla, InteractiveElement, - IntoElement, Model, ParentElement, Path, Render, Stateful, StatefulInteractiveElement, Styled, - Subscription, ViewContext, VisualContext, WeakView, WindowBounds, + actions, canvas, div, overlay, point, px, rems, AppContext, DismissEvent, Div, Element, + FocusableView, Hsla, InteractiveElement, IntoElement, Model, Overlay, ParentElement, Path, + Render, Stateful, StatefulInteractiveElement, Styled, Subscription, ViewContext, VisualContext, + WeakView, WindowBounds, }; use project::{Project, RepositoryEntry}; +use recent_projects::RecentProjects; use std::sync::Arc; use theme::{ActiveTheme, PlayerColors}; use ui::{ @@ -14,7 +16,7 @@ use ui::{ IconButton, IconElement, KeyBinding, Tooltip, }; use util::ResultExt; -use workspace::{notifications::NotifyResultExt, Workspace}; +use workspace::{notifications::NotifyResultExt, Workspace, WORKSPACE_DB}; const MAX_PROJECT_NAME_LENGTH: usize = 40; const MAX_BRANCH_NAME_LENGTH: usize = 40; @@ -49,7 +51,7 @@ pub struct CollabTitlebarItem { client: Arc, workspace: WeakView, //branch_popover: Option>, - //project_popover: Option>, + project_popover: Option, //user_menu: ViewHandle, _subscriptions: Vec, } @@ -328,7 +330,7 @@ impl CollabTitlebarItem { // menu // }), // branch_popover: None, - // project_popover: None, + project_popover: None, _subscriptions: subscriptions, } } @@ -366,11 +368,27 @@ impl CollabTitlebarItem { let name = util::truncate_and_trailoff(name, MAX_PROJECT_NAME_LENGTH); - div().border().border_color(gpui::red()).child( - Button::new("project_name_trigger", name) - .style(ButtonStyle::Subtle) - .tooltip(move |cx| Tooltip::text("Recent Projects", cx)), - ) + div() + .border() + .border_color(gpui::red()) + .child( + Button::new("project_name_trigger", name) + .style(ButtonStyle::Subtle) + .tooltip(move |cx| Tooltip::text("Recent Projects", cx)) + .on_click(cx.listener(|this, _, cx| { + this.toggle_project_menu(&ToggleProjectMenu, cx); + })), + ) + .children(self.project_popover.as_ref().map(|popover| { + overlay().child( + div() + .min_w_56() + .on_mouse_down_out(cx.listener_for(&popover.picker, |picker, _, cx| { + picker.cancel(&Default::default(), cx) + })) + .child(popover.picker.clone()), + ) + })) } pub fn render_project_branch(&self, cx: &mut ViewContext) -> Option { @@ -611,43 +629,40 @@ impl CollabTitlebarItem { // cx.notify(); // } - // pub fn toggle_project_menu(&mut self, _: &ToggleProjectMenu, cx: &mut ViewContext) { - // let workspace = self.workspace.clone(); - // if self.project_popover.take().is_none() { - // cx.spawn(|this, mut cx| async move { - // let workspaces = WORKSPACE_DB - // .recent_workspaces_on_disk() - // .await - // .unwrap_or_default() - // .into_iter() - // .map(|(_, location)| location) - // .collect(); - - // let workspace = workspace.clone(); - // this.update(&mut cx, move |this, cx| { - // let view = cx.add_view(|cx| build_recent_projects(workspace, workspaces, cx)); - - // cx.subscribe(&view, |this, _, event, cx| { - // match event { - // PickerEvent::Dismiss => { - // this.project_popover = None; - // } - // } - - // cx.notify(); - // }) - // .detach(); - // cx.focus(&view); - // this.branch_popover.take(); - // this.project_popover = Some(view); - // cx.notify(); - // }) - // .log_err(); - // }) - // .detach(); - // } - // cx.notify(); - // } + pub fn toggle_project_menu(&mut self, _: &ToggleProjectMenu, cx: &mut ViewContext) { + let workspace = self.workspace.clone(); + if self.project_popover.take().is_none() { + cx.spawn(|this, mut cx| async move { + let workspaces = WORKSPACE_DB + .recent_workspaces_on_disk() + .await + .unwrap_or_default() + .into_iter() + .map(|(_, location)| location) + .collect(); + + let workspace = workspace.clone(); + this.update(&mut cx, move |this, cx| { + let view = RecentProjects::open_popover(workspace, workspaces, cx); + + cx.subscribe(&view.picker, |this, _, _: &DismissEvent, cx| { + this.project_popover = None; + cx.notify(); + }) + .detach(); + let focus_handle = view.focus_handle(cx); + cx.focus(&focus_handle); + // todo!() + //this.branch_popover.take(); + this.project_popover = Some(view); + cx.notify(); + }) + .log_err(); + }) + .detach(); + } + cx.notify(); + } // fn render_user_menu_button( // &self, diff --git a/crates/picker2/src/picker2.rs b/crates/picker2/src/picker2.rs index 98b6ce5ff099326943feb2009f9e7f27a9d43d62..db5eebff5389a1f3bd9f0561a017fcb109ec904e 100644 --- a/crates/picker2/src/picker2.rs +++ b/crates/picker2/src/picker2.rs @@ -1,8 +1,8 @@ use editor::Editor; use gpui::{ - div, prelude::*, rems, uniform_list, AnyElement, AppContext, Div, FocusHandle, FocusableView, - MouseButton, MouseDownEvent, Render, Task, UniformListScrollHandle, View, ViewContext, - WindowContext, + div, prelude::*, rems, uniform_list, AnyElement, AppContext, DismissEvent, Div, EventEmitter, + FocusHandle, FocusableView, MouseButton, MouseDownEvent, Render, Task, UniformListScrollHandle, + View, ViewContext, WindowContext, }; use std::{cmp, sync::Arc}; use ui::{prelude::*, v_stack, Color, Divider, Label}; @@ -113,8 +113,9 @@ impl Picker { cx.notify(); } - fn cancel(&mut self, _: &menu::Cancel, cx: &mut ViewContext) { + pub fn cancel(&mut self, _: &menu::Cancel, cx: &mut ViewContext) { self.delegate.dismissed(cx); + cx.emit(DismissEvent); } fn confirm(&mut self, _: &menu::Confirm, cx: &mut ViewContext) { @@ -146,9 +147,15 @@ impl Picker { event: &editor::EditorEvent, cx: &mut ViewContext, ) { - if let editor::EditorEvent::BufferEdited = event { - let query = self.editor.read(cx).text(cx); - self.update_matches(query, cx); + match event { + editor::EditorEvent::BufferEdited => { + let query = self.editor.read(cx).text(cx); + self.update_matches(query, cx); + } + editor::EditorEvent::Blurred => { + self.cancel(&menu::Cancel, cx); + } + _ => {} } } @@ -189,6 +196,8 @@ impl Picker { } } +impl EventEmitter for Picker {} + impl Render for Picker { type Element = Div; diff --git a/crates/recent_projects2/src/recent_projects.rs b/crates/recent_projects2/src/recent_projects.rs index e0147836876bf47a431fae5344911abd65d96292..dff6aa12ccc30f43766451d244619159c2a7c8bb 100644 --- a/crates/recent_projects2/src/recent_projects.rs +++ b/crates/recent_projects2/src/recent_projects.rs @@ -23,14 +23,15 @@ pub fn init(cx: &mut AppContext) { cx.observe_new_views(RecentProjects::register).detach(); } +#[derive(Clone)] pub struct RecentProjects { - picker: View>, + pub picker: View>, } impl ModalView for RecentProjects {} impl RecentProjects { - fn new(delegate: RecentProjectsDelegate, cx: &mut ViewContext) -> Self { + fn new(delegate: RecentProjectsDelegate, cx: &mut WindowContext<'_>) -> Self { Self { picker: cx.build_view(|cx| Picker::new(delegate, cx)), } @@ -86,6 +87,16 @@ impl RecentProjects { Ok(()) })) } + pub fn open_popover( + workspace: WeakView, + workspaces: Vec, + cx: &mut WindowContext<'_>, + ) -> Self { + Self::new( + RecentProjectsDelegate::new(workspace, workspaces, false), + cx, + ) + } } impl EventEmitter for RecentProjects {} @@ -127,7 +138,7 @@ impl RecentProjectsDelegate { } } } - +impl EventEmitter for RecentProjectsDelegate {} impl PickerDelegate for RecentProjectsDelegate { type ListItem = ListItem; @@ -202,11 +213,11 @@ impl PickerDelegate for RecentProjectsDelegate { .open_workspace_for_paths(workspace_location.paths().as_ref().clone(), cx) }) .detach_and_log_err(cx); - self.dismissed(cx); + cx.emit(DismissEvent); } } - fn dismissed(&mut self, _cx: &mut ViewContext>) {} + fn dismissed(&mut self, _: &mut ViewContext>) {} fn render_match( &self, From 72eef116c965f49ead482b1cc765a580c50cd191 Mon Sep 17 00:00:00 2001 From: Piotr Osiewicz <24362066+osiewicz@users.noreply.github.com> Date: Wed, 13 Dec 2023 17:58:17 +0100 Subject: [PATCH 11/21] fixup! collab_ui: Wire up project picker --- crates/collab_ui2/src/collab_titlebar_item.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/collab_ui2/src/collab_titlebar_item.rs b/crates/collab_ui2/src/collab_titlebar_item.rs index f48a78fb1d87dd1d69db7011c70e3c726f48d733..3d8fedd06bb363c4efacd4e6458b6e796a366f94 100644 --- a/crates/collab_ui2/src/collab_titlebar_item.rs +++ b/crates/collab_ui2/src/collab_titlebar_item.rs @@ -3,8 +3,8 @@ use call::{ActiveCall, ParticipantLocation, Room}; use client::{proto::PeerId, Client, ParticipantIndex, User, UserStore}; use gpui::{ actions, canvas, div, overlay, point, px, rems, AppContext, DismissEvent, Div, Element, - FocusableView, Hsla, InteractiveElement, IntoElement, Model, Overlay, ParentElement, Path, - Render, Stateful, StatefulInteractiveElement, Styled, Subscription, ViewContext, VisualContext, + FocusableView, Hsla, InteractiveElement, IntoElement, Model, ParentElement, Path, Render, + Stateful, StatefulInteractiveElement, Styled, Subscription, ViewContext, VisualContext, WeakView, WindowBounds, }; use project::{Project, RepositoryEntry}; From 26a31b41b96d56815c581b587d381d632e9cf85b Mon Sep 17 00:00:00 2001 From: Max Brunsfeld Date: Wed, 13 Dec 2023 13:02:19 -0800 Subject: [PATCH 12/21] frame time --- crates/gpui2/src/window.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/crates/gpui2/src/window.rs b/crates/gpui2/src/window.rs index 77eb4e27be20bd734c27258a00fd05eaeff35caf..a0db7d6d9e8d26f6c7cc848860e3779d66ed0669 100644 --- a/crates/gpui2/src/window.rs +++ b/crates/gpui2/src/window.rs @@ -1236,6 +1236,8 @@ impl<'a> WindowContext<'a> { /// Draw pixels to the display for this window based on the contents of its scene. pub(crate) fn draw(&mut self) -> Scene { + let t0 = std::time::Instant::now(); + let window_was_focused = self .window .focus @@ -1326,6 +1328,7 @@ impl<'a> WindowContext<'a> { } self.window.dirty = false; + eprintln!("frame: {:?}", t0.elapsed()); scene } From 1e4a7e6ef18e765fc30303e2ec7176a61a1d8b72 Mon Sep 17 00:00:00 2001 From: Nathan Sobo Date: Wed, 13 Dec 2023 16:01:49 -0700 Subject: [PATCH 13/21] Don't notify when drawing --- crates/gpui2/src/window.rs | 20 ++++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-) diff --git a/crates/gpui2/src/window.rs b/crates/gpui2/src/window.rs index a0db7d6d9e8d26f6c7cc848860e3779d66ed0669..d0056617edea93099a40e2f1df30921eae867497 100644 --- a/crates/gpui2/src/window.rs +++ b/crates/gpui2/src/window.rs @@ -237,6 +237,7 @@ pub struct Window { bounds_observers: SubscriberSet<(), AnyObserver>, active: bool, pub(crate) dirty: bool, + pub(crate) drawing: bool, activation_observers: SubscriberSet<(), AnyObserver>, pub(crate) last_blur: Option>, pub(crate) focus: Option, @@ -371,6 +372,7 @@ impl Window { bounds_observers: SubscriberSet::new(), active: false, dirty: false, + drawing: false, activation_observers: SubscriberSet::new(), last_blur: None, focus: None, @@ -422,7 +424,9 @@ impl<'a> WindowContext<'a> { /// Mark the window as dirty, scheduling it to be redrawn on the next frame. pub fn notify(&mut self) { - self.window.dirty = true; + if !self.window.drawing { + self.window.dirty = true; + } } /// Close this window. @@ -1237,6 +1241,8 @@ impl<'a> WindowContext<'a> { /// Draw pixels to the display for this window based on the contents of its scene. pub(crate) fn draw(&mut self) -> Scene { let t0 = std::time::Instant::now(); + self.window.dirty = false; + self.window.drawing = true; let window_was_focused = self .window @@ -1327,7 +1333,7 @@ impl<'a> WindowContext<'a> { self.platform.set_cursor_style(cursor_style); } - self.window.dirty = false; + self.window.drawing = false; eprintln!("frame: {:?}", t0.elapsed()); scene @@ -2346,10 +2352,12 @@ impl<'a, V: 'static> ViewContext<'a, V> { } pub fn notify(&mut self) { - self.window_cx.notify(); - self.window_cx.app.push_effect(Effect::Notify { - emitter: self.view.model.entity_id, - }); + if !self.window.drawing { + self.window_cx.notify(); + self.window_cx.app.push_effect(Effect::Notify { + emitter: self.view.model.entity_id, + }); + } } pub fn observe_window_bounds( From c863227dc2f84a7bd6285963d8377b3772c70322 Mon Sep 17 00:00:00 2001 From: Nathan Sobo Date: Wed, 13 Dec 2023 18:44:21 -0700 Subject: [PATCH 14/21] Log frame timings --- crates/gpui2/src/platform/mac/metal_renderer.rs | 6 ++++++ crates/gpui2/src/view.rs | 6 ++++++ crates/gpui2/src/window.rs | 2 +- 3 files changed, 13 insertions(+), 1 deletion(-) diff --git a/crates/gpui2/src/platform/mac/metal_renderer.rs b/crates/gpui2/src/platform/mac/metal_renderer.rs index c477440df5d888658e96c8e9d4d3f7e70d214679..3210a53c634e81e5410e732c2971c86a553c808f 100644 --- a/crates/gpui2/src/platform/mac/metal_renderer.rs +++ b/crates/gpui2/src/platform/mac/metal_renderer.rs @@ -187,6 +187,8 @@ impl MetalRenderer { } pub fn draw(&mut self, scene: &Scene) { + let start = std::time::Instant::now(); + let layer = self.layer.clone(); let viewport_size = layer.drawable_size(); let viewport_size: Size = size( @@ -303,6 +305,10 @@ impl MetalRenderer { command_buffer.commit(); self.sprite_atlas.clear_textures(AtlasTextureKind::Path); + + let duration_since_start = start.elapsed(); + println!("renderer draw: {:?}", duration_since_start); + command_buffer.wait_until_completed(); drawable.present(); } diff --git a/crates/gpui2/src/view.rs b/crates/gpui2/src/view.rs index 280c52df2afad19af029a75e336222eae82aa74e..46a90864783b0e8933731a275704cd1ce9dd4d32 100644 --- a/crates/gpui2/src/view.rs +++ b/crates/gpui2/src/view.rs @@ -209,8 +209,14 @@ impl AnyView { ) { cx.with_absolute_element_offset(origin, |cx| { let (layout_id, rendered_element) = (self.layout)(self, cx); + let start_time = std::time::Instant::now(); cx.compute_layout(layout_id, available_space); + let duration = start_time.elapsed(); + println!("compute layout: {:?}", duration); + let start_time = std::time::Instant::now(); (self.paint)(self, rendered_element, cx); + let duration = start_time.elapsed(); + println!("paint: {:?}", duration); }) } } diff --git a/crates/gpui2/src/window.rs b/crates/gpui2/src/window.rs index d0056617edea93099a40e2f1df30921eae867497..4624bcf20bbc1829c0f6d0cde24c1948d88d1ce0 100644 --- a/crates/gpui2/src/window.rs +++ b/crates/gpui2/src/window.rs @@ -1334,7 +1334,7 @@ impl<'a> WindowContext<'a> { } self.window.drawing = false; - eprintln!("frame: {:?}", t0.elapsed()); + eprintln!("window draw: {:?}", t0.elapsed()); scene } From 6f17cf73370c4482ff7a0ad63bac00ffce45d5b0 Mon Sep 17 00:00:00 2001 From: Nathan Sobo Date: Thu, 14 Dec 2023 09:25:09 -0700 Subject: [PATCH 15/21] WIP --- crates/gpui2/src/elements/div.rs | 16 +++++++-------- crates/gpui2/src/view.rs | 5 +++++ crates/gpui2/src/window.rs | 34 ++++++++++++++++++++++++-------- debug.plist | 8 ++++++++ 4 files changed, 47 insertions(+), 16 deletions(-) create mode 100644 debug.plist diff --git a/crates/gpui2/src/elements/div.rs b/crates/gpui2/src/elements/div.rs index a102c71a6fbc1d8d0dbc0b2d984efcbdbc677276..5ae051644af2212f28ab4b6aaea8bed4f2789d0b 100644 --- a/crates/gpui2/src/elements/div.rs +++ b/crates/gpui2/src/elements/div.rs @@ -778,28 +778,28 @@ impl Interactivity { }); } - for listener in self.mouse_down_listeners.drain(..) { + for listener in self.mouse_down_listeners { let interactive_bounds = interactive_bounds.clone(); cx.on_mouse_event(move |event: &MouseDownEvent, phase, cx| { listener(event, &*interactive_bounds, phase, cx); }) } - for listener in self.mouse_up_listeners.drain(..) { + for listener in self.mouse_up_listeners { let interactive_bounds = interactive_bounds.clone(); cx.on_mouse_event(move |event: &MouseUpEvent, phase, cx| { listener(event, &*interactive_bounds, phase, cx); }) } - for listener in self.mouse_move_listeners.drain(..) { + for listener in self.mouse_move_listeners { let interactive_bounds = interactive_bounds.clone(); cx.on_mouse_event(move |event: &MouseMoveEvent, phase, cx| { listener(event, &*interactive_bounds, phase, cx); }) } - for listener in self.scroll_wheel_listeners.drain(..) { + for listener in self.scroll_wheel_listeners { let interactive_bounds = interactive_bounds.clone(); cx.on_mouse_event(move |event: &ScrollWheelEvent, phase, cx| { listener(event, &*interactive_bounds, phase, cx); @@ -868,8 +868,8 @@ impl Interactivity { } } - let click_listeners = mem::take(&mut self.click_listeners); - let drag_listener = mem::take(&mut self.drag_listener); + let click_listeners = self.click_listeners; + let drag_listener = self.drag_listener; if !click_listeners.is_empty() || drag_listener.is_some() { let pending_mouse_down = element_state.pending_mouse_down.clone(); @@ -1086,13 +1086,13 @@ impl Interactivity { self.key_context.clone(), element_state.focus_handle.clone(), |_, cx| { - for listener in self.key_down_listeners.drain(..) { + for listener in self.key_down_listeners { cx.on_key_event(move |event: &KeyDownEvent, phase, cx| { listener(event, phase, cx); }) } - for listener in self.key_up_listeners.drain(..) { + for listener in self.key_up_listeners { cx.on_key_event(move |event: &KeyUpEvent, phase, cx| { listener(event, phase, cx); }) diff --git a/crates/gpui2/src/view.rs b/crates/gpui2/src/view.rs index 46a90864783b0e8933731a275704cd1ce9dd4d32..d3506e93fa1f4630d620258b77c8995c1c4cc0c3 100644 --- a/crates/gpui2/src/view.rs +++ b/crates/gpui2/src/view.rs @@ -208,11 +208,16 @@ impl AnyView { cx: &mut WindowContext, ) { cx.with_absolute_element_offset(origin, |cx| { + let start_time = std::time::Instant::now(); let (layout_id, rendered_element) = (self.layout)(self, cx); + let duration = start_time.elapsed(); + println!("request layout: {:?}", duration); + let start_time = std::time::Instant::now(); cx.compute_layout(layout_id, available_space); let duration = start_time.elapsed(); println!("compute layout: {:?}", duration); + let start_time = std::time::Instant::now(); (self.paint)(self, rendered_element, cx); let duration = start_time.elapsed(); diff --git a/crates/gpui2/src/window.rs b/crates/gpui2/src/window.rs index 4624bcf20bbc1829c0f6d0cde24c1948d88d1ce0..a6e738db54ea9650417944bec0c15a62e64dc714 100644 --- a/crates/gpui2/src/window.rs +++ b/crates/gpui2/src/window.rs @@ -42,8 +42,26 @@ const ACTIVE_DRAG_Z_INDEX: u32 = 1; /// A global stacking order, which is created by stacking successive z-index values. /// Each z-index will always be interpreted in the context of its parent z-index. -#[derive(Deref, DerefMut, Ord, PartialOrd, Eq, PartialEq, Clone, Default, Debug)] -pub struct StackingOrder(pub(crate) SmallVec<[u32; 16]>); +#[derive(Deref, DerefMut, Ord, PartialOrd, Eq, PartialEq, Clone, Debug)] +pub struct StackingOrder(pub(crate) Arc>); + +impl Default for StackingOrder { + fn default() -> Self { + StackingOrder(Arc::new(Vec::new())) + } +} + +impl StackingOrder { + /// Pushes a new z-index onto the stacking order. + pub fn push(&mut self, z_index: u32) { + Arc::make_mut(&mut self.0).push(z_index); + } + + /// Pops the last z-index off the stacking order. + pub fn pop(&mut self) { + Arc::make_mut(&mut self.0).pop(); + } +} /// Represents the two different phases when dispatching events. #[derive(Default, Copy, Clone, Debug, Eq, PartialEq)] @@ -2892,12 +2910,12 @@ impl AnyWindowHandle { } } -#[cfg(any(test, feature = "test-support"))] -impl From> for StackingOrder { - fn from(small_vec: SmallVec<[u32; 16]>) -> Self { - StackingOrder(small_vec) - } -} +// #[cfg(any(test, feature = "test-support"))] +// impl From> for StackingOrder { +// fn from(small_vec: SmallVec<[u32; 16]>) -> Self { +// StackingOrder(small_vec) +// } +// } #[derive(Clone, Debug, Eq, PartialEq, Hash)] pub enum ElementId { diff --git a/debug.plist b/debug.plist new file mode 100644 index 0000000000000000000000000000000000000000..e09573c9d1c1499f8b1357d3a86bd90d306bded3 --- /dev/null +++ b/debug.plist @@ -0,0 +1,8 @@ + + + + + com.apple.security.get-task-allow + + + From 1ae25f52a114919abe9062e3ea3506473164345f Mon Sep 17 00:00:00 2001 From: Nathan Sobo Date: Thu, 14 Dec 2023 10:31:45 -0700 Subject: [PATCH 16/21] WIP --- crates/collab_ui2/src/face_pile.rs | 2 +- crates/gpui2/src/elements/div.rs | 65 ++++++++++++++++++------ crates/gpui2/src/style.rs | 2 +- crates/gpui2/src/styled.rs | 2 +- crates/gpui2/src/window.rs | 24 +++++---- crates/storybook2/src/stories/z_index.rs | 4 +- crates/ui2/src/styles/elevation.rs | 12 ++--- crates/workspace2/src/modal_layer.rs | 2 +- 8 files changed, 77 insertions(+), 36 deletions(-) diff --git a/crates/collab_ui2/src/face_pile.rs b/crates/collab_ui2/src/face_pile.rs index d181509c46f1e568460b935f6d403dd6b15a1fff..fd675127e4a0786da76f3f5eb044d836652f7fab 100644 --- a/crates/collab_ui2/src/face_pile.rs +++ b/crates/collab_ui2/src/face_pile.rs @@ -17,7 +17,7 @@ impl RenderOnce for FacePile { let isnt_last = ix < player_count - 1; div() - .z_index((player_count - ix) as u32) + .z_index((player_count - ix) as u8) .when(isnt_last, |div| div.neg_mr_1()) .child(player) }); diff --git a/crates/gpui2/src/elements/div.rs b/crates/gpui2/src/elements/div.rs index 5ae051644af2212f28ab4b6aaea8bed4f2789d0b..cc82ff3cb09dbba6c5b5fff18795f27ef3b8c77a 100644 --- a/crates/gpui2/src/elements/div.rs +++ b/crates/gpui2/src/elements/div.rs @@ -646,7 +646,10 @@ pub struct DivState { impl DivState { pub fn is_active(&self) -> bool { - self.interactive_state.pending_mouse_down.borrow().is_some() + self.interactive_state + .pending_mouse_down + .as_ref() + .map_or(false, |pending| pending.borrow().is_some()) } } @@ -872,11 +875,17 @@ impl Interactivity { let drag_listener = self.drag_listener; if !click_listeners.is_empty() || drag_listener.is_some() { - let pending_mouse_down = element_state.pending_mouse_down.clone(); + let pending_mouse_down = element_state + .pending_mouse_down + .get_or_insert_with(Default::default) + .clone(); let mouse_down = pending_mouse_down.borrow().clone(); if let Some(mouse_down) = mouse_down { if let Some(drag_listener) = drag_listener { - let active_state = element_state.clicked_state.clone(); + let active_state = element_state + .clicked_state + .get_or_insert_with(Default::default) + .clone(); let interactive_bounds = interactive_bounds.clone(); cx.on_mouse_event(move |event: &MouseMoveEvent, phase, cx| { @@ -929,8 +938,14 @@ impl Interactivity { } if let Some(hover_listener) = self.hover_listener.take() { - let was_hovered = element_state.hover_state.clone(); - let has_mouse_down = element_state.pending_mouse_down.clone(); + let was_hovered = element_state + .hover_state + .get_or_insert_with(Default::default) + .clone(); + let has_mouse_down = element_state + .pending_mouse_down + .get_or_insert_with(Default::default) + .clone(); let interactive_bounds = interactive_bounds.clone(); cx.on_mouse_event(move |event: &MouseMoveEvent, phase, cx| { @@ -951,8 +966,14 @@ impl Interactivity { } if let Some(tooltip_builder) = self.tooltip_builder.take() { - let active_tooltip = element_state.active_tooltip.clone(); - let pending_mouse_down = element_state.pending_mouse_down.clone(); + let active_tooltip = element_state + .active_tooltip + .get_or_insert_with(Default::default) + .clone(); + let pending_mouse_down = element_state + .pending_mouse_down + .get_or_insert_with(Default::default) + .clone(); let interactive_bounds = interactive_bounds.clone(); cx.on_mouse_event(move |event: &MouseMoveEvent, phase, cx| { @@ -994,19 +1015,30 @@ impl Interactivity { } }); - let active_tooltip = element_state.active_tooltip.clone(); + let active_tooltip = element_state + .active_tooltip + .get_or_insert_with(Default::default) + .clone(); cx.on_mouse_event(move |_: &MouseDownEvent, _, _| { active_tooltip.borrow_mut().take(); }); - if let Some(active_tooltip) = element_state.active_tooltip.borrow().as_ref() { + if let Some(active_tooltip) = element_state + .active_tooltip + .get_or_insert_with(Default::default) + .borrow() + .as_ref() + { if active_tooltip.tooltip.is_some() { cx.active_tooltip = active_tooltip.tooltip.clone() } } } - let active_state = element_state.clicked_state.clone(); + let active_state = element_state + .clicked_state + .get_or_insert_with(Default::default) + .clone(); if active_state.borrow().is_clicked() { cx.on_mouse_event(move |_: &MouseUpEvent, phase, cx| { if phase == DispatchPhase::Capture { @@ -1180,7 +1212,10 @@ impl Interactivity { } } - let clicked_state = element_state.clicked_state.borrow(); + let clicked_state = element_state + .clicked_state + .get_or_insert_with(Default::default) + .borrow(); if clicked_state.group { if let Some(group) = self.group_active_style.as_ref() { style.refine(&group.style) @@ -1235,11 +1270,11 @@ impl Default for Interactivity { #[derive(Default)] pub struct InteractiveElementState { pub focus_handle: Option, - pub clicked_state: Rc>, - pub hover_state: Rc>, - pub pending_mouse_down: Rc>>, + pub clicked_state: Option>>, + pub hover_state: Option>>, + pub pending_mouse_down: Option>>>, pub scroll_offset: Option>>>, - pub active_tooltip: Rc>>, + pub active_tooltip: Option>>>, } pub struct ActiveTooltip { diff --git a/crates/gpui2/src/style.rs b/crates/gpui2/src/style.rs index 04f247d07627ac6572fe55724f1eb7b29c76463a..d330e73585c5cf31046c782a55c19d570e991194 100644 --- a/crates/gpui2/src/style.rs +++ b/crates/gpui2/src/style.rs @@ -107,7 +107,7 @@ pub struct Style { /// The mouse cursor style shown when the mouse pointer is over an element. pub mouse_cursor: Option, - pub z_index: Option, + pub z_index: Option, } impl Styled for StyleRefinement { diff --git a/crates/gpui2/src/styled.rs b/crates/gpui2/src/styled.rs index a39e5f9cf955883405437347af5220d6dff6ab40..c7312da7ac4bafc3edc800ebe3222f50971581ee 100644 --- a/crates/gpui2/src/styled.rs +++ b/crates/gpui2/src/styled.rs @@ -12,7 +12,7 @@ pub trait Styled: Sized { gpui2_macros::style_helpers!(); - fn z_index(mut self, z_index: u32) -> Self { + fn z_index(mut self, z_index: u8) -> Self { self.style().z_index = Some(z_index); self } diff --git a/crates/gpui2/src/window.rs b/crates/gpui2/src/window.rs index a6e738db54ea9650417944bec0c15a62e64dc714..31e9afc695378b4dfe974173a02ea1a2a371113b 100644 --- a/crates/gpui2/src/window.rs +++ b/crates/gpui2/src/window.rs @@ -38,28 +38,34 @@ use std::{ }; use util::ResultExt; -const ACTIVE_DRAG_Z_INDEX: u32 = 1; +const ACTIVE_DRAG_Z_INDEX: u8 = 1; /// A global stacking order, which is created by stacking successive z-index values. /// Each z-index will always be interpreted in the context of its parent z-index. -#[derive(Deref, DerefMut, Ord, PartialOrd, Eq, PartialEq, Clone, Debug)] -pub struct StackingOrder(pub(crate) Arc>); +#[derive(Deref, DerefMut, Clone, Debug, Ord, PartialOrd, PartialEq, Eq)] +pub struct StackingOrder { + #[deref] + #[deref_mut] + z_indices: Arc>, +} impl Default for StackingOrder { fn default() -> Self { - StackingOrder(Arc::new(Vec::new())) + StackingOrder { + z_indices: Arc::new(SmallVec::new()), + } } } impl StackingOrder { /// Pushes a new z-index onto the stacking order. - pub fn push(&mut self, z_index: u32) { - Arc::make_mut(&mut self.0).push(z_index); + pub fn push(&mut self, z_index: u8) { + Arc::make_mut(&mut self.z_indices).push(z_index); } /// Pops the last z-index off the stacking order. pub fn pop(&mut self) { - Arc::make_mut(&mut self.0).pop(); + Arc::make_mut(&mut self.z_indices).pop(); } } @@ -905,7 +911,7 @@ impl<'a> WindowContext<'a> { /// Called during painting to invoke the given closure in a new stacking context. The given /// z-index is interpreted relative to the previous call to `stack`. - pub fn with_z_index(&mut self, z_index: u32, f: impl FnOnce(&mut Self) -> R) -> R { + pub fn with_z_index(&mut self, z_index: u8, f: impl FnOnce(&mut Self) -> R) -> R { self.window.next_frame.z_index_stack.push(z_index); let result = f(self); self.window.next_frame.z_index_stack.pop(); @@ -2233,7 +2239,7 @@ impl<'a, V: 'static> ViewContext<'a, V> { &mut self.window_cx } - pub fn with_z_index(&mut self, z_index: u32, f: impl FnOnce(&mut Self) -> R) -> R { + pub fn with_z_index(&mut self, z_index: u8, f: impl FnOnce(&mut Self) -> R) -> R { self.window.next_frame.z_index_stack.push(z_index); let result = f(self); self.window.next_frame.z_index_stack.pop(); diff --git a/crates/storybook2/src/stories/z_index.rs b/crates/storybook2/src/stories/z_index.rs index c6a4b68cc369f4e0bf409f714e585c2bde6f47f4..9579b8c7fcf891c4fcda7ef691d37f583b2bd77a 100644 --- a/crates/storybook2/src/stories/z_index.rs +++ b/crates/storybook2/src/stories/z_index.rs @@ -78,7 +78,7 @@ impl Styles for Div {} #[derive(IntoElement)] struct ZIndexExample { - z_index: u32, + z_index: u8, } impl RenderOnce for ZIndexExample { @@ -170,7 +170,7 @@ impl RenderOnce for ZIndexExample { } impl ZIndexExample { - pub fn new(z_index: u32) -> Self { + pub fn new(z_index: u8) -> Self { Self { z_index } } } diff --git a/crates/ui2/src/styles/elevation.rs b/crates/ui2/src/styles/elevation.rs index 88b2ff2e56aeaf5d2e212fca7218afa3940a4742..7b3835c2e54b3e60528ab212311d245dfd7223d3 100644 --- a/crates/ui2/src/styles/elevation.rs +++ b/crates/ui2/src/styles/elevation.rs @@ -20,14 +20,14 @@ pub enum ElevationIndex { } impl ElevationIndex { - pub fn z_index(self) -> u32 { + pub fn z_index(self) -> u8 { match self { ElevationIndex::Background => 0, - ElevationIndex::Surface => 100, - ElevationIndex::ElevatedSurface => 200, - ElevationIndex::Wash => 250, - ElevationIndex::ModalSurface => 300, - ElevationIndex::DraggedElement => 900, + ElevationIndex::Surface => 42, + ElevationIndex::ElevatedSurface => 84, + ElevationIndex::Wash => 126, + ElevationIndex::ModalSurface => 168, + ElevationIndex::DraggedElement => 210, } } diff --git a/crates/workspace2/src/modal_layer.rs b/crates/workspace2/src/modal_layer.rs index a428ba3e18352ec7750f13ecd19289b5682a75be..e0a6395f31a7024eff0cfe3d62a37e8d7f577a2c 100644 --- a/crates/workspace2/src/modal_layer.rs +++ b/crates/workspace2/src/modal_layer.rs @@ -116,7 +116,7 @@ impl Render for ModalLayer { .size_full() .top_0() .left_0() - .z_index(400) + .z_index(169) .child( v_stack() .h(px(0.0)) From 0d30b698a493f92b774ae70675f4d5e825c98d65 Mon Sep 17 00:00:00 2001 From: Nathan Sobo Date: Thu, 14 Dec 2023 11:28:52 -0700 Subject: [PATCH 17/21] Don't allocate interactive bounds --- crates/gpui2/src/elements/div.rs | 12 ++++++------ crates/gpui2/src/window.rs | 16 ++-------------- 2 files changed, 8 insertions(+), 20 deletions(-) diff --git a/crates/gpui2/src/elements/div.rs b/crates/gpui2/src/elements/div.rs index cc82ff3cb09dbba6c5b5fff18795f27ef3b8c77a..fa8ef50bbb749a0430887e62139f71438e74b2d3 100644 --- a/crates/gpui2/src/elements/div.rs +++ b/crates/gpui2/src/elements/div.rs @@ -748,10 +748,10 @@ impl Interactivity { cx.with_z_index(style.z_index.unwrap_or(0), |cx| cx.add_opaque_layer(bounds)) } - let interactive_bounds = Rc::new(InteractiveBounds { + let interactive_bounds = InteractiveBounds { bounds: bounds.intersect(&cx.content_mask().bounds), stacking_order: cx.stacking_order().clone(), - }); + }; if let Some(mouse_cursor) = style.mouse_cursor { let mouse_position = &cx.mouse_position(); @@ -784,28 +784,28 @@ impl Interactivity { for listener in self.mouse_down_listeners { let interactive_bounds = interactive_bounds.clone(); cx.on_mouse_event(move |event: &MouseDownEvent, phase, cx| { - listener(event, &*interactive_bounds, phase, cx); + listener(event, &interactive_bounds, phase, cx); }) } for listener in self.mouse_up_listeners { let interactive_bounds = interactive_bounds.clone(); cx.on_mouse_event(move |event: &MouseUpEvent, phase, cx| { - listener(event, &*interactive_bounds, phase, cx); + listener(event, &interactive_bounds, phase, cx); }) } for listener in self.mouse_move_listeners { let interactive_bounds = interactive_bounds.clone(); cx.on_mouse_event(move |event: &MouseMoveEvent, phase, cx| { - listener(event, &*interactive_bounds, phase, cx); + listener(event, &interactive_bounds, phase, cx); }) } for listener in self.scroll_wheel_listeners { let interactive_bounds = interactive_bounds.clone(); cx.on_mouse_event(move |event: &ScrollWheelEvent, phase, cx| { - listener(event, &*interactive_bounds, phase, cx); + listener(event, &interactive_bounds, phase, cx); }) } diff --git a/crates/gpui2/src/window.rs b/crates/gpui2/src/window.rs index 31e9afc695378b4dfe974173a02ea1a2a371113b..d43263f815749eb66d55760e935721bb1d781c88 100644 --- a/crates/gpui2/src/window.rs +++ b/crates/gpui2/src/window.rs @@ -46,29 +46,17 @@ const ACTIVE_DRAG_Z_INDEX: u8 = 1; pub struct StackingOrder { #[deref] #[deref_mut] - z_indices: Arc>, + z_indices: SmallVec<[u8; 32]>, } impl Default for StackingOrder { fn default() -> Self { StackingOrder { - z_indices: Arc::new(SmallVec::new()), + z_indices: SmallVec::new(), } } } -impl StackingOrder { - /// Pushes a new z-index onto the stacking order. - pub fn push(&mut self, z_index: u8) { - Arc::make_mut(&mut self.z_indices).push(z_index); - } - - /// Pops the last z-index off the stacking order. - pub fn pop(&mut self) { - Arc::make_mut(&mut self.z_indices).pop(); - } -} - /// Represents the two different phases when dispatching events. #[derive(Default, Copy, Clone, Debug, Eq, PartialEq)] pub enum DispatchPhase { From 3d1dae9a0610c4b023cd348e01c57001c04d8396 Mon Sep 17 00:00:00 2001 From: Nathan Sobo Date: Thu, 14 Dec 2023 11:37:48 -0700 Subject: [PATCH 18/21] Make z_indices bigger in StackingOrder --- crates/gpui2/src/window.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/gpui2/src/window.rs b/crates/gpui2/src/window.rs index d43263f815749eb66d55760e935721bb1d781c88..e3b1cb4eb523cbdca8df63e96a47024f60958e50 100644 --- a/crates/gpui2/src/window.rs +++ b/crates/gpui2/src/window.rs @@ -46,7 +46,7 @@ const ACTIVE_DRAG_Z_INDEX: u8 = 1; pub struct StackingOrder { #[deref] #[deref_mut] - z_indices: SmallVec<[u8; 32]>, + z_indices: SmallVec<[u8; 64]>, } impl Default for StackingOrder { From 0dd6c50a200bdc3b1cad2d48b8f38b85f9f5a458 Mon Sep 17 00:00:00 2001 From: Nathan Sobo Date: Thu, 14 Dec 2023 14:06:19 -0700 Subject: [PATCH 19/21] Use FxHashMap for element state --- crates/gpui2/src/window.rs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/crates/gpui2/src/window.rs b/crates/gpui2/src/window.rs index e3b1cb4eb523cbdca8df63e96a47024f60958e50..fc8754afefbc7b628603cf9973ee2ee6720f39ff 100644 --- a/crates/gpui2/src/window.rs +++ b/crates/gpui2/src/window.rs @@ -12,7 +12,7 @@ use crate::{ VisualContext, WeakView, WindowBounds, WindowOptions, SUBPIXEL_VARIANTS, }; use anyhow::{anyhow, Context as _, Result}; -use collections::HashMap; +use collections::FxHashMap; use derive_more::{Deref, DerefMut}; use futures::{ channel::{mpsc, oneshot}, @@ -263,8 +263,8 @@ pub(crate) struct ElementStateBox { // #[derive(Default)] pub(crate) struct Frame { - pub(crate) element_states: HashMap, - mouse_listeners: HashMap>, + pub(crate) element_states: FxHashMap, + mouse_listeners: FxHashMap>, pub(crate) dispatch_tree: DispatchTree, pub(crate) focus_listeners: Vec, pub(crate) scene_builder: SceneBuilder, @@ -277,8 +277,8 @@ pub(crate) struct Frame { impl Frame { fn new(dispatch_tree: DispatchTree) -> Self { Frame { - element_states: HashMap::default(), - mouse_listeners: HashMap::default(), + element_states: FxHashMap::default(), + mouse_listeners: FxHashMap::default(), dispatch_tree, focus_listeners: Vec::new(), scene_builder: SceneBuilder::default(), From d13a21c2388c6507ec66775529ccaa7ac1783e2b Mon Sep 17 00:00:00 2001 From: Nathan Sobo Date: Thu, 14 Dec 2023 15:15:18 -0700 Subject: [PATCH 20/21] Don't move in paint --- crates/editor2/src/element.rs | 9 +- crates/gpui2/src/element.rs | 24 +- crates/gpui2/src/elements/canvas.rs | 8 +- crates/gpui2/src/elements/div.rs | 516 +++++++++++------- crates/gpui2/src/elements/img.rs | 5 +- crates/gpui2/src/elements/list.rs | 4 +- crates/gpui2/src/elements/overlay.rs | 4 +- crates/gpui2/src/elements/svg.rs | 8 +- crates/gpui2/src/elements/text.rs | 15 +- crates/gpui2/src/elements/uniform_list.rs | 6 +- crates/gpui2/src/view.rs | 16 +- crates/terminal_view2/src/terminal_element.rs | 299 +++++----- crates/ui2/src/components/popover_menu.rs | 6 +- crates/ui2/src/components/right_click_menu.rs | 8 +- crates/workspace2/src/pane_group.rs | 4 +- 15 files changed, 538 insertions(+), 394 deletions(-) diff --git a/crates/editor2/src/element.rs b/crates/editor2/src/element.rs index 9b95e256a65e0342a6b4191f8b300b98166232f8..831b6cd35ae8c80282ba312bc965fb8577e99bd3 100644 --- a/crates/editor2/src/element.rs +++ b/crates/editor2/src/element.rs @@ -933,7 +933,7 @@ impl EditorElement { cx.stop_propagation(); }, )) - .draw( + .draw2( fold_bounds.origin, fold_bounds.size, cx, @@ -1199,11 +1199,10 @@ impl EditorElement { .child(mouse_context_menu.context_menu.clone()) .anchor(AnchorCorner::TopLeft) .snap_to_window(); - element.draw( + element.into_any().draw( gpui::Point::default(), size(AvailableSpace::MinContent, AvailableSpace::MinContent), cx, - |_, _| {}, ); } } @@ -1496,7 +1495,7 @@ impl EditorElement { let scroll_left = scroll_position.x * layout.position_map.em_width; let scroll_top = scroll_position.y * layout.position_map.line_height; - for block in layout.blocks.drain(..) { + for mut block in layout.blocks.drain(..) { let mut origin = bounds.origin + point( Pixels::ZERO, @@ -2781,7 +2780,7 @@ impl Element for EditorElement { } fn paint( - mut self, + &mut self, bounds: Bounds, element_state: &mut Self::State, cx: &mut gpui::WindowContext, diff --git a/crates/gpui2/src/element.rs b/crates/gpui2/src/element.rs index e5ecd195baa14694bc65a15e9102d5cbd56be10a..f4bcb17f3c8180be4bef821092d6ef7ea1b0f88d 100644 --- a/crates/gpui2/src/element.rs +++ b/crates/gpui2/src/element.rs @@ -23,7 +23,7 @@ pub trait IntoElement: Sized { self.into_element().into_any() } - fn draw( + fn draw2( self, origin: Point, available_space: Size, @@ -92,7 +92,7 @@ pub trait Element: 'static + IntoElement { cx: &mut WindowContext, ) -> (LayoutId, Self::State); - fn paint(self, bounds: Bounds, state: &mut Self::State, cx: &mut WindowContext); + fn paint(&mut self, bounds: Bounds, state: &mut Self::State, cx: &mut WindowContext); fn into_any(self) -> AnyElement { AnyElement::new(self) @@ -150,8 +150,8 @@ impl Element for Component { } } - fn paint(self, bounds: Bounds, state: &mut Self::State, cx: &mut WindowContext) { - let element = state.rendered_element.take().unwrap(); + fn paint(&mut self, bounds: Bounds, state: &mut Self::State, cx: &mut WindowContext) { + let mut element = state.rendered_element.take().unwrap(); if let Some(element_id) = element.element_id() { cx.with_element_state(element_id, |element_state, cx| { let mut element_state = element_state.unwrap(); @@ -420,7 +420,7 @@ impl AnyElement { self.0.layout(cx) } - pub fn paint(mut self, cx: &mut WindowContext) { + pub fn paint(&mut self, cx: &mut WindowContext) { self.0.paint(cx) } @@ -435,7 +435,7 @@ impl AnyElement { /// Initializes this element and performs layout in the available space, then paints it at the given origin. pub fn draw( - mut self, + &mut self, origin: Point, available_space: Size, cx: &mut WindowContext, @@ -465,8 +465,8 @@ impl Element for AnyElement { (layout_id, ()) } - fn paint(self, _: Bounds, _: &mut Self::State, cx: &mut WindowContext) { - self.paint(cx); + fn paint(&mut self, _: Bounds, _: &mut Self::State, cx: &mut WindowContext) { + self.paint(cx) } } @@ -508,5 +508,11 @@ impl Element for () { (cx.request_layout(&crate::Style::default(), None), ()) } - fn paint(self, _bounds: Bounds, _state: &mut Self::State, _cx: &mut WindowContext) {} + fn paint( + &mut self, + _bounds: Bounds, + _state: &mut Self::State, + _cx: &mut WindowContext, + ) { + } } diff --git a/crates/gpui2/src/elements/canvas.rs b/crates/gpui2/src/elements/canvas.rs index b3afd335d41d4544267a9453e8ffedea5c990b18..56cfef4553470a146913d4664e862f4dab3ec328 100644 --- a/crates/gpui2/src/elements/canvas.rs +++ b/crates/gpui2/src/elements/canvas.rs @@ -4,13 +4,13 @@ use crate::{Bounds, Element, IntoElement, Pixels, Style, StyleRefinement, Styled pub fn canvas(callback: impl 'static + FnOnce(&Bounds, &mut WindowContext)) -> Canvas { Canvas { - paint_callback: Box::new(callback), + paint_callback: Some(Box::new(callback)), style: StyleRefinement::default(), } } pub struct Canvas { - paint_callback: Box, &mut WindowContext)>, + paint_callback: Option, &mut WindowContext)>>, style: StyleRefinement, } @@ -40,8 +40,8 @@ impl Element for Canvas { (layout_id, ()) } - fn paint(self, bounds: Bounds, _: &mut (), cx: &mut WindowContext) { - (self.paint_callback)(&bounds, cx) + fn paint(&mut self, bounds: Bounds, _: &mut (), cx: &mut WindowContext) { + (self.paint_callback.take().unwrap())(&bounds, cx) } } diff --git a/crates/gpui2/src/elements/div.rs b/crates/gpui2/src/elements/div.rs index c24b5617d5d9e795de212e9e42cfae27e82d35e3..ff2e87e8e7f15aeff8b8157a0c689765b5105efc 100644 --- a/crates/gpui2/src/elements/div.rs +++ b/crates/gpui2/src/elements/div.rs @@ -35,6 +35,281 @@ pub struct DragMoveEvent { pub drag: View, } +impl Interactivity { + pub fn on_mouse_down( + &mut self, + button: MouseButton, + listener: impl Fn(&MouseDownEvent, &mut WindowContext) + 'static, + ) { + self.mouse_down_listeners + .push(Box::new(move |event, bounds, phase, cx| { + if phase == DispatchPhase::Bubble + && event.button == button + && bounds.visibly_contains(&event.position, cx) + { + (listener)(event, cx) + } + })); + } + + pub fn on_any_mouse_down( + &mut self, + listener: impl Fn(&MouseDownEvent, &mut WindowContext) + 'static, + ) { + self.mouse_down_listeners + .push(Box::new(move |event, bounds, phase, cx| { + if phase == DispatchPhase::Bubble && bounds.visibly_contains(&event.position, cx) { + (listener)(event, cx) + } + })); + } + + pub fn on_mouse_up( + &mut self, + button: MouseButton, + listener: impl Fn(&MouseUpEvent, &mut WindowContext) + 'static, + ) { + self.mouse_up_listeners + .push(Box::new(move |event, bounds, phase, cx| { + if phase == DispatchPhase::Bubble + && event.button == button + && bounds.visibly_contains(&event.position, cx) + { + (listener)(event, cx) + } + })); + } + + pub fn on_any_mouse_up( + &mut self, + listener: impl Fn(&MouseUpEvent, &mut WindowContext) + 'static, + ) { + self.mouse_up_listeners + .push(Box::new(move |event, bounds, phase, cx| { + if phase == DispatchPhase::Bubble && bounds.visibly_contains(&event.position, cx) { + (listener)(event, cx) + } + })); + } + + pub fn on_mouse_down_out( + &mut self, + listener: impl Fn(&MouseDownEvent, &mut WindowContext) + 'static, + ) { + self.mouse_down_listeners + .push(Box::new(move |event, bounds, phase, cx| { + if phase == DispatchPhase::Capture && !bounds.visibly_contains(&event.position, cx) + { + (listener)(event, cx) + } + })); + } + + pub fn on_mouse_up_out( + &mut self, + button: MouseButton, + listener: impl Fn(&MouseUpEvent, &mut WindowContext) + 'static, + ) { + self.mouse_up_listeners + .push(Box::new(move |event, bounds, phase, cx| { + if phase == DispatchPhase::Capture + && event.button == button + && !bounds.visibly_contains(&event.position, cx) + { + (listener)(event, cx); + } + })); + } + + pub fn on_mouse_move( + &mut self, + listener: impl Fn(&MouseMoveEvent, &mut WindowContext) + 'static, + ) { + self.mouse_move_listeners + .push(Box::new(move |event, bounds, phase, cx| { + if phase == DispatchPhase::Bubble && bounds.visibly_contains(&event.position, cx) { + (listener)(event, cx); + } + })); + } + + pub fn on_drag_move( + &mut self, + listener: impl Fn(&DragMoveEvent, &mut WindowContext) + 'static, + ) where + W: Render, + { + self.mouse_move_listeners + .push(Box::new(move |event, bounds, phase, cx| { + if phase == DispatchPhase::Capture + && bounds.drag_target_contains(&event.position, cx) + { + if let Some(view) = cx.active_drag().and_then(|view| view.downcast::().ok()) + { + (listener)( + &DragMoveEvent { + event: event.clone(), + drag: view, + }, + cx, + ); + } + } + })); + } + + pub fn on_scroll_wheel( + &mut self, + listener: impl Fn(&ScrollWheelEvent, &mut WindowContext) + 'static, + ) { + self.scroll_wheel_listeners + .push(Box::new(move |event, bounds, phase, cx| { + if phase == DispatchPhase::Bubble && bounds.visibly_contains(&event.position, cx) { + (listener)(event, cx); + } + })); + } + + pub fn capture_action( + &mut self, + listener: impl Fn(&A, &mut WindowContext) + 'static, + ) { + self.action_listeners.push(( + TypeId::of::(), + Box::new(move |action, phase, cx| { + let action = action.downcast_ref().unwrap(); + if phase == DispatchPhase::Capture { + (listener)(action, cx) + } + }), + )); + } + + pub fn on_action(&mut self, listener: impl Fn(&A, &mut WindowContext) + 'static) { + self.action_listeners.push(( + TypeId::of::(), + Box::new(move |action, phase, cx| { + let action = action.downcast_ref().unwrap(); + if phase == DispatchPhase::Bubble { + (listener)(action, cx) + } + }), + )); + } + + pub fn on_boxed_action( + &mut self, + action: &Box, + listener: impl Fn(&Box, &mut WindowContext) + 'static, + ) { + let action = action.boxed_clone(); + self.action_listeners.push(( + (*action).type_id(), + Box::new(move |_, phase, cx| { + if phase == DispatchPhase::Bubble { + (listener)(&action, cx) + } + }), + )); + } + + pub fn on_key_down(&mut self, listener: impl Fn(&KeyDownEvent, &mut WindowContext) + 'static) { + self.key_down_listeners + .push(Box::new(move |event, phase, cx| { + if phase == DispatchPhase::Bubble { + (listener)(event, cx) + } + })); + } + + pub fn capture_key_down( + &mut self, + listener: impl Fn(&KeyDownEvent, &mut WindowContext) + 'static, + ) { + self.key_down_listeners + .push(Box::new(move |event, phase, cx| { + if phase == DispatchPhase::Capture { + listener(event, cx) + } + })); + } + + pub fn on_key_up(&mut self, listener: impl Fn(&KeyUpEvent, &mut WindowContext) + 'static) { + self.key_up_listeners + .push(Box::new(move |event, phase, cx| { + if phase == DispatchPhase::Bubble { + listener(event, cx) + } + })); + } + + pub fn capture_key_up(&mut self, listener: impl Fn(&KeyUpEvent, &mut WindowContext) + 'static) { + self.key_up_listeners + .push(Box::new(move |event, phase, cx| { + if phase == DispatchPhase::Capture { + listener(event, cx) + } + })); + } + + pub fn on_drop( + &mut self, + listener: impl Fn(&View, &mut WindowContext) + 'static, + ) { + self.drop_listeners.push(( + TypeId::of::(), + Box::new(move |dragged_view, cx| { + listener(&dragged_view.downcast().unwrap(), cx); + }), + )); + } + + pub fn on_click(&mut self, listener: impl Fn(&ClickEvent, &mut WindowContext) + 'static) + where + Self: Sized, + { + self.click_listeners + .push(Box::new(move |event, cx| listener(event, cx))); + } + + pub fn on_drag(&mut self, constructor: impl Fn(&mut WindowContext) -> View + 'static) + where + Self: Sized, + W: 'static + Render, + { + debug_assert!( + self.drag_listener.is_none(), + "calling on_drag more than once on the same element is not supported" + ); + self.drag_listener = Some(Box::new(move |cursor_offset, cx| AnyDrag { + view: constructor(cx).into(), + cursor_offset, + })); + } + + pub fn on_hover(&mut self, listener: impl Fn(&bool, &mut WindowContext) + 'static) + where + Self: Sized, + { + debug_assert!( + self.hover_listener.is_none(), + "calling on_hover more than once on the same element is not supported" + ); + self.hover_listener = Some(Box::new(listener)); + } + + pub fn tooltip(&mut self, build_tooltip: impl Fn(&mut WindowContext) -> AnyView + 'static) + where + Self: Sized, + { + debug_assert!( + self.tooltip_builder.is_none(), + "calling tooltip more than once on the same element is not supported" + ); + self.tooltip_builder = Some(Rc::new(build_tooltip)); + } +} + pub trait InteractiveElement: Sized { fn interactivity(&mut self) -> &mut Interactivity; @@ -92,16 +367,7 @@ pub trait InteractiveElement: Sized { button: MouseButton, listener: impl Fn(&MouseDownEvent, &mut WindowContext) + 'static, ) -> Self { - self.interactivity().mouse_down_listeners.push(Box::new( - move |event, bounds, phase, cx| { - if phase == DispatchPhase::Bubble - && event.button == button - && bounds.visibly_contains(&event.position, cx) - { - (listener)(event, cx) - } - }, - )); + self.interactivity().on_mouse_down(button, listener); self } @@ -109,13 +375,7 @@ pub trait InteractiveElement: Sized { mut self, listener: impl Fn(&MouseDownEvent, &mut WindowContext) + 'static, ) -> Self { - self.interactivity().mouse_down_listeners.push(Box::new( - move |event, bounds, phase, cx| { - if phase == DispatchPhase::Bubble && bounds.visibly_contains(&event.position, cx) { - (listener)(event, cx) - } - }, - )); + self.interactivity().on_any_mouse_down(listener); self } @@ -124,30 +384,7 @@ pub trait InteractiveElement: Sized { button: MouseButton, listener: impl Fn(&MouseUpEvent, &mut WindowContext) + 'static, ) -> Self { - self.interactivity() - .mouse_up_listeners - .push(Box::new(move |event, bounds, phase, cx| { - if phase == DispatchPhase::Bubble - && event.button == button - && bounds.visibly_contains(&event.position, cx) - { - (listener)(event, cx) - } - })); - self - } - - fn on_any_mouse_up( - mut self, - listener: impl Fn(&MouseUpEvent, &mut WindowContext) + 'static, - ) -> Self { - self.interactivity() - .mouse_up_listeners - .push(Box::new(move |event, bounds, phase, cx| { - if phase == DispatchPhase::Bubble && bounds.visibly_contains(&event.position, cx) { - (listener)(event, cx) - } - })); + self.interactivity().on_mouse_up(button, listener); self } @@ -155,14 +392,7 @@ pub trait InteractiveElement: Sized { mut self, listener: impl Fn(&MouseDownEvent, &mut WindowContext) + 'static, ) -> Self { - self.interactivity().mouse_down_listeners.push(Box::new( - move |event, bounds, phase, cx| { - if phase == DispatchPhase::Capture && !bounds.visibly_contains(&event.position, cx) - { - (listener)(event, cx) - } - }, - )); + self.interactivity().on_mouse_down_out(listener); self } @@ -171,16 +401,7 @@ pub trait InteractiveElement: Sized { button: MouseButton, listener: impl Fn(&MouseUpEvent, &mut WindowContext) + 'static, ) -> Self { - self.interactivity() - .mouse_up_listeners - .push(Box::new(move |event, bounds, phase, cx| { - if phase == DispatchPhase::Capture - && event.button == button - && !bounds.visibly_contains(&event.position, cx) - { - (listener)(event, cx); - } - })); + self.interactivity().on_mouse_up_out(button, listener); self } @@ -188,13 +409,7 @@ pub trait InteractiveElement: Sized { mut self, listener: impl Fn(&MouseMoveEvent, &mut WindowContext) + 'static, ) -> Self { - self.interactivity().mouse_move_listeners.push(Box::new( - move |event, bounds, phase, cx| { - if phase == DispatchPhase::Bubble && bounds.visibly_contains(&event.position, cx) { - (listener)(event, cx); - } - }, - )); + self.interactivity().on_mouse_move(listener); self } @@ -205,24 +420,7 @@ pub trait InteractiveElement: Sized { where W: Render, { - self.interactivity().mouse_move_listeners.push(Box::new( - move |event, bounds, phase, cx| { - if phase == DispatchPhase::Capture - && bounds.drag_target_contains(&event.position, cx) - { - if let Some(view) = cx.active_drag().and_then(|view| view.downcast::().ok()) - { - (listener)( - &DragMoveEvent { - event: event.clone(), - drag: view, - }, - cx, - ); - } - } - }, - )); + self.interactivity().on_drag_move(listener); self } @@ -230,13 +428,7 @@ pub trait InteractiveElement: Sized { mut self, listener: impl Fn(&ScrollWheelEvent, &mut WindowContext) + 'static, ) -> Self { - self.interactivity().scroll_wheel_listeners.push(Box::new( - move |event, bounds, phase, cx| { - if phase == DispatchPhase::Bubble && bounds.visibly_contains(&event.position, cx) { - (listener)(event, cx); - } - }, - )); + self.interactivity().on_scroll_wheel(listener); self } @@ -245,29 +437,13 @@ pub trait InteractiveElement: Sized { mut self, listener: impl Fn(&A, &mut WindowContext) + 'static, ) -> Self { - self.interactivity().action_listeners.push(( - TypeId::of::(), - Box::new(move |action, phase, cx| { - let action = action.downcast_ref().unwrap(); - if phase == DispatchPhase::Capture { - (listener)(action, cx) - } - }), - )); + self.interactivity().capture_action(listener); self } /// Add a listener for the given action, fires during the bubble event phase fn on_action(mut self, listener: impl Fn(&A, &mut WindowContext) + 'static) -> Self { - self.interactivity().action_listeners.push(( - TypeId::of::(), - Box::new(move |action, phase, cx| { - let action = action.downcast_ref().unwrap(); - if phase == DispatchPhase::Bubble { - (listener)(action, cx) - } - }), - )); + self.interactivity().on_action(listener); self } @@ -276,15 +452,7 @@ pub trait InteractiveElement: Sized { action: &Box, listener: impl Fn(&Box, &mut WindowContext) + 'static, ) -> Self { - let action = action.boxed_clone(); - self.interactivity().action_listeners.push(( - (*action).type_id(), - Box::new(move |_, phase, cx| { - if phase == DispatchPhase::Bubble { - (listener)(&action, cx) - } - }), - )); + self.interactivity().on_boxed_action(action, listener); self } @@ -292,13 +460,7 @@ pub trait InteractiveElement: Sized { mut self, listener: impl Fn(&KeyDownEvent, &mut WindowContext) + 'static, ) -> Self { - self.interactivity() - .key_down_listeners - .push(Box::new(move |event, phase, cx| { - if phase == DispatchPhase::Bubble { - (listener)(event, cx) - } - })); + self.interactivity().on_key_down(listener); self } @@ -306,24 +468,12 @@ pub trait InteractiveElement: Sized { mut self, listener: impl Fn(&KeyDownEvent, &mut WindowContext) + 'static, ) -> Self { - self.interactivity() - .key_down_listeners - .push(Box::new(move |event, phase, cx| { - if phase == DispatchPhase::Capture { - listener(event, cx) - } - })); + self.interactivity().capture_key_down(listener); self } fn on_key_up(mut self, listener: impl Fn(&KeyUpEvent, &mut WindowContext) + 'static) -> Self { - self.interactivity() - .key_up_listeners - .push(Box::new(move |event, phase, cx| { - if phase == DispatchPhase::Bubble { - listener(event, cx) - } - })); + self.interactivity().on_key_up(listener); self } @@ -331,13 +481,15 @@ pub trait InteractiveElement: Sized { mut self, listener: impl Fn(&KeyUpEvent, &mut WindowContext) + 'static, ) -> Self { - self.interactivity() - .key_up_listeners - .push(Box::new(move |event, phase, cx| { - if phase == DispatchPhase::Capture { - listener(event, cx) - } - })); + self.interactivity().capture_key_up(listener); + self + } + + fn on_drop( + mut self, + listener: impl Fn(&View, &mut WindowContext) + 'static, + ) -> Self { + self.interactivity().on_drop(listener); self } @@ -362,19 +514,6 @@ pub trait InteractiveElement: Sized { )); self } - - fn on_drop( - mut self, - listener: impl Fn(&View, &mut WindowContext) + 'static, - ) -> Self { - self.interactivity().drop_listeners.push(( - TypeId::of::(), - Box::new(move |dragged_view, cx| { - listener(&dragged_view.downcast().unwrap(), cx); - }), - )); - self - } } pub trait StatefulInteractiveElement: InteractiveElement { @@ -431,9 +570,7 @@ pub trait StatefulInteractiveElement: InteractiveElement { where Self: Sized, { - self.interactivity() - .click_listeners - .push(Box::new(move |event, cx| listener(event, cx))); + self.interactivity().on_click(listener); self } @@ -442,14 +579,7 @@ pub trait StatefulInteractiveElement: InteractiveElement { Self: Sized, W: 'static + Render, { - debug_assert!( - self.interactivity().drag_listener.is_none(), - "calling on_drag more than once on the same element is not supported" - ); - self.interactivity().drag_listener = Some(Box::new(move |cursor_offset, cx| AnyDrag { - view: constructor(cx).into(), - cursor_offset, - })); + self.interactivity().on_drag(constructor); self } @@ -457,11 +587,7 @@ pub trait StatefulInteractiveElement: InteractiveElement { where Self: Sized, { - debug_assert!( - self.interactivity().hover_listener.is_none(), - "calling on_hover more than once on the same element is not supported" - ); - self.interactivity().hover_listener = Some(Box::new(listener)); + self.interactivity().on_hover(listener); self } @@ -469,11 +595,7 @@ pub trait StatefulInteractiveElement: InteractiveElement { where Self: Sized, { - debug_assert!( - self.interactivity().tooltip_builder.is_none(), - "calling tooltip more than once on the same element is not supported" - ); - self.interactivity().tooltip_builder = Some(Rc::new(build_tooltip)); + self.interactivity().tooltip(build_tooltip); self } } @@ -529,6 +651,7 @@ pub type ActionListener = Box Div { + #[allow(unused_mut)] let mut div = Div { interactivity: Interactivity::default(), children: SmallVec::default(), @@ -598,7 +721,7 @@ impl Element for Div { } fn paint( - self, + &mut self, bounds: Bounds, element_state: &mut Self::State, cx: &mut WindowContext, @@ -649,7 +772,7 @@ impl Element for Div { cx.with_text_style(style.text_style().cloned(), |cx| { cx.with_content_mask(style.overflow_mask(bounds), |cx| { cx.with_element_offset(scroll_offset, |cx| { - for child in self.children { + for child in &mut self.children { child.paint(cx); } }) @@ -769,7 +892,7 @@ impl Interactivity { } pub fn paint( - mut self, + &mut self, bounds: Bounds, content_size: Size, element_state: &mut InteractiveElementState, @@ -788,7 +911,7 @@ impl Interactivity { && bounds.contains(&cx.mouse_position()) { const FONT_SIZE: crate::Pixels = crate::Pixels(10.); - let element_id = format!("{:?}", self.element_id.unwrap()); + let element_id = format!("{:?}", self.element_id.as_ref().unwrap()); let str_len = element_id.len(); let render_debug_text = |cx: &mut WindowContext| { @@ -934,28 +1057,28 @@ impl Interactivity { }); } - for listener in self.mouse_down_listeners { + for listener in self.mouse_down_listeners.drain(..) { let interactive_bounds = interactive_bounds.clone(); cx.on_mouse_event(move |event: &MouseDownEvent, phase, cx| { listener(event, &interactive_bounds, phase, cx); }) } - for listener in self.mouse_up_listeners { + for listener in self.mouse_up_listeners.drain(..) { let interactive_bounds = interactive_bounds.clone(); cx.on_mouse_event(move |event: &MouseUpEvent, phase, cx| { listener(event, &interactive_bounds, phase, cx); }) } - for listener in self.mouse_move_listeners { + for listener in self.mouse_move_listeners.drain(..) { let interactive_bounds = interactive_bounds.clone(); cx.on_mouse_event(move |event: &MouseMoveEvent, phase, cx| { listener(event, &interactive_bounds, phase, cx); }) } - for listener in self.scroll_wheel_listeners { + for listener in self.scroll_wheel_listeners.drain(..) { let interactive_bounds = interactive_bounds.clone(); cx.on_mouse_event(move |event: &ScrollWheelEvent, phase, cx| { listener(event, &interactive_bounds, phase, cx); @@ -1024,8 +1147,8 @@ impl Interactivity { } } - let click_listeners = self.click_listeners; - let drag_listener = self.drag_listener; + let click_listeners = mem::take(&mut self.click_listeners); + let drag_listener = mem::take(&mut self.drag_listener); if !click_listeners.is_empty() || drag_listener.is_some() { let pending_mouse_down = element_state @@ -1267,23 +1390,26 @@ impl Interactivity { .as_ref() .map(|scroll_offset| *scroll_offset.borrow()); + let key_down_listeners = mem::take(&mut self.key_down_listeners); + let key_up_listeners = mem::take(&mut self.key_up_listeners); + let action_listeners = mem::take(&mut self.action_listeners); cx.with_key_dispatch( self.key_context.clone(), element_state.focus_handle.clone(), |_, cx| { - for listener in self.key_down_listeners { + for listener in key_down_listeners { cx.on_key_event(move |event: &KeyDownEvent, phase, cx| { listener(event, phase, cx); }) } - for listener in self.key_up_listeners { + for listener in key_up_listeners { cx.on_key_event(move |event: &KeyUpEvent, phase, cx| { listener(event, phase, cx); }) } - for (action_type, listener) in self.action_listeners { + for (action_type, listener) in action_listeners { cx.on_action(action_type, listener) } @@ -1522,7 +1648,7 @@ where self.element.layout(state, cx) } - fn paint(self, bounds: Bounds, state: &mut Self::State, cx: &mut WindowContext) { + fn paint(&mut self, bounds: Bounds, state: &mut Self::State, cx: &mut WindowContext) { self.element.paint(bounds, state, cx) } } @@ -1596,7 +1722,7 @@ where self.element.layout(state, cx) } - fn paint(self, bounds: Bounds, state: &mut Self::State, cx: &mut WindowContext) { + fn paint(&mut self, bounds: Bounds, state: &mut Self::State, cx: &mut WindowContext) { self.element.paint(bounds, state, cx) } } diff --git a/crates/gpui2/src/elements/img.rs b/crates/gpui2/src/elements/img.rs index f6aae2de66aebb7bc894bd63a8d9a85a6e74e089..4f81f604c8d3799923b9fb76742019cb1724c0b5 100644 --- a/crates/gpui2/src/elements/img.rs +++ b/crates/gpui2/src/elements/img.rs @@ -81,11 +81,12 @@ impl Element for Img { } fn paint( - self, + &mut self, bounds: Bounds, element_state: &mut Self::State, cx: &mut WindowContext, ) { + let source = self.source.clone(); self.interactivity.paint( bounds, bounds.size, @@ -94,7 +95,7 @@ impl Element for Img { |style, _scroll_offset, cx| { let corner_radii = style.corner_radii.to_pixels(bounds.size, cx.rem_size()); cx.with_z_index(1, |cx| { - match self.source { + match source { ImageSource::Uri(uri) => { let image_future = cx.image_cache.get(uri.clone()); if let Some(data) = image_future diff --git a/crates/gpui2/src/elements/list.rs b/crates/gpui2/src/elements/list.rs index ba479e1ea8f460ecf5915661f877a89f132f288d..6818c5c7a2e62baab27aad701dfa27cfa80dbce4 100644 --- a/crates/gpui2/src/elements/list.rs +++ b/crates/gpui2/src/elements/list.rs @@ -257,7 +257,7 @@ impl Element for List { } fn paint( - self, + &mut self, bounds: crate::Bounds, _state: &mut Self::State, cx: &mut crate::WindowContext, @@ -385,7 +385,7 @@ impl Element for List { // Paint the visible items let mut item_origin = bounds.origin; item_origin.y -= scroll_top.offset_in_item; - for mut item_element in item_elements { + for item_element in &mut item_elements { let item_height = item_element.measure(available_item_space, cx).height; item_element.draw(item_origin, available_item_space, cx); item_origin.y += item_height; diff --git a/crates/gpui2/src/elements/overlay.rs b/crates/gpui2/src/elements/overlay.rs index e925d03d275ea75d40633b1add4228b3c1ffce38..5b72019f177f899f886a375fe4468bcf403c336c 100644 --- a/crates/gpui2/src/elements/overlay.rs +++ b/crates/gpui2/src/elements/overlay.rs @@ -81,7 +81,7 @@ impl Element for Overlay { } fn paint( - self, + &mut self, bounds: crate::Bounds, element_state: &mut Self::State, cx: &mut WindowContext, @@ -149,7 +149,7 @@ impl Element for Overlay { cx.with_element_offset(desired.origin - bounds.origin, |cx| { cx.break_content_mask(|cx| { - for child in self.children { + for child in &mut self.children { child.paint(cx); } }) diff --git a/crates/gpui2/src/elements/svg.rs b/crates/gpui2/src/elements/svg.rs index aba31686f588fbfca2d9aabf2e04e52daa15d5bd..9ca9baf470e6c3bdeec2fafb1806d34430c44aea 100644 --- a/crates/gpui2/src/elements/svg.rs +++ b/crates/gpui2/src/elements/svg.rs @@ -36,8 +36,12 @@ impl Element for Svg { }) } - fn paint(self, bounds: Bounds, element_state: &mut Self::State, cx: &mut WindowContext) - where + fn paint( + &mut self, + bounds: Bounds, + element_state: &mut Self::State, + cx: &mut WindowContext, + ) where Self: Sized, { self.interactivity diff --git a/crates/gpui2/src/elements/text.rs b/crates/gpui2/src/elements/text.rs index b8fe5e68666d7abe3e7f07b90feb4e7cdc7a5354..175a79c19a512832c7c70571780adb6268b91ab2 100644 --- a/crates/gpui2/src/elements/text.rs +++ b/crates/gpui2/src/elements/text.rs @@ -6,7 +6,7 @@ use crate::{ use anyhow::anyhow; use parking_lot::{Mutex, MutexGuard}; use smallvec::SmallVec; -use std::{cell::Cell, ops::Range, rc::Rc, sync::Arc}; +use std::{cell::Cell, mem, ops::Range, rc::Rc, sync::Arc}; use util::ResultExt; impl Element for &'static str { @@ -22,7 +22,7 @@ impl Element for &'static str { (layout_id, state) } - fn paint(self, bounds: Bounds, state: &mut TextState, cx: &mut WindowContext) { + fn paint(&mut self, bounds: Bounds, state: &mut TextState, cx: &mut WindowContext) { state.paint(bounds, self, cx) } } @@ -52,7 +52,7 @@ impl Element for SharedString { (layout_id, state) } - fn paint(self, bounds: Bounds, state: &mut TextState, cx: &mut WindowContext) { + fn paint(&mut self, bounds: Bounds, state: &mut TextState, cx: &mut WindowContext) { let text_str: &str = self.as_ref(); state.paint(bounds, text_str, cx) } @@ -128,7 +128,7 @@ impl Element for StyledText { (layout_id, state) } - fn paint(self, bounds: Bounds, state: &mut Self::State, cx: &mut WindowContext) { + fn paint(&mut self, bounds: Bounds, state: &mut Self::State, cx: &mut WindowContext) { state.paint(bounds, &self.text, cx) } } @@ -356,8 +356,8 @@ impl Element for InteractiveText { } } - fn paint(self, bounds: Bounds, state: &mut Self::State, cx: &mut WindowContext) { - if let Some(click_listener) = self.click_listener { + fn paint(&mut self, bounds: Bounds, state: &mut Self::State, cx: &mut WindowContext) { + if let Some(click_listener) = self.click_listener.take() { if let Some(ix) = state .text_state .index_for_position(bounds, cx.mouse_position()) @@ -374,13 +374,14 @@ impl Element for InteractiveText { let text_state = state.text_state.clone(); let mouse_down = state.mouse_down_index.clone(); if let Some(mouse_down_index) = mouse_down.get() { + let clickable_ranges = mem::take(&mut self.clickable_ranges); cx.on_mouse_event(move |event: &MouseUpEvent, phase, cx| { if phase == DispatchPhase::Bubble { if let Some(mouse_up_index) = text_state.index_for_position(bounds, event.position) { click_listener( - &self.clickable_ranges, + &clickable_ranges, InteractiveTextClickEvent { mouse_down_index, mouse_up_index, diff --git a/crates/gpui2/src/elements/uniform_list.rs b/crates/gpui2/src/elements/uniform_list.rs index debd365c87da2da4fbf402dc6bf4188267c191ee..9fedbad41c580b767d5c4425be1aa7a5c5f3b9b9 100644 --- a/crates/gpui2/src/elements/uniform_list.rs +++ b/crates/gpui2/src/elements/uniform_list.rs @@ -155,7 +155,7 @@ impl Element for UniformList { } fn paint( - self, + &mut self, bounds: Bounds, element_state: &mut Self::State, cx: &mut WindowContext, @@ -220,11 +220,11 @@ impl Element for UniformList { let visible_range = first_visible_element_ix ..cmp::min(last_visible_element_ix, self.item_count); - let items = (self.render_items)(visible_range.clone(), cx); + let mut items = (self.render_items)(visible_range.clone(), cx); cx.with_z_index(1, |cx| { let content_mask = ContentMask { bounds }; cx.with_content_mask(Some(content_mask), |cx| { - for (item, ix) in items.into_iter().zip(visible_range) { + for (item, ix) in items.iter_mut().zip(visible_range) { let item_origin = padded_bounds.origin + point(px(0.), item_height * ix + scroll_offset.y); let available_space = size( diff --git a/crates/gpui2/src/view.rs b/crates/gpui2/src/view.rs index d3506e93fa1f4630d620258b77c8995c1c4cc0c3..7657ae25120c526d6581fb8be8709bdb2e2024bb 100644 --- a/crates/gpui2/src/view.rs +++ b/crates/gpui2/src/view.rs @@ -90,7 +90,7 @@ impl Element for View { (layout_id, Some(element)) } - fn paint(self, _: Bounds, element: &mut Self::State, cx: &mut WindowContext) { + fn paint(&mut self, _: Bounds, element: &mut Self::State, cx: &mut WindowContext) { element.take().unwrap().paint(cx); } } @@ -170,7 +170,7 @@ impl Eq for WeakView {} pub struct AnyView { model: AnyModel, layout: fn(&AnyView, &mut WindowContext) -> (LayoutId, AnyElement), - paint: fn(&AnyView, AnyElement, &mut WindowContext), + paint: fn(&AnyView, &mut AnyElement, &mut WindowContext), } impl AnyView { @@ -209,7 +209,7 @@ impl AnyView { ) { cx.with_absolute_element_offset(origin, |cx| { let start_time = std::time::Instant::now(); - let (layout_id, rendered_element) = (self.layout)(self, cx); + let (layout_id, mut rendered_element) = (self.layout)(self, cx); let duration = start_time.elapsed(); println!("request layout: {:?}", duration); @@ -219,7 +219,7 @@ impl AnyView { println!("compute layout: {:?}", duration); let start_time = std::time::Instant::now(); - (self.paint)(self, rendered_element, cx); + (self.paint)(self, &mut rendered_element, cx); let duration = start_time.elapsed(); println!("paint: {:?}", duration); }) @@ -248,12 +248,12 @@ impl Element for AnyView { (layout_id, Some(state)) } - fn paint(self, _: Bounds, state: &mut Self::State, cx: &mut WindowContext) { + fn paint(&mut self, _: Bounds, state: &mut Self::State, cx: &mut WindowContext) { debug_assert!( state.is_some(), "state is None. Did you include an AnyView twice in the tree?" ); - (self.paint)(&self, state.take().unwrap(), cx) + (self.paint)(&self, state.as_mut().unwrap(), cx) } } @@ -284,7 +284,7 @@ impl IntoElement for AnyView { pub struct AnyWeakView { model: AnyWeakModel, layout: fn(&AnyView, &mut WindowContext) -> (LayoutId, AnyElement), - paint: fn(&AnyView, AnyElement, &mut WindowContext), + paint: fn(&AnyView, &mut AnyElement, &mut WindowContext), } impl AnyWeakView { @@ -335,7 +335,7 @@ mod any_view { pub(crate) fn paint( _view: &AnyView, - element: AnyElement, + element: &mut AnyElement, cx: &mut WindowContext, ) { element.paint(cx); diff --git a/crates/terminal_view2/src/terminal_element.rs b/crates/terminal_view2/src/terminal_element.rs index 7358f2e1d735bd9170ab2815035d4232c3e4f933..7f221129f03009115be75c2f405990cc228be7a3 100644 --- a/crates/terminal_view2/src/terminal_element.rs +++ b/crates/terminal_view2/src/terminal_element.rs @@ -2,8 +2,8 @@ use editor::{Cursor, HighlightedRange, HighlightedRangeLine}; use gpui::{ black, div, fill, point, px, red, relative, AnyElement, AsyncWindowContext, AvailableSpace, Bounds, DispatchPhase, Element, ElementId, ExternalPaths, FocusHandle, Font, FontStyle, - FontWeight, HighlightStyle, Hsla, InteractiveElement, InteractiveElementState, IntoElement, - LayoutId, Model, ModelContext, ModifiersChangedEvent, MouseButton, Pixels, + FontWeight, HighlightStyle, Hsla, InteractiveElement, InteractiveElementState, Interactivity, + IntoElement, LayoutId, Model, ModelContext, ModifiersChangedEvent, MouseButton, Pixels, PlatformInputHandler, Point, Rgba, ShapedLine, Size, StatefulInteractiveElement, Styled, TextRun, TextStyle, TextSystem, UnderlineStyle, WhiteSpace, WindowContext, }; @@ -145,11 +145,11 @@ pub struct TerminalElement { focused: bool, cursor_visible: bool, can_navigate_to_selected_word: bool, - interactivity: gpui::Interactivity, + interactivity: Interactivity, } impl InteractiveElement for TerminalElement { - fn interactivity(&mut self) -> &mut gpui::Interactivity { + fn interactivity(&mut self) -> &mut Interactivity { &mut self.interactivity } } @@ -605,141 +605,157 @@ impl TerminalElement { } fn register_mouse_listeners( - self, + &mut self, origin: Point, mode: TermMode, bounds: Bounds, cx: &mut WindowContext, - ) -> Self { + ) { let focus = self.focus.clone(); - let connection = self.terminal.clone(); - - let mut this = self - .on_mouse_down(MouseButton::Left, { - let connection = connection.clone(); - let focus = focus.clone(); - move |e, cx| { - cx.focus(&focus); - //todo!(context menu) - // v.context_menu.update(cx, |menu, _cx| menu.delay_cancel()); - connection.update(cx, |terminal, cx| { - terminal.mouse_down(&e, origin); + let terminal = self.terminal.clone(); + + self.interactivity.on_mouse_down(MouseButton::Left, { + let terminal = terminal.clone(); + let focus = focus.clone(); + move |e, cx| { + cx.focus(&focus); + //todo!(context menu) + // v.context_menu.update(cx, |menu, _cx| menu.delay_cancel()); + terminal.update(cx, |terminal, cx| { + terminal.mouse_down(&e, origin); + cx.notify(); + }) + } + }); + self.interactivity.on_mouse_move({ + let terminal = terminal.clone(); + let focus = focus.clone(); + move |e, cx| { + if e.pressed_button.is_some() && focus.is_focused(cx) && !cx.has_active_drag() { + terminal.update(cx, |terminal, cx| { + terminal.mouse_drag(e, origin, bounds); cx.notify(); }) } - }) - .on_mouse_move({ - let connection = connection.clone(); - let focus = focus.clone(); - move |e, cx| { - if e.pressed_button.is_some() && focus.is_focused(cx) && !cx.has_active_drag() { - connection.update(cx, |terminal, cx| { - terminal.mouse_drag(e, origin, bounds); - cx.notify(); - }) - } - } - }) - .on_mouse_up( - MouseButton::Left, - TerminalElement::generic_button_handler( - connection.clone(), - origin, - focus.clone(), - move |terminal, origin, e, cx| { - terminal.mouse_up(&e, origin, cx); - }, - ), - ) - .on_click({ - let connection = connection.clone(); - move |e, cx| { - if e.down.button == MouseButton::Right { - let mouse_mode = connection.update(cx, |terminal, _cx| { - terminal.mouse_mode(e.down.modifiers.shift) - }); - - if !mouse_mode { - //todo!(context menu) - // view.deploy_context_menu(e.position, cx); - } - } - } - }) - .on_mouse_move({ - let connection = connection.clone(); - let focus = focus.clone(); - move |e, cx| { - if focus.is_focused(cx) { - connection.update(cx, |terminal, cx| { - terminal.mouse_move(&e, origin); - cx.notify(); - }) + } + }); + self.interactivity.on_mouse_up( + MouseButton::Left, + TerminalElement::generic_button_handler( + terminal.clone(), + origin, + focus.clone(), + move |terminal, origin, e, cx| { + terminal.mouse_up(&e, origin, cx); + }, + ), + ); + self.interactivity.on_click({ + let terminal = terminal.clone(); + move |e, cx| { + if e.down.button == MouseButton::Right { + let mouse_mode = terminal.update(cx, |terminal, _cx| { + terminal.mouse_mode(e.down.modifiers.shift) + }); + + if !mouse_mode { + //todo!(context menu) + // view.deploy_context_menu(e.position, cx); } } - }) - .on_scroll_wheel({ - let connection = connection.clone(); - move |e, cx| { - connection.update(cx, |terminal, cx| { - terminal.scroll_wheel(e, origin); + } + }); + + self.interactivity.on_mouse_move({ + let terminal = terminal.clone(); + let focus = focus.clone(); + move |e, cx| { + if focus.is_focused(cx) { + terminal.update(cx, |terminal, cx| { + terminal.mouse_move(&e, origin); cx.notify(); }) } - }); + } + }); + self.interactivity.on_scroll_wheel({ + let terminal = terminal.clone(); + move |e, cx| { + terminal.update(cx, |terminal, cx| { + terminal.scroll_wheel(e, origin); + cx.notify(); + }) + } + }); + + self.interactivity.on_drop::({ + let focus = focus.clone(); + let terminal = terminal.clone(); + move |external_paths, cx| { + cx.focus(&focus); + let mut new_text = external_paths + .read(cx) + .paths() + .iter() + .map(|path| format!(" {path:?}")) + .join(""); + new_text.push(' '); + terminal.update(cx, |terminal, _| { + // todo!() long paths are not displayed properly albeit the text is there + terminal.paste(&new_text); + }); + } + }); // Mouse mode handlers: // All mouse modes need the extra click handlers if mode.intersects(TermMode::MOUSE_MODE) { - this = this - .on_mouse_down( - MouseButton::Right, - TerminalElement::generic_button_handler( - connection.clone(), - origin, - focus.clone(), - move |terminal, origin, e, _cx| { - terminal.mouse_down(&e, origin); - }, - ), - ) - .on_mouse_down( - MouseButton::Middle, - TerminalElement::generic_button_handler( - connection.clone(), - origin, - focus.clone(), - move |terminal, origin, e, _cx| { - terminal.mouse_down(&e, origin); - }, - ), - ) - .on_mouse_up( - MouseButton::Right, - TerminalElement::generic_button_handler( - connection.clone(), - origin, - focus.clone(), - move |terminal, origin, e, cx| { - terminal.mouse_up(&e, origin, cx); - }, - ), - ) - .on_mouse_up( - MouseButton::Middle, - TerminalElement::generic_button_handler( - connection, - origin, - focus, - move |terminal, origin, e, cx| { - terminal.mouse_up(&e, origin, cx); - }, - ), - ) + self.interactivity.on_mouse_down( + MouseButton::Right, + TerminalElement::generic_button_handler( + terminal.clone(), + origin, + focus.clone(), + move |terminal, origin, e, _cx| { + terminal.mouse_down(&e, origin); + }, + ), + ); + self.interactivity.on_mouse_down( + MouseButton::Middle, + TerminalElement::generic_button_handler( + terminal.clone(), + origin, + focus.clone(), + move |terminal, origin, e, _cx| { + terminal.mouse_down(&e, origin); + }, + ), + ); + self.interactivity.on_mouse_up( + MouseButton::Right, + TerminalElement::generic_button_handler( + terminal.clone(), + origin, + focus.clone(), + move |terminal, origin, e, cx| { + terminal.mouse_up(&e, origin, cx); + }, + ), + ); + self.interactivity.on_mouse_up( + MouseButton::Middle, + TerminalElement::generic_button_handler( + terminal, + origin, + focus, + move |terminal, origin, e, cx| { + terminal.mouse_up(&e, origin, cx); + }, + ), + ); } - - this } } @@ -764,7 +780,12 @@ impl Element for TerminalElement { (layout_id, interactive_state) } - fn paint(self, bounds: Bounds, state: &mut Self::State, cx: &mut WindowContext<'_>) { + fn paint( + &mut self, + bounds: Bounds, + state: &mut Self::State, + cx: &mut WindowContext<'_>, + ) { let mut layout = self.compute_layout(bounds, cx); let theme = cx.theme(); @@ -783,33 +804,19 @@ impl Element for TerminalElement { let terminal_focus_handle = self.focus.clone(); let terminal_handle = self.terminal.clone(); - let mut this: TerminalElement = self - .register_mouse_listeners(origin, layout.mode, bounds, cx) - .drag_over::(|style| { - // todo!() why does not it work? z-index of elements? - style.bg(cx.theme().colors().ghost_element_hover) - }) - .on_drop::(move |external_paths, cx| { - cx.focus(&terminal_focus_handle); - let mut new_text = external_paths - .read(cx) - .paths() - .iter() - .map(|path| format!(" {path:?}")) - .join(""); - new_text.push(' '); - terminal_handle.update(cx, |terminal, _| { - // todo!() long paths are not displayed properly albeit the text is there - terminal.paste(&new_text); - }); - }); + self.register_mouse_listeners(origin, layout.mode, bounds, cx); - let interactivity = mem::take(&mut this.interactivity); + // todo!(change this to work in terms of on_drag_move or some such) + // .drag_over::(|style| { + // // todo!() why does not it work? z-index of elements? + // style.bg(cx.theme().colors().ghost_element_hover) + // }) + let mut interactivity = mem::take(&mut self.interactivity); interactivity.paint(bounds, bounds.size, state, cx, |_, _, cx| { - cx.handle_input(&this.focus, terminal_input_handler); + cx.handle_input(&self.focus, terminal_input_handler); - this.register_key_listeners(cx); + self.register_key_listeners(cx); for rect in &layout.rects { rect.paint(origin, &layout, cx); @@ -840,7 +847,7 @@ impl Element for TerminalElement { } }); - if this.cursor_visible { + if self.cursor_visible { cx.with_z_index(3, |cx| { if let Some(cursor) = &layout.cursor { cursor.paint(origin, cx); @@ -848,7 +855,7 @@ impl Element for TerminalElement { }); } - if let Some(element) = layout.hyperlink_tooltip.take() { + if let Some(mut element) = layout.hyperlink_tooltip.take() { let width: AvailableSpace = bounds.size.width.into(); let height: AvailableSpace = bounds.size.height.into(); element.draw(origin, Size { width, height }, cx) diff --git a/crates/ui2/src/components/popover_menu.rs b/crates/ui2/src/components/popover_menu.rs index 4b5144e7c7de468e823cd7e60d062083ea065386..0f2fa6d23f147ba846695d1177ca5189f9130b3e 100644 --- a/crates/ui2/src/components/popover_menu.rs +++ b/crates/ui2/src/components/popover_menu.rs @@ -182,12 +182,12 @@ impl Element for PopoverMenu { } fn paint( - self, + &mut self, _: Bounds, element_state: &mut Self::State, cx: &mut WindowContext, ) { - if let Some(child) = element_state.child_element.take() { + if let Some(mut child) = element_state.child_element.take() { child.paint(cx); } @@ -195,7 +195,7 @@ impl Element for PopoverMenu { element_state.child_bounds = Some(cx.layout_bounds(child_layout_id)); } - if let Some(menu) = element_state.menu_element.take() { + if let Some(mut menu) = element_state.menu_element.take() { menu.paint(cx); if let Some(child_bounds) = element_state.child_bounds { diff --git a/crates/ui2/src/components/right_click_menu.rs b/crates/ui2/src/components/right_click_menu.rs index 19031b2be70f7953e21a1305dd8957912ddfb63a..a3a454d652fa4dcbea48a6c8114c7c83e390c555 100644 --- a/crates/ui2/src/components/right_click_menu.rs +++ b/crates/ui2/src/components/right_click_menu.rs @@ -112,21 +112,21 @@ impl Element for RightClickMenu { } fn paint( - self, + &mut self, bounds: Bounds, element_state: &mut Self::State, cx: &mut WindowContext, ) { - if let Some(child) = element_state.child_element.take() { + if let Some(mut child) = element_state.child_element.take() { child.paint(cx); } - if let Some(menu) = element_state.menu_element.take() { + if let Some(mut menu) = element_state.menu_element.take() { menu.paint(cx); return; } - let Some(builder) = self.menu_builder else { + let Some(builder) = self.menu_builder.take() else { return; }; let menu = element_state.menu.clone(); diff --git a/crates/workspace2/src/pane_group.rs b/crates/workspace2/src/pane_group.rs index 5f14df833d1dfd5df8b83edf52dd0f1fce8ad2eb..5d79109dee817d9b35558904bd8497fa5f4ea364 100644 --- a/crates/workspace2/src/pane_group.rs +++ b/crates/workspace2/src/pane_group.rs @@ -896,7 +896,7 @@ mod element { } fn paint( - self, + &mut self, bounds: gpui::Bounds, state: &mut Self::State, cx: &mut ui::prelude::WindowContext, @@ -912,7 +912,7 @@ mod element { let mut bounding_boxes = self.bounding_boxes.lock(); bounding_boxes.clear(); - for (ix, child) in self.children.into_iter().enumerate() { + for (ix, mut child) in self.children.iter_mut().enumerate() { //todo!(active_pane_magnification) // If usign active pane magnification, need to switch to using // 1 for all non-active panes, and then the magnification for the From ad8165ae797d48db42689424429bc5f2e195edf7 Mon Sep 17 00:00:00 2001 From: Nathan Sobo Date: Thu, 14 Dec 2023 17:20:27 -0700 Subject: [PATCH 21/21] Rename draw2 -> draw_and_update_state --- crates/editor2/src/element.rs | 2 +- crates/gpui2/src/element.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/editor2/src/element.rs b/crates/editor2/src/element.rs index 831b6cd35ae8c80282ba312bc965fb8577e99bd3..0f1b565b9d818504e905ca2a668578ffafc04069 100644 --- a/crates/editor2/src/element.rs +++ b/crates/editor2/src/element.rs @@ -933,7 +933,7 @@ impl EditorElement { cx.stop_propagation(); }, )) - .draw2( + .draw_and_update_state( fold_bounds.origin, fold_bounds.size, cx, diff --git a/crates/gpui2/src/element.rs b/crates/gpui2/src/element.rs index f4bcb17f3c8180be4bef821092d6ef7ea1b0f88d..b446c2fe86eb4bd4ce12ddc183d55f58262aeaa9 100644 --- a/crates/gpui2/src/element.rs +++ b/crates/gpui2/src/element.rs @@ -23,7 +23,7 @@ pub trait IntoElement: Sized { self.into_element().into_any() } - fn draw2( + fn draw_and_update_state( self, origin: Point, available_space: Size,