Remove 2 suffix for language_tools, search, terminal_view, auto_update

Co-authored-by: Mikayla <mikayla@zed.dev>
This commit is contained in:
Max Brunsfeld 2024-01-03 10:52:40 -08:00
parent 292b3397ab
commit 0ac8aae17b
51 changed files with 3900 additions and 14333 deletions

View file

@ -10,24 +10,25 @@ doctest = false
[dependencies]
collections = { path = "../collections" }
editor = { path = "../editor" }
settings = { path = "../settings" }
theme = { path = "../theme" }
language = { path = "../language" }
project = { path = "../project" }
workspace = { path = "../workspace" }
gpui = { path = "../gpui" }
editor = { package = "editor2", path = "../editor2" }
settings = { package = "settings2", path = "../settings2" }
theme = { package = "theme2", path = "../theme2" }
language = { package = "language2", path = "../language2" }
project = { package = "project2", path = "../project2" }
workspace = { package = "workspace2", path = "../workspace2" }
gpui = { package = "gpui2", path = "../gpui2" }
ui = { package = "ui2", path = "../ui2" }
util = { path = "../util" }
lsp = { path = "../lsp" }
lsp = { package = "lsp2", path = "../lsp2" }
futures.workspace = true
serde.workspace = true
anyhow.workspace = true
tree-sitter.workspace = true
[dev-dependencies]
client = { path = "../client", features = ["test-support"] }
editor = { path = "../editor", features = ["test-support"] }
gpui = { path = "../gpui", features = ["test-support"] }
client = { package = "client2", path = "../client2", features = ["test-support"] }
editor = { package = "editor2", path = "../editor2", features = ["test-support"] }
gpui = { package = "gpui2", path = "../gpui2", features = ["test-support"] }
util = { path = "../util", features = ["test-support"] }
env_logger.workspace = true
unindent.workspace = true

View file

