Get diagnostics view almost building in the zed2 world

Co-Authored-By: Nathan Sobo <nathan@zed.dev>
This commit is contained in:
Julia 2023-11-14 19:25:55 -05:00
parent 96f0257fb3
commit f4eb219c75
22 changed files with 2251 additions and 91 deletions

28
Cargo.lock generated
View File

@ -2573,6 +2573,34 @@ dependencies = [
"workspace",
]
[[package]]
name = "diagnostics2"
version = "0.1.0"
dependencies = [
"anyhow",
"client2",
"collections",
"editor2",
"futures 0.3.28",
"gpui2",
"language2",
"log",
"lsp2",
"postage",
"project2",
"schemars",
"serde",
"serde_derive",
"serde_json",
"settings2",
"smallvec",
"theme2",
"ui2",
"unindent",
"util",
"workspace2",
]
[[package]]
name = "diff"
version = "0.1.13"

View File

@ -31,6 +31,7 @@ members = [
"crates/refineable",
"crates/refineable/derive_refineable",
"crates/diagnostics",
"crates/diagnostics2",
"crates/drag_and_drop",
"crates/editor",
"crates/feature_flags",

View File

@ -0,0 +1,43 @@
[package]
name = "diagnostics2"
version = "0.1.0"
edition = "2021"
publish = false
[lib]
path = "src/diagnostics.rs"
doctest = false
[dependencies]
collections = { path = "../collections" }
editor = { package = "editor2", path = "../editor2" }
gpui = { package = "gpui2", path = "../gpui2" }
ui = { package = "ui2", path = "../ui2" }
language = { package = "language2", path = "../language2" }
lsp = { package = "lsp2", path = "../lsp2" }
project = { package = "project2", path = "../project2" }
settings = { package = "settings2", path = "../settings2" }
theme = { package = "theme2", path = "../theme2" }
util = { path = "../util" }
workspace = { package = "workspace2", path = "../workspace2" }
log.workspace = true
anyhow.workspace = true
futures.workspace = true
schemars.workspace = true
serde.workspace = true
serde_derive.workspace = true
smallvec.workspace = true
postage.workspace = true
[dev-dependencies]
client = { package = "client2", path = "../client2", features = ["test-support"] }
editor = { package = "editor2", path = "../editor2", features = ["test-support"] }
language = { package = "language2", path = "../language2", features = ["test-support"] }
lsp = { package = "lsp2", path = "../lsp2", features = ["test-support"] }
gpui = { package = "gpui2", path = "../gpui2", features = ["test-support"] }
workspace = { package = "workspace2", path = "../workspace2", features = ["test-support"] }
theme = { package = "theme2", path = "../theme2", features = ["test-support"] }
serde_json.workspace = true
unindent.workspace = true

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,251 @@
use collections::HashSet;
use editor::{Editor, GoToDiagnostic};
use gpui::{
div, serde_json, AppContext, CursorStyle, Div, Entity, EventEmitter, MouseButton, Render,
Styled, Subscription, View, ViewContext, WeakView,
};
use language::Diagnostic;
use lsp::LanguageServerId;
use workspace::{item::ItemHandle, StatusItemView, ToolbarItemEvent, Workspace};
use crate::ProjectDiagnosticsEditor;
// todo!()
// pub fn init(cx: &mut AppContext) {
// cx.add_action(DiagnosticIndicator::go_to_next_diagnostic);
// }
pub struct DiagnosticIndicator {
summary: project::DiagnosticSummary,
active_editor: Option<WeakView<Editor>>,
workspace: WeakView<Workspace>,
current_diagnostic: Option<Diagnostic>,
in_progress_checks: HashSet<LanguageServerId>,
_observe_active_editor: Option<Subscription>,
}
impl Render for DiagnosticIndicator {
type Element = Div<Self>;
fn render(&mut self, cx: &mut ViewContext<Self>) -> Self::Element {
div().size_full().bg(gpui::red())
}
}
impl DiagnosticIndicator {
pub fn new(workspace: &Workspace, cx: &mut ViewContext<Self>) -> Self {
let project = workspace.project();
cx.subscribe(project, |this, project, event, cx| match event {
project::Event::DiskBasedDiagnosticsStarted { language_server_id } => {
this.in_progress_checks.insert(*language_server_id);
cx.notify();
}
project::Event::DiskBasedDiagnosticsFinished { language_server_id }
| project::Event::LanguageServerRemoved(language_server_id) => {
this.summary = project.read(cx).diagnostic_summary(cx);
this.in_progress_checks.remove(language_server_id);
cx.notify();
}
project::Event::DiagnosticsUpdated { .. } => {
this.summary = project.read(cx).diagnostic_summary(cx);
cx.notify();
}
_ => {}
})
.detach();
Self {
summary: project.read(cx).diagnostic_summary(cx),
in_progress_checks: project
.read(cx)
.language_servers_running_disk_based_diagnostics()
.collect(),
active_editor: None,
workspace: workspace.weak_handle(),
current_diagnostic: None,
_observe_active_editor: None,
}
}
fn go_to_next_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
if let Some(editor) = self.active_editor.as_ref().and_then(|e| e.upgrade()) {
editor.update(cx, |editor, cx| {
editor.go_to_diagnostic_impl(editor::Direction::Next, cx);
})
}
}
fn update(&mut self, editor: View<Editor>, cx: &mut ViewContext<Self>) {
let editor = editor.read(cx);
let buffer = editor.buffer().read(cx);
let cursor_position = editor.selections.newest::<usize>(cx).head();
let new_diagnostic = buffer
.snapshot(cx)
.diagnostics_in_range::<_, usize>(cursor_position..cursor_position, false)
.filter(|entry| !entry.range.is_empty())
.min_by_key(|entry| (entry.diagnostic.severity, entry.range.len()))
.map(|entry| entry.diagnostic);
if new_diagnostic != self.current_diagnostic {
self.current_diagnostic = new_diagnostic;
cx.notify();
}
}
}
// todo: is this nessesary anymore?
impl EventEmitter<ToolbarItemEvent> for DiagnosticIndicator {}
// impl View for DiagnosticIndicator {
// fn ui_name() -> &'static str {
// "DiagnosticIndicator"
// }
// fn render(&mut self, cx: &mut ViewContext<Self>) -> AnyElement<Self> {
// enum Summary {}
// enum Message {}
// let tooltip_style = theme::current(cx).tooltip.clone();
// let in_progress = !self.in_progress_checks.is_empty();
// let mut element = Flex::row().with_child(
// MouseEventHandler::new::<Summary, _>(0, cx, |state, cx| {
// let theme = theme::current(cx);
// let style = theme
// .workspace
// .status_bar
// .diagnostic_summary
// .style_for(state);
// let mut summary_row = Flex::row();
// if self.summary.error_count > 0 {
// summary_row.add_child(
// Svg::new("icons/error.svg")
// .with_color(style.icon_color_error)
// .constrained()
// .with_width(style.icon_width)
// .aligned()
// .contained()
// .with_margin_right(style.icon_spacing),
// );
// summary_row.add_child(
// Label::new(self.summary.error_count.to_string(), style.text.clone())
// .aligned(),
// );
// }
// if self.summary.warning_count > 0 {
// summary_row.add_child(
// Svg::new("icons/warning.svg")
// .with_color(style.icon_color_warning)
// .constrained()
// .with_width(style.icon_width)
// .aligned()
// .contained()
// .with_margin_right(style.icon_spacing)
// .with_margin_left(if self.summary.error_count > 0 {
// style.summary_spacing
// } else {
// 0.
// }),
// );
// summary_row.add_child(
// Label::new(self.summary.warning_count.to_string(), style.text.clone())
// .aligned(),
// );
// }
// if self.summary.error_count == 0 && self.summary.warning_count == 0 {
// summary_row.add_child(
// Svg::new("icons/check_circle.svg")
// .with_color(style.icon_color_ok)
// .constrained()
// .with_width(style.icon_width)
// .aligned()
// .into_any_named("ok-icon"),
// );
// }
// summary_row
// .constrained()
// .with_height(style.height)
// .contained()
// .with_style(if self.summary.error_count > 0 {
// style.container_error
// } else if self.summary.warning_count > 0 {
// style.container_warning
// } else {
// style.container_ok
// })
// })
// .with_cursor_style(CursorStyle::PointingHand)
// .on_click(MouseButton::Left, |_, this, cx| {
// if let Some(workspace) = this.workspace.upgrade(cx) {
// workspace.update(cx, |workspace, cx| {
// ProjectDiagnosticsEditor::deploy(workspace, &Default::default(), cx)
// })
// }
// })
// .with_tooltip::<Summary>(
// 0,
// "Project Diagnostics",
// Some(Box::new(crate::Deploy)),
// tooltip_style,
// cx,
// )
// .aligned()
// .into_any(),
// );
// let style = &theme::current(cx).workspace.status_bar;
// let item_spacing = style.item_spacing;
// if in_progress {
// element.add_child(
// Label::new("Checking…", style.diagnostic_message.default.text.clone())
// .aligned()
// .contained()
// .with_margin_left(item_spacing),
// );
// } else if let Some(diagnostic) = &self.current_diagnostic {
// let message_style = style.diagnostic_message.clone();
// element.add_child(
// MouseEventHandler::new::<Message, _>(1, cx, |state, _| {
// Label::new(
// diagnostic.message.split('\n').next().unwrap().to_string(),
// message_style.style_for(state).text.clone(),
// )
// .aligned()
// .contained()
// .with_margin_left(item_spacing)
// })
// .with_cursor_style(CursorStyle::PointingHand)
// .on_click(MouseButton::Left, |_, this, cx| {
// this.go_to_next_diagnostic(&Default::default(), cx)
// }),
// );
// }
// element.into_any_named("diagnostic indicator")
// }
// fn debug_json(&self, _: &gpui::AppContext) -> serde_json::Value {
// serde_json::json!({ "summary": self.summary })
// }
// }
impl StatusItemView for DiagnosticIndicator {
fn set_active_pane_item(
&mut self,
active_pane_item: Option<&dyn ItemHandle>,
cx: &mut ViewContext<Self>,
) {
if let Some(editor) = active_pane_item.and_then(|item| item.downcast::<Editor>()) {
self.active_editor = Some(editor.downgrade());
self._observe_active_editor = Some(cx.observe(&editor, Self::update));
self.update(editor, cx);
} else {
self.active_editor = None;
self.current_diagnostic = None;
self._observe_active_editor = None;
}
cx.notify();
}
}

View File

@ -0,0 +1,28 @@
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
#[derive(Deserialize, Debug)]
pub struct ProjectDiagnosticsSettings {
pub include_warnings: bool,
}
#[derive(Clone, Default, Serialize, Deserialize, JsonSchema, Debug)]
pub struct ProjectDiagnosticsSettingsContent {
include_warnings: Option<bool>,
}
impl settings::Settings for ProjectDiagnosticsSettings {
const KEY: Option<&'static str> = Some("diagnostics");
type FileContent = ProjectDiagnosticsSettingsContent;
fn load(
default_value: &Self::FileContent,
user_values: &[&Self::FileContent],
_cx: &mut gpui::AppContext,
) -> anyhow::Result<Self>
where
Self: Sized,
{
Self::load_via_json_merge(default_value, user_values)
}
}

View File

@ -0,0 +1,123 @@
use crate::{ProjectDiagnosticsEditor, ToggleWarnings};
use gpui::{
div, Action, CursorStyle, Div, Entity, EventEmitter, MouseButton, ParentComponent, Render,
View, ViewContext, WeakView,
};
use ui::{Icon, IconButton, StyledExt};
use workspace::{item::ItemHandle, ToolbarItemEvent, ToolbarItemLocation, ToolbarItemView};
pub struct ToolbarControls {
editor: Option<WeakView<ProjectDiagnosticsEditor>>,
}
impl Render for ToolbarControls {
type Element = Div<Self>;
fn render(&mut self, cx: &mut ViewContext<Self>) -> Self::Element {
div()
.h_flex()
.child(IconButton::new("toggle-warnings", Icon::Warning).on_click(|view, cx| todo!()))
}
}
impl EventEmitter<ToolbarItemEvent> for ToolbarControls {}
// impl View for ToolbarControls {
// fn ui_name() -> &'static str {
// "ToolbarControls"
// }
// fn render(&mut self, cx: &mut ViewContext<Self>) -> AnyElement<Self> {
// let include_warnings = self
// .editor
// .as_ref()
// .and_then(|editor| editor.upgrade(cx))
// .map(|editor| editor.read(cx).include_warnings)
// .unwrap_or(false);
// let tooltip = if include_warnings {
// "Exclude Warnings".into()
// } else {
// "Include Warnings".into()
// };
// Flex::row()
// .with_child(render_toggle_button(
// 0,
// "icons/warning.svg",
// include_warnings,
// (tooltip, Some(Box::new(ToggleWarnings))),
// cx,
// move |this, cx| {
// if let Some(editor) = this.editor.and_then(|editor| editor.upgrade(cx)) {
// editor.update(cx, |editor, cx| {
// editor.toggle_warnings(&Default::default(), cx)
// });
// }
// },
// ))
// .into_any()
// }
// }
impl ToolbarItemView for ToolbarControls {
fn set_active_pane_item(
&mut self,
active_pane_item: Option<&dyn ItemHandle>,
_: &mut ViewContext<Self>,
) -> ToolbarItemLocation {
if let Some(pane_item) = active_pane_item.as_ref() {
if let Some(editor) = pane_item.downcast::<ProjectDiagnosticsEditor>() {
self.editor = Some(editor.downgrade());
ToolbarItemLocation::PrimaryRight { flex: None }
} else {
ToolbarItemLocation::Hidden
}
} else {
ToolbarItemLocation::Hidden
}
}
}
impl ToolbarControls {
pub fn new() -> Self {
ToolbarControls { editor: None }
}
}
// fn render_toggle_button<
// F: 'static + Fn(&mut ToolbarControls, &mut EventContext<ToolbarControls>),
// >(
// index: usize,
// icon: &'static str,
// toggled: bool,
// tooltip: (String, Option<Box<dyn Action>>),
// cx: &mut ViewContext<ToolbarControls>,
// on_click: F,
// ) -> AnyElement<ToolbarControls> {
// enum Button {}
// let theme = theme::current(cx);
// let (tooltip_text, action) = tooltip;
// MouseEventHandler::new::<Button, _>(index, cx, |mouse_state, _| {
// let style = theme
// .workspace
// .toolbar
// .toggleable_tool
// .in_state(toggled)
// .style_for(mouse_state);
// Svg::new(icon)
// .with_color(style.color)
// .constrained()
// .with_width(style.icon_width)
// .aligned()
// .constrained()
// .with_width(style.button_width)
// .with_height(style.button_width)
// .contained()
// .with_style(style.container)
// })
// .with_cursor_style(CursorStyle::PointingHand)
// .on_click(MouseButton::Left, move |_, view, cx| on_click(view, cx))
// .with_tooltip::<Button>(index, tooltip_text, action, theme.tooltip.clone(), cx)
// .into_any_named("quick action bar button")
// }