@ -1,25 +1,20 @@
use collections::{HashMap, VecDeque};
use editor::{Editor, MoveToEnd};
use editor::{Editor, EditorEvent, MoveToEnd};
use futures::{channel::mpsc, StreamExt};
use gpui::{
actions,
elements::{
AnchorCorner, ChildView, Empty, Flex, Label, MouseEventHandler, Overlay, OverlayFitMode,
ParentElement, Stack,
},
platform::{CursorStyle, MouseButton},
AnyElement, AppContext, Element, Entity, ModelContext, ModelHandle, Subscription, View,
ViewContext, ViewHandle, WeakModelHandle,
actions, div, AnchorCorner, AnyElement, AppContext, Context, EventEmitter, FocusHandle,
FocusableView, IntoElement, Model, ModelContext, ParentElement, Render, Styled, Subscription,
View, ViewContext, VisualContext, WeakModel, WindowContext,
};
use language::{LanguageServerId, LanguageServerName};
use lsp::IoKind;
use project::{search::SearchQuery, Project};
use std::{borrow::Cow, sync::Arc};
use theme::{ui, Theme};
use ui::{h_stack, popover_menu, Button, Checkbox, Clickable, ContextMenu, Label, Selection};
use workspace::{
item::{Item, ItemHandle},
searchable::{SearchableItem, SearchableItemHandle},
ToolbarItemLocation, ToolbarItemView, Workspace, WorkspaceCreated,
searchable::{SearchEvent, SearchableItem, SearchableItemHandle},
ToolbarItemEvent, ToolbarItemLocation, ToolbarItemView, Workspace,
};
const SEND_LINE: &str = "// Send:";
@ -27,8 +22,8 @@ const RECEIVE_LINE: &str = "// Receive:";
const MAX_STORED_LOG_ENTRIES: usize = 2000;
pub struct LogStore {
projects: HashMap<WeakModelHandle<Project>, ProjectState>,
io_tx: mpsc::UnboundedSender<(WeakModelHandle<Project>, LanguageServerId, IoKind, String)>,
projects: HashMap<WeakModel<Project>, ProjectState>,
io_tx: mpsc::UnboundedSender<(WeakModel<Project>, LanguageServerId, IoKind, String)>,
}
struct ProjectState {
@ -49,19 +44,19 @@ struct LanguageServerRpcState {
}
pub struct LspLogView {
pub(crate) editor: ViewHandle<Editor>,
pub(crate) editor: View<Editor>,
editor_subscription: Subscription,
log_store: ModelHandle<LogStore>,
log_store: Model<LogStore>,
current_server_id: Option<LanguageServerId>,
is_showing_rpc_trace: bool,
project: ModelHandle<Project>,
project: Model<Project>,
focus_handle: FocusHandle,
_log_store_subscriptions: Vec<Subscription>,
}
pub struct LspLogToolbarItemView {
log_view: Option<ViewHandle<LspLogView>>,
log_view: Option<View<LspLogView>>,
_log_view_subscription: Option<Subscription>,
menu_open: bool,
}
#[derive(Copy, Clone, PartialEq, Eq)]
@ -83,37 +78,30 @@ pub(crate) struct LogMenuItem {
actions!(debug, [OpenLanguageServerLogs]);
pub fn init(cx: &mut AppContext) {
let log_store = cx.add_model(|cx| LogStore::new(cx));
let log_store = cx.new_model(|cx| LogStore::new(cx));
cx.subscribe_global::<WorkspaceCreated, _>({
let log_store = log_store.clone();
move |event, cx| {
let workspace = &event.0;
if let Some(workspace) = workspace.upgrade(cx) {
let project = workspace.read(cx).project().clone();
if project.read(cx).is_local() {
log_store.update(cx, |store, cx| {
store.add_project(&project, cx);
});
}
}
cx.observe_new_views(move |workspace: &mut Workspace, cx| {
let project = workspace.project();
if project.read(cx).is_local() {
log_store.update(cx, |store, cx| {
store.add_project(&project, cx);
});
}
})
.detach();
cx.add_action(
move |workspace: &mut Workspace, _: &OpenLanguageServerLogs, cx: _| {
let log_store = log_store.clone();
workspace.register_action(move |workspace, _: &OpenLanguageServerLogs, cx| {
let project = workspace.project().read(cx);
if project.is_local() {
workspace.add_item(
Box::new(cx.add_view(|cx| {
Box::new(cx.new_view(|cx| {
LspLogView::new(workspace.project().clone(), log_store.clone(), cx)
})),
cx,
);
}
},
);
});
})
.detach();
}
impl LogStore {
@ -123,28 +111,28 @@ impl LogStore {
projects: HashMap::default(),
io_tx,
};
cx.spawn_weak(|this, mut cx| async move {
cx.spawn(|this, mut cx| async move {
while let Some((project, server_id, io_kind, message)) = io_rx.next().await {
if let Some(this) = this.upgrade(&cx) {
if let Some(this) = this.upgrade() {
this.update(&mut cx, |this, cx| {
this.on_io(project, server_id, io_kind, &message, cx);
});
})?;
}
}
anyhow::Ok(())
})
.detach();
.detach_and_log_err(cx);
this
}
pub fn add_project(&mut self, project: &ModelHandle<Project>, cx: &mut ModelContext<Self>) {
pub fn add_project(&mut self, project: &Model<Project>, cx: &mut ModelContext<Self>) {
let weak_project = project.downgrade();
self.projects.insert(
weak_project,
project.downgrade(),
ProjectState {
servers: HashMap::default(),
_subscriptions: [
cx.observe_release(&project, move |this, _, _| {
cx.observe_release(project, move |this, _, _| {
this.projects.remove(&weak_project);
}),
cx.subscribe(project, |this, project, event, cx| match event {
@ -166,7 +154,7 @@ impl LogStore {
fn add_language_server(
&mut self,
project: &ModelHandle<Project>,
project: &Model<Project>,
id: LanguageServerId,
cx: &mut ModelContext<Self>,
) -> Option<&mut LanguageServerState> {
@ -194,22 +182,21 @@ impl LogStore {
server_state._io_logs_subscription = server.as_ref().map(|server| {
server.on_io(move |io_kind, message| {
io_tx
.unbounded_send((weak_project, id, io_kind, message.to_string()))
.unbounded_send((weak_project.clone(), id, io_kind, message.to_string()))
.ok();
})
});
let this = cx.weak_handle();
let this = cx.handle().downgrade();
let weak_project = project.downgrade();
server_state._lsp_logs_subscription = server.map(|server| {
let server_id = server.server_id();
server.on_notification::<lsp::notification::LogMessage, _>({
move |params, mut cx| {
if let Some((project, this)) =
weak_project.upgrade(&mut cx).zip(this.upgrade(&mut cx))
{
if let Some((project, this)) = weak_project.upgrade().zip(this.upgrade()) {
this.update(&mut cx, |this, cx| {
this.add_language_server_log(&project, server_id, &params.message, cx);
});
})
.ok();
}
}
})
@ -219,7 +206,7 @@ impl LogStore {
fn add_language_server_log(
&mut self,
project: &ModelHandle<Project>,
project: &Model<Project>,
id: LanguageServerId,
message: &str,
cx: &mut ModelContext<Self>,
@ -251,7 +238,7 @@ impl LogStore {
fn remove_language_server(
&mut self,
project: &ModelHandle<Project>,
project: &Model<Project>,
id: LanguageServerId,
cx: &mut ModelContext<Self>,
) -> Option<()> {
@ -263,7 +250,7 @@ impl LogStore {
fn server_logs(
&self,
project: &ModelHandle<Project>,
project: &Model<Project>,
server_id: LanguageServerId,
) -> Option<&VecDeque<String>> {
let weak_project = project.downgrade();
@ -274,7 +261,7 @@ impl LogStore {
fn enable_rpc_trace_for_language_server(
&mut self,
project: &ModelHandle<Project>,
project: &Model<Project>,
server_id: LanguageServerId,
) -> Option<&mut LanguageServerRpcState> {
let weak_project = project.downgrade();
@ -291,7 +278,7 @@ impl LogStore {
pub fn disable_rpc_trace_for_language_server(
&mut self,
project: &ModelHandle<Project>,
project: &Model<Project>,
server_id: LanguageServerId,
_: &mut ModelContext<Self>,
) -> Option<()> {
@ -304,7 +291,7 @@ impl LogStore {
fn on_io(
&mut self,
project: WeakModelHandle<Project>,
project: WeakModel<Project>,
language_server_id: LanguageServerId,
io_kind: IoKind,
message: &str,
@ -314,7 +301,7 @@ impl LogStore {
IoKind::StdOut => true,
IoKind::StdIn => false,
IoKind::StdErr => {
let project = project.upgrade(cx)?;
let project = project.upgrade()?;
let message = format!("stderr: {}", message.trim());
self.add_language_server_log(&project, language_server_id, &message, cx);
return Some(());
@ -365,8 +352,8 @@ impl LogStore {
impl LspLogView {
pub fn new(
project: ModelHandle<Project>,
log_store: ModelHandle<LogStore>,
project: Model<Project>,
log_store: Model<LogStore>,
cx: &mut ViewContext<Self>,
) -> Self {
let server_id = log_store
@ -427,14 +414,25 @@ impl LspLogView {
}
});
let (editor, editor_subscription) = Self::editor_for_logs(String::new(), cx);
let focus_handle = cx.focus_handle();
let focus_subscription = cx.on_focus(&focus_handle, |log_view, cx| {
cx.focus_view(&log_view.editor);
});
let mut this = Self {
focus_handle,
editor,
editor_subscription,
project,
log_store,
current_server_id: None,
is_showing_rpc_trace: false,
_log_store_subscriptions: vec![model_changes_subscription, events_subscriptions],
_log_store_subscriptions: vec![
model_changes_subscription,
events_subscriptions,
focus_subscription,
],
};
if let Some(server_id) = server_id {
this.show_logs_for_server(server_id, cx);
@ -445,15 +443,20 @@ impl LspLogView {
fn editor_for_logs(
log_contents: String,
cx: &mut ViewContext<Self>,
) -> (ViewHandle<Editor>, Subscription) {
let editor = cx.add_view(|cx| {
let mut editor = Editor::multi_line(None, cx);
) -> (View<Editor>, Subscription) {
let editor = cx.new_view(|cx| {
let mut editor = Editor::multi_line(cx);
editor.set_text(log_contents, cx);
editor.move_to_end(&MoveToEnd, cx);
editor.set_read_only(true);
editor
});
let editor_subscription = cx.subscribe(&editor, |_, _, event, cx| cx.emit(event.clone()));
let editor_subscription = cx.subscribe(
&editor,
|_, _, event: &EditorEvent, cx: &mut ViewContext<'_, LspLogView>| {
cx.emit(event.clone())
},
);
(editor, editor_subscription)
}
@ -516,6 +519,7 @@ impl LspLogView {
self.editor_subscription = editor_subscription;
cx.notify();
}
cx.focus(&self.focus_handle);
}
fn show_rpc_trace_for_server(
@ -540,22 +544,24 @@ impl LspLogView {
.as_singleton()
.expect("log buffer should be a singleton")
.update(cx, |_, cx| {
cx.spawn_weak({
cx.spawn({
let buffer = cx.handle();
|_, mut cx| async move {
let language = language.await.ok();
buffer.update(&mut cx, |buffer, cx| {
buffer.set_language(language, cx);
});
})
}
})
.detach();
.detach_and_log_err(cx);
});
self.editor = editor;
self.editor_subscription = editor_subscription;
cx.notify();
}
cx.focus(&self.focus_handle);
}
fn toggle_rpc_trace_for_server(
@ -588,33 +594,31 @@ fn log_contents(lines: &VecDeque<String>) -> String {
}
}
impl View for LspLogView {
fn ui_name() -> &'static str {
"LspLogView"
impl Render for LspLogView {
fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
self.editor
.update(cx, |editor, cx| editor.render(cx).into_any_element())
}
}
fn render(&mut self, cx: &mut ViewContext<Self>) -> AnyElement<Self> {
ChildView::new(&self.editor, cx).into_any()
}
fn focus_in(&mut self, _: gpui::AnyViewHandle, cx: &mut ViewContext<Self>) {
if cx.is_self_focused() {
cx.focus(&self.editor);
}
impl FocusableView for LspLogView {
fn focus_handle(&self, _: &AppContext) -> FocusHandle {
self.focus_handle.clone()
}
}
impl Item for LspLogView {
fn tab_content<V: 'static>(
&self,
_: Option<usize>,
style: &theme::Tab,
_: &AppContext,
) -> AnyElement<V> {
Label::new("LSP Logs", style.label.clone()).into_any()
type Event = EditorEvent;
fn to_item_events(event: &Self::Event, f: impl FnMut(workspace::item::ItemEvent)) {
Editor::to_item_events(event, f)
}
fn as_searchable(&self, handle: &ViewHandle<Self>) -> Option<Box<dyn SearchableItemHandle>> {
fn tab_content(&self, _: Option<usize>, _: bool, _: &WindowContext<'_>) -> AnyElement {
Label::new("LSP Logs").into_any_element()
}
fn as_searchable(&self, handle: &View<Self>) -> Option<Box<dyn SearchableItemHandle>> {
Some(Box::new(handle.clone()))
}
}
@ -622,15 +626,6 @@ impl Item for LspLogView {
impl SearchableItem for LspLogView {
type Match = <Editor as SearchableItem>::Match;
fn to_search_event(
&mut self,
event: &Self::Event,
cx: &mut ViewContext<Self>,
) -> Option<workspace::searchable::SearchEvent> {
self.editor
.update(cx, |editor, cx| editor.to_search_event(event, cx))
}
fn clear_matches(&mut self, cx: &mut ViewContext<Self>) {
self.editor.update(cx, |e, cx| e.clear_matches(cx))
}
@ -689,22 +684,21 @@ impl SearchableItem for LspLogView {
}
}
impl EventEmitter<ToolbarItemEvent> for LspLogToolbarItemView {}
impl ToolbarItemView for LspLogToolbarItemView {
fn set_active_pane_item(
&mut self,
active_pane_item: Option<&dyn ItemHandle>,
cx: &mut ViewContext<Self>,
) -> workspace::ToolbarItemLocation {
self.menu_open = false;
if let Some(item) = active_pane_item {
if let Some(log_view) = item.downcast::<LspLogView>() {
self.log_view = Some(log_view.clone());
self._log_view_subscription = Some(cx.observe(&log_view, |_, _, cx| {
cx.notify();
}));
return ToolbarItemLocation::PrimaryLeft {
flex: Some((1., false)),
};
return ToolbarItemLocation::PrimaryLeft;
}
}
self.log_view = None;
@ -713,15 +707,10 @@ impl ToolbarItemView for LspLogToolbarItemView {
}
}
impl View for LspLogToolbarItemView {
fn ui_name() -> &'static str {
"LspLogView"
}
fn render(&mut self, cx: &mut ViewContext<Self>) -> AnyElement<Self> {
let theme = theme::current(cx).clone();
let Some(log_view) = self.log_view.as_ref() else {
return Empty::new().into_any();
impl Render for LspLogToolbarItemView {
fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
let Some(log_view) = self.log_view.clone() else {
return div();
};
let (menu_rows, current_server_id) = log_view.update(cx, |log_view, cx| {
let menu_rows = log_view.menu_items(cx).unwrap_or_default();
@ -736,99 +725,128 @@ impl View for LspLogToolbarItemView {
None
}
});
let server_selected = current_server.is_some();
enum LspLogScroll {}
enum Menu {}
let lsp_menu = Stack::new()
.with_child(Self::render_language_server_menu_header(
current_server,
&theme,
cx,
))
.with_children(if self.menu_open {
Some(
Overlay::new(
MouseEventHandler::new::<Menu, _>(0, cx, move |_, cx| {
Flex::column()
.scrollable::<LspLogScroll>(0, None, cx)
.with_children(menu_rows.into_iter().map(|row| {
Self::render_language_server_menu_item(
row.server_id,
row.server_name,
&row.worktree_root_name,
row.rpc_trace_enabled,
row.logs_selected,
row.rpc_trace_selected,
&theme,
cx,
)
}))
.contained()
.with_style(theme.toolbar_dropdown_menu.container)
.constrained()
.with_width(400.)
.with_height(400.)
})
.on_down_out(MouseButton::Left, |_, this, cx| {
this.menu_open = false;
cx.notify()
}),
)
.with_hoverable(true)
.with_fit_mode(OverlayFitMode::SwitchAnchor)
.with_anchor_corner(AnchorCorner::TopLeft)
.with_z_index(999)
.aligned()
.bottom()
.left(),
)
} else {
None
})
.aligned()
.left()
.clipped();
enum LspCleanupButton {}
let log_cleanup_button =
MouseEventHandler::new::<LspCleanupButton, _>(1, cx, |state, cx| {
let theme = theme::current(cx).clone();
let style = theme
.workspace
.toolbar
.toggleable_text_tool
.in_state(server_selected)
.style_for(state);
Label::new("Clear", style.text.clone())
.aligned()
.contained()
.with_style(style.container)
.constrained()
.with_height(theme.toolbar_dropdown_menu.row_height / 6.0 * 5.0)
})
.on_click(MouseButton::Left, move |_, this, cx| {
if let Some(log_view) = this.log_view.as_ref() {
log_view.update(cx, |log_view, cx| {
log_view.editor.update(cx, |editor, cx| {
editor.set_read_only(false);
editor.clear(cx);
editor.set_read_only(true);
});
let log_toolbar_view = cx.view().clone();
let lsp_menu = popover_menu("LspLogView")
.anchor(AnchorCorner::TopLeft)
.trigger(Button::new(
"language_server_menu_header",
current_server
.and_then(|row| {
Some(Cow::Owned(format!(
"{} ({}) - {}",
row.server_name.0,
row.worktree_root_name,
if row.rpc_trace_selected {
RPC_MESSAGES
} else {
SERVER_LOGS
},
)))
})
}
})
.with_cursor_style(CursorStyle::PointingHand)
.aligned()
.right();
.unwrap_or_else(|| "No server selected".into()),
))
.menu(move |cx| {
let menu_rows = menu_rows.clone();
let log_view = log_view.clone();
let log_toolbar_view = log_toolbar_view.clone();
ContextMenu::build(cx, move |mut menu, cx| {
for (ix, row) in menu_rows.into_iter().enumerate() {
let server_selected = Some(row.server_id) == current_server_id;
menu = menu
.header(format!(
"{} ({})",
row.server_name.0, row.worktree_root_name
))
.entry(
SERVER_LOGS,
None,
cx.handler_for(&log_view, move |view, cx| {
view.show_logs_for_server(row.server_id, cx);
}),
);
if server_selected && row.logs_selected {
debug_assert_eq!(
Some(ix * 3 + 1),
menu.select_last(),
"Could not scroll to a just added LSP menu item"
);
}
Flex::row()
.with_child(lsp_menu)
.with_child(log_cleanup_button)
.contained()
.aligned()
.left()
.into_any_named("lsp log controls")
menu = menu.custom_entry(
{
let log_toolbar_view = log_toolbar_view.clone();
move |cx| {
h_stack()
.w_full()
.justify_between()
.child(Label::new(RPC_MESSAGES))
.child(
div().z_index(120).child(
Checkbox::new(
ix,
if row.rpc_trace_enabled {
Selection::Selected
} else {
Selection::Unselected
},
)
.on_click(cx.listener_for(
&log_toolbar_view,
move |view, selection, cx| {
let enabled = matches!(
selection,
Selection::Selected
);
view.toggle_logging_for_server(
row.server_id,
enabled,
cx,
);
cx.stop_propagation();
},
)),
),
)
.into_any_element()
}
},
cx.handler_for(&log_view, move |view, cx| {
view.show_rpc_trace_for_server(row.server_id, cx);
}),
);
if server_selected && row.rpc_trace_selected {
debug_assert_eq!(
Some(ix * 3 + 2),
menu.select_last(),
"Could not scroll to a just added LSP menu item"
);
}
}
menu
})
.into()
});
h_stack().size_full().child(lsp_menu).child(
div()
.child(
Button::new("clear_log_button", "Clear").on_click(cx.listener(
|this, _, cx| {
if let Some(log_view) = this.log_view.as_ref() {
log_view.update(cx, |log_view, cx| {
log_view.editor.update(cx, |editor, cx| {
editor.set_read_only(false);
editor.clear(cx);
editor.set_read_only(true);
});
})
}
},
)),
)
.ml_2(),
)
}
}
@ -838,17 +856,11 @@ const SERVER_LOGS: &str = "Server Logs";
impl LspLogToolbarItemView {
pub fn new() -> Self {
Self {
menu_open: false,
log_view: None,
_log_view_subscription: None,
}
}
fn toggle_menu(&mut self, cx: &mut ViewContext<Self>) {
self.menu_open = !self.menu_open;
cx.notify();
}
fn toggle_logging_for_server(
&mut self,
id: LanguageServerId,
@ -862,144 +874,11 @@ impl LspLogToolbarItemView {
log_view.show_logs_for_server(id, cx);
cx.notify();
}
cx.focus(&log_view.focus_handle);
});
}
cx.notify();
}
fn show_logs_for_server(&mut self, id: LanguageServerId, cx: &mut ViewContext<Self>) {
if let Some(log_view) = &self.log_view {
log_view.update(cx, |view, cx| view.show_logs_for_server(id, cx));
self.menu_open = false;
cx.notify();
}
}
fn show_rpc_trace_for_server(&mut self, id: LanguageServerId, cx: &mut ViewContext<Self>) {
if let Some(log_view) = &self.log_view {
log_view.update(cx, |view, cx| view.show_rpc_trace_for_server(id, cx));
self.menu_open = false;
cx.notify();
}
}
fn render_language_server_menu_header(
current_server: Option<LogMenuItem>,
theme: &Arc<Theme>,
cx: &mut ViewContext<Self>,
) -> impl Element<Self> {
enum ToggleMenu {}
MouseEventHandler::new::<ToggleMenu, _>(0, cx, move |state, _| {
let label: Cow<str> = current_server
.and_then(|row| {
Some(
format!(
"{} ({}) - {}",
row.server_name.0,
row.worktree_root_name,
if row.rpc_trace_selected {
RPC_MESSAGES
} else {
SERVER_LOGS
},
)
.into(),
)
})
.unwrap_or_else(|| "No server selected".into());
let style = theme.toolbar_dropdown_menu.header.style_for(state);
Label::new(label, style.text.clone())
.contained()
.with_style(style.container)
})
.with_cursor_style(CursorStyle::PointingHand)
.on_click(MouseButton::Left, move |_, view, cx| {
view.toggle_menu(cx);
})
}
fn render_language_server_menu_item(
id: LanguageServerId,
name: LanguageServerName,
worktree_root_name: &str,
rpc_trace_enabled: bool,
logs_selected: bool,
rpc_trace_selected: bool,
theme: &Arc<Theme>,
cx: &mut ViewContext<Self>,
) -> impl Element<Self> {
enum ActivateLog {}
enum ActivateRpcTrace {}
enum LanguageServerCheckbox {}
Flex::column()
.with_child({
let style = &theme.toolbar_dropdown_menu.section_header;
Label::new(
format!("{} ({})", name.0, worktree_root_name),
style.text.clone(),
)
.contained()
.with_style(style.container)
.constrained()
.with_height(theme.toolbar_dropdown_menu.row_height)
})
.with_child(
MouseEventHandler::new::<ActivateLog, _>(id.0, cx, move |state, _| {
let style = theme
.toolbar_dropdown_menu
.item
.in_state(logs_selected)
.style_for(state);
Label::new(SERVER_LOGS, style.text.clone())
.contained()
.with_style(style.container)
.constrained()
.with_height(theme.toolbar_dropdown_menu.row_height)
})
.with_cursor_style(CursorStyle::PointingHand)
.on_click(MouseButton::Left, move |_, view, cx| {
view.show_logs_for_server(id, cx);
}),
)
.with_child(
MouseEventHandler::new::<ActivateRpcTrace, _>(id.0, cx, move |state, cx| {
let style = theme
.toolbar_dropdown_menu
.item
.in_state(rpc_trace_selected)
.style_for(state);
Flex::row()
.with_child(
Label::new(RPC_MESSAGES, style.text.clone())
.constrained()
.with_height(theme.toolbar_dropdown_menu.row_height),
)
.with_child(
ui::checkbox_with_label::<LanguageServerCheckbox, _, Self, _>(
Empty::new(),
&theme.welcome.checkbox,
rpc_trace_enabled,
id.0,
cx,
move |this, enabled, cx| {
this.toggle_logging_for_server(id, enabled, cx);
},
)
.flex_float(),
)
.align_children_center()
.contained()
.with_style(style.container)
.constrained()
.with_height(theme.toolbar_dropdown_menu.row_height)
})
.with_cursor_style(CursorStyle::PointingHand)
.on_click(MouseButton::Left, move |_, view, cx| {
view.show_rpc_trace_for_server(id, cx);
}),
)
}
}
pub enum Event {
@ -1010,14 +889,7 @@ pub enum Event {
},
}
impl Entity for LogStore {
type Event = Event;
}
impl Entity for LspLogView {
type Event = editor::Event;
}
impl Entity for LspLogToolbarItemView {
type Event = ();
}
impl EventEmitter<Event> for LogStore {}
impl EventEmitter<Event> for LspLogView {}
impl EventEmitter<EditorEvent> for LspLogView {}
impl EventEmitter<SearchEvent> for LspLogView {}

View file

@ -4,7 +4,7 @@ use crate::lsp_log::LogMenuItem;
use super::*;
use futures::StreamExt;
use gpui::{serde_json::json, TestAppContext};
use gpui::{serde_json::json, Context, TestAppContext, VisualTestContext};
use language::{tree_sitter_rust, FakeLspAdapter, Language, LanguageConfig, LanguageServerName};
use project::{FakeFs, Project};
use settings::SettingsStore;
@ -32,7 +32,7 @@ async fn test_lsp_logs(cx: &mut TestAppContext) {
}))
.await;
let fs = FakeFs::new(cx.background());
let fs = FakeFs::new(cx.background_executor.clone());
fs.insert_tree(
"/the-root",
json!({
@ -46,7 +46,7 @@ async fn test_lsp_logs(cx: &mut TestAppContext) {
project.languages().add(Arc::new(rust_language));
});
let log_store = cx.add_model(|cx| LogStore::new(cx));
let log_store = cx.new_model(|cx| LogStore::new(cx));
log_store.update(cx, |store, cx| store.add_project(&project, cx));
let _rust_buffer = project
@ -61,17 +61,17 @@ async fn test_lsp_logs(cx: &mut TestAppContext) {
.receive_notification::<lsp::notification::DidOpenTextDocument>()
.await;
let log_view = cx
.add_window(|cx| LspLogView::new(project.clone(), log_store.clone(), cx))
.root(cx);
let window = cx.add_window(|cx| LspLogView::new(project.clone(), log_store.clone(), cx));
let log_view = window.root(cx).unwrap();
let mut cx = VisualTestContext::from_window(*window, cx);
language_server.notify::<lsp::notification::LogMessage>(lsp::LogMessageParams {
message: "hello from the server".into(),
typ: lsp::MessageType::INFO,
});
cx.foreground().run_until_parked();
cx.executor().run_until_parked();
log_view.read_with(cx, |view, cx| {
log_view.update(&mut cx, |view, cx| {
assert_eq!(
view.menu_items(cx).unwrap(),
&[LogMenuItem {
@ -79,7 +79,7 @@ async fn test_lsp_logs(cx: &mut TestAppContext) {
server_name: LanguageServerName("the-rust-language-server".into()),
worktree_root_name: project
.read(cx)
.worktrees(cx)
.worktrees()
.next()
.unwrap()
.read(cx)
@ -95,11 +95,10 @@ async fn test_lsp_logs(cx: &mut TestAppContext) {
}
fn init_test(cx: &mut gpui::TestAppContext) {
cx.foreground().forbid_parking();
cx.update(|cx| {
cx.set_global(SettingsStore::test(cx));
theme::init((), cx);
let settings_store = SettingsStore::test(cx);
cx.set_global(settings_store);
theme::init(theme::LoadThemes::JustBase, cx);
language::init(cx);
client::init_settings(cx);
Project::init_settings(cx);

View file

@ -1,85 +1,85 @@
use editor::{scroll::autoscroll::Autoscroll, Anchor, Editor, ExcerptId};
use gpui::{
actions,
elements::{
AnchorCorner, Empty, Flex, Label, MouseEventHandler, Overlay, OverlayFitMode,
ParentElement, ScrollTarget, Stack, UniformList, UniformListState,
},
fonts::TextStyle,
platform::{CursorStyle, MouseButton},
AppContext, Element, Entity, ModelHandle, View, ViewContext, ViewHandle, WeakViewHandle,
actions, canvas, div, rems, uniform_list, AnyElement, AppContext, AvailableSpace, Div,
EventEmitter, FocusHandle, FocusableView, Hsla, InteractiveElement, IntoElement, Model,
MouseButton, MouseDownEvent, MouseMoveEvent, ParentElement, Pixels, Render, Styled,
UniformListScrollHandle, View, ViewContext, VisualContext, WeakView, WindowContext,
};
use language::{Buffer, OwnedSyntaxLayerInfo, SyntaxLayerInfo};
use std::{mem, ops::Range, sync::Arc};
use theme::{Theme, ThemeSettings};
use language::{Buffer, OwnedSyntaxLayerInfo};
use settings::Settings;
use std::{mem, ops::Range};
use theme::{ActiveTheme, ThemeSettings};
use tree_sitter::{Node, TreeCursor};
use ui::{h_stack, popover_menu, ButtonLike, Color, ContextMenu, Label, LabelCommon, PopoverMenu};
use workspace::{
item::{Item, ItemHandle},
ToolbarItemLocation, ToolbarItemView, Workspace,
SplitDirection, ToolbarItemEvent, ToolbarItemLocation, ToolbarItemView, Workspace,
};
actions!(debug, [OpenSyntaxTreeView]);
pub fn init(cx: &mut AppContext) {
cx.add_action(
move |workspace: &mut Workspace, _: &OpenSyntaxTreeView, cx: _| {
cx.observe_new_views(|workspace: &mut Workspace, _| {
workspace.register_action(|workspace, _: &OpenSyntaxTreeView, cx| {
let active_item = workspace.active_item(cx);
let workspace_handle = workspace.weak_handle();
let syntax_tree_view =
cx.add_view(|cx| SyntaxTreeView::new(workspace_handle, active_item, cx));
workspace.add_item(Box::new(syntax_tree_view), cx);
},
);
cx.new_view(|cx| SyntaxTreeView::new(workspace_handle, active_item, cx));
workspace.split_item(SplitDirection::Right, Box::new(syntax_tree_view), cx)
});
})
.detach();
}
pub struct SyntaxTreeView {
workspace_handle: WeakViewHandle<Workspace>,
workspace_handle: WeakView<Workspace>,
editor: Option<EditorState>,
mouse_y: Option<f32>,
line_height: Option<f32>,
list_state: UniformListState,
mouse_y: Option<Pixels>,
line_height: Option<Pixels>,
list_scroll_handle: UniformListScrollHandle,
selected_descendant_ix: Option<usize>,
hovered_descendant_ix: Option<usize>,
focus_handle: FocusHandle,
}
pub struct SyntaxTreeToolbarItemView {
tree_view: Option<ViewHandle<SyntaxTreeView>>,
tree_view: Option<View<SyntaxTreeView>>,
subscription: Option<gpui::Subscription>,
menu_open: bool,
}
struct EditorState {
editor: ViewHandle<Editor>,
editor: View<Editor>,
active_buffer: Option<BufferState>,
_subscription: gpui::Subscription,
}
#[derive(Clone)]
struct BufferState {
buffer: ModelHandle<Buffer>,
buffer: Model<Buffer>,
excerpt_id: ExcerptId,
active_layer: Option<OwnedSyntaxLayerInfo>,
}
impl SyntaxTreeView {
pub fn new(
workspace_handle: WeakViewHandle<Workspace>,
workspace_handle: WeakView<Workspace>,
active_item: Option<Box<dyn ItemHandle>>,
cx: &mut ViewContext<Self>,
) -> Self {
let mut this = Self {
workspace_handle: workspace_handle.clone(),
list_state: UniformListState::default(),
list_scroll_handle: UniformListScrollHandle::new(),
editor: None,
mouse_y: None,
line_height: None,
hovered_descendant_ix: None,
selected_descendant_ix: None,
focus_handle: cx.focus_handle(),
};
this.workspace_updated(active_item, cx);
cx.observe(
&workspace_handle.upgrade(cx).unwrap(),
&workspace_handle.upgrade().unwrap(),
|this, workspace, cx| {
this.workspace_updated(workspace.read(cx).active_item(cx), cx);
},
@ -95,7 +95,7 @@ impl SyntaxTreeView {
cx: &mut ViewContext<Self>,
) {
if let Some(item) = active_item {
if item.id() != cx.view_id() {
if item.item_id() != cx.entity_id() {
if let Some(editor) = item.act_as::<Editor>(cx) {
self.set_editor(editor, cx);
}
@ -103,7 +103,7 @@ impl SyntaxTreeView {
}
}
fn set_editor(&mut self, editor: ViewHandle<Editor>, cx: &mut ViewContext<Self>) {
fn set_editor(&mut self, editor: View<Editor>, cx: &mut ViewContext<Self>) {
if let Some(state) = &self.editor {
if state.editor == editor {
return;
@ -115,8 +115,8 @@ impl SyntaxTreeView {
let subscription = cx.subscribe(&editor, |this, _, event, cx| {
let did_reparse = match event {
editor::Event::Reparsed => true,
editor::Event::SelectionsChanged { .. } => false,
editor::EditorEvent::Reparsed => true,
editor::EditorEvent::SelectionsChanged { .. } => false,
_ => return,
};
this.editor_updated(did_reparse, cx);
@ -202,15 +202,15 @@ impl SyntaxTreeView {
let descendant_ix = cursor.descendant_index();
self.selected_descendant_ix = Some(descendant_ix);
self.list_state.scroll_to(ScrollTarget::Show(descendant_ix));
self.list_scroll_handle.scroll_to_item(descendant_ix);
cx.notify();
Some(())
}
fn handle_click(&mut self, y: f32, cx: &mut ViewContext<SyntaxTreeView>) -> Option<()> {
fn handle_click(&mut self, y: Pixels, cx: &mut ViewContext<SyntaxTreeView>) -> Option<()> {
let line_height = self.line_height?;
let ix = ((self.list_state.scroll_top() + y) / line_height) as usize;
let ix = ((self.list_scroll_handle.scroll_top() + y) / line_height) as usize;
self.update_editor_with_range_for_descendant_ix(ix, cx, |editor, mut range, cx| {
// Put the cursor at the beginning of the node.
@ -225,14 +225,14 @@ impl SyntaxTreeView {
fn hover_state_changed(&mut self, cx: &mut ViewContext<SyntaxTreeView>) {
if let Some((y, line_height)) = self.mouse_y.zip(self.line_height) {
let ix = ((self.list_state.scroll_top() + y) / line_height) as usize;
let ix = ((self.list_scroll_handle.scroll_top() + y) / line_height) as usize;
if self.hovered_descendant_ix != Some(ix) {
self.hovered_descendant_ix = Some(ix);
self.update_editor_with_range_for_descendant_ix(ix, cx, |editor, range, cx| {
editor.clear_background_highlights::<Self>(cx);
editor.highlight_background::<Self>(
vec![range],
|theme| theme.editor.document_highlight_write_background,
|theme| theme.editor_document_highlight_write_background,
cx,
);
});
@ -275,113 +275,48 @@ impl SyntaxTreeView {
Some(())
}
fn render_node(
cursor: &TreeCursor,
depth: u32,
selected: bool,
hovered: bool,
list_hovered: bool,
style: &TextStyle,
editor_theme: &theme::Editor,
cx: &AppContext,
) -> gpui::AnyElement<SyntaxTreeView> {
let node = cursor.node();
let mut range_style = style.clone();
let em_width = style.em_width(cx.font_cache());
let gutter_padding = (em_width * editor_theme.gutter_padding_factor).round();
range_style.color = editor_theme.line_number;
let mut anonymous_node_style = style.clone();
let string_color = editor_theme
.syntax
.highlights
.iter()
.find_map(|(name, style)| (name == "string").then(|| style.color)?);
let property_color = editor_theme
.syntax
.highlights
.iter()
.find_map(|(name, style)| (name == "property").then(|| style.color)?);
if let Some(color) = string_color {
anonymous_node_style.color = color;
}
let mut row = Flex::row();
fn render_node(cursor: &TreeCursor, depth: u32, selected: bool, cx: &AppContext) -> Div {
let colors = cx.theme().colors();
let mut row = h_stack();
if let Some(field_name) = cursor.field_name() {
let mut field_style = style.clone();
if let Some(color) = property_color {
field_style.color = color;
}
row.add_children([
Label::new(field_name, field_style),
Label::new(": ", style.clone()),
]);
row = row.children([Label::new(field_name).color(Color::Info), Label::new(": ")]);
}
let node = cursor.node();
return row
.with_child(
if node.is_named() {
Label::new(node.kind(), style.clone())
} else {
Label::new(format!("\"{}\"", node.kind()), anonymous_node_style)
}
.contained()
.with_margin_right(em_width),
)
.with_child(Label::new(format_node_range(node), range_style))
.contained()
.with_background_color(if selected {
editor_theme.selection.selection
} else if hovered && list_hovered {
editor_theme.active_line_background
.child(if node.is_named() {
Label::new(node.kind()).color(Color::Default)
} else {
Default::default()
Label::new(format!("\"{}\"", node.kind())).color(Color::Created)
})
.with_padding_left(gutter_padding + depth as f32 * 18.0)
.into_any();
.child(
div()
.child(Label::new(format_node_range(node)).color(Color::Muted))
.pl_1(),
)
.text_bg(if selected {
colors.element_selected
} else {
Hsla::default()
})
.pl(rems(depth as f32))
.hover(|style| style.bg(colors.element_hover));
}
}
impl Entity for SyntaxTreeView {
type Event = ();
}
impl View for SyntaxTreeView {
fn ui_name() -> &'static str {
"SyntaxTreeView"
}
fn render(&mut self, cx: &mut gpui::ViewContext<'_, '_, Self>) -> gpui::AnyElement<Self> {
let settings = settings::get::<ThemeSettings>(cx);
let font_family_id = settings.buffer_font_family;
let font_family_name = cx.font_cache().family_name(font_family_id).unwrap();
let font_properties = Default::default();
let font_id = cx
.font_cache()
.select_font(font_family_id, &font_properties)
.unwrap();
let font_size = settings.buffer_font_size(cx);
let editor_theme = settings.theme.editor.clone();
let style = TextStyle {
color: editor_theme.text_color,
font_family_name,
font_family_id,
font_id,
font_size,
font_properties: Default::default(),
underline: Default::default(),
soft_wrap: false,
};
let line_height = cx.font_cache().line_height(font_size);
impl Render for SyntaxTreeView {
fn render(&mut self, cx: &mut gpui::ViewContext<'_, Self>) -> impl IntoElement {
let settings = ThemeSettings::get_global(cx);
let line_height = cx
.text_style()
.line_height_in_pixels(settings.buffer_font_size(cx));
if Some(line_height) != self.line_height {
self.line_height = Some(line_height);
self.hover_state_changed(cx);
}
let mut rendered = div().flex_1();
if let Some(layer) = self
.editor
.as_ref()
@ -389,108 +324,118 @@ impl View for SyntaxTreeView {
.and_then(|buffer| buffer.active_layer.as_ref())
{
let layer = layer.clone();
let theme = editor_theme.clone();
return MouseEventHandler::new::<Self, _>(0, cx, move |state, cx| {
let list_hovered = state.hovered();
UniformList::new(
self.list_state.clone(),
layer.node().descendant_count(),
cx,
move |this, range, items, cx| {
let mut cursor = layer.node().walk();
let mut descendant_ix = range.start as usize;
cursor.goto_descendant(descendant_ix);
let mut depth = cursor.depth();
let mut visited_children = false;
while descendant_ix < range.end {
if visited_children {
if cursor.goto_next_sibling() {
visited_children = false;
} else if cursor.goto_parent() {
depth -= 1;
} else {
break;
}
let list = uniform_list(
cx.view().clone(),
"SyntaxTreeView",
layer.node().descendant_count(),
move |this, range, cx| {
let mut items = Vec::new();
let mut cursor = layer.node().walk();
let mut descendant_ix = range.start as usize;
cursor.goto_descendant(descendant_ix);
let mut depth = cursor.depth();
let mut visited_children = false;
while descendant_ix < range.end {
if visited_children {
if cursor.goto_next_sibling() {
visited_children = false;
} else if cursor.goto_parent() {
depth -= 1;
} else {
items.push(Self::render_node(
&cursor,
depth,
Some(descendant_ix) == this.selected_descendant_ix,
Some(descendant_ix) == this.hovered_descendant_ix,
list_hovered,
&style,
&theme,
cx,
));
descendant_ix += 1;
if cursor.goto_first_child() {
depth += 1;
} else {
visited_children = true;
}
break;
}
} else {
items.push(Self::render_node(
&cursor,
depth,
Some(descendant_ix) == this.selected_descendant_ix,
cx,
));
descendant_ix += 1;
if cursor.goto_first_child() {
depth += 1;
} else {
visited_children = true;
}
}
},
)
})
.on_move(move |event, this, cx| {
let y = event.position.y() - event.region.origin_y();
this.mouse_y = Some(y);
this.hover_state_changed(cx);
})
.on_click(MouseButton::Left, move |event, this, cx| {
let y = event.position.y() - event.region.origin_y();
this.handle_click(y, cx);
})
.contained()
.with_background_color(editor_theme.background)
.into_any();
}
items
},
)
.size_full()
.track_scroll(self.list_scroll_handle.clone())
.on_mouse_move(cx.listener(move |tree_view, event: &MouseMoveEvent, cx| {
tree_view.mouse_y = Some(event.position.y);
tree_view.hover_state_changed(cx);
}))
.on_mouse_down(
MouseButton::Left,
cx.listener(move |tree_view, event: &MouseDownEvent, cx| {
tree_view.handle_click(event.position.y, cx);
}),
)
.text_bg(cx.theme().colors().background);
rendered = rendered.child(
canvas(move |bounds, cx| {
list.into_any_element().draw(
bounds.origin,
bounds.size.map(AvailableSpace::Definite),
cx,
)
})
.size_full(),
);
}
Empty::new().into_any()
rendered
}
}
impl EventEmitter<()> for SyntaxTreeView {}
impl FocusableView for SyntaxTreeView {
fn focus_handle(&self, _: &AppContext) -> gpui::FocusHandle {
self.focus_handle.clone()
}
}
impl Item for SyntaxTreeView {
fn tab_content<V: 'static>(
&self,
_: Option<usize>,
style: &theme::Tab,
_: &AppContext,
) -> gpui::AnyElement<V> {
Label::new("Syntax Tree", style.label.clone()).into_any()
type Event = ();
fn to_item_events(_: &Self::Event, _: impl FnMut(workspace::item::ItemEvent)) {}
fn tab_content(&self, _: Option<usize>, _: bool, _: &WindowContext<'_>) -> AnyElement {
Label::new("Syntax Tree").into_any_element()
}
fn clone_on_split(
&self,
_workspace_id: workspace::WorkspaceId,
_: workspace::WorkspaceId,
cx: &mut ViewContext<Self>,
) -> Option<Self>
) -> Option<View<Self>>
where
Self: Sized,
{
let mut clone = Self::new(self.workspace_handle.clone(), None, cx);
if let Some(editor) = &self.editor {
clone.set_editor(editor.editor.clone(), cx)
}
Some(clone)
Some(cx.new_view(|cx| {
let mut clone = Self::new(self.workspace_handle.clone(), None, cx);
if let Some(editor) = &self.editor {
clone.set_editor(editor.editor.clone(), cx)
}
clone
}))
}
}
impl SyntaxTreeToolbarItemView {
pub fn new() -> Self {
Self {
menu_open: false,
tree_view: None,
subscription: None,
}
}
fn render_menu(
&mut self,
cx: &mut ViewContext<'_, '_, Self>,
) -> Option<gpui::AnyElement<Self>> {
let theme = theme::current(cx).clone();
fn render_menu(&mut self, cx: &mut ViewContext<'_, Self>) -> Option<PopoverMenu<ContextMenu>> {
let tree_view = self.tree_view.as_ref()?;
let tree_view = tree_view.read(cx);
@ -499,51 +444,32 @@ impl SyntaxTreeToolbarItemView {
let active_layer = buffer_state.active_layer.clone()?;
let active_buffer = buffer_state.buffer.read(cx).snapshot();
enum Menu {}
let view = cx.view().clone();
Some(
Stack::new()
.with_child(Self::render_header(&theme, &active_layer, cx))
.with_children(self.menu_open.then(|| {
Overlay::new(
MouseEventHandler::new::<Menu, _>(0, cx, move |_, cx| {
Flex::column()
.with_children(active_buffer.syntax_layers().enumerate().map(
|(ix, layer)| {
Self::render_menu_item(&theme, &active_layer, layer, ix, cx)
},
))
.contained()
.with_style(theme.toolbar_dropdown_menu.container)
.constrained()
.with_width(400.)
.with_height(400.)
})
.on_down_out(MouseButton::Left, |_, this, cx| {
this.menu_open = false;
cx.notify()
}),
)
.with_hoverable(true)
.with_fit_mode(OverlayFitMode::SwitchAnchor)
.with_anchor_corner(AnchorCorner::TopLeft)
.with_z_index(999)
.aligned()
.bottom()
.left()
}))
.aligned()
.left()
.clipped()
.into_any(),
popover_menu("Syntax Tree")
.trigger(Self::render_header(&active_layer))
.menu(move |cx| {
ContextMenu::build(cx, |mut menu, cx| {
for (layer_ix, layer) in active_buffer.syntax_layers().enumerate() {
menu = menu.entry(
format!(
"{} {}",
layer.language.name(),
format_node_range(layer.node())
),
None,
cx.handler_for(&view, move |view, cx| {
view.select_layer(layer_ix, cx);
}),
);
}
menu
})
.into()
}),
)
}
fn toggle_menu(&mut self, cx: &mut ViewContext<Self>) {
self.menu_open = !self.menu_open;
cx.notify();
}
fn select_layer(&mut self, layer_ix: usize, cx: &mut ViewContext<Self>) -> Option<()> {
let tree_view = self.tree_view.as_ref()?;
tree_view.update(cx, |view, cx| {
@ -553,77 +479,16 @@ impl SyntaxTreeToolbarItemView {
let layer = snapshot.syntax_layers().nth(layer_ix)?;
buffer_state.active_layer = Some(layer.to_owned());
view.selected_descendant_ix = None;
self.menu_open = false;
cx.notify();
view.focus_handle.focus(cx);
Some(())
})
}
fn render_header(
theme: &Arc<Theme>,
active_layer: &OwnedSyntaxLayerInfo,
cx: &mut ViewContext<Self>,
) -> impl Element<Self> {
enum ToggleMenu {}
MouseEventHandler::new::<ToggleMenu, _>(0, cx, move |state, _| {
let style = theme.toolbar_dropdown_menu.header.style_for(state);
Flex::row()
.with_child(
Label::new(active_layer.language.name().to_string(), style.text.clone())
.contained()
.with_margin_right(style.secondary_text_spacing),
)
.with_child(Label::new(
format_node_range(active_layer.node()),
style
.secondary_text
.clone()
.unwrap_or_else(|| style.text.clone()),
))
.contained()
.with_style(style.container)
})
.with_cursor_style(CursorStyle::PointingHand)
.on_click(MouseButton::Left, move |_, view, cx| {
view.toggle_menu(cx);
})
}
fn render_menu_item(
theme: &Arc<Theme>,
active_layer: &OwnedSyntaxLayerInfo,
layer: SyntaxLayerInfo,
layer_ix: usize,
cx: &mut ViewContext<Self>,
) -> impl Element<Self> {
enum ActivateLayer {}
MouseEventHandler::new::<ActivateLayer, _>(layer_ix, cx, move |state, _| {
let is_selected = layer.node() == active_layer.node();
let style = theme
.toolbar_dropdown_menu
.item
.in_state(is_selected)
.style_for(state);
Flex::row()
.with_child(
Label::new(layer.language.name().to_string(), style.text.clone())
.contained()
.with_margin_right(style.secondary_text_spacing),
)
.with_child(Label::new(
format_node_range(layer.node()),
style
.secondary_text
.clone()
.unwrap_or_else(|| style.text.clone()),
))
.contained()
.with_style(style.container)
})
.with_cursor_style(CursorStyle::PointingHand)
.on_click(MouseButton::Left, move |_, view, cx| {
view.select_layer(layer_ix, cx);
})
fn render_header(active_layer: &OwnedSyntaxLayerInfo) -> ButtonLike {
ButtonLike::new("syntax tree header")
.child(Label::new(active_layer.language.name()))
.child(Label::new(format_node_range(active_layer.node())))
}
}
@ -639,35 +504,26 @@ fn format_node_range(node: Node) -> String {
)
}
impl Entity for SyntaxTreeToolbarItemView {
type Event = ();
}
impl View for SyntaxTreeToolbarItemView {
fn ui_name() -> &'static str {
"SyntaxTreeToolbarItemView"
}
fn render(&mut self, cx: &mut ViewContext<'_, '_, Self>) -> gpui::AnyElement<Self> {
impl Render for SyntaxTreeToolbarItemView {
fn render(&mut self, cx: &mut ViewContext<'_, Self>) -> impl IntoElement {
self.render_menu(cx)
.unwrap_or_else(|| Empty::new().into_any())
.unwrap_or_else(|| popover_menu("Empty Syntax Tree"))
}
}
impl EventEmitter<ToolbarItemEvent> for SyntaxTreeToolbarItemView {}
impl ToolbarItemView for SyntaxTreeToolbarItemView {
fn set_active_pane_item(
&mut self,
active_pane_item: Option<&dyn ItemHandle>,
cx: &mut ViewContext<Self>,
) -> workspace::ToolbarItemLocation {
self.menu_open = false;
) -> ToolbarItemLocation {
if let Some(item) = active_pane_item {
if let Some(view) = item.downcast::<SyntaxTreeView>() {
self.tree_view = Some(view.clone());
self.subscription = Some(cx.observe(&view, |_, _, cx| cx.notify()));
return ToolbarItemLocation::PrimaryLeft {
flex: Some((1., false)),
};
return ToolbarItemLocation::PrimaryLeft;
}
}
self.tree_view = None;