View File

@ -2318,7 +2318,7 @@ impl Editor {
}
self.blink_manager.update(cx, BlinkManager::pause_blinking);
cx.emit(Event::SelectionsChanged { local });
cx.emit(EditorEvent::SelectionsChanged { local });
if self.selections.disjoint_anchors().len() == 1 {
cx.emit(SearchEvent::ActiveMatchChanged)
@ -4242,7 +4242,7 @@ impl Editor {
self.report_copilot_event(Some(completion.uuid.clone()), true, cx)
}
cx.emit(Event::InputHandled {
cx.emit(EditorEvent::InputHandled {
utf16_range_to_replace: None,
text: suggestion.text.to_string().into(),
});
@ -5664,7 +5664,7 @@ impl Editor {
self.request_autoscroll(Autoscroll::fit(), cx);
self.unmark_text(cx);
self.refresh_copilot_suggestions(true, cx);
cx.emit(Event::Edited);
cx.emit(EditorEvent::Edited);
}
}
@ -5679,7 +5679,7 @@ impl Editor {
self.request_autoscroll(Autoscroll::fit(), cx);
self.unmark_text(cx);
self.refresh_copilot_suggestions(true, cx);
cx.emit(Event::Edited);
cx.emit(EditorEvent::Edited);
}
}
@ -8123,7 +8123,7 @@ impl Editor {
log::error!("unexpectedly ended a transaction that wasn't started by this editor");
}
cx.emit(Event::Edited);
cx.emit(EditorEvent::Edited);
Some(tx_id)
} else {
None
@ -8711,7 +8711,7 @@ impl Editor {
if self.has_active_copilot_suggestion(cx) {
self.update_visible_copilot_suggestion(cx);
}
cx.emit(Event::BufferEdited);
cx.emit(EditorEvent::BufferEdited);
cx.emit(ItemEvent::Edit);
cx.emit(ItemEvent::UpdateBreadcrumbs);
cx.emit(SearchEvent::MatchesInvalidated);
@ -8750,7 +8750,7 @@ impl Editor {
predecessor,
excerpts,
} => {
cx.emit(Event::ExcerptsAdded {
cx.emit(EditorEvent::ExcerptsAdded {
buffer: buffer.clone(),
predecessor: *predecessor,
excerpts: excerpts.clone(),
@ -8759,7 +8759,7 @@ impl Editor {
}
multi_buffer::Event::ExcerptsRemoved { ids } => {
self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
cx.emit(Event::ExcerptsRemoved { ids: ids.clone() })
cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
}
multi_buffer::Event::Reparsed => {
cx.emit(ItemEvent::UpdateBreadcrumbs);
@ -8773,7 +8773,7 @@ impl Editor {
cx.emit(ItemEvent::UpdateTab);
cx.emit(ItemEvent::UpdateBreadcrumbs);
}
multi_buffer::Event::DiffBaseChanged => cx.emit(Event::DiffBaseChanged),
multi_buffer::Event::DiffBaseChanged => cx.emit(EditorEvent::DiffBaseChanged),
multi_buffer::Event::Closed => cx.emit(ItemEvent::CloseItem),
multi_buffer::Event::DiagnosticsUpdated => {
self.refresh_active_diagnostics(cx);
@ -9113,7 +9113,7 @@ impl Editor {
cx: &mut ViewContext<Self>,
) {
if !self.input_enabled {
cx.emit(Event::InputIgnored { text: text.into() });
cx.emit(EditorEvent::InputIgnored { text: text.into() });
return;
}
if let Some(relative_utf16_range) = relative_utf16_range {
@ -9177,7 +9177,7 @@ impl Editor {
// todo!()
// let focused_event = EditorFocused(cx.handle());
// cx.emit_global(focused_event);
cx.emit(Event::Focused);
cx.emit(EditorEvent::Focused);
}
if let Some(rename) = self.pending_rename.as_ref() {
let rename_editor_focus_handle = rename.editor.read(cx).focus_handle.clone();
@ -9207,7 +9207,7 @@ impl Editor {
.update(cx, |buffer, cx| buffer.remove_active_selections(cx));
self.hide_context_menu(cx);
hide_hover(self, cx);
cx.emit(Event::Blurred);
cx.emit(EditorEvent::Blurred);
cx.notify();
}
}
@ -9330,7 +9330,7 @@ impl Deref for EditorSnapshot {
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Event {
pub enum EditorEvent {
InputIgnored {
text: Arc<str>,
},
@ -9348,8 +9348,12 @@ pub enum Event {
},
BufferEdited,
Edited,
Reparsed,
Focused,
Blurred,
DirtyChanged,
Saved,
TitleChanged,
DiffBaseChanged,
SelectionsChanged {
local: bool,
@ -9358,6 +9362,7 @@ pub enum Event {
local: bool,
autoscroll: bool,
},
Closed,
}
pub struct EditorFocused(pub View<Editor>);
@ -9372,7 +9377,7 @@ pub struct EditorReleased(pub WeakView<Editor>);
// }
// }
//
impl EventEmitter<Event> for Editor {}
impl EventEmitter<EditorEvent> for Editor {}
impl Render for Editor {
type Element = EditorElement;
@ -9571,7 +9576,7 @@ impl InputHandler for Editor {
cx: &mut ViewContext<Self>,
) {
if !self.input_enabled {
cx.emit(Event::InputIgnored { text: text.into() });
cx.emit(EditorEvent::InputIgnored { text: text.into() });
return;
}
@ -9601,7 +9606,7 @@ impl InputHandler for Editor {
})
});
cx.emit(Event::InputHandled {
cx.emit(EditorEvent::InputHandled {
utf16_range_to_replace: range_to_replace,
text: text.into(),
});
@ -9632,7 +9637,7 @@ impl InputHandler for Editor {
cx: &mut ViewContext<Self>,
) {
if !self.input_enabled {
cx.emit(Event::InputIgnored { text: text.into() });
cx.emit(EditorEvent::InputIgnored { text: text.into() });
return;
}
@ -9675,7 +9680,7 @@ impl InputHandler for Editor {
})
});
cx.emit(Event::InputHandled {
cx.emit(EditorEvent::InputHandled {
utf16_range_to_replace: range_to_replace,
text: text.into(),
});

View File

@ -3853,7 +3853,7 @@ async fn test_select_larger_smaller_syntax_node(cx: &mut gpui::TestAppContext) {
let buffer = cx.build_model(|cx| MultiBuffer::singleton(buffer, cx));
let (view, mut cx) = cx.add_window_view(|cx| build_editor(buffer, cx));
view.condition::<crate::Event>(&cx, |view, cx| !view.buffer.read(cx).is_parsing(cx))
view.condition::<crate::EditorEvent>(&cx, |view, cx| !view.buffer.read(cx).is_parsing(cx))
.await;
view.update(&mut cx, |view, cx| {
@ -4020,7 +4020,7 @@ async fn test_autoindent_selections(cx: &mut gpui::TestAppContext) {
let (editor, mut cx) = cx.add_window_view(|cx| build_editor(buffer, cx));
let cx = &mut cx;
editor
.condition::<crate::Event>(cx, |editor, cx| !editor.buffer.read(cx).is_parsing(cx))
.condition::<crate::EditorEvent>(cx, |editor, cx| !editor.buffer.read(cx).is_parsing(cx))
.await;
editor.update(cx, |editor, cx| {
@ -4585,7 +4585,7 @@ async fn test_surround_with_pair(cx: &mut gpui::TestAppContext) {
let buffer = cx.build_model(|cx| MultiBuffer::singleton(buffer, cx));
let (view, mut cx) = cx.add_window_view(|cx| build_editor(buffer, cx));
let cx = &mut cx;
view.condition::<crate::Event>(cx, |view, cx| !view.buffer.read(cx).is_parsing(cx))
view.condition::<crate::EditorEvent>(cx, |view, cx| !view.buffer.read(cx).is_parsing(cx))
.await;
view.update(cx, |view, cx| {
@ -4737,7 +4737,7 @@ async fn test_delete_autoclose_pair(cx: &mut gpui::TestAppContext) {
let (editor, mut cx) = cx.add_window_view(|cx| build_editor(buffer, cx));
let cx = &mut cx;
editor
.condition::<crate::Event>(cx, |view, cx| !view.buffer.read(cx).is_parsing(cx))
.condition::<crate::EditorEvent>(cx, |view, cx| !view.buffer.read(cx).is_parsing(cx))
.await;
editor.update(cx, |editor, cx| {
@ -6304,7 +6304,7 @@ async fn test_extra_newline_insertion(cx: &mut gpui::TestAppContext) {
let buffer = cx.build_model(|cx| MultiBuffer::singleton(buffer, cx));
let (view, mut cx) = cx.add_window_view(|cx| build_editor(buffer, cx));
let cx = &mut cx;
view.condition::<crate::Event>(cx, |view, cx| !view.buffer.read(cx).is_parsing(cx))
view.condition::<crate::EditorEvent>(cx, |view, cx| !view.buffer.read(cx).is_parsing(cx))
.await;
view.update(cx, |view, cx| {

View File

@ -20,9 +20,9 @@ use collections::{BTreeMap, HashMap};
use gpui::{
point, px, relative, size, transparent_black, Action, AnyElement, AvailableSpace, BorrowWindow,
Bounds, Component, ContentMask, Corners, DispatchPhase, Edges, Element, ElementId,
ElementInputHandler, Entity, EntityId, Hsla, Line, MouseButton, MouseDownEvent, MouseMoveEvent,
MouseUpEvent, ParentComponent, Pixels, ScrollWheelEvent, Size, Style, Styled, TextRun,
TextStyle, View, ViewContext, WindowContext,
ElementInputHandler, Entity, EntityId, Hsla, InteractiveComponent, Line, MouseButton,
MouseDownEvent, MouseMoveEvent, MouseUpEvent, ParentComponent, Pixels, ScrollWheelEvent, Size,
Style, Styled, TextRun, TextStyle, View, ViewContext, WindowContext,
};
use itertools::Itertools;
use language::language_settings::ShowWhitespaceSetting;
@ -2062,6 +2062,7 @@ impl EditorElement {
}
h_stack()
.id("path header block")
.size_full()
.bg(gpui::red())
.child(filename.unwrap_or_else(|| "untitled".to_string()))
@ -2070,6 +2071,7 @@ impl EditorElement {
} else {
let text_style = style.text.clone();
h_stack()
.id("collapsed context")
.size_full()
.bg(gpui::red())
.child("")

View File

@ -1,7 +1,7 @@
use crate::{
editor_settings::SeedQuerySetting, link_go_to_definition::hide_link_definition,
movement::surrounding_word, persistence::DB, scroll::ScrollAnchor, Anchor, Autoscroll, Editor,
EditorSettings, Event, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot,
EditorEvent, EditorSettings, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot,
NavigationData, ToPoint as _,
};
use anyhow::{anyhow, Context, Result};
@ -41,11 +41,12 @@ use workspace::{
pub const MAX_TAB_TITLE_LEN: usize = 24;
impl FollowableEvents for Event {
impl FollowableEvents for EditorEvent {
fn to_follow_event(&self) -> Option<workspace::item::FollowEvent> {
match self {
Event::Edited => Some(FollowEvent::Unfollow),
Event::SelectionsChanged { local } | Event::ScrollPositionChanged { local, .. } => {
EditorEvent::Edited => Some(FollowEvent::Unfollow),
EditorEvent::SelectionsChanged { local }
| EditorEvent::ScrollPositionChanged { local, .. } => {
if *local {
Some(FollowEvent::Unfollow)
} else {
@ -60,7 +61,7 @@ impl FollowableEvents for Event {
impl EventEmitter<ItemEvent> for Editor {}
impl FollowableItem for Editor {
type FollowableEvent = Event;
type FollowableEvent = EditorEvent;
fn remote_id(&self) -> Option<ViewId> {
self.remote_id
}
@ -248,7 +249,7 @@ impl FollowableItem for Editor {
match update {
proto::update_view::Variant::Editor(update) => match event {
Event::ExcerptsAdded {
EditorEvent::ExcerptsAdded {
buffer,
predecessor,
excerpts,
@ -269,20 +270,20 @@ impl FollowableItem for Editor {
}
true
}
Event::ExcerptsRemoved { ids } => {
EditorEvent::ExcerptsRemoved { ids } => {
update
.deleted_excerpts
.extend(ids.iter().map(ExcerptId::to_proto));
true
}
Event::ScrollPositionChanged { .. } => {
EditorEvent::ScrollPositionChanged { .. } => {
let scroll_anchor = self.scroll_manager.anchor();
update.scroll_top_anchor = Some(serialize_anchor(&scroll_anchor.anchor));
update.scroll_x = scroll_anchor.offset.x;
update.scroll_y = scroll_anchor.offset.y;
true
}
Event::SelectionsChanged { .. } => {
EditorEvent::SelectionsChanged { .. } => {
update.selections = self
.selections
.disjoint_anchors()

View File

@ -6,8 +6,8 @@ use crate::{
display_map::{DisplaySnapshot, ToDisplayPoint},
hover_popover::hide_hover,
persistence::DB,
Anchor, DisplayPoint, Editor, EditorMode, Event, InlayHintRefreshReason, MultiBufferSnapshot,
ToPoint,
Anchor, DisplayPoint, Editor, EditorEvent, EditorMode, InlayHintRefreshReason,
MultiBufferSnapshot, ToPoint,
};
use gpui::{point, px, AppContext, Entity, Pixels, Styled, Task, ViewContext};
use language::{Bias, Point};
@ -224,7 +224,7 @@ impl ScrollManager {
cx: &mut ViewContext<Editor>,
) {
self.anchor = anchor;
cx.emit(Event::ScrollPositionChanged { local, autoscroll });
cx.emit(EditorEvent::ScrollPositionChanged { local, autoscroll });
self.show_scrollbar(cx);
self.autoscroll_request.take();
if let Some(workspace_id) = workspace_id {

View File

@ -71,7 +71,8 @@ impl<'a> EditorTestContext<'a> {
&self,
predicate: impl FnMut(&Editor, &AppContext) -> bool,
) -> impl Future<Output = ()> {
self.editor.condition::<crate::Event>(&self.cx, predicate)
self.editor
.condition::<crate::EditorEvent>(&self.cx, predicate)
}
#[track_caller]

View File

@ -83,13 +83,13 @@ impl GoToLine {
fn on_line_editor_event(
&mut self,
_: View<Editor>,
event: &editor::Event,
event: &editor::EditorEvent,
cx: &mut ViewContext<Self>,
) {
match event {
// todo!() this isn't working...
editor::Event::Blurred => cx.emit(ModalEvent::Dismissed),
editor::Event::BufferEdited { .. } => self.highlight_current_line(cx),
editor::EditorEvent::Blurred => cx.emit(ModalEvent::Dismissed),
editor::EditorEvent::BufferEdited { .. } => self.highlight_current_line(cx),
_ => {}
}
}

View File

@ -60,6 +60,7 @@ pub trait ParentComponent<V: 'static> {
}
trait ElementObject<V> {
fn element_id(&self) -> Option<ElementId>;
fn initialize(&mut self, view_state: &mut V, cx: &mut ViewContext<V>);
fn layout(&mut self, view_state: &mut V, cx: &mut ViewContext<V>) -> LayoutId;
fn paint(&mut self, view_state: &mut V, cx: &mut ViewContext<V>);
@ -119,6 +120,10 @@ where
E: Element<V>,
E::ElementState: 'static,
{
fn element_id(&self) -> Option<ElementId> {
self.element.element_id()
}
fn initialize(&mut self, view_state: &mut V, cx: &mut ViewContext<V>) {
let frame_state = if let Some(id) = self.element.element_id() {
cx.with_element_state(id, |element_state, cx| {
@ -271,6 +276,10 @@ impl<V> AnyElement<V> {
AnyElement(Box::new(RenderedElement::new(element)))
}
pub fn element_id(&self) -> Option<ElementId> {
self.0.element_id()
}
pub fn initialize(&mut self, view_state: &mut V, cx: &mut ViewContext<V>) {
self.0.initialize(view_state, cx);
}

View File

@ -269,17 +269,17 @@ impl<V: Render> From<WeakView<V>> for AnyWeakView {
}
}
impl<T, E> Render for T
where
T: 'static + FnMut(&mut WindowContext) -> E,
E: 'static + Send + Element<T>,
{
type Element = E;
// impl<T, E> Render for T
// where
// T: 'static + FnMut(&mut WindowContext) -> E,
// E: 'static + Send + Element<T>,
// {
// type Element = E;
fn render(&mut self, cx: &mut ViewContext<Self>) -> Self::Element {
(self)(cx)
}
}
// fn render(&mut self, cx: &mut ViewContext<Self>) -> Self::Element {
// (self)(cx)
// }
// }
mod any_view {
use crate::{AnyElement, AnyView, BorrowWindow, LayoutId, Render, WindowContext};

View File

@ -2476,6 +2476,18 @@ pub enum ElementId {
FocusHandle(FocusId),
}
impl TryInto<SharedString> for ElementId {
type Error = anyhow::Error;
fn try_into(self) -> anyhow::Result<SharedString> {
if let ElementId::Name(name) = self {
Ok(name)
} else {
Err(anyhow!("element id is not string"))
}
}
}
impl From<EntityId> for ElementId {
fn from(id: EntityId) -> Self {
ElementId::View(id)

View File

@ -137,10 +137,10 @@ impl<D: PickerDelegate> Picker<D> {
fn on_input_editor_event(
&mut self,
_: View<Editor>,
event: &editor::Event,
event: &editor::EditorEvent,
cx: &mut ViewContext<Self>,
) {
if let editor::Event::BufferEdited = event {
if let editor::EditorEvent::BufferEdited = event {
let query = self.editor.read(cx).text(cx);
self.update_matches(query, cx);
}

View File

@ -193,10 +193,11 @@ impl ProjectPanel {
let filename_editor = cx.build_view(|cx| Editor::single_line(cx));
cx.subscribe(&filename_editor, |this, _, event, cx| match event {
editor::Event::BufferEdited | editor::Event::SelectionsChanged { .. } => {
editor::EditorEvent::BufferEdited
| editor::EditorEvent::SelectionsChanged { .. } => {
this.autoscroll(cx);
}
editor::Event::Blurred => {
editor::EditorEvent::Blurred => {
if this
.edit_state
.as_ref()

View File

@ -16,8 +16,12 @@ pub enum Icon {
ArrowLeft,
ArrowRight,
ArrowUpRight,
AtSign,
AudioOff,
AudioOn,
Bell,
BellOff,
BellRing,
Bolt,
Check,
ChevronDown,
@ -25,12 +29,14 @@ pub enum Icon {
ChevronRight,
ChevronUp,
Close,
Copilot,
Dash,
Exit,
Envelope,
ExclamationTriangle,
Exit,
File,
FileGeneric,
FileDoc,
FileGeneric,
FileGit,
FileLock,
FileRust,
@ -43,6 +49,7 @@ pub enum Icon {
InlayHint,
MagicWand,
MagnifyingGlass,
MailOpen,
Maximize,
Menu,
MessageBubbles,
@ -57,14 +64,8 @@ pub enum Icon {
Split,
SplitMessage,
Terminal,
Warning,
XCircle,
Copilot,
Envelope,
Bell,
BellOff,
BellRing,
MailOpen,
AtSign,
}
impl Icon {
@ -74,8 +75,12 @@ impl Icon {
Icon::ArrowLeft => "icons/arrow_left.svg",
Icon::ArrowRight => "icons/arrow_right.svg",
Icon::ArrowUpRight => "icons/arrow_up_right.svg",
Icon::AtSign => "icons/at-sign.svg",
Icon::AudioOff => "icons/speaker-off.svg",
Icon::AudioOn => "icons/speaker-loud.svg",
Icon::Bell => "icons/bell.svg",
Icon::BellOff => "icons/bell-off.svg",
Icon::BellRing => "icons/bell-ring.svg",
Icon::Bolt => "icons/bolt.svg",
Icon::Check => "icons/check.svg",
Icon::ChevronDown => "icons/chevron_down.svg",
@ -83,12 +88,14 @@ impl Icon {
Icon::ChevronRight => "icons/chevron_right.svg",
Icon::ChevronUp => "icons/chevron_up.svg",
Icon::Close => "icons/x.svg",
Icon::Copilot => "icons/copilot.svg",
Icon::Dash => "icons/dash.svg",
Icon::Exit => "icons/exit.svg",
Icon::Envelope => "icons/feedback.svg",
Icon::ExclamationTriangle => "icons/warning.svg",
Icon::Exit => "icons/exit.svg",
Icon::File => "icons/file.svg",
Icon::FileGeneric => "icons/file_icons/file.svg",
Icon::FileDoc => "icons/file_icons/book.svg",
Icon::FileGeneric => "icons/file_icons/file.svg",
Icon::FileGit => "icons/file_icons/git.svg",
Icon::FileLock => "icons/file_icons/lock.svg",
Icon::FileRust => "icons/file_icons/rust.svg",
@ -101,6 +108,7 @@ impl Icon {
Icon::InlayHint => "icons/inlay_hint.svg",
Icon::MagicWand => "icons/magic-wand.svg",
Icon::MagnifyingGlass => "icons/magnifying_glass.svg",
Icon::MailOpen => "icons/mail-open.svg",
Icon::Maximize => "icons/maximize.svg",
Icon::Menu => "icons/menu.svg",
Icon::MessageBubbles => "icons/conversations.svg",
@ -115,14 +123,8 @@ impl Icon {
Icon::Split => "icons/split.svg",
Icon::SplitMessage => "icons/split_message.svg",
Icon::Terminal => "icons/terminal.svg",
Icon::Warning => "icons/warning.svg",
Icon::XCircle => "icons/error.svg",
Icon::Copilot => "icons/copilot.svg",
Icon::Envelope => "icons/feedback.svg",
Icon::Bell => "icons/bell.svg",
Icon::BellOff => "icons/bell-off.svg",
Icon::BellRing => "icons/bell-ring.svg",
Icon::MailOpen => "icons/mail-open.svg",
Icon::AtSign => "icons/at-sign.svg",
}
}
}

View File

@ -619,11 +619,11 @@ impl Pane {
self.items.iter()
}
// pub fn items_of_type<T: View>(&self) -> impl '_ + Iterator<Item = ViewHandle<T>> {
// self.items
// .iter()
// .filter_map(|item| item.as_any().clone().downcast())
// }
pub fn items_of_type<T: 'static>(&self) -> impl '_ + Iterator<Item = View<T>> {
self.items
.iter()
.filter_map(|item| item.to_any().clone().downcast().ok())
}
pub fn active_item(&self) -> Option<Box<dyn ItemHandle>> {
self.items.get(self.active_item_index).cloned()

View File

@ -67,7 +67,7 @@ use std::{
time::Duration,
};
use theme2::{ActiveTheme, ThemeSettings};
pub use toolbar::{ToolbarItemLocation, ToolbarItemView};
pub use toolbar::{ToolbarItemEvent, ToolbarItemLocation, ToolbarItemView};
use ui::TextColor;
use ui::{h_stack, Button, ButtonVariant, KeyBinding, Label, TextTooltip};
use util::ResultExt;
@ -1433,18 +1433,18 @@ impl Workspace {
self.panes.iter().flat_map(|pane| pane.read(cx).items())
}
// pub fn item_of_type<T: Item>(&self, cx: &AppContext) -> Option<View<T>> {
// self.items_of_type(cx).max_by_key(|item| item.id())
// }
pub fn item_of_type<T: Item>(&self, cx: &AppContext) -> Option<View<T>> {
self.items_of_type(cx).max_by_key(|item| item.entity_id())
}
// pub fn items_of_type<'a, T: Item>(
// &'a self,
// cx: &'a AppContext,
// ) -> impl 'a + Iterator<Item = View<T>> {
// self.panes
// .iter()
// .flat_map(|pane| pane.read(cx).items_of_type())
// }
pub fn items_of_type<'a, T: Item>(
&'a self,
cx: &'a AppContext,
) -> impl 'a + Iterator<Item = View<T>> {
self.panes
.iter()
.flat_map(|pane| pane.read(cx).items_of_type())
}
pub fn active_item(&self, cx: &AppContext) -> Option<Box<dyn ItemHandle>> {
self.active_pane().read(cx).active_item()