Refactor the scrollbar component (#36105)

Closes https://github.com/zed-industries/zed/issues/37621
Improves https://github.com/zed-industries/zed/issues/24623

Adding scrollbars withing Zed's UI currently is rather cumbersome, as it
requires the copying of a lot of code in order for these to work. Wiring
up settings for scrollbar visibilty always has to be done at the call
site and the state has to be saved and maintained by the caller as well.
Similarly, reserving space has to also be handled by the caller.

This PR changes the way scrollbars work in Zed fundamentally by making
use of the new `use_keyed_state` APIs: Instead of saving the state at
the call site, the window now keeps track of the state corresponding to
scrollbars. This enables us to add scrollbars with e.g. one simple call
on divs:
```rust
div()
    .vertical_scrollbar(window, cx)
```
will add a scrollbar to the corresponding container. There are some more
improvements regarding tracking of scrollbar visibility settings (which
is now handled by a trait for each setting that supports this) as well
as reserving space.
Additionally, all needed stuff for layouting, catching events and
reserving space is also now managed by the scrollbar component instead.
This drastically reduces the amount of event listeners and makes
layouting of two scrollbars easier.

Furthermore, this paves the way for more improvements to scrollbars,
such as graceful auto-hide. Only downsight here is that we lose some
customizability in a few areas. However, once this lands, we gain the
ability to quickly follow these up without breaking stuff elsewhere.

This also already fixes a few bugs:
- Scrollbars no longer flicker on first render. 
- Auto-hide now properly works for all scrollbars.
- If the content size changes, the scrollbar is updated on the same
frame. Both of these happened because we were computing the scrollbar
sizes too early, causing us to use the sizes from the previous frame or
unitialized sizes.
- The project panel no longer jumps if scrolled all the way to the
bottom and the scrollbar actually auto-hides.

Still TODO:
- [x] Fix scrolling in the debugger memory view
- [x] Clean up some more in the scrollbar component and reduce clones
there
- [x] Ensure we don't over-notify the entity the scrollbar is rendered
within
- [x] Make sure auto-hide properly works for all cases
- [x] Check whether we want to implement the scrollbar trait for
`UniformList`s as well
    - ~~ [ ] Use for uniformlist where possible~~ Postponed
- [x] Improve layout for cases where we render both scrollbars.

Release Notes:

- N/A
This commit is contained in:
Finn Evers
2025-09-13 00:43:16 +02:00
committed by GitHub
parent 53c5db4495
commit ded6467604
35 changed files with 1566 additions and 2386 deletions
Generated
+1 -1
View File
@@ -12214,7 +12214,6 @@ dependencies = [
"serde", "serde",
"serde_json", "serde_json",
"ui", "ui",
"util",
"workspace", "workspace",
"workspace-hack", "workspace-hack",
] ]
@@ -17632,6 +17631,7 @@ dependencies = [
"icons", "icons",
"itertools 0.14.0", "itertools 0.14.0",
"menu", "menu",
"schemars",
"serde", "serde",
"settings", "settings",
"smallvec", "smallvec",
+5 -49
View File
@@ -5,15 +5,15 @@ use chrono::{Datelike as _, Local, NaiveDate, TimeDelta};
use editor::{Editor, EditorEvent}; use editor::{Editor, EditorEvent};
use fuzzy::StringMatchCandidate; use fuzzy::StringMatchCandidate;
use gpui::{ use gpui::{
App, Entity, EventEmitter, FocusHandle, Focusable, ScrollStrategy, Stateful, Task, App, Entity, EventEmitter, FocusHandle, Focusable, ScrollStrategy, Task,
UniformListScrollHandle, WeakEntity, Window, uniform_list, UniformListScrollHandle, WeakEntity, Window, uniform_list,
}; };
use std::{fmt::Display, ops::Range}; use std::{fmt::Display, ops::Range};
use text::Bias; use text::Bias;
use time::{OffsetDateTime, UtcOffset}; use time::{OffsetDateTime, UtcOffset};
use ui::{ use ui::{
HighlightedLabel, IconButtonShape, ListItem, ListItemSpacing, Scrollbar, ScrollbarState, HighlightedLabel, IconButtonShape, ListItem, ListItemSpacing, Tooltip, WithScrollbar,
Tooltip, prelude::*, prelude::*,
}; };
pub struct AcpThreadHistory { pub struct AcpThreadHistory {
@@ -26,8 +26,6 @@ pub struct AcpThreadHistory {
visible_items: Vec<ListItemType>, visible_items: Vec<ListItemType>,
scrollbar_visibility: bool,
scrollbar_state: ScrollbarState,
local_timezone: UtcOffset, local_timezone: UtcOffset,
_update_task: Task<()>, _update_task: Task<()>,
@@ -90,7 +88,6 @@ impl AcpThreadHistory {
}); });
let scroll_handle = UniformListScrollHandle::default(); let scroll_handle = UniformListScrollHandle::default();
let scrollbar_state = ScrollbarState::new(scroll_handle.clone());
let mut this = Self { let mut this = Self {
history_store, history_store,
@@ -99,8 +96,6 @@ impl AcpThreadHistory {
hovered_index: None, hovered_index: None,
visible_items: Default::default(), visible_items: Default::default(),
search_editor, search_editor,
scrollbar_visibility: true,
scrollbar_state,
local_timezone: UtcOffset::from_whole_seconds( local_timezone: UtcOffset::from_whole_seconds(
chrono::Local::now().offset().local_minus_utc(), chrono::Local::now().offset().local_minus_utc(),
) )
@@ -339,43 +334,6 @@ impl AcpThreadHistory {
task.detach_and_log_err(cx); task.detach_and_log_err(cx);
} }
fn render_scrollbar(&self, cx: &mut Context<Self>) -> Option<Stateful<Div>> {
if !(self.scrollbar_visibility || self.scrollbar_state.is_dragging()) {
return None;
}
Some(
div()
.occlude()
.id("thread-history-scroll")
.h_full()
.bg(cx.theme().colors().panel_background.opacity(0.8))
.border_l_1()
.border_color(cx.theme().colors().border_variant)
.absolute()
.right_1()
.top_0()
.bottom_0()
.w_4()
.pl_1()
.cursor_default()
.on_mouse_move(cx.listener(|_, _, _window, cx| {
cx.notify();
cx.stop_propagation()
}))
.on_hover(|_, _window, cx| {
cx.stop_propagation();
})
.on_any_mouse_down(|_, _window, cx| {
cx.stop_propagation();
})
.on_scroll_wheel(cx.listener(|_, _, _window, cx| {
cx.notify();
}))
.children(Scrollbar::vertical(self.scrollbar_state.clone())),
)
}
fn render_list_items( fn render_list_items(
&mut self, &mut self,
range: Range<usize>, range: Range<usize>,
@@ -491,7 +449,7 @@ impl Focusable for AcpThreadHistory {
} }
impl Render for AcpThreadHistory { impl Render for AcpThreadHistory {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement { fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
v_flex() v_flex()
.key_context("ThreadHistory") .key_context("ThreadHistory")
.size_full() .size_full()
@@ -555,9 +513,7 @@ impl Render for AcpThreadHistory {
.track_scroll(self.scroll_handle.clone()) .track_scroll(self.scroll_handle.clone())
.flex_grow(), .flex_grow(),
) )
.when_some(self.render_scrollbar(cx), |div, scrollbar| { .vertical_scrollbar_for(self.scroll_handle.clone(), window, cx)
div.child(scrollbar)
})
} }
}) })
} }
+22 -52
View File
@@ -24,10 +24,9 @@ use futures::FutureExt as _;
use gpui::{ use gpui::{
Action, Animation, AnimationExt, AnyView, App, BorderStyle, ClickEvent, ClipboardItem, Action, Animation, AnimationExt, AnyView, App, BorderStyle, ClickEvent, ClipboardItem,
CursorStyle, EdgesRefinement, ElementId, Empty, Entity, FocusHandle, Focusable, Hsla, Length, CursorStyle, EdgesRefinement, ElementId, Empty, Entity, FocusHandle, Focusable, Hsla, Length,
ListOffset, ListState, MouseButton, PlatformDisplay, SharedString, Stateful, StyleRefinement, ListOffset, ListState, PlatformDisplay, SharedString, StyleRefinement, Subscription, Task,
Subscription, Task, TextStyle, TextStyleRefinement, UnderlineStyle, WeakEntity, Window, TextStyle, TextStyleRefinement, UnderlineStyle, WeakEntity, Window, WindowHandle, div,
WindowHandle, div, ease_in_out, linear_color_stop, linear_gradient, list, point, prelude::*, ease_in_out, linear_color_stop, linear_gradient, list, point, prelude::*, pulsating_between,
pulsating_between,
}; };
use language::Buffer; use language::Buffer;
@@ -47,7 +46,7 @@ use text::Anchor;
use theme::{AgentFontSize, ThemeSettings}; use theme::{AgentFontSize, ThemeSettings};
use ui::{ use ui::{
Callout, CommonAnimationExt, Disclosure, Divider, DividerColor, ElevationIndex, KeyBinding, Callout, CommonAnimationExt, Disclosure, Divider, DividerColor, ElevationIndex, KeyBinding,
PopoverMenuHandle, Scrollbar, ScrollbarState, SpinnerLabel, TintColor, Tooltip, prelude::*, PopoverMenuHandle, SpinnerLabel, TintColor, Tooltip, WithScrollbar, prelude::*,
}; };
use util::{ResultExt, size::format_file_size, time::duration_alt_display}; use util::{ResultExt, size::format_file_size, time::duration_alt_display};
use workspace::{CollaboratorId, Workspace}; use workspace::{CollaboratorId, Workspace};
@@ -281,7 +280,6 @@ pub struct AcpThreadView {
thread_error: Option<ThreadError>, thread_error: Option<ThreadError>,
thread_feedback: ThreadFeedbackState, thread_feedback: ThreadFeedbackState,
list_state: ListState, list_state: ListState,
scrollbar_state: ScrollbarState,
auth_task: Option<Task<()>>, auth_task: Option<Task<()>>,
expanded_tool_calls: HashSet<acp::ToolCallId>, expanded_tool_calls: HashSet<acp::ToolCallId>,
expanded_thinking_blocks: HashSet<(usize, usize)>, expanded_thinking_blocks: HashSet<(usize, usize)>,
@@ -405,8 +403,7 @@ impl AcpThreadView {
notifications: Vec::new(), notifications: Vec::new(),
notification_subscriptions: HashMap::default(), notification_subscriptions: HashMap::default(),
list_state: list_state.clone(), list_state: list_state,
scrollbar_state: ScrollbarState::new(list_state).parent_entity(&cx.entity()),
thread_retry_status: None, thread_retry_status: None,
thread_error: None, thread_error: None,
thread_feedback: Default::default(), thread_feedback: Default::default(),
@@ -4764,39 +4761,6 @@ impl AcpThreadView {
cx.notify(); cx.notify();
} }
fn render_vertical_scrollbar(&self, cx: &mut Context<Self>) -> Stateful<Div> {
div()
.id("acp-thread-scrollbar")
.occlude()
.on_mouse_move(cx.listener(|_, _, _, cx| {
cx.notify();
cx.stop_propagation()
}))
.on_hover(|_, _, cx| {
cx.stop_propagation();
})
.on_any_mouse_down(|_, _, cx| {
cx.stop_propagation();
})
.on_mouse_up(
MouseButton::Left,
cx.listener(|_, _, _, cx| {
cx.stop_propagation();
}),
)
.on_scroll_wheel(cx.listener(|_, _, _, cx| {
cx.notify();
}))
.h_full()
.absolute()
.right_1()
.top_1()
.bottom_0()
.w(px(12.))
.cursor_default()
.children(Scrollbar::vertical(self.scrollbar_state.clone()).map(|s| s.auto_hide(cx)))
}
fn render_token_limit_callout( fn render_token_limit_callout(
&self, &self,
line_height: Pixels, line_height: Pixels,
@@ -5370,23 +5334,27 @@ impl Render for AcpThreadView {
configuration_view, configuration_view,
pending_auth_method, pending_auth_method,
.. ..
} => self.render_auth_required_state( } => self
connection, .render_auth_required_state(
description.as_ref(), connection,
configuration_view.as_ref(), description.as_ref(),
pending_auth_method.as_ref(), configuration_view.as_ref(),
window, pending_auth_method.as_ref(),
cx, window,
), cx,
)
.into_any(),
ThreadState::Loading { .. } => v_flex() ThreadState::Loading { .. } => v_flex()
.flex_1() .flex_1()
.child(self.render_recent_history(window, cx)), .child(self.render_recent_history(window, cx))
.into_any(),
ThreadState::LoadError(e) => v_flex() ThreadState::LoadError(e) => v_flex()
.flex_1() .flex_1()
.size_full() .size_full()
.items_center() .items_center()
.justify_end() .justify_end()
.child(self.render_load_error(e, window, cx)), .child(self.render_load_error(e, window, cx))
.into_any(),
ThreadState::Ready { .. } => v_flex().flex_1().map(|this| { ThreadState::Ready { .. } => v_flex().flex_1().map(|this| {
if has_messages { if has_messages {
this.child( this.child(
@@ -5406,9 +5374,11 @@ impl Render for AcpThreadView {
.flex_grow() .flex_grow()
.into_any(), .into_any(),
) )
.child(self.render_vertical_scrollbar(cx)) .vertical_scrollbar_for(self.list_state.clone(), window, cx)
.into_any()
} else { } else {
this.child(self.render_recent_history(window, cx)) this.child(self.render_recent_history(window, cx))
.into_any()
} }
}), }),
}) })
+15 -42
View File
@@ -35,8 +35,7 @@ use project::{
use settings::{Settings, SettingsStore, update_settings_file}; use settings::{Settings, SettingsStore, update_settings_file};
use ui::{ use ui::{
Chip, CommonAnimationExt, ContextMenu, Disclosure, Divider, DividerColor, ElevationIndex, Chip, CommonAnimationExt, ContextMenu, Disclosure, Divider, DividerColor, ElevationIndex,
Indicator, PopoverMenu, Scrollbar, ScrollbarState, Switch, SwitchColor, SwitchField, Tooltip, Indicator, PopoverMenu, Switch, SwitchColor, SwitchField, Tooltip, WithScrollbar, prelude::*,
prelude::*,
}; };
use util::ResultExt as _; use util::ResultExt as _;
use workspace::{Workspace, create_and_open_local_file}; use workspace::{Workspace, create_and_open_local_file};
@@ -64,7 +63,6 @@ pub struct AgentConfiguration {
tools: Entity<ToolWorkingSet>, tools: Entity<ToolWorkingSet>,
_registry_subscription: Subscription, _registry_subscription: Subscription,
scroll_handle: ScrollHandle, scroll_handle: ScrollHandle,
scrollbar_state: ScrollbarState,
_check_for_gemini: Task<()>, _check_for_gemini: Task<()>,
} }
@@ -101,9 +99,6 @@ impl AgentConfiguration {
cx.subscribe(&context_server_store, |_, _, _, cx| cx.notify()) cx.subscribe(&context_server_store, |_, _, _, cx| cx.notify())
.detach(); .detach();
let scroll_handle = ScrollHandle::new();
let scrollbar_state = ScrollbarState::new(scroll_handle.clone());
let mut this = Self { let mut this = Self {
fs, fs,
language_registry, language_registry,
@@ -116,8 +111,7 @@ impl AgentConfiguration {
expanded_provider_configurations: HashMap::default(), expanded_provider_configurations: HashMap::default(),
tools, tools,
_registry_subscription: registry_subscription, _registry_subscription: registry_subscription,
scroll_handle, scroll_handle: ScrollHandle::new(),
scrollbar_state,
_check_for_gemini: Task::ready(()), _check_for_gemini: Task::ready(()),
}; };
this.build_provider_configuration_views(window, cx); this.build_provider_configuration_views(window, cx);
@@ -1157,42 +1151,21 @@ impl Render for AgentConfiguration {
.size_full() .size_full()
.pb_8() .pb_8()
.bg(cx.theme().colors().panel_background) .bg(cx.theme().colors().panel_background)
.child(
v_flex()
.id("assistant-configuration-content")
.track_scroll(&self.scroll_handle)
.size_full()
.overflow_y_scroll()
.child(self.render_general_settings_section(cx))
.child(self.render_agent_servers_section(cx))
.child(self.render_context_servers_section(window, cx))
.child(self.render_provider_configuration_section(cx)),
)
.child( .child(
div() div()
.id("assistant-configuration-scrollbar") .size_full()
.occlude() .child(
.absolute() v_flex()
.right(px(3.)) .id("assistant-configuration-content")
.top_0() .track_scroll(&self.scroll_handle)
.bottom_0() .size_full()
.pb_6() .overflow_y_scroll()
.w(px(12.)) .child(self.render_general_settings_section(cx))
.cursor_default() .child(self.render_agent_servers_section(cx))
.on_mouse_move(cx.listener(|_, _, _window, cx| { .child(self.render_context_servers_section(window, cx))
cx.notify(); .child(self.render_provider_configuration_section(cx)),
cx.stop_propagation() )
})) .vertical_scrollbar_for(self.scroll_handle.clone(), window, cx),
.on_hover(|_, _window, cx| {
cx.stop_propagation();
})
.on_any_mouse_down(|_, _window, cx| {
cx.stop_propagation();
})
.on_scroll_wheel(cx.listener(|_, _, _window, cx| {
cx.notify();
}))
.children(Scrollbar::vertical(self.scrollbar_state.clone())),
) )
} }
} }
@@ -10,7 +10,7 @@ use db::kvp::KEY_VALUE_STORE;
use editor::Editor; use editor::Editor;
use gpui::{ use gpui::{
Action, AppContext, ClickEvent, Entity, FocusHandle, Focusable, MouseButton, ScrollStrategy, Action, AppContext, ClickEvent, Entity, FocusHandle, Focusable, MouseButton, ScrollStrategy,
Stateful, Task, UniformListScrollHandle, WeakEntity, actions, uniform_list, Task, UniformListScrollHandle, WeakEntity, actions, uniform_list,
}; };
use language::Point; use language::Point;
use project::{ use project::{
@@ -23,8 +23,8 @@ use project::{
worktree_store::WorktreeStore, worktree_store::WorktreeStore,
}; };
use ui::{ use ui::{
Divider, DividerColor, FluentBuilder as _, Indicator, IntoElement, ListItem, Render, Scrollbar, Divider, DividerColor, FluentBuilder as _, Indicator, IntoElement, ListItem, Render,
ScrollbarState, StatefulInteractiveElement, Tooltip, prelude::*, StatefulInteractiveElement, Tooltip, WithScrollbar, prelude::*,
}; };
use workspace::Workspace; use workspace::Workspace;
use zed_actions::{ToggleEnableBreakpoint, UnsetBreakpoint}; use zed_actions::{ToggleEnableBreakpoint, UnsetBreakpoint};
@@ -49,7 +49,6 @@ pub(crate) struct BreakpointList {
breakpoint_store: Entity<BreakpointStore>, breakpoint_store: Entity<BreakpointStore>,
dap_store: Entity<DapStore>, dap_store: Entity<DapStore>,
worktree_store: Entity<WorktreeStore>, worktree_store: Entity<WorktreeStore>,
scrollbar_state: ScrollbarState,
breakpoints: Vec<BreakpointEntry>, breakpoints: Vec<BreakpointEntry>,
session: Option<Entity<Session>>, session: Option<Entity<Session>>,
focus_handle: FocusHandle, focus_handle: FocusHandle,
@@ -87,7 +86,6 @@ impl BreakpointList {
let dap_store = project.dap_store(); let dap_store = project.dap_store();
let focus_handle = cx.focus_handle(); let focus_handle = cx.focus_handle();
let scroll_handle = UniformListScrollHandle::new(); let scroll_handle = UniformListScrollHandle::new();
let scrollbar_state = ScrollbarState::new(scroll_handle.clone());
let adapter_name = session.as_ref().map(|session| session.read(cx).adapter()); let adapter_name = session.as_ref().map(|session| session.read(cx).adapter());
cx.new(|cx| { cx.new(|cx| {
@@ -95,7 +93,6 @@ impl BreakpointList {
breakpoint_store, breakpoint_store,
dap_store, dap_store,
worktree_store, worktree_store,
scrollbar_state,
breakpoints: Default::default(), breakpoints: Default::default(),
workspace, workspace,
session, session,
@@ -576,39 +573,6 @@ impl BreakpointList {
.flex_1() .flex_1()
} }
fn render_vertical_scrollbar(&self, cx: &mut Context<Self>) -> Stateful<Div> {
div()
.occlude()
.id("breakpoint-list-vertical-scrollbar")
.on_mouse_move(cx.listener(|_, _, _, cx| {
cx.notify();
cx.stop_propagation()
}))
.on_hover(|_, _, cx| {
cx.stop_propagation();
})
.on_any_mouse_down(|_, _, cx| {
cx.stop_propagation();
})
.on_mouse_up(
MouseButton::Left,
cx.listener(|_, _, _, cx| {
cx.stop_propagation();
}),
)
.on_scroll_wheel(cx.listener(|_, _, _, cx| {
cx.notify();
}))
.h_full()
.absolute()
.right_1()
.top_1()
.bottom_0()
.w(px(12.))
.cursor_default()
.children(Scrollbar::vertical(self.scrollbar_state.clone()).map(|s| s.auto_hide(cx)))
}
pub(crate) fn render_control_strip(&self) -> AnyElement { pub(crate) fn render_control_strip(&self) -> AnyElement {
let selection_kind = self.selection_kind(); let selection_kind = self.selection_kind();
let focus_handle = self.focus_handle.clone(); let focus_handle = self.focus_handle.clone();
@@ -789,7 +753,7 @@ impl Render for BreakpointList {
.size_full() .size_full()
.pt_1() .pt_1()
.child(self.render_list(cx)) .child(self.render_list(cx))
.child(self.render_vertical_scrollbar(cx)) .vertical_scrollbar_for(self.scroll_handle.clone(), window, cx)
.when_some(self.strip_mode, |this, _| { .when_some(self.strip_mode, |this, _| {
this.child(Divider::horizontal().color(DividerColor::Border)) this.child(Divider::horizontal().color(DividerColor::Border))
.child( .child(
@@ -1,17 +1,17 @@
use std::{ use std::{
cell::LazyCell, cell::{LazyCell, RefCell, RefMut},
fmt::Write, fmt::Write,
ops::RangeInclusive, ops::RangeInclusive,
rc::Rc,
sync::{Arc, LazyLock}, sync::{Arc, LazyLock},
time::Duration, time::Duration,
}; };
use editor::{Editor, EditorElement, EditorStyle}; use editor::{Editor, EditorElement, EditorStyle};
use gpui::{ use gpui::{
Action, AppContext, DismissEvent, DragMoveEvent, Empty, Entity, FocusHandle, Focusable, Action, Along, AppContext, Axis, DismissEvent, DragMoveEvent, Empty, Entity, FocusHandle,
MouseButton, Point, ScrollStrategy, ScrollWheelEvent, Stateful, Subscription, Task, TextStyle, Focusable, MouseButton, Point, ScrollStrategy, ScrollWheelEvent, Subscription, Task, TextStyle,
UniformList, UniformListScrollHandle, WeakEntity, actions, anchored, deferred, point, UniformList, UniformListScrollHandle, WeakEntity, actions, anchored, deferred, uniform_list,
uniform_list,
}; };
use notifications::status_toast::{StatusToast, ToastIcon}; use notifications::status_toast::{StatusToast, ToastIcon};
use project::debugger::{MemoryCell, dap_command::DataBreakpointContext, session::Session}; use project::debugger::{MemoryCell, dap_command::DataBreakpointContext, session::Session};
@@ -19,7 +19,7 @@ use settings::Settings;
use theme::ThemeSettings; use theme::ThemeSettings;
use ui::{ use ui::{
ContextMenu, Divider, DropdownMenu, FluentBuilder, IntoElement, PopoverMenuHandle, Render, ContextMenu, Divider, DropdownMenu, FluentBuilder, IntoElement, PopoverMenuHandle, Render,
Scrollbar, ScrollbarState, StatefulInteractiveElement, Tooltip, prelude::*, ScrollableHandle, StatefulInteractiveElement, Tooltip, WithScrollbar, prelude::*,
}; };
use workspace::Workspace; use workspace::Workspace;
@@ -29,11 +29,9 @@ actions!(debugger, [GoToSelectedAddress]);
pub(crate) struct MemoryView { pub(crate) struct MemoryView {
workspace: WeakEntity<Workspace>, workspace: WeakEntity<Workspace>,
scroll_handle: UniformListScrollHandle,
scroll_state: ScrollbarState,
stack_frame_list: WeakEntity<StackFrameList>, stack_frame_list: WeakEntity<StackFrameList>,
focus_handle: FocusHandle, focus_handle: FocusHandle,
view_state: ViewState, view_state_handle: ViewStateHandle,
query_editor: Entity<Editor>, query_editor: Entity<Editor>,
session: Entity<Session>, session: Entity<Session>,
width_picker_handle: PopoverMenuHandle<ContextMenu>, width_picker_handle: PopoverMenuHandle<ContextMenu>,
@@ -90,18 +88,29 @@ impl SelectedMemoryRange {
} }
} }
#[derive(Clone)]
struct ViewStateHandle(Rc<RefCell<ViewState>>);
impl ViewStateHandle {
fn new(base_row: u64, line_width: ViewWidth) -> Self {
Self(Rc::new(RefCell::new(ViewState::new(base_row, line_width))))
}
}
#[derive(Clone)] #[derive(Clone)]
struct ViewState { struct ViewState {
/// Uppermost row index /// Uppermost row index
base_row: u64, base_row: u64,
/// How many cells per row do we have? /// How many cells per row do we have?
line_width: ViewWidth, line_width: ViewWidth,
scroll_handle: UniformListScrollHandle,
selection: Option<SelectedMemoryRange>, selection: Option<SelectedMemoryRange>,
} }
impl ViewState { impl ViewState {
fn new(base_row: u64, line_width: ViewWidth) -> Self { fn new(base_row: u64, line_width: ViewWidth) -> Self {
Self { Self {
scroll_handle: UniformListScrollHandle::new(),
base_row, base_row,
line_width, line_width,
selection: None, selection: None,
@@ -119,13 +128,39 @@ impl ViewState {
fn schedule_scroll_up(&mut self) { fn schedule_scroll_up(&mut self) {
self.base_row = self.base_row.saturating_sub(1); self.base_row = self.base_row.saturating_sub(1);
} }
fn set_offset(&mut self, point: Point<Pixels>) {
if point.y >= -Pixels::ZERO {
self.schedule_scroll_up();
} else if point.y <= -self.scroll_handle.max_offset().height {
self.schedule_scroll_down();
}
self.scroll_handle.set_offset(point);
}
} }
struct ScrollbarDragging; impl ScrollableHandle for ViewStateHandle {
fn max_offset(&self) -> gpui::Size<Pixels> {
self.0.borrow().scroll_handle.max_offset()
}
fn set_offset(&self, point: Point<Pixels>) {
self.0.borrow_mut().set_offset(point);
}
fn offset(&self) -> Point<Pixels> {
self.0.borrow().scroll_handle.offset()
}
fn viewport(&self) -> gpui::Bounds<Pixels> {
self.0.borrow().scroll_handle.viewport()
}
}
static HEX_BYTES_MEMOIZED: LazyLock<[SharedString; 256]> = static HEX_BYTES_MEMOIZED: LazyLock<[SharedString; 256]> =
LazyLock::new(|| std::array::from_fn(|byte| SharedString::from(format!("{byte:02X}")))); LazyLock::new(|| std::array::from_fn(|byte| SharedString::from(format!("{byte:02X}"))));
static UNKNOWN_BYTE: SharedString = SharedString::new_static("??"); static UNKNOWN_BYTE: SharedString = SharedString::new_static("??");
impl MemoryView { impl MemoryView {
pub(crate) fn new( pub(crate) fn new(
session: Entity<Session>, session: Entity<Session>,
@@ -134,19 +169,15 @@ impl MemoryView {
window: &mut Window, window: &mut Window,
cx: &mut Context<Self>, cx: &mut Context<Self>,
) -> Self { ) -> Self {
let view_state = ViewState::new(0, WIDTHS[4].clone()); let view_state_handle = ViewStateHandle::new(0, WIDTHS[4].clone());
let scroll_handle = UniformListScrollHandle::default();
let query_editor = cx.new(|cx| Editor::single_line(window, cx)); let query_editor = cx.new(|cx| Editor::single_line(window, cx));
let scroll_state = ScrollbarState::new(scroll_handle.clone());
let mut this = Self { let mut this = Self {
workspace, workspace,
scroll_state,
scroll_handle,
stack_frame_list, stack_frame_list,
focus_handle: cx.focus_handle(), focus_handle: cx.focus_handle(),
view_state, view_state_handle,
query_editor, query_editor,
session, session,
width_picker_handle: Default::default(), width_picker_handle: Default::default(),
@@ -162,50 +193,17 @@ impl MemoryView {
this this
} }
fn render_vertical_scrollbar(&self, cx: &mut Context<Self>) -> Stateful<Div> { fn view_state(&self) -> RefMut<'_, ViewState> {
div() self.view_state_handle.0.borrow_mut()
.occlude()
.id("memory-view-vertical-scrollbar")
.on_drag_move(cx.listener(|this, evt, _, cx| {
let did_handle = this.handle_scroll_drag(evt);
cx.notify();
if did_handle {
cx.stop_propagation()
}
}))
.on_drag(ScrollbarDragging, |_, _, _, cx| cx.new(|_| Empty))
.on_hover(|_, _, cx| {
cx.stop_propagation();
})
.on_any_mouse_down(|_, _, cx| {
cx.stop_propagation();
})
.on_mouse_up(
MouseButton::Left,
cx.listener(|_, _, _, cx| {
cx.stop_propagation();
}),
)
.on_scroll_wheel(cx.listener(|_, _, _, cx| {
cx.notify();
}))
.h_full()
.absolute()
.right_1()
.top_1()
.bottom_0()
.w(px(12.))
.cursor_default()
.children(Scrollbar::vertical(self.scroll_state.clone()).map(|s| s.auto_hide(cx)))
} }
fn render_memory(&self, cx: &mut Context<Self>) -> UniformList { fn render_memory(&self, cx: &mut Context<Self>) -> UniformList {
let weak = cx.weak_entity(); let weak = cx.weak_entity();
let session = self.session.clone(); let session = self.session.clone();
let view_state = self.view_state.clone(); let view_state = self.view_state_handle.0.borrow().clone();
uniform_list( uniform_list(
"debugger-memory-view", "debugger-memory-view",
self.view_state.row_count() as usize, view_state.row_count() as usize,
move |range, _, cx| { move |range, _, cx| {
let mut line_buffer = Vec::with_capacity(view_state.line_width.width as usize); let mut line_buffer = Vec::with_capacity(view_state.line_width.width as usize);
let memory_start = let memory_start =
@@ -230,22 +228,13 @@ impl MemoryView {
rows rows
}, },
) )
.track_scroll(self.scroll_handle.clone()) .track_scroll(view_state.scroll_handle)
.on_scroll_wheel(cx.listener(|this, evt: &ScrollWheelEvent, window, _| { .on_scroll_wheel(cx.listener(|this, evt: &ScrollWheelEvent, window, _| {
let mut view_state = this.view_state();
let delta = evt.delta.pixel_delta(window.line_height()); let delta = evt.delta.pixel_delta(window.line_height());
let scroll_handle = this.scroll_state.scroll_handle(); let current_offset = view_state.scroll_handle.offset();
let size = scroll_handle.content_size(); view_state
let viewport = scroll_handle.viewport(); .set_offset(current_offset.apply_along(Axis::Vertical, |offset| offset + delta.y));
let current_offset = scroll_handle.offset();
let first_entry_offset_boundary = size.height / this.view_state.row_count() as f32;
let last_entry_offset_boundary = size.height - first_entry_offset_boundary;
if first_entry_offset_boundary + viewport.size.height > current_offset.y.abs() {
// The topmost entry is visible, hence if we're scrolling up, we need to load extra lines.
this.view_state.schedule_scroll_up();
} else if last_entry_offset_boundary < current_offset.y.abs() + viewport.size.height {
this.view_state.schedule_scroll_down();
}
scroll_handle.set_offset(current_offset + point(px(0.), delta.y));
})) }))
} }
fn render_query_bar(&self, cx: &Context<Self>) -> impl IntoElement { fn render_query_bar(&self, cx: &Context<Self>) -> impl IntoElement {
@@ -275,7 +264,7 @@ impl MemoryView {
cx.spawn(async move |this, cx| { cx.spawn(async move |this, cx| {
let access_size = access_size.await.unwrap_or(1); let access_size = access_size.await.unwrap_or(1);
this.update(cx, |this, cx| { this.update(cx, |this, cx| {
this.view_state.selection = Some(SelectedMemoryRange::DragComplete(Drag { this.view_state().selection = Some(SelectedMemoryRange::DragComplete(Drag {
start_address: as_address, start_address: as_address,
end_address: as_address + access_size - 1, end_address: as_address + access_size - 1,
})); }));
@@ -287,43 +276,23 @@ impl MemoryView {
} }
fn handle_memory_drag(&mut self, evt: &DragMoveEvent<Drag>) { fn handle_memory_drag(&mut self, evt: &DragMoveEvent<Drag>) {
if !self let mut view_state = self.view_state();
.view_state if !view_state
.selection .selection
.as_ref() .as_ref()
.is_some_and(|selection| selection.is_dragging()) .is_some_and(|selection| selection.is_dragging())
{ {
return; return;
} }
let row_count = self.view_state.row_count(); let row_count = view_state.row_count();
debug_assert!(row_count > 1); debug_assert!(row_count > 1);
let scroll_handle = self.scroll_state.scroll_handle(); let scroll_handle = &view_state.scroll_handle;
let viewport = scroll_handle.viewport(); let viewport = scroll_handle.viewport();
if viewport.bottom() < evt.event.position.y { if viewport.bottom() < evt.event.position.y {
self.view_state.schedule_scroll_down(); view_state.schedule_scroll_down();
} else if viewport.top() > evt.event.position.y { } else if viewport.top() > evt.event.position.y {
self.view_state.schedule_scroll_up(); view_state.schedule_scroll_up();
}
}
fn handle_scroll_drag(&mut self, evt: &DragMoveEvent<ScrollbarDragging>) -> bool {
if !self.scroll_state.is_dragging() {
return false;
}
let row_count = self.view_state.row_count();
debug_assert!(row_count > 1);
let scroll_handle = self.scroll_state.scroll_handle();
let viewport = scroll_handle.viewport();
if viewport.bottom() < evt.event.position.y {
self.view_state.schedule_scroll_down();
true
} else if viewport.top() > evt.event.position.y {
self.view_state.schedule_scroll_up();
true
} else {
false
} }
} }
@@ -354,7 +323,7 @@ impl MemoryView {
fn render_width_picker(&self, window: &mut Window, cx: &mut Context<Self>) -> DropdownMenu { fn render_width_picker(&self, window: &mut Window, cx: &mut Context<Self>) -> DropdownMenu {
let weak = cx.weak_entity(); let weak = cx.weak_entity();
let selected_width = self.view_state.line_width.clone(); let selected_width = self.view_state().line_width.clone();
DropdownMenu::new( DropdownMenu::new(
"memory-view-width-picker", "memory-view-width-picker",
selected_width.label.clone(), selected_width.label.clone(),
@@ -364,24 +333,25 @@ impl MemoryView {
let width = width.clone(); let width = width.clone();
this = this.entry(width.label.clone(), None, move |_, cx| { this = this.entry(width.label.clone(), None, move |_, cx| {
_ = weak.update(cx, |this, _| { _ = weak.update(cx, |this, _| {
let mut view_state = this.view_state();
// Convert base ix between 2 line widths to keep the shown memory address roughly the same. // Convert base ix between 2 line widths to keep the shown memory address roughly the same.
// All widths are powers of 2, so the conversion should be lossless. // All widths are powers of 2, so the conversion should be lossless.
match this.view_state.line_width.width.cmp(&width.width) { match view_state.line_width.width.cmp(&width.width) {
std::cmp::Ordering::Less => { std::cmp::Ordering::Less => {
// We're converting up. // We're converting up.
let shift = width.width.trailing_zeros() let shift = width.width.trailing_zeros()
- this.view_state.line_width.width.trailing_zeros(); - view_state.line_width.width.trailing_zeros();
this.view_state.base_row >>= shift; view_state.base_row >>= shift;
} }
std::cmp::Ordering::Greater => { std::cmp::Ordering::Greater => {
// We're converting down. // We're converting down.
let shift = this.view_state.line_width.width.trailing_zeros() let shift = view_state.line_width.width.trailing_zeros()
- width.width.trailing_zeros(); - width.width.trailing_zeros();
this.view_state.base_row <<= shift; view_state.base_row <<= shift;
} }
_ => {} _ => {}
} }
this.view_state.line_width = width.clone(); view_state.line_width = width.clone();
}); });
}); });
} }
@@ -400,18 +370,18 @@ impl MemoryView {
} }
fn page_down(&mut self, _: &menu::SelectLast, _: &mut Window, cx: &mut Context<Self>) { fn page_down(&mut self, _: &menu::SelectLast, _: &mut Window, cx: &mut Context<Self>) {
self.view_state.base_row = self let mut view_state = self.view_state();
.view_state view_state.base_row = view_state
.base_row .base_row
.overflowing_add(self.view_state.row_count()) .overflowing_add(view_state.row_count())
.0; .0;
cx.notify(); cx.notify();
} }
fn page_up(&mut self, _: &menu::SelectFirst, _: &mut Window, cx: &mut Context<Self>) { fn page_up(&mut self, _: &menu::SelectFirst, _: &mut Window, cx: &mut Context<Self>) {
self.view_state.base_row = self let mut view_state = self.view_state();
.view_state view_state.base_row = view_state
.base_row .base_row
.overflowing_sub(self.view_state.row_count()) .overflowing_sub(view_state.row_count())
.0; .0;
cx.notify(); cx.notify();
} }
@@ -447,7 +417,8 @@ impl MemoryView {
_: &mut Window, _: &mut Window,
cx: &mut Context<Self>, cx: &mut Context<Self>,
) { ) {
let Some(SelectedMemoryRange::DragComplete(selection)) = self.view_state.selection.clone() let Some(SelectedMemoryRange::DragComplete(selection)) =
self.view_state().selection.clone()
else { else {
return; return;
}; };
@@ -484,7 +455,8 @@ impl MemoryView {
} }
fn confirm(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) { fn confirm(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
if let Some(SelectedMemoryRange::DragComplete(drag)) = &self.view_state.selection { let selection = self.view_state().selection.clone();
if let Some(SelectedMemoryRange::DragComplete(drag)) = selection {
// Go into memory writing mode. // Go into memory writing mode.
if !self.is_writing_memory { if !self.is_writing_memory {
let should_return = self.session.update(cx, |session, cx| { let should_return = self.session.update(cx, |session, cx| {
@@ -558,9 +530,11 @@ impl MemoryView {
} }
fn jump_to_address(&mut self, address: u64, cx: &mut Context<Self>) { fn jump_to_address(&mut self, address: u64, cx: &mut Context<Self>) {
self.view_state.base_row = (address & !0xfff) / self.view_state.line_width.width as u64; let mut view_state = self.view_state();
let line_ix = (address & 0xfff) / self.view_state.line_width.width as u64; view_state.base_row = (address & !0xfff) / view_state.line_width.width as u64;
self.scroll_handle let line_ix = (address & 0xfff) / view_state.line_width.width as u64;
view_state
.scroll_handle
.scroll_to_item(line_ix as usize, ScrollStrategy::Center); .scroll_to_item(line_ix as usize, ScrollStrategy::Center);
cx.notify(); cx.notify();
} }
@@ -595,7 +569,7 @@ impl MemoryView {
} }
fn cancel(&mut self, _: &menu::Cancel, _: &mut Window, cx: &mut Context<Self>) { fn cancel(&mut self, _: &menu::Cancel, _: &mut Window, cx: &mut Context<Self>) {
self.view_state.selection = None; self.view_state().selection = None;
cx.notify(); cx.notify();
} }
@@ -606,7 +580,7 @@ impl MemoryView {
window: &mut Window, window: &mut Window,
cx: &mut Context<Self>, cx: &mut Context<Self>,
) { ) {
let Some(SelectedMemoryRange::DragComplete(drag)) = self.view_state.selection.clone() let Some(SelectedMemoryRange::DragComplete(drag)) = self.view_state().selection.clone()
else { else {
return; return;
}; };
@@ -718,7 +692,7 @@ fn render_single_memory_view_line(
weak: gpui::WeakEntity<MemoryView>, weak: gpui::WeakEntity<MemoryView>,
cx: &mut App, cx: &mut App,
) -> AnyElement { ) -> AnyElement {
let Ok(view_state) = weak.update(cx, |this, _| this.view_state.clone()) else { let Ok(view_state) = weak.update(cx, |this, _| this.view_state().clone()) else {
return div().into_any(); return div().into_any();
}; };
let base_address = (view_state.base_row + ix) * view_state.line_width.width as u64; let base_address = (view_state.base_row + ix) * view_state.line_width.width as u64;
@@ -799,7 +773,7 @@ fn render_single_memory_view_line(
let weak = weak.clone(); let weak = weak.clone();
move |drag, _, _, cx| { move |drag, _, _, cx| {
_ = weak.update(cx, |this, _| { _ = weak.update(cx, |this, _| {
this.view_state.selection = this.view_state().selection =
Some(SelectedMemoryRange::DragUnderway(drag.clone())); Some(SelectedMemoryRange::DragUnderway(drag.clone()));
}); });
@@ -811,7 +785,7 @@ fn render_single_memory_view_line(
let weak = weak.clone(); let weak = weak.clone();
move |drag: &Drag, _, cx| { move |drag: &Drag, _, cx| {
_ = weak.update(cx, |this, _| { _ = weak.update(cx, |this, _| {
this.view_state.selection = this.view_state().selection =
Some(SelectedMemoryRange::DragComplete(Drag { Some(SelectedMemoryRange::DragComplete(Drag {
start_address: drag.start_address, start_address: drag.start_address,
end_address: base_address + cell_ix as u64, end_address: base_address + cell_ix as u64,
@@ -821,7 +795,7 @@ fn render_single_memory_view_line(
}) })
.drag_over(move |style, drag: &Drag, _, cx| { .drag_over(move |style, drag: &Drag, _, cx| {
_ = weak.update(cx, |this, _| { _ = weak.update(cx, |this, _| {
this.view_state.selection = this.view_state().selection =
Some(SelectedMemoryRange::DragUnderway(Drag { Some(SelectedMemoryRange::DragUnderway(Drag {
start_address: drag.start_address, start_address: drag.start_address,
end_address: base_address + cell_ix as u64, end_address: base_address + cell_ix as u64,
@@ -943,7 +917,7 @@ impl Render for MemoryView {
) )
.with_priority(1) .with_priority(1)
})) }))
.child(self.render_vertical_scrollbar(cx)), .vertical_scrollbar_for(self.view_state_handle.clone(), window, cx),
) )
} }
} }
@@ -1,15 +1,15 @@
use anyhow::anyhow; use anyhow::anyhow;
use dap::Module; use dap::Module;
use gpui::{ use gpui::{
AnyElement, Entity, FocusHandle, Focusable, MouseButton, ScrollStrategy, Stateful, AnyElement, Entity, FocusHandle, Focusable, ScrollStrategy, Subscription, Task,
Subscription, Task, UniformListScrollHandle, WeakEntity, uniform_list, UniformListScrollHandle, WeakEntity, uniform_list,
}; };
use project::{ use project::{
ProjectItem as _, ProjectPath, ProjectItem as _, ProjectPath,
debugger::session::{Session, SessionEvent}, debugger::session::{Session, SessionEvent},
}; };
use std::{ops::Range, path::Path, sync::Arc}; use std::{ops::Range, path::Path, sync::Arc};
use ui::{Scrollbar, ScrollbarState, prelude::*}; use ui::{WithScrollbar, prelude::*};
use workspace::Workspace; use workspace::Workspace;
pub struct ModuleList { pub struct ModuleList {
@@ -18,7 +18,6 @@ pub struct ModuleList {
session: Entity<Session>, session: Entity<Session>,
workspace: WeakEntity<Workspace>, workspace: WeakEntity<Workspace>,
focus_handle: FocusHandle, focus_handle: FocusHandle,
scrollbar_state: ScrollbarState,
entries: Vec<Module>, entries: Vec<Module>,
_rebuild_task: Option<Task<()>>, _rebuild_task: Option<Task<()>>,
_subscription: Subscription, _subscription: Subscription,
@@ -44,7 +43,6 @@ impl ModuleList {
let scroll_handle = UniformListScrollHandle::new(); let scroll_handle = UniformListScrollHandle::new();
Self { Self {
scrollbar_state: ScrollbarState::new(scroll_handle.clone()),
scroll_handle, scroll_handle,
session, session,
workspace, workspace,
@@ -167,38 +165,6 @@ impl ModuleList {
self.session self.session
.update(cx, |session, cx| session.modules(cx).to_vec()) .update(cx, |session, cx| session.modules(cx).to_vec())
} }
fn render_vertical_scrollbar(&self, cx: &mut Context<Self>) -> Stateful<Div> {
div()
.occlude()
.id("module-list-vertical-scrollbar")
.on_mouse_move(cx.listener(|_, _, _, cx| {
cx.notify();
cx.stop_propagation()
}))
.on_hover(|_, _, cx| {
cx.stop_propagation();
})
.on_any_mouse_down(|_, _, cx| {
cx.stop_propagation();
})
.on_mouse_up(
MouseButton::Left,
cx.listener(|_, _, _, cx| {
cx.stop_propagation();
}),
)
.on_scroll_wheel(cx.listener(|_, _, _, cx| {
cx.notify();
}))
.h_full()
.absolute()
.right_1()
.top_1()
.bottom_0()
.w(px(12.))
.cursor_default()
.children(Scrollbar::vertical(self.scrollbar_state.clone()))
}
fn confirm(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) { fn confirm(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
let Some(ix) = self.selected_ix else { return }; let Some(ix) = self.selected_ix else { return };
@@ -313,6 +279,6 @@ impl Render for ModuleList {
.size_full() .size_full()
.p_1() .p_1()
.child(self.render_list(window, cx)) .child(self.render_list(window, cx))
.child(self.render_vertical_scrollbar(cx)) .vertical_scrollbar_for(self.scroll_handle.clone(), window, cx)
} }
} }
@@ -7,7 +7,7 @@ use dap::StackFrameId;
use db::kvp::KEY_VALUE_STORE; use db::kvp::KEY_VALUE_STORE;
use gpui::{ use gpui::{
Action, AnyElement, Entity, EventEmitter, FocusHandle, Focusable, FontWeight, ListState, Action, AnyElement, Entity, EventEmitter, FocusHandle, Focusable, FontWeight, ListState,
MouseButton, Stateful, Subscription, Task, WeakEntity, list, Subscription, Task, WeakEntity, list,
}; };
use util::debug_panic; use util::debug_panic;
@@ -16,7 +16,7 @@ use language::PointUtf16;
use project::debugger::breakpoint_store::ActiveStackFrame; use project::debugger::breakpoint_store::ActiveStackFrame;
use project::debugger::session::{Session, SessionEvent, StackFrame, ThreadStatus}; use project::debugger::session::{Session, SessionEvent, StackFrame, ThreadStatus};
use project::{ProjectItem, ProjectPath}; use project::{ProjectItem, ProjectPath};
use ui::{Scrollbar, ScrollbarState, Tooltip, prelude::*}; use ui::{Tooltip, WithScrollbar, prelude::*};
use workspace::{ItemHandle, Workspace}; use workspace::{ItemHandle, Workspace};
use super::RunningState; use super::RunningState;
@@ -64,7 +64,6 @@ pub struct StackFrameList {
workspace: WeakEntity<Workspace>, workspace: WeakEntity<Workspace>,
selected_ix: Option<usize>, selected_ix: Option<usize>,
opened_stack_frame_id: Option<StackFrameId>, opened_stack_frame_id: Option<StackFrameId>,
scrollbar_state: ScrollbarState,
list_state: ListState, list_state: ListState,
list_filter: StackFrameFilter, list_filter: StackFrameFilter,
filter_entries_indices: Vec<usize>, filter_entries_indices: Vec<usize>,
@@ -102,7 +101,6 @@ impl StackFrameList {
}); });
let list_state = ListState::new(0, gpui::ListAlignment::Top, px(1000.)); let list_state = ListState::new(0, gpui::ListAlignment::Top, px(1000.));
let scrollbar_state = ScrollbarState::new(list_state.clone());
let list_filter = KEY_VALUE_STORE let list_filter = KEY_VALUE_STORE
.read_kvp(&format!( .read_kvp(&format!(
@@ -127,7 +125,6 @@ impl StackFrameList {
opened_stack_frame_id: None, opened_stack_frame_id: None,
list_filter, list_filter,
list_state, list_state,
scrollbar_state,
_refresh_task: Task::ready(()), _refresh_task: Task::ready(()),
}; };
this.schedule_refresh(true, window, cx); this.schedule_refresh(true, window, cx);
@@ -697,39 +694,6 @@ impl StackFrameList {
} }
} }
fn render_vertical_scrollbar(&self, cx: &mut Context<Self>) -> Stateful<Div> {
div()
.occlude()
.id("stack-frame-list-vertical-scrollbar")
.on_mouse_move(cx.listener(|_, _, _, cx| {
cx.notify();
cx.stop_propagation()
}))
.on_hover(|_, _, cx| {
cx.stop_propagation();
})
.on_any_mouse_down(|_, _, cx| {
cx.stop_propagation();
})
.on_mouse_up(
MouseButton::Left,
cx.listener(|_, _, _, cx| {
cx.stop_propagation();
}),
)
.on_scroll_wheel(cx.listener(|_, _, _, cx| {
cx.notify();
}))
.h_full()
.absolute()
.right_1()
.top_1()
.bottom_0()
.w(px(12.))
.cursor_default()
.children(Scrollbar::vertical(self.scrollbar_state.clone()))
}
fn select_ix(&mut self, ix: Option<usize>, cx: &mut Context<Self>) { fn select_ix(&mut self, ix: Option<usize>, cx: &mut Context<Self>) {
self.selected_ix = ix; self.selected_ix = ix;
cx.notify(); cx.notify();
@@ -941,7 +905,7 @@ impl Render for StackFrameList {
) )
}) })
.child(self.render_list(window, cx)) .child(self.render_list(window, cx))
.child(self.render_vertical_scrollbar(cx)) .vertical_scrollbar_for(self.list_state.clone(), window, cx)
} }
} }
@@ -8,9 +8,8 @@ use dap::{
use editor::Editor; use editor::Editor;
use gpui::{ use gpui::{
Action, AnyElement, ClickEvent, ClipboardItem, Context, DismissEvent, Empty, Entity, Action, AnyElement, ClickEvent, ClipboardItem, Context, DismissEvent, Empty, Entity,
FocusHandle, Focusable, Hsla, MouseButton, MouseDownEvent, Point, Stateful, Subscription, FocusHandle, Focusable, Hsla, MouseDownEvent, Point, Subscription, TextStyleRefinement,
TextStyleRefinement, UniformListScrollHandle, WeakEntity, actions, anchored, deferred, UniformListScrollHandle, WeakEntity, actions, anchored, deferred, uniform_list,
uniform_list,
}; };
use menu::{SelectFirst, SelectLast, SelectNext, SelectPrevious}; use menu::{SelectFirst, SelectLast, SelectNext, SelectPrevious};
use project::debugger::{ use project::debugger::{
@@ -18,7 +17,7 @@ use project::debugger::{
session::{Session, SessionEvent, Watcher}, session::{Session, SessionEvent, Watcher},
}; };
use std::{collections::HashMap, ops::Range, sync::Arc}; use std::{collections::HashMap, ops::Range, sync::Arc};
use ui::{ContextMenu, ListItem, ScrollableHandle, Scrollbar, ScrollbarState, Tooltip, prelude::*}; use ui::{ContextMenu, ListItem, ScrollableHandle, Tooltip, WithScrollbar, prelude::*};
use util::{debug_panic, maybe}; use util::{debug_panic, maybe};
actions!( actions!(
@@ -189,7 +188,6 @@ pub struct VariableList {
entry_states: HashMap<EntryPath, EntryState>, entry_states: HashMap<EntryPath, EntryState>,
selected_stack_frame_id: Option<StackFrameId>, selected_stack_frame_id: Option<StackFrameId>,
list_handle: UniformListScrollHandle, list_handle: UniformListScrollHandle,
scrollbar_state: ScrollbarState,
session: Entity<Session>, session: Entity<Session>,
selection: Option<EntryPath>, selection: Option<EntryPath>,
open_context_menu: Option<(Entity<ContextMenu>, Point<Pixels>, Subscription)>, open_context_menu: Option<(Entity<ContextMenu>, Point<Pixels>, Subscription)>,
@@ -235,7 +233,6 @@ impl VariableList {
let list_state = UniformListScrollHandle::default(); let list_state = UniformListScrollHandle::default();
Self { Self {
scrollbar_state: ScrollbarState::new(list_state.clone()),
list_handle: list_state, list_handle: list_state,
session, session,
focus_handle, focus_handle,
@@ -1500,39 +1497,6 @@ impl VariableList {
) )
.into_any() .into_any()
} }
fn render_vertical_scrollbar(&self, cx: &mut Context<Self>) -> Stateful<Div> {
div()
.occlude()
.id("variable-list-vertical-scrollbar")
.on_mouse_move(cx.listener(|_, _, _, cx| {
cx.notify();
cx.stop_propagation()
}))
.on_hover(|_, _, cx| {
cx.stop_propagation();
})
.on_any_mouse_down(|_, _, cx| {
cx.stop_propagation();
})
.on_mouse_up(
MouseButton::Left,
cx.listener(|_, _, _, cx| {
cx.stop_propagation();
}),
)
.on_scroll_wheel(cx.listener(|_, _, _, cx| {
cx.notify();
}))
.h_full()
.absolute()
.right_1()
.top_1()
.bottom_0()
.w(px(12.))
.cursor_default()
.children(Scrollbar::vertical(self.scrollbar_state.clone()))
}
} }
impl Focusable for VariableList { impl Focusable for VariableList {
@@ -1542,7 +1506,7 @@ impl Focusable for VariableList {
} }
impl Render for VariableList { impl Render for VariableList {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement { fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
v_flex() v_flex()
.track_focus(&self.focus_handle) .track_focus(&self.focus_handle)
.key_context("VariableList") .key_context("VariableList")
@@ -1587,7 +1551,7 @@ impl Render for VariableList {
) )
.with_priority(1) .with_priority(1)
})) }))
.child(self.render_vertical_scrollbar(cx)) .vertical_scrollbar_for(self.list_handle.clone(), window, cx)
} }
} }
+3 -3
View File
@@ -55,7 +55,7 @@ pub use display_map::{ChunkRenderer, ChunkRendererContext, DisplayPoint, FoldPla
pub use edit_prediction::Direction; pub use edit_prediction::Direction;
pub use editor_settings::{ pub use editor_settings::{
CurrentLineHighlight, DocumentColorsRenderMode, EditorSettings, HideMouseMode, CurrentLineHighlight, DocumentColorsRenderMode, EditorSettings, HideMouseMode,
ScrollBeyondLastLine, ScrollbarAxes, SearchSettings, ShowMinimap, ShowScrollbar, ScrollBeyondLastLine, ScrollbarAxes, SearchSettings, ShowMinimap,
}; };
pub use editor_settings_controls::*; pub use editor_settings_controls::*;
pub use element::{ pub use element::{
@@ -166,7 +166,7 @@ use project::{
}; };
use rand::seq::SliceRandom; use rand::seq::SliceRandom;
use rpc::{ErrorCode, ErrorExt, proto::PeerId}; use rpc::{ErrorCode, ErrorExt, proto::PeerId};
use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide}; use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager};
use selections_collection::{ use selections_collection::{
MutableSelectionsCollection, SelectionsCollection, resolve_selections, MutableSelectionsCollection, SelectionsCollection, resolve_selections,
}; };
@@ -196,7 +196,7 @@ use theme::{
}; };
use ui::{ use ui::{
ButtonSize, ButtonStyle, ContextMenu, Disclosure, IconButton, IconButtonShape, IconName, ButtonSize, ButtonStyle, ContextMenu, Disclosure, IconButton, IconButtonShape, IconName,
IconSize, Indicator, Key, Tooltip, h_flex, prelude::*, IconSize, Indicator, Key, Tooltip, h_flex, prelude::*, scrollbars::ScrollbarAutoHide,
}; };
use util::{RangeExt, ResultExt, TryFutureExt, maybe, post_inc}; use util::{RangeExt, ResultExt, TryFutureExt, maybe, post_inc};
use workspace::{ use workspace::{
+7 -17
View File
@@ -7,6 +7,7 @@ use project::project_settings::DiagnosticSeverity;
use schemars::JsonSchema; use schemars::JsonSchema;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use settings::{Settings, SettingsKey, SettingsSources, SettingsUi, VsCodeSettings}; use settings::{Settings, SettingsKey, SettingsSources, SettingsUi, VsCodeSettings};
use ui::scrollbars::{ScrollbarVisibility, ShowScrollbar};
use util::serde::default_true; use util::serde::default_true;
/// Imports from the VSCode settings at /// Imports from the VSCode settings at
@@ -205,23 +206,6 @@ pub struct Gutter {
pub folds: bool, pub folds: bool,
} }
/// When to show the scrollbar in the editor.
///
/// Default: auto
#[derive(Copy, Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum ShowScrollbar {
/// Show the scrollbar if there's important information or
/// follow the system's configured behavior.
Auto,
/// Match the system's configured behavior.
System,
/// Always show the scrollbar.
Always,
/// Never show the scrollbar.
Never,
}
/// When to show the minimap in the editor. /// When to show the minimap in the editor.
/// ///
/// Default: never /// Default: never
@@ -778,6 +762,12 @@ impl EditorSettings {
} }
} }
impl ScrollbarVisibility for EditorSettings {
fn visibility(&self, _cx: &App) -> ShowScrollbar {
self.scrollbar.show
}
}
impl Settings for EditorSettings { impl Settings for EditorSettings {
type FileContent = EditorSettingsContent; type FileContent = EditorSettingsContent;
+2 -2
View File
@@ -18,7 +18,7 @@ use crate::{
editor_settings::{ editor_settings::{
CurrentLineHighlight, DocumentColorsRenderMode, DoubleClickInMultibuffer, Minimap, CurrentLineHighlight, DocumentColorsRenderMode, DoubleClickInMultibuffer, Minimap,
MinimapThumb, MinimapThumbBorder, ScrollBeyondLastLine, ScrollbarAxes, MinimapThumb, MinimapThumbBorder, ScrollBeyondLastLine, ScrollbarAxes,
ScrollbarDiagnostics, ShowMinimap, ShowScrollbar, ScrollbarDiagnostics, ShowMinimap,
}, },
git::blame::{BlameRenderer, GitBlame, GlobalBlameRenderer}, git::blame::{BlameRenderer, GitBlame, GlobalBlameRenderer},
hover_popover::{ hover_popover::{
@@ -85,7 +85,7 @@ use theme::{ActiveTheme, Appearance, BufferLineHeight, PlayerColor};
use ui::utils::ensure_minimum_contrast; use ui::utils::ensure_minimum_contrast;
use ui::{ use ui::{
ButtonLike, ContextMenu, Indicator, KeyBinding, POPOVER_Y_PADDING, Tooltip, h_flex, prelude::*, ButtonLike, ContextMenu, Indicator, KeyBinding, POPOVER_Y_PADDING, Tooltip, h_flex, prelude::*,
right_click_menu, right_click_menu, scrollbars::ShowScrollbar,
}; };
use unicode_segmentation::UnicodeSegmentation; use unicode_segmentation::UnicodeSegmentation;
use util::post_inc; use util::post_inc;
+15 -77
View File
@@ -9,8 +9,8 @@ use anyhow::Context as _;
use gpui::{ use gpui::{
AnyElement, AsyncWindowContext, Context, Entity, Focusable as _, FontWeight, Hsla, AnyElement, AsyncWindowContext, Context, Entity, Focusable as _, FontWeight, Hsla,
InteractiveElement, IntoElement, MouseButton, ParentElement, Pixels, ScrollHandle, Size, InteractiveElement, IntoElement, MouseButton, ParentElement, Pixels, ScrollHandle, Size,
Stateful, StatefulInteractiveElement, StyleRefinement, Styled, Subscription, Task, StatefulInteractiveElement, StyleRefinement, Styled, Subscription, Task, TextStyleRefinement,
TextStyleRefinement, Window, div, px, Window, div, px,
}; };
use itertools::Itertools; use itertools::Itertools;
use language::{DiagnosticEntry, Language, LanguageRegistry}; use language::{DiagnosticEntry, Language, LanguageRegistry};
@@ -23,7 +23,7 @@ use std::{borrow::Cow, cell::RefCell};
use std::{ops::Range, sync::Arc, time::Duration}; use std::{ops::Range, sync::Arc, time::Duration};
use std::{path::PathBuf, rc::Rc}; use std::{path::PathBuf, rc::Rc};
use theme::ThemeSettings; use theme::ThemeSettings;
use ui::{Scrollbar, ScrollbarState, prelude::*, theme_is_transparent}; use ui::{Scrollbars, WithScrollbar, prelude::*, theme_is_transparent};
use url::Url; use url::Url;
use util::TryFutureExt; use util::TryFutureExt;
use workspace::{OpenOptions, OpenVisible, Workspace}; use workspace::{OpenOptions, OpenVisible, Workspace};
@@ -184,7 +184,6 @@ pub fn hover_at_inlay(
let hover_popover = InfoPopover { let hover_popover = InfoPopover {
symbol_range: RangeInEditor::Inlay(inlay_hover.range.clone()), symbol_range: RangeInEditor::Inlay(inlay_hover.range.clone()),
parsed_content, parsed_content,
scrollbar_state: ScrollbarState::new(scroll_handle.clone()),
scroll_handle, scroll_handle,
keyboard_grace: Rc::new(RefCell::new(false)), keyboard_grace: Rc::new(RefCell::new(false)),
anchor: None, anchor: None,
@@ -387,7 +386,6 @@ fn show_hover(
local_diagnostic, local_diagnostic,
markdown, markdown,
border_color, border_color,
scrollbar_state: ScrollbarState::new(scroll_handle.clone()),
scroll_handle, scroll_handle,
background_color, background_color,
keyboard_grace: Rc::new(RefCell::new(ignore_timeout)), keyboard_grace: Rc::new(RefCell::new(ignore_timeout)),
@@ -457,7 +455,6 @@ fn show_hover(
info_popovers.push(InfoPopover { info_popovers.push(InfoPopover {
symbol_range: RangeInEditor::Text(range), symbol_range: RangeInEditor::Text(range),
parsed_content, parsed_content,
scrollbar_state: ScrollbarState::new(scroll_handle.clone()),
scroll_handle, scroll_handle,
keyboard_grace: Rc::new(RefCell::new(ignore_timeout)), keyboard_grace: Rc::new(RefCell::new(ignore_timeout)),
anchor: Some(anchor), anchor: Some(anchor),
@@ -507,7 +504,6 @@ fn show_hover(
info_popovers.push(InfoPopover { info_popovers.push(InfoPopover {
symbol_range: RangeInEditor::Text(range), symbol_range: RangeInEditor::Text(range),
parsed_content, parsed_content,
scrollbar_state: ScrollbarState::new(scroll_handle.clone()),
scroll_handle, scroll_handle,
keyboard_grace: Rc::new(RefCell::new(ignore_timeout)), keyboard_grace: Rc::new(RefCell::new(ignore_timeout)),
anchor: Some(anchor), anchor: Some(anchor),
@@ -846,7 +842,6 @@ pub struct InfoPopover {
pub symbol_range: RangeInEditor, pub symbol_range: RangeInEditor,
pub parsed_content: Option<Entity<Markdown>>, pub parsed_content: Option<Entity<Markdown>>,
pub scroll_handle: ScrollHandle, pub scroll_handle: ScrollHandle,
pub scrollbar_state: ScrollbarState,
pub keyboard_grace: Rc<RefCell<bool>>, pub keyboard_grace: Rc<RefCell<bool>>,
pub anchor: Option<Anchor>, pub anchor: Option<Anchor>,
_subscription: Option<Subscription>, _subscription: Option<Subscription>,
@@ -891,7 +886,12 @@ impl InfoPopover {
.on_url_click(open_markdown_url), .on_url_click(open_markdown_url),
), ),
) )
.child(self.render_vertical_scrollbar(cx)) .custom_scrollbars(
Scrollbars::for_settings::<EditorSettings>()
.tracked_scroll_handle(self.scroll_handle.clone()),
window,
cx,
)
}) })
.into_any_element() .into_any_element()
} }
@@ -905,39 +905,6 @@ impl InfoPopover {
cx.notify(); cx.notify();
self.scroll_handle.set_offset(current); self.scroll_handle.set_offset(current);
} }
fn render_vertical_scrollbar(&self, cx: &mut Context<Editor>) -> Stateful<Div> {
div()
.occlude()
.id("info-popover-vertical-scroll")
.on_mouse_move(cx.listener(|_, _, _, cx| {
cx.notify();
cx.stop_propagation()
}))
.on_hover(|_, _, cx| {
cx.stop_propagation();
})
.on_any_mouse_down(|_, _, cx| {
cx.stop_propagation();
})
.on_mouse_up(
MouseButton::Left,
cx.listener(|_, _, _, cx| {
cx.stop_propagation();
}),
)
.on_scroll_wheel(cx.listener(|_, _, _, cx| {
cx.notify();
}))
.h_full()
.absolute()
.right_1()
.top_1()
.bottom_0()
.w(px(12.))
.cursor_default()
.children(Scrollbar::vertical(self.scrollbar_state.clone()))
}
} }
pub struct DiagnosticPopover { pub struct DiagnosticPopover {
@@ -949,7 +916,6 @@ pub struct DiagnosticPopover {
pub anchor: Anchor, pub anchor: Anchor,
_subscription: Subscription, _subscription: Subscription,
pub scroll_handle: ScrollHandle, pub scroll_handle: ScrollHandle,
pub scrollbar_state: ScrollbarState,
} }
impl DiagnosticPopover { impl DiagnosticPopover {
@@ -1013,43 +979,15 @@ impl DiagnosticPopover {
), ),
), ),
) )
.child(self.render_vertical_scrollbar(cx)), .custom_scrollbars(
Scrollbars::for_settings::<EditorSettings>()
.tracked_scroll_handle(self.scroll_handle.clone()),
window,
cx,
),
) )
.into_any_element() .into_any_element()
} }
fn render_vertical_scrollbar(&self, cx: &mut Context<Editor>) -> Stateful<Div> {
div()
.occlude()
.id("diagnostic-popover-vertical-scroll")
.on_mouse_move(cx.listener(|_, _, _, cx| {
cx.notify();
cx.stop_propagation()
}))
.on_hover(|_, _, cx| {
cx.stop_propagation();
})
.on_any_mouse_down(|_, _, cx| {
cx.stop_propagation();
})
.on_mouse_up(
MouseButton::Left,
cx.listener(|_, _, _, cx| {
cx.stop_propagation();
}),
)
.on_scroll_wheel(cx.listener(|_, _, _, cx| {
cx.notify();
}))
.h_full()
.absolute()
.right_1()
.top_1()
.bottom_0()
.w(px(12.))
.cursor_default()
.children(Scrollbar::vertical(self.scrollbar_state.clone()))
}
} }
#[cfg(test)] #[cfg(test)]
+3 -7
View File
@@ -12,7 +12,7 @@ use crate::{
}; };
pub use autoscroll::{Autoscroll, AutoscrollStrategy}; pub use autoscroll::{Autoscroll, AutoscrollStrategy};
use core::fmt::Debug; use core::fmt::Debug;
use gpui::{Along, App, Axis, Context, Global, Pixels, Task, Window, point, px}; use gpui::{Along, App, Axis, Context, Pixels, Task, Window, point, px};
use language::language_settings::{AllLanguageSettings, SoftWrap}; use language::language_settings::{AllLanguageSettings, SoftWrap};
use language::{Bias, Point}; use language::{Bias, Point};
pub use scroll_amount::ScrollAmount; pub use scroll_amount::ScrollAmount;
@@ -21,6 +21,7 @@ use std::{
cmp::Ordering, cmp::Ordering,
time::{Duration, Instant}, time::{Duration, Instant},
}; };
use ui::scrollbars::ScrollbarAutoHide;
use util::ResultExt; use util::ResultExt;
use workspace::{ItemId, WorkspaceId}; use workspace::{ItemId, WorkspaceId};
@@ -29,11 +30,6 @@ const SCROLLBAR_SHOW_INTERVAL: Duration = Duration::from_secs(1);
pub struct WasScrolled(pub(crate) bool); pub struct WasScrolled(pub(crate) bool);
#[derive(Default)]
pub struct ScrollbarAutoHide(pub bool);
impl Global for ScrollbarAutoHide {}
#[derive(Clone, Copy, Debug, PartialEq)] #[derive(Clone, Copy, Debug, PartialEq)]
pub struct ScrollAnchor { pub struct ScrollAnchor {
pub offset: gpui::Point<f32>, pub offset: gpui::Point<f32>,
@@ -327,7 +323,7 @@ impl ScrollManager {
cx.notify(); cx.notify();
} }
if cx.default_global::<ScrollbarAutoHide>().0 { if cx.default_global::<ScrollbarAutoHide>().should_hide() {
self.hide_scrollbar_task = Some(cx.spawn_in(window, async move |editor, cx| { self.hide_scrollbar_task = Some(cx.spawn_in(window, async move |editor, cx| {
cx.background_executor() cx.background_executor()
.timer(SCROLLBAR_SHOW_INTERVAL) .timer(SCROLLBAR_SHOW_INTERVAL)
+6 -29
View File
@@ -2,8 +2,8 @@ use crate::actions::ShowSignatureHelp;
use crate::hover_popover::open_markdown_url; use crate::hover_popover::open_markdown_url;
use crate::{Editor, EditorSettings, ToggleAutoSignatureHelp, hover_markdown_style}; use crate::{Editor, EditorSettings, ToggleAutoSignatureHelp, hover_markdown_style};
use gpui::{ use gpui::{
App, Context, Div, Entity, HighlightStyle, MouseButton, ScrollHandle, Size, Stateful, App, Context, Entity, HighlightStyle, MouseButton, ScrollHandle, Size, StyledText, Task,
StyledText, Task, TextStyle, Window, combine_highlights, TextStyle, Window, combine_highlights,
}; };
use language::BufferSnapshot; use language::BufferSnapshot;
use markdown::{Markdown, MarkdownElement}; use markdown::{Markdown, MarkdownElement};
@@ -15,8 +15,8 @@ use theme::ThemeSettings;
use ui::{ use ui::{
ActiveTheme, AnyElement, ButtonCommon, ButtonStyle, Clickable, FluentBuilder, IconButton, ActiveTheme, AnyElement, ButtonCommon, ButtonStyle, Clickable, FluentBuilder, IconButton,
IconButtonShape, IconName, IconSize, InteractiveElement, IntoElement, Label, LabelCommon, IconButtonShape, IconName, IconSize, InteractiveElement, IntoElement, Label, LabelCommon,
LabelSize, ParentElement, Pixels, Scrollbar, ScrollbarState, SharedString, LabelSize, ParentElement, Pixels, SharedString, StatefulInteractiveElement, Styled, StyledExt,
StatefulInteractiveElement, Styled, StyledExt, div, px, relative, WithScrollbar, div, relative,
}; };
// Language-specific settings may define quotes as "brackets", so filter them out separately. // Language-specific settings may define quotes as "brackets", so filter them out separately.
@@ -243,7 +243,6 @@ impl Editor {
.min(signatures.len().saturating_sub(1)); .min(signatures.len().saturating_sub(1));
let signature_help_popover = SignatureHelpPopover { let signature_help_popover = SignatureHelpPopover {
scrollbar_state: ScrollbarState::new(scroll_handle.clone()),
style, style,
signatures, signatures,
current_signature, current_signature,
@@ -330,7 +329,6 @@ pub struct SignatureHelpPopover {
pub signatures: Vec<SignatureHelp>, pub signatures: Vec<SignatureHelp>,
pub current_signature: usize, pub current_signature: usize,
scroll_handle: ScrollHandle, scroll_handle: ScrollHandle,
scrollbar_state: ScrollbarState,
} }
impl SignatureHelpPopover { impl SignatureHelpPopover {
@@ -391,7 +389,8 @@ impl SignatureHelpPopover {
) )
}), }),
) )
.child(self.render_vertical_scrollbar(cx)); .vertical_scrollbar(window, cx);
let controls = if self.signatures.len() > 1 { let controls = if self.signatures.len() > 1 {
let prev_button = IconButton::new("signature_help_prev", IconName::ChevronUp) let prev_button = IconButton::new("signature_help_prev", IconName::ChevronUp)
.shape(IconButtonShape::Square) .shape(IconButtonShape::Square)
@@ -460,26 +459,4 @@ impl SignatureHelpPopover {
.child(main_content) .child(main_content)
.into_any_element() .into_any_element()
} }
fn render_vertical_scrollbar(&self, cx: &mut Context<Editor>) -> Stateful<Div> {
div()
.occlude()
.id("signature_help_scrollbar")
.on_mouse_move(cx.listener(|_, _, _, cx| {
cx.notify();
cx.stop_propagation()
}))
.on_hover(|_, _, cx| cx.stop_propagation())
.on_any_mouse_down(|_, _, cx| cx.stop_propagation())
.on_mouse_up(MouseButton::Left, |_, _, cx| cx.stop_propagation())
.on_scroll_wheel(cx.listener(|_, _, _, cx| cx.notify()))
.h_full()
.absolute()
.right_1()
.top_1()
.bottom_1()
.w(px(12.))
.cursor_default()
.children(Scrollbar::vertical(self.scrollbar_state.clone()))
}
} }
+20 -23
View File
@@ -24,8 +24,8 @@ use settings::Settings;
use strum::IntoEnumIterator as _; use strum::IntoEnumIterator as _;
use theme::ThemeSettings; use theme::ThemeSettings;
use ui::{ use ui::{
CheckboxWithLabel, Chip, ContextMenu, PopoverMenu, ScrollableHandle, Scrollbar, ScrollbarState, CheckboxWithLabel, Chip, ContextMenu, PopoverMenu, ScrollableHandle, ToggleButton, Tooltip,
ToggleButton, Tooltip, prelude::*, WithScrollbar, prelude::*,
}; };
use vim_mode_setting::VimModeSetting; use vim_mode_setting::VimModeSetting;
use workspace::{ use workspace::{
@@ -290,7 +290,6 @@ pub struct ExtensionsPage {
_subscriptions: [gpui::Subscription; 2], _subscriptions: [gpui::Subscription; 2],
extension_fetch_task: Option<Task<()>>, extension_fetch_task: Option<Task<()>>,
upsells: BTreeSet<Feature>, upsells: BTreeSet<Feature>,
scrollbar_state: ScrollbarState,
} }
impl ExtensionsPage { impl ExtensionsPage {
@@ -339,7 +338,7 @@ impl ExtensionsPage {
let mut this = Self { let mut this = Self {
workspace: workspace.weak_handle(), workspace: workspace.weak_handle(),
list: scroll_handle.clone(), list: scroll_handle,
is_fetching_extensions: false, is_fetching_extensions: false,
filter: ExtensionFilter::All, filter: ExtensionFilter::All,
dev_extension_entries: Vec::new(), dev_extension_entries: Vec::new(),
@@ -351,7 +350,6 @@ impl ExtensionsPage {
_subscriptions: subscriptions, _subscriptions: subscriptions,
query_editor, query_editor,
upsells: BTreeSet::default(), upsells: BTreeSet::default(),
scrollbar_state: ScrollbarState::new(scroll_handle),
}; };
this.fetch_extensions( this.fetch_extensions(
this.search_query(cx), this.search_query(cx),
@@ -1375,7 +1373,7 @@ impl ExtensionsPage {
} }
impl Render for ExtensionsPage { impl Render for ExtensionsPage {
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement { fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
v_flex() v_flex()
.size_full() .size_full()
.bg(cx.theme().colors().editor_background) .bg(cx.theme().colors().editor_background)
@@ -1520,25 +1518,24 @@ impl Render for ExtensionsPage {
} }
if count == 0 { if count == 0 {
return this.py_4().child(self.render_empty_state(cx)); this.py_4()
} .child(self.render_empty_state(cx))
.into_any_element()
let scroll_handle = self.list.clone(); } else {
this.child( let scroll_handle = self.list.clone();
uniform_list("entries", count, cx.processor(Self::render_extensions)) this.child(
uniform_list(
"entries",
count,
cx.processor(Self::render_extensions),
)
.flex_grow() .flex_grow()
.pb_4() .pb_4()
.track_scroll(scroll_handle), .track_scroll(scroll_handle.clone()),
) )
.child( .vertical_scrollbar_for(scroll_handle, window, cx)
div() .into_any_element()
.absolute() }
.right_1()
.top_0()
.bottom_0()
.w(px(12.))
.children(Scrollbar::vertical(self.scrollbar_state.clone())),
)
}), }),
) )
} }
+14 -377
View File
@@ -13,10 +13,7 @@ use agent_settings::AgentSettings;
use anyhow::Context as _; use anyhow::Context as _;
use askpass::AskPassDelegate; use askpass::AskPassDelegate;
use db::kvp::KEY_VALUE_STORE; use db::kvp::KEY_VALUE_STORE;
use editor::{ use editor::{Editor, EditorElement, EditorMode, MultiBuffer};
Editor, EditorElement, EditorMode, EditorSettings, MultiBuffer, ShowScrollbar,
scroll::ScrollbarAutoHide,
};
use futures::StreamExt as _; use futures::StreamExt as _;
use git::blame::ParsedCommitMessage; use git::blame::ParsedCommitMessage;
use git::repository::{ use git::repository::{
@@ -32,11 +29,10 @@ use git::{
TrashUntrackedFiles, UnstageAll, TrashUntrackedFiles, UnstageAll,
}; };
use gpui::{ use gpui::{
Action, AsyncApp, AsyncWindowContext, Axis, ClickEvent, Corner, DismissEvent, Entity, Action, AsyncApp, AsyncWindowContext, ClickEvent, Corner, DismissEvent, Entity, EventEmitter,
EventEmitter, FocusHandle, Focusable, KeyContext, ListHorizontalSizingBehavior, FocusHandle, Focusable, KeyContext, ListHorizontalSizingBehavior, ListSizingBehavior,
ListSizingBehavior, MouseButton, MouseDownEvent, Point, PromptLevel, ScrollStrategy, MouseButton, MouseDownEvent, Point, PromptLevel, ScrollStrategy, Subscription, Task,
Subscription, Task, UniformListScrollHandle, WeakEntity, actions, anchored, deferred, UniformListScrollHandle, WeakEntity, actions, anchored, deferred, uniform_list,
uniform_list,
}; };
use itertools::Itertools; use itertools::Itertools;
use language::{Buffer, File}; use language::{Buffer, File};
@@ -64,7 +60,7 @@ use strum::{IntoEnumIterator, VariantNames};
use time::OffsetDateTime; use time::OffsetDateTime;
use ui::{ use ui::{
Checkbox, CommonAnimationExt, ContextMenu, ElevationIndex, IconPosition, Label, LabelSize, Checkbox, CommonAnimationExt, ContextMenu, ElevationIndex, IconPosition, Label, LabelSize,
PopoverMenu, Scrollbar, ScrollbarState, SplitButton, Tooltip, prelude::*, PopoverMenu, ScrollAxes, Scrollbars, SplitButton, Tooltip, WithScrollbar, prelude::*,
}; };
use util::{ResultExt, TryFutureExt, maybe}; use util::{ResultExt, TryFutureExt, maybe};
use workspace::SERIALIZATION_THROTTLE_TIME; use workspace::SERIALIZATION_THROTTLE_TIME;
@@ -291,61 +287,6 @@ struct PendingOperation {
op_id: usize, op_id: usize,
} }
// computed state related to how to render scrollbars
// one per axis
// on render we just read this off the panel
// we update it when
// - settings change
// - on focus in, on focus out, on hover, etc.
#[derive(Debug)]
struct ScrollbarProperties {
axis: Axis,
show_scrollbar: bool,
show_track: bool,
auto_hide: bool,
hide_task: Option<Task<()>>,
state: ScrollbarState,
}
impl ScrollbarProperties {
// Shows the scrollbar and cancels any pending hide task
fn show(&mut self, cx: &mut Context<GitPanel>) {
if !self.auto_hide {
return;
}
self.show_scrollbar = true;
self.hide_task.take();
cx.notify();
}
fn hide(&mut self, window: &mut Window, cx: &mut Context<GitPanel>) {
const SCROLLBAR_SHOW_INTERVAL: Duration = Duration::from_secs(1);
if !self.auto_hide {
return;
}
let axis = self.axis;
self.hide_task = Some(cx.spawn_in(window, async move |panel, cx| {
cx.background_executor()
.timer(SCROLLBAR_SHOW_INTERVAL)
.await;
if let Some(panel) = panel.upgrade() {
panel
.update(cx, |panel, cx| {
match axis {
Axis::Vertical => panel.vertical_scrollbar.show_scrollbar = false,
Axis::Horizontal => panel.horizontal_scrollbar.show_scrollbar = false,
}
cx.notify();
})
.log_err();
}
}));
}
}
pub struct GitPanel { pub struct GitPanel {
pub(crate) active_repository: Option<Entity<Repository>>, pub(crate) active_repository: Option<Entity<Repository>>,
pub(crate) commit_editor: Entity<Editor>, pub(crate) commit_editor: Entity<Editor>,
@@ -358,8 +299,6 @@ pub struct GitPanel {
single_tracked_entry: Option<GitStatusEntry>, single_tracked_entry: Option<GitStatusEntry>,
focus_handle: FocusHandle, focus_handle: FocusHandle,
fs: Arc<dyn Fs>, fs: Arc<dyn Fs>,
horizontal_scrollbar: ScrollbarProperties,
vertical_scrollbar: ScrollbarProperties,
new_count: usize, new_count: usize,
entry_count: usize, entry_count: usize,
new_staged_count: usize, new_staged_count: usize,
@@ -443,10 +382,6 @@ impl GitPanel {
cx.new(|cx| { cx.new(|cx| {
let focus_handle = cx.focus_handle(); let focus_handle = cx.focus_handle();
cx.on_focus(&focus_handle, window, Self::focus_in).detach(); cx.on_focus(&focus_handle, window, Self::focus_in).detach();
cx.on_focus_out(&focus_handle, window, |this, _, window, cx| {
this.hide_scrollbars(window, cx);
})
.detach();
let mut was_sort_by_path = GitPanelSettings::get_global(cx).sort_by_path; let mut was_sort_by_path = GitPanelSettings::get_global(cx).sort_by_path;
cx.observe_global_in::<SettingsStore>(window, move |this, window, cx| { cx.observe_global_in::<SettingsStore>(window, move |this, window, cx| {
@@ -471,24 +406,6 @@ impl GitPanel {
let scroll_handle = UniformListScrollHandle::new(); let scroll_handle = UniformListScrollHandle::new();
let vertical_scrollbar = ScrollbarProperties {
axis: Axis::Vertical,
state: ScrollbarState::new(scroll_handle.clone()).parent_entity(&cx.entity()),
show_scrollbar: false,
show_track: false,
auto_hide: false,
hide_task: None,
};
let horizontal_scrollbar = ScrollbarProperties {
axis: Axis::Horizontal,
state: ScrollbarState::new(scroll_handle.clone()).parent_entity(&cx.entity()),
show_scrollbar: false,
show_track: false,
auto_hide: false,
hide_task: None,
};
let mut assistant_enabled = AgentSettings::get_global(cx).enabled; let mut assistant_enabled = AgentSettings::get_global(cx).enabled;
let mut was_ai_disabled = DisableAiSettings::get_global(cx).disable_ai; let mut was_ai_disabled = DisableAiSettings::get_global(cx).disable_ai;
let _settings_subscription = cx.observe_global::<SettingsStore>(move |_, cx| { let _settings_subscription = cx.observe_global::<SettingsStore>(move |_, cx| {
@@ -570,8 +487,6 @@ impl GitPanel {
workspace: workspace.weak_handle(), workspace: workspace.weak_handle(),
modal_open: false, modal_open: false,
entry_count: 0, entry_count: 0,
horizontal_scrollbar,
vertical_scrollbar,
bulk_staging: None, bulk_staging: None,
stash_entries: Default::default(), stash_entries: Default::default(),
_settings_subscription, _settings_subscription,
@@ -582,86 +497,6 @@ impl GitPanel {
}) })
} }
fn hide_scrollbars(&mut self, window: &mut Window, cx: &mut Context<Self>) {
self.horizontal_scrollbar.hide(window, cx);
self.vertical_scrollbar.hide(window, cx);
}
fn update_scrollbar_properties(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
// TODO: This PR should have defined Editor's `scrollbar.axis`
// as an Option<ScrollbarAxis>, not a ScrollbarAxes as it would allow you to
// `.unwrap_or(EditorSettings::get_global(cx).scrollbar.show)`.
//
// Once this is fixed we can extend the GitPanelSettings with a `scrollbar.axis`
// so we can show each axis based on the settings.
//
// We should fix this. PR: https://github.com/zed-industries/zed/pull/19495
let show_setting = GitPanelSettings::get_global(cx)
.scrollbar
.show
.unwrap_or(EditorSettings::get_global(cx).scrollbar.show);
let scroll_handle = self.scroll_handle.0.borrow();
let autohide = |show: ShowScrollbar, cx: &mut Context<Self>| match show {
ShowScrollbar::Auto => true,
ShowScrollbar::System => cx
.try_global::<ScrollbarAutoHide>()
.map_or_else(|| cx.should_auto_hide_scrollbars(), |autohide| autohide.0),
ShowScrollbar::Always => false,
ShowScrollbar::Never => false,
};
let longest_item_width = scroll_handle.last_item_size.and_then(|size| {
(size.contents.width > size.item.width).then_some(size.contents.width)
});
// is there an item long enough that we should show a horizontal scrollbar?
let item_wider_than_container = if let Some(longest_item_width) = longest_item_width {
longest_item_width > px(scroll_handle.base_handle.bounds().size.width.0)
} else {
true
};
let show_horizontal = match (show_setting, item_wider_than_container) {
(_, false) => false,
(ShowScrollbar::Auto | ShowScrollbar::System | ShowScrollbar::Always, true) => true,
(ShowScrollbar::Never, true) => false,
};
let show_vertical = match show_setting {
ShowScrollbar::Auto | ShowScrollbar::System | ShowScrollbar::Always => true,
ShowScrollbar::Never => false,
};
let show_horizontal_track =
show_horizontal && matches!(show_setting, ShowScrollbar::Always);
// TODO: we probably should hide the scroll track when the list doesn't need to scroll
let show_vertical_track = show_vertical && matches!(show_setting, ShowScrollbar::Always);
self.vertical_scrollbar = ScrollbarProperties {
axis: self.vertical_scrollbar.axis,
state: self.vertical_scrollbar.state.clone(),
show_scrollbar: show_vertical,
show_track: show_vertical_track,
auto_hide: autohide(show_setting, cx),
hide_task: None,
};
self.horizontal_scrollbar = ScrollbarProperties {
axis: self.horizontal_scrollbar.axis,
state: self.horizontal_scrollbar.state.clone(),
show_scrollbar: show_horizontal,
show_track: show_horizontal_track,
auto_hide: autohide(show_setting, cx),
hide_task: None,
};
cx.notify();
}
pub fn entry_by_path(&self, path: &RepoPath, cx: &App) -> Option<usize> { pub fn entry_by_path(&self, path: &RepoPath, cx: &App) -> Option<usize> {
if GitPanelSettings::get_global(cx).sort_by_path { if GitPanelSettings::get_global(cx).sort_by_path {
return self return self
@@ -2676,7 +2511,6 @@ impl GitPanel {
git_panel.clear_pending(); git_panel.clear_pending();
} }
git_panel.update_visible_entries(window, cx); git_panel.update_visible_entries(window, cx);
git_panel.update_scrollbar_properties(window, cx);
}) })
.ok(); .ok();
} }
@@ -3799,110 +3633,6 @@ impl GitPanel {
) )
} }
fn render_vertical_scrollbar(
&self,
show_horizontal_scrollbar_container: bool,
cx: &mut Context<Self>,
) -> impl IntoElement {
div()
.id("git-panel-vertical-scroll")
.occlude()
.flex_none()
.h_full()
.cursor_default()
.absolute()
.right_0()
.top_0()
.bottom_0()
.w(px(12.))
.when(show_horizontal_scrollbar_container, |this| {
this.pb_neg_3p5()
})
.on_mouse_move(cx.listener(|_, _, _, cx| {
cx.notify();
cx.stop_propagation()
}))
.on_hover(|_, _, cx| {
cx.stop_propagation();
})
.on_any_mouse_down(|_, _, cx| {
cx.stop_propagation();
})
.on_mouse_up(
MouseButton::Left,
cx.listener(|this, _, window, cx| {
if !this.vertical_scrollbar.state.is_dragging()
&& !this.focus_handle.contains_focused(window, cx)
{
this.vertical_scrollbar.hide(window, cx);
cx.notify();
}
cx.stop_propagation();
}),
)
.on_scroll_wheel(cx.listener(|_, _, _, cx| {
cx.notify();
}))
.children(Scrollbar::vertical(
// percentage as f32..end_offset as f32,
self.vertical_scrollbar.state.clone(),
))
}
/// Renders the horizontal scrollbar.
///
/// The right offset is used to determine how far to the right the
/// scrollbar should extend to, useful for ensuring it doesn't collide
/// with the vertical scrollbar when visible.
fn render_horizontal_scrollbar(
&self,
right_offset: Pixels,
cx: &mut Context<Self>,
) -> impl IntoElement {
div()
.id("git-panel-horizontal-scroll")
.occlude()
.flex_none()
.w_full()
.cursor_default()
.absolute()
.bottom_neg_px()
.left_0()
.right_0()
.pr(right_offset)
.on_mouse_move(cx.listener(|_, _, _, cx| {
cx.notify();
cx.stop_propagation()
}))
.on_hover(|_, _, cx| {
cx.stop_propagation();
})
.on_any_mouse_down(|_, _, cx| {
cx.stop_propagation();
})
.on_mouse_up(
MouseButton::Left,
cx.listener(|this, _, window, cx| {
if !this.horizontal_scrollbar.state.is_dragging()
&& !this.focus_handle.contains_focused(window, cx)
{
this.horizontal_scrollbar.hide(window, cx);
cx.notify();
}
cx.stop_propagation();
}),
)
.on_scroll_wheel(cx.listener(|_, _, _, cx| {
cx.notify();
}))
.children(Scrollbar::horizontal(
// percentage as f32..end_offset as f32,
self.horizontal_scrollbar.state.clone(),
))
}
fn render_buffer_header_controls( fn render_buffer_header_controls(
&self, &self,
entity: &Entity<Self>, entity: &Entity<Self>,
@@ -3950,33 +3680,16 @@ impl GitPanel {
fn render_entries( fn render_entries(
&self, &self,
has_write_access: bool, has_write_access: bool,
_: &Window, window: &mut Window,
cx: &mut Context<Self>, cx: &mut Context<Self>,
) -> impl IntoElement { ) -> impl IntoElement {
let entry_count = self.entries.len(); let entry_count = self.entries.len();
let scroll_track_size = px(16.);
let h_scroll_offset = if self.vertical_scrollbar.show_scrollbar {
// magic number
px(3.)
} else {
px(0.)
};
v_flex() v_flex()
.flex_1() .flex_1()
.size_full() .size_full()
.overflow_hidden() .overflow_hidden()
.relative() .relative()
// Show a border on the top and bottom of the container when
// the vertical scrollbar container is visible so we don't have a
// floating left border in the panel.
.when(self.vertical_scrollbar.show_track, |this| {
this.border_t_1()
.border_b_1()
.border_color(cx.theme().colors().border)
})
.child( .child(
h_flex() h_flex()
.flex_1() .flex_1()
@@ -4017,15 +3730,6 @@ impl GitPanel {
items items
}), }),
) )
.when(
!self.horizontal_scrollbar.show_track
&& self.horizontal_scrollbar.show_scrollbar,
|this| {
// when not showing the horizontal scrollbar track, make sure we don't
// obscure the last entry
this.pb(scroll_track_size)
},
)
.size_full() .size_full()
.flex_grow() .flex_grow()
.with_sizing_behavior(ListSizingBehavior::Auto) .with_sizing_behavior(ListSizingBehavior::Auto)
@@ -4041,72 +3745,14 @@ impl GitPanel {
this.deploy_panel_context_menu(event.position, window, cx) this.deploy_panel_context_menu(event.position, window, cx)
}), }),
) )
.when(self.vertical_scrollbar.show_track, |this| { .custom_scrollbars(
this.child( Scrollbars::for_settings::<GitPanelSettings>()
v_flex() .tracked_scroll_handle(self.scroll_handle.clone())
.h_full() .with_track_along(ScrollAxes::Horizontal),
.flex_none() window,
.w(scroll_track_size) cx,
.bg(cx.theme().colors().panel_background) ),
.child(
div()
.size_full()
.flex_1()
.border_l_1()
.border_color(cx.theme().colors().border),
),
)
})
.when(self.vertical_scrollbar.show_scrollbar, |this| {
this.child(
self.render_vertical_scrollbar(
self.horizontal_scrollbar.show_track,
cx,
),
)
}),
) )
.when(self.horizontal_scrollbar.show_track, |this| {
this.child(
h_flex()
.w_full()
.h(scroll_track_size)
.flex_none()
.relative()
.child(
div()
.w_full()
.flex_1()
// for some reason the horizontal scrollbar is 1px
// taller than the vertical scrollbar??
.h(scroll_track_size - px(1.))
.bg(cx.theme().colors().panel_background)
.border_t_1()
.border_color(cx.theme().colors().border),
)
.when(self.vertical_scrollbar.show_track, |this| {
this.child(
div()
.flex_none()
// -1px prevents a missing pixel between the two container borders
.w(scroll_track_size - px(1.))
.h_full(),
)
.child(
// HACK: Fill the missing 1px 🥲
div()
.absolute()
.right(scroll_track_size - px(1.))
.bottom(scroll_track_size - px(1.))
.size_px()
.bg(cx.theme().colors().border),
)
}),
)
})
.when(self.horizontal_scrollbar.show_scrollbar, |this| {
this.child(self.render_horizontal_scrollbar(h_scroll_offset, cx))
})
} }
fn entry_label(&self, label: impl Into<SharedString>, color: Color) -> Label { fn entry_label(&self, label: impl Into<SharedString>, color: Color) -> Label {
@@ -4620,15 +4266,6 @@ impl Render for GitPanel {
git_panel.on_action(cx.listener(Self::toggle_fill_co_authors)) git_panel.on_action(cx.listener(Self::toggle_fill_co_authors))
}) })
.on_action(cx.listener(Self::toggle_sort_by_path)) .on_action(cx.listener(Self::toggle_sort_by_path))
.on_hover(cx.listener(move |this, hovered, window, cx| {
if *hovered {
this.horizontal_scrollbar.show(cx);
this.vertical_scrollbar.show(cx);
cx.notify();
} else if !this.focus_handle.contains_focused(window, cx) {
this.hide_scrollbars(window, cx);
}
}))
.size_full() .size_full()
.overflow_hidden() .overflow_hidden()
.bg(cx.theme().colors().panel_background) .bg(cx.theme().colors().panel_background)
+18 -1
View File
@@ -1,8 +1,9 @@
use editor::ShowScrollbar; use editor::EditorSettings;
use gpui::Pixels; use gpui::Pixels;
use schemars::JsonSchema; use schemars::JsonSchema;
use serde_derive::{Deserialize, Serialize}; use serde_derive::{Deserialize, Serialize};
use settings::{Settings, SettingsKey, SettingsSources, SettingsUi}; use settings::{Settings, SettingsKey, SettingsSources, SettingsUi};
use ui::scrollbars::{ScrollbarVisibility, ShowScrollbar};
use workspace::dock::DockPosition; use workspace::dock::DockPosition;
#[derive(Copy, Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] #[derive(Copy, Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
@@ -90,6 +91,22 @@ pub struct GitPanelSettings {
pub collapse_untracked_diff: bool, pub collapse_untracked_diff: bool,
} }
impl ScrollbarVisibility for GitPanelSettings {
fn visibility(&self, cx: &ui::App) -> ShowScrollbar {
// TODO: This PR should have defined Editor's `scrollbar.axis`
// as an Option<ScrollbarAxis>, not a ScrollbarAxes as it would allow you to
// `.unwrap_or(EditorSettings::get_global(cx).scrollbar.show)`.
//
// Once this is fixed we can extend the GitPanelSettings with a `scrollbar.axis`
// so we can show each axis based on the settings.
//
// We should fix this. PR: https://github.com/zed-industries/zed/pull/19495
self.scrollbar
.show
.unwrap_or_else(|| EditorSettings::get_global(cx).scrollbar.show)
}
}
impl Settings for GitPanelSettings { impl Settings for GitPanelSettings {
type FileContent = GitPanelSettingsContent; type FileContent = GitPanelSettingsContent;
+13 -4
View File
@@ -16,10 +16,10 @@
//! constructed by combining these two systems into an all-in-one element. //! constructed by combining these two systems into an all-in-one element.
use crate::{ use crate::{
Action, AnyDrag, AnyElement, AnyTooltip, AnyView, App, Bounds, ClickEvent, DispatchPhase, AbsoluteLength, Action, AnyDrag, AnyElement, AnyTooltip, AnyView, App, Bounds, ClickEvent,
Element, ElementId, Entity, FocusHandle, Global, GlobalElementId, Hitbox, HitboxBehavior, DispatchPhase, Element, ElementId, Entity, FocusHandle, Global, GlobalElementId, Hitbox,
HitboxId, InspectorElementId, IntoElement, IsZero, KeyContext, KeyDownEvent, KeyUpEvent, HitboxBehavior, HitboxId, InspectorElementId, IntoElement, IsZero, KeyContext, KeyDownEvent,
KeyboardButton, KeyboardClickEvent, LayoutId, ModifiersChangedEvent, MouseButton, KeyUpEvent, KeyboardButton, KeyboardClickEvent, LayoutId, ModifiersChangedEvent, MouseButton,
MouseClickEvent, MouseDownEvent, MouseMoveEvent, MouseUpEvent, Overflow, ParentElement, Pixels, MouseClickEvent, MouseDownEvent, MouseMoveEvent, MouseUpEvent, Overflow, ParentElement, Pixels,
Point, Render, ScrollWheelEvent, SharedString, Size, Style, StyleRefinement, Styled, Task, Point, Render, ScrollWheelEvent, SharedString, Size, Style, StyleRefinement, Styled, Task,
TooltipId, Visibility, Window, WindowControlArea, point, px, size, TooltipId, Visibility, Window, WindowControlArea, point, px, size,
@@ -1036,6 +1036,15 @@ pub trait StatefulInteractiveElement: InteractiveElement {
self self
} }
/// Set the space to be reserved for rendering the scrollbar.
///
/// This will only affect the layout of the element when overflow for this element is set to
/// `Overflow::Scroll`.
fn scrollbar_width(mut self, width: impl Into<AbsoluteLength>) -> Self {
self.interactivity().base_style.scrollbar_width = Some(width.into());
self
}
/// Track the scroll state of this element with the given handle. /// Track the scroll state of this element with the given handle.
fn track_scroll(mut self, scroll_handle: &ScrollHandle) -> Self { fn track_scroll(mut self, scroll_handle: &ScrollHandle) -> Self {
self.interactivity().tracked_scroll_handle = Some(scroll_handle.clone()); self.interactivity().tracked_scroll_handle = Some(scroll_handle.clone());
+30 -5
View File
@@ -5,10 +5,10 @@
//! elements with uniform height. //! elements with uniform height.
use crate::{ use crate::{
AnyElement, App, AvailableSpace, Bounds, ContentMask, Element, ElementId, GlobalElementId, AnyElement, App, AvailableSpace, Bounds, ContentMask, Element, ElementId, Entity,
Hitbox, InspectorElementId, InteractiveElement, Interactivity, IntoElement, IsZero, LayoutId, GlobalElementId, Hitbox, InspectorElementId, InteractiveElement, Interactivity, IntoElement,
ListSizingBehavior, Overflow, Pixels, Point, ScrollHandle, Size, StyleRefinement, Styled, IsZero, LayoutId, ListSizingBehavior, Overflow, Pixels, Point, ScrollHandle, Size,
Window, point, size, StyleRefinement, Styled, Window, point, size,
}; };
use smallvec::SmallVec; use smallvec::SmallVec;
use std::{cell::RefCell, cmp, ops::Range, rc::Rc}; use std::{cell::RefCell, cmp, ops::Range, rc::Rc};
@@ -71,7 +71,7 @@ pub struct UniformList {
/// Frame state used by the [UniformList]. /// Frame state used by the [UniformList].
pub struct UniformListFrameState { pub struct UniformListFrameState {
items: SmallVec<[AnyElement; 32]>, items: SmallVec<[AnyElement; 32]>,
decorations: SmallVec<[AnyElement; 1]>, decorations: SmallVec<[AnyElement; 2]>,
} }
/// A handle for controlling the scroll position of a uniform list. /// A handle for controlling the scroll position of a uniform list.
@@ -529,6 +529,31 @@ pub trait UniformListDecoration {
) -> AnyElement; ) -> AnyElement;
} }
impl<T: UniformListDecoration + 'static> UniformListDecoration for Entity<T> {
fn compute(
&self,
visible_range: Range<usize>,
bounds: Bounds<Pixels>,
scroll_offset: Point<Pixels>,
item_height: Pixels,
item_count: usize,
window: &mut Window,
cx: &mut App,
) -> AnyElement {
self.update(cx, |inner, cx| {
inner.compute(
visible_range,
bounds,
scroll_offset,
item_height,
item_count,
window,
cx,
)
})
}
}
impl UniformList { impl UniformList {
/// Selects a specific list item for measurement. /// Selects a specific list item for measurement.
pub fn with_width_from_item(mut self, item_index: Option<usize>) -> Self { pub fn with_width_from_item(mut self, item_index: Option<usize>) -> Self {
+2 -2
View File
@@ -153,7 +153,7 @@ pub struct Style {
#[refineable] #[refineable]
pub overflow: Point<Overflow>, pub overflow: Point<Overflow>,
/// How much space (in points) should be reserved for the scrollbars of `Overflow::Scroll` and `Overflow::Auto` nodes. /// How much space (in points) should be reserved for the scrollbars of `Overflow::Scroll` and `Overflow::Auto` nodes.
pub scrollbar_width: f32, pub scrollbar_width: AbsoluteLength,
/// Whether both x and y axis should be scrollable at the same time. /// Whether both x and y axis should be scrollable at the same time.
pub allow_concurrent_scroll: bool, pub allow_concurrent_scroll: bool,
/// Whether scrolling should be restricted to the axis indicated by the mouse wheel. /// Whether scrolling should be restricted to the axis indicated by the mouse wheel.
@@ -745,7 +745,7 @@ impl Default for Style {
}, },
allow_concurrent_scroll: false, allow_concurrent_scroll: false,
restrict_scroll_to_axis: false, restrict_scroll_to_axis: false,
scrollbar_width: 0.0, scrollbar_width: AbsoluteLength::default(),
position: Position::Relative, position: Position::Relative,
inset: Edges::auto(), inset: Edges::auto(),
margin: Edges::<Length>::zero(), margin: Edges::<Length>::zero(),
+10 -1
View File
@@ -277,7 +277,7 @@ impl ToTaffy<taffy::style::Style> for Style {
taffy::style::Style { taffy::style::Style {
display: self.display.into(), display: self.display.into(),
overflow: self.overflow.into(), overflow: self.overflow.into(),
scrollbar_width: self.scrollbar_width, scrollbar_width: self.scrollbar_width.to_taffy(rem_size),
position: self.position.into(), position: self.position.into(),
inset: self.inset.to_taffy(rem_size), inset: self.inset.to_taffy(rem_size),
size: self.size.to_taffy(rem_size), size: self.size.to_taffy(rem_size),
@@ -314,6 +314,15 @@ impl ToTaffy<taffy::style::Style> for Style {
} }
} }
impl ToTaffy<f32> for AbsoluteLength {
fn to_taffy(&self, rem_size: Pixels) -> f32 {
match self {
AbsoluteLength::Pixels(pixels) => pixels.into(),
AbsoluteLength::Rems(rems) => (*rems * rem_size).into(),
}
}
}
impl ToTaffy<taffy::style::LengthPercentageAuto> for Length { impl ToTaffy<taffy::style::LengthPercentageAuto> for Length {
fn to_taffy(&self, rem_size: Pixels) -> taffy::prelude::LengthPercentageAuto { fn to_taffy(&self, rem_size: Pixels) -> taffy::prelude::LengthPercentageAuto {
match self { match self {
+6
View File
@@ -4960,6 +4960,12 @@ impl<T: Into<SharedString>> From<(ElementId, T)> for ElementId {
} }
} }
impl From<&'static core::panic::Location<'static>> for ElementId {
fn from(location: &'static core::panic::Location<'static>) -> Self {
ElementId::CodeLocation(*location)
}
}
/// A rectangle to be rendered in the window at the given position and size. /// A rectangle to be rendered in the window at the given position and size.
/// Passed as an argument [`Window::paint_quad`]. /// Passed as an argument [`Window::paint_quad`].
#[derive(Clone)] #[derive(Clone)]
+9 -16
View File
@@ -13,8 +13,8 @@ use editor::{CompletionProvider, Editor, EditorEvent};
use fs::Fs; use fs::Fs;
use fuzzy::{StringMatch, StringMatchCandidate}; use fuzzy::{StringMatch, StringMatchCandidate};
use gpui::{ use gpui::{
Action, AppContext as _, AsyncApp, Axis, ClickEvent, Context, DismissEvent, Entity, Action, AppContext as _, AsyncApp, ClickEvent, Context, DismissEvent, Entity, EventEmitter,
EventEmitter, FocusHandle, Focusable, Global, IsZero, FocusHandle, Focusable, Global, IsZero,
KeyBindingContextPredicate::{And, Descendant, Equal, Identifier, Not, NotEqual, Or}, KeyBindingContextPredicate::{And, Descendant, Equal, Identifier, Not, NotEqual, Or},
KeyContext, KeybindingKeystroke, MouseButton, PlatformKeyboardMapper, Point, ScrollStrategy, KeyContext, KeybindingKeystroke, MouseButton, PlatformKeyboardMapper, Point, ScrollStrategy,
ScrollWheelEvent, Stateful, StyledText, Subscription, Task, TextStyleRefinement, WeakEntity, ScrollWheelEvent, Stateful, StyledText, Subscription, Task, TextStyleRefinement, WeakEntity,
@@ -425,7 +425,7 @@ impl KeymapEditor {
fn new(workspace: WeakEntity<Workspace>, window: &mut Window, cx: &mut Context<Self>) -> Self { fn new(workspace: WeakEntity<Workspace>, window: &mut Window, cx: &mut Context<Self>) -> Self {
let _keymap_subscription = let _keymap_subscription =
cx.observe_global_in::<KeymapEventChannel>(window, Self::on_keymap_changed); cx.observe_global_in::<KeymapEventChannel>(window, Self::on_keymap_changed);
let table_interaction_state = TableInteractionState::new(window, cx); let table_interaction_state = TableInteractionState::new(cx);
let keystroke_editor = cx.new(|cx| { let keystroke_editor = cx.new(|cx| {
let mut keystroke_editor = KeystrokeInput::new(None, window, cx); let mut keystroke_editor = KeystrokeInput::new(None, window, cx);
@@ -781,9 +781,8 @@ impl KeymapEditor {
match previous_edit { match previous_edit {
// should remove scroll from process_query // should remove scroll from process_query
PreviousEdit::ScrollBarOffset(offset) => { PreviousEdit::ScrollBarOffset(offset) => {
this.table_interaction_state.update(cx, |table, _| { this.table_interaction_state
table.set_scrollbar_offset(Axis::Vertical, offset) .update(cx, |table, _| table.set_scroll_offset(offset))
})
// set selected index and scroll // set selected index and scroll
} }
PreviousEdit::Keybinding { PreviousEdit::Keybinding {
@@ -812,9 +811,8 @@ impl KeymapEditor {
cx, cx,
); );
} else { } else {
this.table_interaction_state.update(cx, |table, _| { this.table_interaction_state
table.set_scrollbar_offset(Axis::Vertical, fallback) .update(cx, |table, _| table.set_scroll_offset(fallback));
});
} }
cx.notify(); cx.notify();
} }
@@ -1199,9 +1197,7 @@ impl KeymapEditor {
}; };
let tab_size = cx.global::<settings::SettingsStore>().json_tab_size(); let tab_size = cx.global::<settings::SettingsStore>().json_tab_size();
self.previous_edit = Some(PreviousEdit::ScrollBarOffset( self.previous_edit = Some(PreviousEdit::ScrollBarOffset(
self.table_interaction_state self.table_interaction_state.read(cx).scroll_offset(),
.read(cx)
.get_scrollbar_offset(Axis::Vertical),
)); ));
let keyboard_mapper = cx.keyboard_mapper().clone(); let keyboard_mapper = cx.keyboard_mapper().clone();
cx.spawn(async move |_, _| { cx.spawn(async move |_, _| {
@@ -2374,10 +2370,7 @@ impl KeybindingEditorModal {
keymap.previous_edit = Some(PreviousEdit::Keybinding { keymap.previous_edit = Some(PreviousEdit::Keybinding {
action_mapping, action_mapping,
action_name, action_name,
fallback: keymap fallback: keymap.table_interaction_state.read(cx).scroll_offset(),
.table_interaction_state
.read(cx)
.get_scrollbar_offset(Axis::Vertical),
}); });
let status_toast = StatusToast::new( let status_toast = StatusToast::new(
format!("Saved edits to the {} action.", humanized_action_name), format!("Saved edits to the {} action.", humanized_action_name),
+33 -438
View File
@@ -1,20 +1,20 @@
use std::{ops::Range, rc::Rc, time::Duration}; use std::{ops::Range, rc::Rc};
use editor::{EditorSettings, ShowScrollbar, scroll::ScrollbarAutoHide}; use editor::EditorSettings;
use gpui::{ use gpui::{
AbsoluteLength, AppContext, Axis, Context, DefiniteLength, DragMoveEvent, Entity, EntityId, AbsoluteLength, AppContext, Context, DefiniteLength, DragMoveEvent, Entity, EntityId,
FocusHandle, Length, ListHorizontalSizingBehavior, ListSizingBehavior, MouseButton, Point, FocusHandle, Length, ListHorizontalSizingBehavior, ListSizingBehavior, Point, Stateful,
Stateful, Task, UniformListScrollHandle, WeakEntity, transparent_black, uniform_list, UniformListScrollHandle, WeakEntity, transparent_black, uniform_list,
}; };
use itertools::intersperse_with; use itertools::intersperse_with;
use settings::Settings as _;
use ui::{ use ui::{
ActiveTheme as _, AnyElement, App, Button, ButtonCommon as _, ButtonStyle, Color, Component, ActiveTheme as _, AnyElement, App, Button, ButtonCommon as _, ButtonStyle, Color, Component,
ComponentScope, Div, ElementId, FixedWidth as _, FluentBuilder as _, Indicator, ComponentScope, Div, ElementId, FixedWidth as _, FluentBuilder as _, Indicator,
InteractiveElement, IntoElement, ParentElement, Pixels, RegisterComponent, RenderOnce, InteractiveElement, IntoElement, ParentElement, Pixels, RegisterComponent, RenderOnce,
Scrollbar, ScrollbarState, SharedString, StatefulInteractiveElement, Styled, StyledExt as _, ScrollableHandle, Scrollbars, SharedString, StatefulInteractiveElement, Styled, StyledExt as _,
StyledTypography, Window, div, example_group_with_title, h_flex, px, single_example, v_flex, StyledTypography, Window, WithScrollbar, div, example_group_with_title, h_flex, px,
single_example, v_flex,
}; };
const RESIZE_COLUMN_WIDTH: f32 = 8.0; const RESIZE_COLUMN_WIDTH: f32 = 8.0;
@@ -56,136 +56,22 @@ impl<const COLS: usize> TableContents<COLS> {
pub struct TableInteractionState { pub struct TableInteractionState {
pub focus_handle: FocusHandle, pub focus_handle: FocusHandle,
pub scroll_handle: UniformListScrollHandle, pub scroll_handle: UniformListScrollHandle,
pub horizontal_scrollbar: ScrollbarProperties,
pub vertical_scrollbar: ScrollbarProperties,
} }
impl TableInteractionState { impl TableInteractionState {
pub fn new(window: &mut Window, cx: &mut App) -> Entity<Self> { pub fn new(cx: &mut App) -> Entity<Self> {
cx.new(|cx| { cx.new(|cx| Self {
let focus_handle = cx.focus_handle(); focus_handle: cx.focus_handle(),
scroll_handle: UniformListScrollHandle::new(),
cx.on_focus_out(&focus_handle, window, |this: &mut Self, _, window, cx| {
this.hide_scrollbars(window, cx);
})
.detach();
let scroll_handle = UniformListScrollHandle::new();
let vertical_scrollbar = ScrollbarProperties {
axis: Axis::Vertical,
state: ScrollbarState::new(scroll_handle.clone()).parent_entity(&cx.entity()),
show_scrollbar: false,
show_track: false,
auto_hide: false,
hide_task: None,
};
let horizontal_scrollbar = ScrollbarProperties {
axis: Axis::Horizontal,
state: ScrollbarState::new(scroll_handle.clone()).parent_entity(&cx.entity()),
show_scrollbar: false,
show_track: false,
auto_hide: false,
hide_task: None,
};
let mut this = Self {
focus_handle,
scroll_handle,
horizontal_scrollbar,
vertical_scrollbar,
};
this.update_scrollbar_visibility(cx);
this
}) })
} }
pub fn get_scrollbar_offset(&self, axis: Axis) -> Point<Pixels> { pub fn scroll_offset(&self) -> Point<Pixels> {
match axis { self.scroll_handle.offset()
Axis::Vertical => self.vertical_scrollbar.state.scroll_handle().offset(),
Axis::Horizontal => self.horizontal_scrollbar.state.scroll_handle().offset(),
}
} }
pub fn set_scrollbar_offset(&self, axis: Axis, offset: Point<Pixels>) { pub fn set_scroll_offset(&self, offset: Point<Pixels>) {
match axis { self.scroll_handle.set_offset(offset);
Axis::Vertical => self
.vertical_scrollbar
.state
.scroll_handle()
.set_offset(offset),
Axis::Horizontal => self
.horizontal_scrollbar
.state
.scroll_handle()
.set_offset(offset),
}
}
fn update_scrollbar_visibility(&mut self, cx: &mut Context<Self>) {
let show_setting = EditorSettings::get_global(cx).scrollbar.show;
let scroll_handle = self.scroll_handle.0.borrow();
let autohide = |show: ShowScrollbar, cx: &mut Context<Self>| match show {
ShowScrollbar::Auto => true,
ShowScrollbar::System => cx
.try_global::<ScrollbarAutoHide>()
.map_or_else(|| cx.should_auto_hide_scrollbars(), |autohide| autohide.0),
ShowScrollbar::Always => false,
ShowScrollbar::Never => false,
};
let longest_item_width = scroll_handle.last_item_size.and_then(|size| {
(size.contents.width > size.item.width).then_some(size.contents.width)
});
// is there an item long enough that we should show a horizontal scrollbar?
let item_wider_than_container = if let Some(longest_item_width) = longest_item_width {
longest_item_width > px(scroll_handle.base_handle.bounds().size.width.0)
} else {
true
};
let show_scrollbar = match show_setting {
ShowScrollbar::Auto | ShowScrollbar::System | ShowScrollbar::Always => true,
ShowScrollbar::Never => false,
};
let show_vertical = show_scrollbar;
let show_horizontal = item_wider_than_container && show_scrollbar;
let show_horizontal_track =
show_horizontal && matches!(show_setting, ShowScrollbar::Always);
// TODO: we probably should hide the scroll track when the list doesn't need to scroll
let show_vertical_track = show_vertical && matches!(show_setting, ShowScrollbar::Always);
self.vertical_scrollbar = ScrollbarProperties {
axis: self.vertical_scrollbar.axis,
state: self.vertical_scrollbar.state.clone(),
show_scrollbar: show_vertical,
show_track: show_vertical_track,
auto_hide: autohide(show_setting, cx),
hide_task: None,
};
self.horizontal_scrollbar = ScrollbarProperties {
axis: self.horizontal_scrollbar.axis,
state: self.horizontal_scrollbar.state.clone(),
show_scrollbar: show_horizontal,
show_track: show_horizontal_track,
auto_hide: autohide(show_setting, cx),
hide_task: None,
};
cx.notify();
}
fn hide_scrollbars(&mut self, window: &mut Window, cx: &mut Context<Self>) {
self.horizontal_scrollbar.hide(window, cx);
self.vertical_scrollbar.hide(window, cx);
} }
pub fn listener<E: ?Sized>( pub fn listener<E: ?Sized>(
@@ -280,183 +166,6 @@ impl TableInteractionState {
.children(dividers) .children(dividers)
.into_any_element() .into_any_element()
} }
fn render_vertical_scrollbar_track(
this: &Entity<Self>,
parent: Div,
scroll_track_size: Pixels,
cx: &mut App,
) -> Div {
if !this.read(cx).vertical_scrollbar.show_track {
return parent;
}
let child = v_flex()
.h_full()
.flex_none()
.w(scroll_track_size)
.bg(cx.theme().colors().background)
.child(
div()
.size_full()
.flex_1()
.border_l_1()
.border_color(cx.theme().colors().border),
);
parent.child(child)
}
fn render_vertical_scrollbar(this: &Entity<Self>, parent: Div, cx: &mut App) -> Div {
if !this.read(cx).vertical_scrollbar.show_scrollbar {
return parent;
}
let child = div()
.id(("table-vertical-scrollbar", this.entity_id()))
.occlude()
.flex_none()
.h_full()
.cursor_default()
.absolute()
.right_0()
.top_0()
.bottom_0()
.w(px(12.))
.on_mouse_move(Self::listener(this, |_, _, _, cx| {
cx.notify();
cx.stop_propagation()
}))
.on_hover(|_, _, cx| {
cx.stop_propagation();
})
.on_mouse_up(
MouseButton::Left,
Self::listener(this, |this, _, window, cx| {
if !this.vertical_scrollbar.state.is_dragging()
&& !this.focus_handle.contains_focused(window, cx)
{
this.vertical_scrollbar.hide(window, cx);
cx.notify();
}
cx.stop_propagation();
}),
)
.on_any_mouse_down(|_, _, cx| {
cx.stop_propagation();
})
.on_scroll_wheel(Self::listener(this, |_, _, _, cx| {
cx.notify();
}))
.children(Scrollbar::vertical(
this.read(cx).vertical_scrollbar.state.clone(),
));
parent.child(child)
}
/// Renders the horizontal scrollbar.
///
/// The right offset is used to determine how far to the right the
/// scrollbar should extend to, useful for ensuring it doesn't collide
/// with the vertical scrollbar when visible.
fn render_horizontal_scrollbar(
this: &Entity<Self>,
parent: Div,
right_offset: Pixels,
cx: &mut App,
) -> Div {
if !this.read(cx).horizontal_scrollbar.show_scrollbar {
return parent;
}
let child = div()
.id(("table-horizontal-scrollbar", this.entity_id()))
.occlude()
.flex_none()
.w_full()
.cursor_default()
.absolute()
.bottom_neg_px()
.left_0()
.right_0()
.pr(right_offset)
.on_mouse_move(Self::listener(this, |_, _, _, cx| {
cx.notify();
cx.stop_propagation()
}))
.on_hover(|_, _, cx| {
cx.stop_propagation();
})
.on_any_mouse_down(|_, _, cx| {
cx.stop_propagation();
})
.on_mouse_up(
MouseButton::Left,
Self::listener(this, |this, _, window, cx| {
if !this.horizontal_scrollbar.state.is_dragging()
&& !this.focus_handle.contains_focused(window, cx)
{
this.horizontal_scrollbar.hide(window, cx);
cx.notify();
}
cx.stop_propagation();
}),
)
.on_scroll_wheel(Self::listener(this, |_, _, _, cx| {
cx.notify();
}))
.children(Scrollbar::horizontal(
// percentage as f32..end_offset as f32,
this.read(cx).horizontal_scrollbar.state.clone(),
));
parent.child(child)
}
fn render_horizontal_scrollbar_track(
this: &Entity<Self>,
parent: Div,
scroll_track_size: Pixels,
cx: &mut App,
) -> Div {
if !this.read(cx).horizontal_scrollbar.show_track {
return parent;
}
let child = h_flex()
.w_full()
.h(scroll_track_size)
.flex_none()
.relative()
.child(
div()
.w_full()
.flex_1()
// for some reason the horizontal scrollbar is 1px
// taller than the vertical scrollbar??
.h(scroll_track_size - px(1.))
.bg(cx.theme().colors().background)
.border_t_1()
.border_color(cx.theme().colors().border),
)
.when(this.read(cx).vertical_scrollbar.show_track, |parent| {
parent
.child(
div()
.flex_none()
// -1px prevents a missing pixel between the two container borders
.w(scroll_track_size - px(1.))
.h_full(),
)
.child(
// HACK: Fill the missing 1px 🥲
div()
.absolute()
.right(scroll_track_size - px(1.))
.bottom(scroll_track_size - px(1.))
.size_px()
.bg(cx.theme().colors().border),
)
});
parent.child(child)
}
} }
#[derive(Debug, Copy, Clone, PartialEq)] #[derive(Debug, Copy, Clone, PartialEq)]
@@ -1054,17 +763,6 @@ impl<const COLS: usize> RenderOnce for Table<COLS> {
.and_then(|widths| Some((widths.current.as_ref()?, widths.resizable, widths.initial))) .and_then(|widths| Some((widths.current.as_ref()?, widths.resizable, widths.initial)))
.map(|(curr, resize_behavior, initial)| (curr.downgrade(), resize_behavior, initial)); .map(|(curr, resize_behavior, initial)| (curr.downgrade(), resize_behavior, initial));
let scroll_track_size = px(16.);
let h_scroll_offset = if interaction_state
.as_ref()
.is_some_and(|state| state.read(cx).vertical_scrollbar.show_scrollbar)
{
// magic number
px(3.)
} else {
px(0.)
};
let width = self.width; let width = self.width;
let no_rows_rendered = self.rows.is_empty(); let no_rows_rendered = self.rows.is_empty();
@@ -1115,8 +813,8 @@ impl<const COLS: usize> RenderOnce for Table<COLS> {
}) })
} }
}) })
.child( .child({
div() let content = div()
.flex_grow() .flex_grow()
.w_full() .w_full()
.relative() .relative()
@@ -1187,25 +885,21 @@ impl<const COLS: usize> RenderOnce for Table<COLS> {
) )
})) }))
}, },
) );
.when_some(interaction_state.as_ref(), |this, interaction_state| {
this.map(|this| { if let Some(state) = interaction_state.as_ref() {
TableInteractionState::render_vertical_scrollbar_track( content
interaction_state, .custom_scrollbars(
this, Scrollbars::for_settings::<EditorSettings>()
scroll_track_size, .tracked_scroll_handle(state.read(cx).scroll_handle.clone()),
cx, window,
) cx,
}) )
.map(|this| { .into_any_element()
TableInteractionState::render_vertical_scrollbar( } else {
interaction_state, content.into_any_element()
this, }
cx, })
)
})
}),
)
.when_some( .when_some(
no_rows_rendered no_rows_rendered
.then_some(self.empty_table_callback) .then_some(self.empty_table_callback)
@@ -1220,52 +914,12 @@ impl<const COLS: usize> RenderOnce for Table<COLS> {
.child(callback(window, cx)), .child(callback(window, cx)),
) )
}, },
)
.when_some(
width.and(interaction_state.as_ref()),
|this, interaction_state| {
this.map(|this| {
TableInteractionState::render_horizontal_scrollbar_track(
interaction_state,
this,
scroll_track_size,
cx,
)
})
.map(|this| {
TableInteractionState::render_horizontal_scrollbar(
interaction_state,
this,
h_scroll_offset,
cx,
)
})
},
); );
if let Some(interaction_state) = interaction_state.as_ref() { if let Some(interaction_state) = interaction_state.as_ref() {
table table
.track_focus(&interaction_state.read(cx).focus_handle) .track_focus(&interaction_state.read(cx).focus_handle)
.id(("table", interaction_state.entity_id())) .id(("table", interaction_state.entity_id()))
.on_hover({
let interaction_state = interaction_state.downgrade();
move |hovered, window, cx| {
interaction_state
.update(cx, |interaction_state, cx| {
if *hovered {
interaction_state.horizontal_scrollbar.show(cx);
interaction_state.vertical_scrollbar.show(cx);
cx.notify();
} else if !interaction_state
.focus_handle
.contains_focused(window, cx)
{
interaction_state.hide_scrollbars(window, cx);
}
})
.ok();
}
})
.into_any_element() .into_any_element()
} else { } else {
table.into_any_element() table.into_any_element()
@@ -1273,65 +927,6 @@ impl<const COLS: usize> RenderOnce for Table<COLS> {
} }
} }
// computed state related to how to render scrollbars
// one per axis
// on render we just read this off the keymap editor
// we update it when
// - settings change
// - on focus in, on focus out, on hover, etc.
#[derive(Debug)]
pub struct ScrollbarProperties {
axis: Axis,
show_scrollbar: bool,
show_track: bool,
auto_hide: bool,
hide_task: Option<Task<()>>,
state: ScrollbarState,
}
impl ScrollbarProperties {
// Shows the scrollbar and cancels any pending hide task
fn show(&mut self, cx: &mut Context<TableInteractionState>) {
if !self.auto_hide {
return;
}
self.show_scrollbar = true;
self.hide_task.take();
cx.notify();
}
fn hide(&mut self, window: &mut Window, cx: &mut Context<TableInteractionState>) {
const SCROLLBAR_SHOW_INTERVAL: Duration = Duration::from_secs(1);
if !self.auto_hide {
return;
}
let axis = self.axis;
self.hide_task = Some(cx.spawn_in(window, async move |keymap_editor, cx| {
cx.background_executor()
.timer(SCROLLBAR_SHOW_INTERVAL)
.await;
if let Some(keymap_editor) = keymap_editor.upgrade() {
keymap_editor
.update(cx, |keymap_editor, cx| {
match axis {
Axis::Vertical => {
keymap_editor.vertical_scrollbar.show_scrollbar = false
}
Axis::Horizontal => {
keymap_editor.horizontal_scrollbar.show_scrollbar = false
}
}
cx.notify();
})
.ok();
}
}));
}
}
impl Component for Table<3> { impl Component for Table<3> {
fn scope() -> ComponentScope { fn scope() -> ComponentScope {
ComponentScope::Layout ComponentScope::Layout
+18 -183
View File
@@ -4,11 +4,11 @@ use anyhow::Context as _;
use collections::{BTreeSet, HashMap, HashSet, hash_map}; use collections::{BTreeSet, HashMap, HashSet, hash_map};
use db::kvp::KEY_VALUE_STORE; use db::kvp::KEY_VALUE_STORE;
use editor::{ use editor::{
AnchorRangeExt, Bias, DisplayPoint, Editor, EditorEvent, EditorSettings, ExcerptId, AnchorRangeExt, Bias, DisplayPoint, Editor, EditorEvent, ExcerptId, ExcerptRange,
ExcerptRange, MultiBufferSnapshot, RangeToAnchorExt, SelectionEffects, ShowScrollbar, MultiBufferSnapshot, RangeToAnchorExt, SelectionEffects,
display_map::ToDisplayPoint, display_map::ToDisplayPoint,
items::{entry_git_aware_label_color, entry_label_color}, items::{entry_git_aware_label_color, entry_label_color},
scroll::{Autoscroll, ScrollAnchor, ScrollbarAutoHide}, scroll::{Autoscroll, ScrollAnchor},
}; };
use file_icons::FileIcons; use file_icons::FileIcons;
use fuzzy::{StringMatch, StringMatchCandidate, match_strings}; use fuzzy::{StringMatch, StringMatchCandidate, match_strings};
@@ -45,19 +45,18 @@ use serde::{Deserialize, Serialize};
use settings::{Settings, SettingsStore}; use settings::{Settings, SettingsStore};
use smol::channel; use smol::channel;
use theme::{SyntaxTheme, ThemeSettings}; use theme::{SyntaxTheme, ThemeSettings};
use ui::{DynamicSpacing, IndentGuideColors, IndentGuideLayout}; use ui::{
ActiveTheme, ButtonCommon, Clickable, Color, ContextMenu, DynamicSpacing, FluentBuilder,
HighlightedLabel, Icon, IconButton, IconButtonShape, IconName, IconSize, IndentGuideColors,
IndentGuideLayout, Label, LabelCommon, ListItem, ScrollAxes, Scrollbars, StyledExt,
StyledTypography, Toggleable, Tooltip, WithScrollbar, h_flex, v_flex,
};
use util::{RangeExt, ResultExt, TryFutureExt, debug_panic}; use util::{RangeExt, ResultExt, TryFutureExt, debug_panic};
use workspace::{ use workspace::{
OpenInTerminal, WeakItemHandle, Workspace, OpenInTerminal, WeakItemHandle, Workspace,
dock::{DockPosition, Panel, PanelEvent}, dock::{DockPosition, Panel, PanelEvent},
item::ItemHandle, item::ItemHandle,
searchable::{SearchEvent, SearchableItem}, searchable::{SearchEvent, SearchableItem},
ui::{
ActiveTheme, ButtonCommon, Clickable, Color, ContextMenu, FluentBuilder, HighlightedLabel,
Icon, IconButton, IconButtonShape, IconName, IconSize, Label, LabelCommon, ListItem,
Scrollbar, ScrollbarState, StyledExt, StyledTypography, Toggleable, Tooltip, h_flex,
v_flex,
},
}; };
use worktree::{Entry, ProjectEntryId, WorktreeId}; use worktree::{Entry, ProjectEntryId, WorktreeId};
@@ -125,10 +124,6 @@ pub struct OutlinePanel {
cached_entries: Vec<CachedEntry>, cached_entries: Vec<CachedEntry>,
filter_editor: Entity<Editor>, filter_editor: Entity<Editor>,
mode: ItemsDisplayMode, mode: ItemsDisplayMode,
show_scrollbar: bool,
vertical_scrollbar_state: ScrollbarState,
horizontal_scrollbar_state: ScrollbarState,
hide_scrollbar_task: Option<Task<()>>,
max_width_item_index: Option<usize>, max_width_item_index: Option<usize>,
preserve_selection_on_buffer_fold_toggles: HashSet<BufferId>, preserve_selection_on_buffer_fold_toggles: HashSet<BufferId>,
pending_default_expansion_depth: Option<usize>, pending_default_expansion_depth: Option<usize>,
@@ -752,10 +747,6 @@ impl OutlinePanel {
let focus_handle = cx.focus_handle(); let focus_handle = cx.focus_handle();
let focus_subscription = cx.on_focus(&focus_handle, window, Self::focus_in); let focus_subscription = cx.on_focus(&focus_handle, window, Self::focus_in);
let focus_out_subscription =
cx.on_focus_out(&focus_handle, window, |outline_panel, _, window, cx| {
outline_panel.hide_scrollbar(window, cx);
});
let workspace_subscription = cx.subscribe_in( let workspace_subscription = cx.subscribe_in(
&workspace &workspace
.weak_handle() .weak_handle()
@@ -868,12 +859,6 @@ impl OutlinePanel {
workspace: workspace_handle, workspace: workspace_handle,
project, project,
fs: workspace.app_state().fs.clone(), fs: workspace.app_state().fs.clone(),
show_scrollbar: !Self::should_autohide_scrollbar(cx),
hide_scrollbar_task: None,
vertical_scrollbar_state: ScrollbarState::new(scroll_handle.clone())
.parent_entity(&cx.entity()),
horizontal_scrollbar_state: ScrollbarState::new(scroll_handle.clone())
.parent_entity(&cx.entity()),
max_width_item_index: None, max_width_item_index: None,
scroll_handle, scroll_handle,
focus_handle, focus_handle,
@@ -903,7 +888,6 @@ impl OutlinePanel {
settings_subscription, settings_subscription,
icons_subscription, icons_subscription,
focus_subscription, focus_subscription,
focus_out_subscription,
workspace_subscription, workspace_subscription,
filter_update_subscription, filter_update_subscription,
], ],
@@ -4489,150 +4473,6 @@ impl OutlinePanel {
cx.notify(); cx.notify();
} }
fn render_vertical_scrollbar(&self, cx: &mut Context<Self>) -> Option<Stateful<Div>> {
if !Self::should_show_scrollbar(cx)
|| !(self.show_scrollbar || self.vertical_scrollbar_state.is_dragging())
{
return None;
}
Some(
div()
.occlude()
.id("project-panel-vertical-scroll")
.on_mouse_move(cx.listener(|_, _, _, cx| {
cx.notify();
cx.stop_propagation()
}))
.on_hover(|_, _, cx| {
cx.stop_propagation();
})
.on_any_mouse_down(|_, _, cx| {
cx.stop_propagation();
})
.on_mouse_up(
MouseButton::Left,
cx.listener(|outline_panel, _, window, cx| {
if !outline_panel.vertical_scrollbar_state.is_dragging()
&& !outline_panel.focus_handle.contains_focused(window, cx)
{
outline_panel.hide_scrollbar(window, cx);
cx.notify();
}
cx.stop_propagation();
}),
)
.on_scroll_wheel(cx.listener(|_, _, _, cx| {
cx.notify();
}))
.h_full()
.absolute()
.right_1()
.top_1()
.bottom_0()
.w(px(12.))
.cursor_default()
.children(Scrollbar::vertical(self.vertical_scrollbar_state.clone())),
)
}
fn render_horizontal_scrollbar(
&self,
_: &mut Window,
cx: &mut Context<Self>,
) -> Option<Stateful<Div>> {
if !Self::should_show_scrollbar(cx)
|| !(self.show_scrollbar || self.horizontal_scrollbar_state.is_dragging())
{
return None;
}
Scrollbar::horizontal(self.horizontal_scrollbar_state.clone()).map(|scrollbar| {
div()
.occlude()
.id("project-panel-horizontal-scroll")
.on_mouse_move(cx.listener(|_, _, _, cx| {
cx.notify();
cx.stop_propagation()
}))
.on_hover(|_, _, cx| {
cx.stop_propagation();
})
.on_any_mouse_down(|_, _, cx| {
cx.stop_propagation();
})
.on_mouse_up(
MouseButton::Left,
cx.listener(|outline_panel, _, window, cx| {
if !outline_panel.horizontal_scrollbar_state.is_dragging()
&& !outline_panel.focus_handle.contains_focused(window, cx)
{
outline_panel.hide_scrollbar(window, cx);
cx.notify();
}
cx.stop_propagation();
}),
)
.on_scroll_wheel(cx.listener(|_, _, _, cx| {
cx.notify();
}))
.w_full()
.absolute()
.right_1()
.left_1()
.bottom_0()
.h(px(12.))
.cursor_default()
.child(scrollbar)
})
}
fn should_show_scrollbar(cx: &App) -> bool {
let show = OutlinePanelSettings::get_global(cx)
.scrollbar
.show
.unwrap_or_else(|| EditorSettings::get_global(cx).scrollbar.show);
match show {
ShowScrollbar::Auto => true,
ShowScrollbar::System => true,
ShowScrollbar::Always => true,
ShowScrollbar::Never => false,
}
}
fn should_autohide_scrollbar(cx: &App) -> bool {
let show = OutlinePanelSettings::get_global(cx)
.scrollbar
.show
.unwrap_or_else(|| EditorSettings::get_global(cx).scrollbar.show);
match show {
ShowScrollbar::Auto => true,
ShowScrollbar::System => cx
.try_global::<ScrollbarAutoHide>()
.map_or_else(|| cx.should_auto_hide_scrollbars(), |autohide| autohide.0),
ShowScrollbar::Always => false,
ShowScrollbar::Never => true,
}
}
fn hide_scrollbar(&mut self, window: &mut Window, cx: &mut Context<Self>) {
const SCROLLBAR_SHOW_INTERVAL: Duration = Duration::from_secs(1);
if !Self::should_autohide_scrollbar(cx) {
return;
}
self.hide_scrollbar_task = Some(cx.spawn_in(window, async move |panel, cx| {
cx.background_executor()
.timer(SCROLLBAR_SHOW_INTERVAL)
.await;
panel
.update(cx, |panel, cx| {
panel.show_scrollbar = false;
cx.notify();
})
.log_err();
}))
}
fn width_estimate(&self, depth: usize, entry: &PanelEntry, cx: &App) -> u64 { fn width_estimate(&self, depth: usize, entry: &PanelEntry, cx: &App) -> u64 {
let item_text_chars = match entry { let item_text_chars = match entry {
PanelEntry::Fs(FsEntry::ExternalFile(external)) => self PanelEntry::Fs(FsEntry::ExternalFile(external)) => self
@@ -4688,7 +4528,7 @@ impl OutlinePanel {
indent_size: f32, indent_size: f32,
window: &mut Window, window: &mut Window,
cx: &mut Context<Self>, cx: &mut Context<Self>,
) -> Div { ) -> impl IntoElement {
let contents = if self.cached_entries.is_empty() { let contents = if self.cached_entries.is_empty() {
let header = if self.updating_fs_entries || self.updating_cached_entries { let header = if self.updating_fs_entries || self.updating_cached_entries {
None None
@@ -4699,6 +4539,7 @@ impl OutlinePanel {
}; };
v_flex() v_flex()
.id("empty-outline-state")
.flex_1() .flex_1()
.justify_center() .justify_center()
.size_full() .size_full()
@@ -4848,10 +4689,13 @@ impl OutlinePanel {
.flex_shrink() .flex_shrink()
.size_full() .size_full()
.child(list_contents.size_full().flex_shrink()) .child(list_contents.size_full().flex_shrink())
.children(self.render_vertical_scrollbar(cx)) .custom_scrollbars(
.when_some( Scrollbars::for_settings::<OutlinePanelSettings>()
self.render_horizontal_scrollbar(window, cx), .tracked_scroll_handle(self.scroll_handle.clone())
|this, scrollbar| this.pb_4().child(scrollbar), .with_track_along(ScrollAxes::Horizontal)
.tracked_entity(cx.entity_id()),
window,
cx,
) )
} }
.children(self.context_menu.as_ref().map(|(menu, position, _)| { .children(self.context_menu.as_ref().map(|(menu, position, _)| {
@@ -5119,15 +4963,6 @@ impl Render for OutlinePanel {
.size_full() .size_full()
.overflow_hidden() .overflow_hidden()
.relative() .relative()
.on_hover(cx.listener(|this, hovered, window, cx| {
if *hovered {
this.show_scrollbar = true;
this.hide_scrollbar_task.take();
cx.notify();
} else if !this.focus_handle.contains_focused(window, cx) {
this.hide_scrollbar(window, cx);
}
}))
.key_context(self.dispatch_context(window, cx)) .key_context(self.dispatch_context(window, cx))
.on_action(cx.listener(Self::open_selected_entry)) .on_action(cx.listener(Self::open_selected_entry))
.on_action(cx.listener(Self::cancel)) .on_action(cx.listener(Self::cancel))
@@ -1,8 +1,9 @@
use editor::ShowScrollbar; use editor::EditorSettings;
use gpui::Pixels; use gpui::{App, Pixels};
use schemars::JsonSchema; use schemars::JsonSchema;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use settings::{Settings, SettingsKey, SettingsSources, SettingsUi}; use settings::{Settings, SettingsKey, SettingsSources, SettingsUi};
use ui::scrollbars::{ScrollbarVisibility, ShowScrollbar};
#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, Copy, PartialEq)] #[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, Copy, PartialEq)]
#[serde(rename_all = "snake_case")] #[serde(rename_all = "snake_case")]
@@ -116,6 +117,14 @@ pub struct OutlinePanelSettingsContent {
pub expand_outlines_with_depth: Option<usize>, pub expand_outlines_with_depth: Option<usize>,
} }
impl ScrollbarVisibility for OutlinePanelSettings {
fn visibility(&self, cx: &App) -> ShowScrollbar {
self.scrollbar
.show
.unwrap_or_else(|| EditorSettings::get_global(cx).scrollbar.show)
}
}
impl Settings for OutlinePanelSettings { impl Settings for OutlinePanelSettings {
type FileContent = OutlinePanelSettingsContent; type FileContent = OutlinePanelSettingsContent;
-1
View File
@@ -23,7 +23,6 @@ menu.workspace = true
schemars.workspace = true schemars.workspace = true
serde.workspace = true serde.workspace = true
ui.workspace = true ui.workspace = true
util.workspace = true
workspace.workspace = true workspace.workspace = true
workspace-hack.workspace = true workspace-hack.workspace = true
+20 -92
View File
@@ -11,17 +11,17 @@ use editor::{
use gpui::{ use gpui::{
Action, AnyElement, App, ClickEvent, Context, DismissEvent, Entity, EventEmitter, FocusHandle, Action, AnyElement, App, ClickEvent, Context, DismissEvent, Entity, EventEmitter, FocusHandle,
Focusable, Length, ListSizingBehavior, ListState, MouseButton, MouseUpEvent, Render, Focusable, Length, ListSizingBehavior, ListState, MouseButton, MouseUpEvent, Render,
ScrollStrategy, Stateful, Task, UniformListScrollHandle, Window, actions, div, list, ScrollStrategy, Task, UniformListScrollHandle, Window, actions, div, list, prelude::*,
prelude::*, uniform_list, uniform_list,
}; };
use head::Head; use head::Head;
use schemars::JsonSchema; use schemars::JsonSchema;
use serde::Deserialize; use serde::Deserialize;
use std::{ops::Range, sync::Arc, time::Duration}; use std::{ops::Range, sync::Arc, time::Duration};
use ui::{ use ui::{
Color, Divider, Label, ListItem, ListItemSpacing, Scrollbar, ScrollbarState, prelude::*, v_flex, Color, Divider, Label, ListItem, ListItemSpacing, ScrollAxes, Scrollbars, WithScrollbar,
prelude::*, v_flex,
}; };
use util::ResultExt;
use workspace::ModalView; use workspace::ModalView;
enum ElementContainer { enum ElementContainer {
@@ -65,13 +65,8 @@ pub struct Picker<D: PickerDelegate> {
width: Option<Length>, width: Option<Length>,
widest_item: Option<usize>, widest_item: Option<usize>,
max_height: Option<Length>, max_height: Option<Length>,
focus_handle: FocusHandle,
/// An external control to display a scrollbar in the `Picker`. /// An external control to display a scrollbar in the `Picker`.
show_scrollbar: bool, show_scrollbar: bool,
/// An internal state that controls whether to show the scrollbar based on the user's focus.
scrollbar_visibility: bool,
scrollbar_state: ScrollbarState,
hide_scrollbar_task: Option<Task<()>>,
/// Whether the `Picker` is rendered as a self-contained modal. /// Whether the `Picker` is rendered as a self-contained modal.
/// ///
/// Set this to `false` when rendering the `Picker` as part of a larger modal. /// Set this to `false` when rendering the `Picker` as part of a larger modal.
@@ -293,13 +288,6 @@ impl<D: PickerDelegate> Picker<D> {
cx: &mut Context<Self>, cx: &mut Context<Self>,
) -> Self { ) -> Self {
let element_container = Self::create_element_container(container); let element_container = Self::create_element_container(container);
let scrollbar_state = match &element_container {
ElementContainer::UniformList(scroll_handle) => {
ScrollbarState::new(scroll_handle.clone())
}
ElementContainer::List(state) => ScrollbarState::new(state.clone()),
};
let focus_handle = cx.focus_handle();
let mut this = Self { let mut this = Self {
delegate, delegate,
head, head,
@@ -309,12 +297,8 @@ impl<D: PickerDelegate> Picker<D> {
width: None, width: None,
widest_item: None, widest_item: None,
max_height: Some(rems(18.).into()), max_height: Some(rems(18.).into()),
focus_handle,
show_scrollbar: false, show_scrollbar: false,
scrollbar_visibility: true,
scrollbar_state,
is_modal: true, is_modal: true,
hide_scrollbar_task: None,
}; };
this.update_matches("".to_string(), window, cx); this.update_matches("".to_string(), window, cx);
// give the delegate 4ms to render the first set of suggestions. // give the delegate 4ms to render the first set of suggestions.
@@ -790,67 +774,6 @@ impl<D: PickerDelegate> Picker<D> {
} }
} }
} }
fn hide_scrollbar(&mut self, cx: &mut Context<Self>) {
const SCROLLBAR_SHOW_INTERVAL: Duration = Duration::from_secs(1);
self.hide_scrollbar_task = Some(cx.spawn(async move |panel, cx| {
cx.background_executor()
.timer(SCROLLBAR_SHOW_INTERVAL)
.await;
panel
.update(cx, |panel, cx| {
panel.scrollbar_visibility = false;
cx.notify();
})
.log_err();
}))
}
fn render_scrollbar(&self, cx: &mut Context<Self>) -> Option<Stateful<Div>> {
if !self.show_scrollbar
|| !(self.scrollbar_visibility || self.scrollbar_state.is_dragging())
{
return None;
}
Some(
div()
.occlude()
.id("picker-scroll")
.h_full()
.absolute()
.right_1()
.top_1()
.bottom_0()
.w(px(12.))
.cursor_default()
.on_mouse_move(cx.listener(|_, _, _window, cx| {
cx.notify();
cx.stop_propagation()
}))
.on_hover(|_, _window, cx| {
cx.stop_propagation();
})
.on_any_mouse_down(|_, _window, cx| {
cx.stop_propagation();
})
.on_mouse_up(
MouseButton::Left,
cx.listener(|picker, _, window, cx| {
if !picker.scrollbar_state.is_dragging()
&& !picker.focus_handle.contains_focused(window, cx)
{
picker.hide_scrollbar(cx);
cx.notify();
}
cx.stop_propagation();
}),
)
.on_scroll_wheel(cx.listener(|_, _, _window, cx| {
cx.notify();
}))
.children(Scrollbar::vertical(self.scrollbar_state.clone())),
)
}
} }
impl<D: PickerDelegate> EventEmitter<DismissEvent> for Picker<D> {} impl<D: PickerDelegate> EventEmitter<DismissEvent> for Picker<D> {}
@@ -900,17 +823,22 @@ impl<D: PickerDelegate> Render for Picker<D> {
.overflow_hidden() .overflow_hidden()
.children(self.delegate.render_header(window, cx)) .children(self.delegate.render_header(window, cx))
.child(self.render_element_container(cx)) .child(self.render_element_container(cx))
.on_hover(cx.listener(|this, hovered, window, cx| { .when(self.show_scrollbar, |this| {
if *hovered { let base_scrollbar_config =
this.scrollbar_visibility = true; Scrollbars::new(ScrollAxes::Vertical).width_sm();
this.hide_scrollbar_task.take();
cx.notify(); this.map(|this| match &self.element_container {
} else if !this.focus_handle.contains_focused(window, cx) { ElementContainer::List(state) => this.custom_scrollbars(
this.hide_scrollbar(cx); base_scrollbar_config.tracked_scroll_handle(state.clone()),
} window,
})) cx,
.when_some(self.render_scrollbar(cx), |div, scrollbar| { ),
div.child(scrollbar) ElementContainer::UniformList(state) => this.custom_scrollbars(
base_scrollbar_config.tracked_scroll_handle(state.clone()),
window,
cx,
),
})
}), }),
) )
}) })
+11 -170
View File
@@ -7,12 +7,11 @@ use collections::{BTreeSet, HashMap, hash_map};
use command_palette_hooks::CommandPaletteFilter; use command_palette_hooks::CommandPaletteFilter;
use db::kvp::KEY_VALUE_STORE; use db::kvp::KEY_VALUE_STORE;
use editor::{ use editor::{
Editor, EditorEvent, EditorSettings, ShowScrollbar, Editor, EditorEvent,
items::{ items::{
entry_diagnostic_aware_icon_decoration_and_color, entry_diagnostic_aware_icon_decoration_and_color,
entry_diagnostic_aware_icon_name_and_color, entry_git_aware_label_color, entry_diagnostic_aware_icon_name_and_color, entry_git_aware_label_color,
}, },
scroll::ScrollbarAutoHide,
}; };
use file_icons::FileIcons; use file_icons::FileIcons;
use git::status::GitSummary; use git::status::GitSummary;
@@ -59,7 +58,8 @@ use theme::ThemeSettings;
use ui::{ use ui::{
Color, ContextMenu, DecoratedIcon, Divider, Icon, IconDecoration, IconDecorationKind, Color, ContextMenu, DecoratedIcon, Divider, Icon, IconDecoration, IconDecorationKind,
IndentGuideColors, IndentGuideLayout, KeyBinding, Label, LabelSize, ListItem, ListItemSpacing, IndentGuideColors, IndentGuideLayout, KeyBinding, Label, LabelSize, ListItem, ListItemSpacing,
ScrollableHandle, Scrollbar, ScrollbarState, StickyCandidate, Tooltip, prelude::*, v_flex, ScrollAxes, ScrollableHandle, Scrollbars, StickyCandidate, Tooltip, WithScrollbar, prelude::*,
v_flex,
}; };
use util::{ResultExt, TakeUntilExt, TryFutureExt, maybe, paths::compare_paths}; use util::{ResultExt, TakeUntilExt, TryFutureExt, maybe, paths::compare_paths};
use workspace::{ use workspace::{
@@ -109,10 +109,6 @@ pub struct ProjectPanel {
workspace: WeakEntity<Workspace>, workspace: WeakEntity<Workspace>,
width: Option<Pixels>, width: Option<Pixels>,
pending_serialization: Task<Option<()>>, pending_serialization: Task<Option<()>>,
show_scrollbar: bool,
vertical_scrollbar_state: ScrollbarState,
horizontal_scrollbar_state: ScrollbarState,
hide_scrollbar_task: Option<Task<()>>,
diagnostics: HashMap<(WorktreeId, PathBuf), DiagnosticSeverity>, diagnostics: HashMap<(WorktreeId, PathBuf), DiagnosticSeverity>,
max_width_item_index: Option<usize>, max_width_item_index: Option<usize>,
diagnostic_summary_update: Task<()>, diagnostic_summary_update: Task<()>,
@@ -461,7 +457,6 @@ impl ProjectPanel {
cx.on_focus(&focus_handle, window, Self::focus_in).detach(); cx.on_focus(&focus_handle, window, Self::focus_in).detach();
cx.on_focus_out(&focus_handle, window, |this, _, window, cx| { cx.on_focus_out(&focus_handle, window, |this, _, window, cx| {
this.focus_out(window, cx); this.focus_out(window, cx);
this.hide_scrollbar(window, cx);
}) })
.detach(); .detach();
@@ -652,12 +647,6 @@ impl ProjectPanel {
workspace: workspace.weak_handle(), workspace: workspace.weak_handle(),
width: None, width: None,
pending_serialization: Task::ready(None), pending_serialization: Task::ready(None),
show_scrollbar: !Self::should_autohide_scrollbar(cx),
hide_scrollbar_task: None,
vertical_scrollbar_state: ScrollbarState::new(scroll_handle.clone())
.parent_entity(&cx.entity()),
horizontal_scrollbar_state: ScrollbarState::new(scroll_handle.clone())
.parent_entity(&cx.entity()),
max_width_item_index: None, max_width_item_index: None,
diagnostics: Default::default(), diagnostics: Default::default(),
diagnostic_summary_update: Task::ready(()), diagnostic_summary_update: Task::ready(()),
@@ -4847,103 +4836,6 @@ impl ProjectPanel {
} }
} }
fn render_vertical_scrollbar(&self, cx: &mut Context<Self>) -> Option<Stateful<Div>> {
if !Self::should_show_scrollbar(cx)
|| !(self.show_scrollbar || self.vertical_scrollbar_state.is_dragging())
{
return None;
}
Some(
div()
.occlude()
.id("project-panel-vertical-scroll")
.on_mouse_move(cx.listener(|_, _, _, cx| {
cx.notify();
cx.stop_propagation()
}))
.on_hover(|_, _, cx| {
cx.stop_propagation();
})
.on_any_mouse_down(|_, _, cx| {
cx.stop_propagation();
})
.on_mouse_up(
MouseButton::Left,
cx.listener(|this, _, window, cx| {
if !this.vertical_scrollbar_state.is_dragging()
&& !this.focus_handle.contains_focused(window, cx)
{
this.hide_scrollbar(window, cx);
cx.notify();
}
cx.stop_propagation();
}),
)
.on_scroll_wheel(cx.listener(|_, _, _, cx| {
cx.notify();
}))
.h_full()
.absolute()
.right_1()
.top_1()
.bottom_1()
.w(px(12.))
.cursor_default()
.children(Scrollbar::vertical(
// percentage as f32..end_offset as f32,
self.vertical_scrollbar_state.clone(),
)),
)
}
fn render_horizontal_scrollbar(&self, cx: &mut Context<Self>) -> Option<Stateful<Div>> {
if !Self::should_show_scrollbar(cx)
|| !(self.show_scrollbar || self.horizontal_scrollbar_state.is_dragging())
{
return None;
}
Scrollbar::horizontal(self.horizontal_scrollbar_state.clone()).map(|scrollbar| {
div()
.occlude()
.id("project-panel-horizontal-scroll")
.on_mouse_move(cx.listener(|_, _, _, cx| {
cx.notify();
cx.stop_propagation()
}))
.on_hover(|_, _, cx| {
cx.stop_propagation();
})
.on_any_mouse_down(|_, _, cx| {
cx.stop_propagation();
})
.on_mouse_up(
MouseButton::Left,
cx.listener(|this, _, window, cx| {
if !this.horizontal_scrollbar_state.is_dragging()
&& !this.focus_handle.contains_focused(window, cx)
{
this.hide_scrollbar(window, cx);
cx.notify();
}
cx.stop_propagation();
}),
)
.on_scroll_wheel(cx.listener(|_, _, _, cx| {
cx.notify();
}))
.w_full()
.absolute()
.right_1()
.left_1()
.bottom_1()
.h(px(12.))
.cursor_default()
.child(scrollbar)
})
}
fn dispatch_context(&self, window: &Window, cx: &Context<Self>) -> KeyContext { fn dispatch_context(&self, window: &Window, cx: &Context<Self>) -> KeyContext {
let mut dispatch_context = KeyContext::new_with_defaults(); let mut dispatch_context = KeyContext::new_with_defaults();
dispatch_context.add("ProjectPanel"); dispatch_context.add("ProjectPanel");
@@ -4959,52 +4851,6 @@ impl ProjectPanel {
dispatch_context dispatch_context
} }
fn should_show_scrollbar(cx: &App) -> bool {
let show = ProjectPanelSettings::get_global(cx)
.scrollbar
.show
.unwrap_or_else(|| EditorSettings::get_global(cx).scrollbar.show);
match show {
ShowScrollbar::Auto => true,
ShowScrollbar::System => true,
ShowScrollbar::Always => true,
ShowScrollbar::Never => false,
}
}
fn should_autohide_scrollbar(cx: &App) -> bool {
let show = ProjectPanelSettings::get_global(cx)
.scrollbar
.show
.unwrap_or_else(|| EditorSettings::get_global(cx).scrollbar.show);
match show {
ShowScrollbar::Auto => true,
ShowScrollbar::System => cx
.try_global::<ScrollbarAutoHide>()
.map_or_else(|| cx.should_auto_hide_scrollbars(), |autohide| autohide.0),
ShowScrollbar::Always => false,
ShowScrollbar::Never => true,
}
}
fn hide_scrollbar(&mut self, window: &mut Window, cx: &mut Context<Self>) {
const SCROLLBAR_SHOW_INTERVAL: Duration = Duration::from_secs(1);
if !Self::should_autohide_scrollbar(cx) {
return;
}
self.hide_scrollbar_task = Some(cx.spawn_in(window, async move |panel, cx| {
cx.background_executor()
.timer(SCROLLBAR_SHOW_INTERVAL)
.await;
panel
.update(cx, |panel, cx| {
panel.show_scrollbar = false;
cx.notify();
})
.log_err();
}))
}
fn reveal_entry( fn reveal_entry(
&mut self, &mut self,
project: Entity<Project>, project: Entity<Project>,
@@ -5357,15 +5203,6 @@ impl Render for ProjectPanel {
this.refresh_drag_cursor_style(&event.modifiers, window, cx); this.refresh_drag_cursor_style(&event.modifiers, window, cx);
}, },
)) ))
.on_hover(cx.listener(|this, hovered, window, cx| {
if *hovered {
this.show_scrollbar = true;
this.hide_scrollbar_task.take();
cx.notify();
} else if !this.focus_handle.contains_focused(window, cx) {
this.hide_scrollbar(window, cx);
}
}))
.on_click(cx.listener(|this, event, _, cx| { .on_click(cx.listener(|this, event, _, cx| {
if matches!(event, gpui::ClickEvent::Keyboard(_)) { if matches!(event, gpui::ClickEvent::Keyboard(_)) {
return; return;
@@ -5755,10 +5592,14 @@ impl Render for ProjectPanel {
) )
.size_full(), .size_full(),
) )
.children(self.render_vertical_scrollbar(cx)) .custom_scrollbars(
.when_some(self.render_horizontal_scrollbar(cx), |this, scrollbar| { Scrollbars::for_settings::<ProjectPanelSettings>()
this.pb_4().child(scrollbar) .tracked_scroll_handle(self.scroll_handle.clone())
}) .with_track_along(ScrollAxes::Horizontal)
.notify_content(),
window,
cx,
)
.children(self.context_menu.as_ref().map(|(menu, position, _)| { .children(self.context_menu.as_ref().map(|(menu, position, _)| {
deferred( deferred(
anchored() anchored()
@@ -1,8 +1,9 @@
use editor::ShowScrollbar; use editor::EditorSettings;
use gpui::Pixels; use gpui::Pixels;
use schemars::JsonSchema; use schemars::JsonSchema;
use serde_derive::{Deserialize, Serialize}; use serde_derive::{Deserialize, Serialize};
use settings::{Settings, SettingsKey, SettingsSources, SettingsUi}; use settings::{Settings, SettingsKey, SettingsSources, SettingsUi};
use ui::scrollbars::{ScrollbarVisibility, ShowScrollbar};
#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, Copy, PartialEq)] #[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, Copy, PartialEq)]
#[serde(rename_all = "snake_case")] #[serde(rename_all = "snake_case")]
@@ -168,6 +169,14 @@ pub struct ProjectPanelSettingsContent {
pub drag_and_drop: Option<bool>, pub drag_and_drop: Option<bool>,
} }
impl ScrollbarVisibility for ProjectPanelSettings {
fn visibility(&self, cx: &ui::App) -> ShowScrollbar {
self.scrollbar
.show
.unwrap_or_else(|| EditorSettings::get_global(cx).scrollbar.show)
}
}
impl Settings for ProjectPanelSettings { impl Settings for ProjectPanelSettings {
type FileContent = ProjectPanelSettingsContent; type FileContent = ProjectPanelSettingsContent;
+5 -23
View File
@@ -23,7 +23,6 @@ use remote::{
use settings::{Settings, SettingsStore, update_settings_file, watch_config_file}; use settings::{Settings, SettingsStore, update_settings_file, watch_config_file};
use smol::stream::StreamExt as _; use smol::stream::StreamExt as _;
use std::{ use std::{
any::Any,
borrow::Cow, borrow::Cow,
collections::BTreeSet, collections::BTreeSet,
path::PathBuf, path::PathBuf,
@@ -35,7 +34,7 @@ use std::{
}; };
use ui::{ use ui::{
IconButtonShape, List, ListItem, ListSeparator, Modal, ModalHeader, Navigable, NavigableEntry, IconButtonShape, List, ListItem, ListSeparator, Modal, ModalHeader, Navigable, NavigableEntry,
Scrollbar, ScrollbarState, Section, Tooltip, prelude::*, Section, Tooltip, WithScrollbar, prelude::*,
}; };
use util::{ use util::{
ResultExt, ResultExt,
@@ -284,7 +283,7 @@ impl RemoteEntry {
#[derive(Clone)] #[derive(Clone)]
struct DefaultState { struct DefaultState {
scrollbar: ScrollbarState, scroll_handle: ScrollHandle,
add_new_server: NavigableEntry, add_new_server: NavigableEntry,
servers: Vec<RemoteEntry>, servers: Vec<RemoteEntry>,
} }
@@ -292,7 +291,6 @@ struct DefaultState {
impl DefaultState { impl DefaultState {
fn new(ssh_config_servers: &BTreeSet<SharedString>, cx: &mut App) -> Self { fn new(ssh_config_servers: &BTreeSet<SharedString>, cx: &mut App) -> Self {
let handle = ScrollHandle::new(); let handle = ScrollHandle::new();
let scrollbar = ScrollbarState::new(handle.clone());
let add_new_server = NavigableEntry::new(&handle, cx); let add_new_server = NavigableEntry::new(&handle, cx);
let ssh_settings = SshSettings::get_global(cx); let ssh_settings = SshSettings::get_global(cx);
@@ -333,7 +331,7 @@ impl DefaultState {
} }
Self { Self {
scrollbar, scroll_handle: handle,
add_new_server, add_new_server,
servers, servers,
} }
@@ -1449,7 +1447,6 @@ impl RemoteServerProjects {
} }
} }
let scroll_state = state.scrollbar.parent_entity(&cx.entity());
let connect_button = div() let connect_button = div()
.id("ssh-connect-new-server-container") .id("ssh-connect-new-server-container")
.track_focus(&state.add_new_server.focus_handle) .track_focus(&state.add_new_server.focus_handle)
@@ -1480,17 +1477,12 @@ impl RemoteServerProjects {
cx.notify(); cx.notify();
})); }));
let handle = &**scroll_state.scroll_handle() as &dyn Any;
let Some(scroll_handle) = handle.downcast_ref::<ScrollHandle>() else {
unreachable!()
};
let mut modal_section = Navigable::new( let mut modal_section = Navigable::new(
v_flex() v_flex()
.track_focus(&self.focus_handle(cx)) .track_focus(&self.focus_handle(cx))
.id("ssh-server-list") .id("ssh-server-list")
.overflow_y_scroll() .overflow_y_scroll()
.track_scroll(scroll_handle) .track_scroll(&state.scroll_handle)
.size_full() .size_full()
.child(connect_button) .child(connect_button)
.child( .child(
@@ -1585,17 +1577,7 @@ impl RemoteServerProjects {
) )
.size_full(), .size_full(),
) )
.child( .vertical_scrollbar_for(state.scroll_handle, window, cx),
div()
.occlude()
.h_full()
.absolute()
.top_1()
.bottom_1()
.right_1()
.w(px(8.))
.children(Scrollbar::vertical(scroll_state)),
),
), ),
) )
.into_any_element() .into_any_element()
+52 -164
View File
@@ -7,12 +7,11 @@ mod terminal_slash_command;
pub mod terminal_tab_tooltip; pub mod terminal_tab_tooltip;
use assistant_slash_command::SlashCommandRegistry; use assistant_slash_command::SlashCommandRegistry;
use editor::{EditorSettings, actions::SelectAll, scroll::ScrollbarAutoHide}; use editor::{EditorSettings, actions::SelectAll};
use gpui::{ use gpui::{
Action, AnyElement, App, DismissEvent, Entity, EventEmitter, FocusHandle, Focusable, Action, AnyElement, App, DismissEvent, Entity, EventEmitter, FocusHandle, Focusable,
KeyContext, KeyDownEvent, Keystroke, MouseButton, MouseDownEvent, Pixels, Render, KeyContext, KeyDownEvent, Keystroke, MouseButton, MouseDownEvent, Pixels, Render,
ScrollWheelEvent, Stateful, Styled, Subscription, Task, WeakEntity, actions, anchored, ScrollWheelEvent, Styled, Subscription, Task, WeakEntity, actions, anchored, deferred, div,
deferred, div,
}; };
use persistence::TERMINAL_DB; use persistence::TERMINAL_DB;
use project::{Project, search::SearchQuery}; use project::{Project, search::SearchQuery};
@@ -35,7 +34,9 @@ use terminal_scrollbar::TerminalScrollHandle;
use terminal_slash_command::TerminalSlashCommand; use terminal_slash_command::TerminalSlashCommand;
use terminal_tab_tooltip::TerminalTooltip; use terminal_tab_tooltip::TerminalTooltip;
use ui::{ use ui::{
ContextMenu, Icon, IconName, Label, Scrollbar, ScrollbarState, Tooltip, h_flex, prelude::*, ContextMenu, Icon, IconName, Label, ScrollAxes, Scrollbars, Tooltip, WithScrollbar, h_flex,
prelude::*,
scrollbars::{self, GlobalSetting, ScrollbarVisibility},
}; };
use util::ResultExt; use util::ResultExt;
use workspace::{ use workspace::{
@@ -68,7 +69,6 @@ struct ImeState {
} }
const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500); const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
const TERMINAL_SCROLLBAR_WIDTH: Pixels = px(12.);
/// Event to transmit the scroll from the element to the view /// Event to transmit the scroll from the element to the view
#[derive(Clone, Debug, PartialEq)] #[derive(Clone, Debug, PartialEq)]
@@ -139,10 +139,7 @@ pub struct TerminalView {
show_breadcrumbs: bool, show_breadcrumbs: bool,
block_below_cursor: Option<Rc<BlockProperties>>, block_below_cursor: Option<Rc<BlockProperties>>,
scroll_top: Pixels, scroll_top: Pixels,
scrollbar_state: ScrollbarState,
scroll_handle: TerminalScrollHandle, scroll_handle: TerminalScrollHandle,
show_scrollbar: bool,
hide_scrollbar_task: Option<Task<()>>,
ime_state: Option<ImeState>, ime_state: Option<ImeState>,
_subscriptions: Vec<Subscription>, _subscriptions: Vec<Subscription>,
_terminal_subscriptions: Vec<Subscription>, _terminal_subscriptions: Vec<Subscription>,
@@ -262,10 +259,7 @@ impl TerminalView {
show_breadcrumbs: TerminalSettings::get_global(cx).toolbar.breadcrumbs, show_breadcrumbs: TerminalSettings::get_global(cx).toolbar.breadcrumbs,
block_below_cursor: None, block_below_cursor: None,
scroll_top: Pixels::ZERO, scroll_top: Pixels::ZERO,
scrollbar_state: ScrollbarState::new(scroll_handle.clone()),
scroll_handle, scroll_handle,
show_scrollbar: !Self::should_autohide_scrollbar(cx),
hide_scrollbar_task: None,
cwd_serialized: false, cwd_serialized: false,
ime_state: None, ime_state: None,
_subscriptions: vec![ _subscriptions: vec![
@@ -836,136 +830,6 @@ impl TerminalView {
self.terminal = terminal; self.terminal = terminal;
} }
// Hack: Using editor in terminal causes cyclic dependency i.e. editor -> terminal -> project -> editor.
fn map_show_scrollbar_from_editor_to_terminal(
show_scrollbar: editor::ShowScrollbar,
) -> terminal_settings::ShowScrollbar {
match show_scrollbar {
editor::ShowScrollbar::Auto => terminal_settings::ShowScrollbar::Auto,
editor::ShowScrollbar::System => terminal_settings::ShowScrollbar::System,
editor::ShowScrollbar::Always => terminal_settings::ShowScrollbar::Always,
editor::ShowScrollbar::Never => terminal_settings::ShowScrollbar::Never,
}
}
fn should_show_scrollbar(cx: &App) -> bool {
let show = TerminalSettings::get_global(cx)
.scrollbar
.show
.unwrap_or_else(|| {
Self::map_show_scrollbar_from_editor_to_terminal(
EditorSettings::get_global(cx).scrollbar.show,
)
});
match show {
terminal_settings::ShowScrollbar::Auto => true,
terminal_settings::ShowScrollbar::System => true,
terminal_settings::ShowScrollbar::Always => true,
terminal_settings::ShowScrollbar::Never => false,
}
}
fn should_autohide_scrollbar(cx: &App) -> bool {
let show = TerminalSettings::get_global(cx)
.scrollbar
.show
.unwrap_or_else(|| {
Self::map_show_scrollbar_from_editor_to_terminal(
EditorSettings::get_global(cx).scrollbar.show,
)
});
match show {
terminal_settings::ShowScrollbar::Auto => true,
terminal_settings::ShowScrollbar::System => cx
.try_global::<ScrollbarAutoHide>()
.map_or_else(|| cx.should_auto_hide_scrollbars(), |autohide| autohide.0),
terminal_settings::ShowScrollbar::Always => false,
terminal_settings::ShowScrollbar::Never => true,
}
}
fn hide_scrollbar(&mut self, cx: &mut Context<Self>) {
const SCROLLBAR_SHOW_INTERVAL: Duration = Duration::from_secs(1);
if !Self::should_autohide_scrollbar(cx) {
return;
}
self.hide_scrollbar_task = Some(cx.spawn(async move |panel, cx| {
cx.background_executor()
.timer(SCROLLBAR_SHOW_INTERVAL)
.await;
panel
.update(cx, |panel, cx| {
panel.show_scrollbar = false;
cx.notify();
})
.log_err();
}))
}
fn render_scrollbar(&self, window: &Window, cx: &mut Context<Self>) -> Option<Stateful<Div>> {
if !Self::should_show_scrollbar(cx)
|| !(self.show_scrollbar || self.scrollbar_state.is_dragging())
|| !self.content_mode(window, cx).is_scrollable()
{
return None;
}
if self.terminal.read(cx).total_lines() == self.terminal.read(cx).viewport_lines() {
return None;
}
self.scroll_handle.update(self.terminal.read(cx));
if let Some(new_display_offset) = self.scroll_handle.future_display_offset.take() {
self.terminal.update(cx, |term, _| {
let delta = new_display_offset as i32 - term.last_content.display_offset as i32;
match delta.cmp(&0) {
std::cmp::Ordering::Greater => term.scroll_up_by(delta as usize),
std::cmp::Ordering::Less => term.scroll_down_by(-delta as usize),
std::cmp::Ordering::Equal => {}
}
});
}
Some(
div()
.occlude()
.id("terminal-view-scroll")
.on_mouse_move(cx.listener(|_, _, _window, cx| {
cx.notify();
cx.stop_propagation()
}))
.on_hover(|_, _window, cx| {
cx.stop_propagation();
})
.on_any_mouse_down(|_, _window, cx| {
cx.stop_propagation();
})
.on_mouse_up(
MouseButton::Left,
cx.listener(|terminal_view, _, window, cx| {
if !terminal_view.scrollbar_state.is_dragging()
&& !terminal_view.focus_handle.contains_focused(window, cx)
{
terminal_view.hide_scrollbar(cx);
cx.notify();
}
cx.stop_propagation();
}),
)
.on_scroll_wheel(cx.listener(|_, _, _window, cx| {
cx.notify();
}))
.absolute()
.top_0()
.bottom_0()
.right_0()
.h_full()
.w(TERMINAL_SCROLLBAR_WIDTH)
.children(Scrollbar::vertical(self.scrollbar_state.clone())),
)
}
fn rerun_button(task: &TaskState) -> Option<IconButton> { fn rerun_button(task: &TaskState) -> Option<IconButton> {
if !task.show_rerun { if !task.show_rerun {
return None; return None;
@@ -1120,6 +984,29 @@ fn regex_search_for_query(query: &project::search::SearchQuery) -> Option<RegexS
} }
} }
struct TerminalScrollbarSettingsWrapper;
impl GlobalSetting for TerminalScrollbarSettingsWrapper {
fn get_value(_cx: &App) -> &Self {
&Self
}
}
impl ScrollbarVisibility for TerminalScrollbarSettingsWrapper {
fn visibility(&self, cx: &App) -> scrollbars::ShowScrollbar {
TerminalSettings::get_global(cx)
.scrollbar
.show
.map(|value| match value {
terminal_settings::ShowScrollbar::Auto => scrollbars::ShowScrollbar::Auto,
terminal_settings::ShowScrollbar::System => scrollbars::ShowScrollbar::System,
terminal_settings::ShowScrollbar::Always => scrollbars::ShowScrollbar::Always,
terminal_settings::ShowScrollbar::Never => scrollbars::ShowScrollbar::Never,
})
.unwrap_or_else(|| EditorSettings::get_global(cx).scrollbar.show)
}
}
impl TerminalView { impl TerminalView {
fn key_down(&mut self, event: &KeyDownEvent, window: &mut Window, cx: &mut Context<Self>) { fn key_down(&mut self, event: &KeyDownEvent, window: &mut Window, cx: &mut Context<Self>) {
self.clear_bell(cx); self.clear_bell(cx);
@@ -1151,28 +1038,31 @@ impl TerminalView {
terminal.focus_out(); terminal.focus_out();
terminal.set_cursor_shape(CursorShape::Hollow); terminal.set_cursor_shape(CursorShape::Hollow);
}); });
self.hide_scrollbar(cx);
cx.notify(); cx.notify();
} }
} }
impl Render for TerminalView { impl Render for TerminalView {
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement { fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
// TODO: this should be moved out of render
self.scroll_handle.update(self.terminal.read(cx));
if let Some(new_display_offset) = self.scroll_handle.future_display_offset.take() {
self.terminal.update(cx, |term, _| {
let delta = new_display_offset as i32 - term.last_content.display_offset as i32;
match delta.cmp(&0) {
std::cmp::Ordering::Greater => term.scroll_up_by(delta as usize),
std::cmp::Ordering::Less => term.scroll_down_by(-delta as usize),
std::cmp::Ordering::Equal => {}
}
});
}
let terminal_handle = self.terminal.clone(); let terminal_handle = self.terminal.clone();
let terminal_view_handle = cx.entity(); let terminal_view_handle = cx.entity();
let focused = self.focus_handle.is_focused(window); let focused = self.focus_handle.is_focused(window);
// Always calculate scrollbar width to prevent layout shift
let scrollbar_width = if Self::should_show_scrollbar(cx)
&& self.content_mode(window, cx).is_scrollable()
&& self.terminal.read(cx).total_lines() > self.terminal.read(cx).viewport_lines()
{
TERMINAL_SCROLLBAR_WIDTH
} else {
px(0.)
};
div() div()
.id("terminal-view") .id("terminal-view")
.size_full() .size_full()
@@ -1209,21 +1099,12 @@ impl Render for TerminalView {
} }
}), }),
) )
.on_hover(cx.listener(|this, hovered, window, cx| {
if *hovered {
this.show_scrollbar = true;
this.hide_scrollbar_task.take();
cx.notify();
} else if !this.focus_handle.contains_focused(window, cx) {
this.hide_scrollbar(cx);
}
}))
.child( .child(
// TODO: Oddly this wrapper div is needed for TerminalElement to not steal events from the context menu // TODO: Oddly this wrapper div is needed for TerminalElement to not steal events from the context menu
div() div()
.id("terminal-view-container")
.size_full() .size_full()
.bg(cx.theme().colors().editor_background) .bg(cx.theme().colors().editor_background)
.when(scrollbar_width > px(0.), |div| div.pr(scrollbar_width))
.child(TerminalElement::new( .child(TerminalElement::new(
terminal_handle, terminal_handle,
terminal_view_handle, terminal_view_handle,
@@ -1234,8 +1115,15 @@ impl Render for TerminalView {
self.block_below_cursor.clone(), self.block_below_cursor.clone(),
self.mode.clone(), self.mode.clone(),
)) ))
.when_some(self.render_scrollbar(window, cx), |div, scrollbar| { .when(self.content_mode(window, cx).is_scrollable(), |div| {
div.child(scrollbar) div.custom_scrollbars(
Scrollbars::for_settings::<TerminalScrollbarSettingsWrapper>()
.show_along(ScrollAxes::Vertical)
.with_track_along(ScrollAxes::Vertical)
.tracked_scroll_handle(self.scroll_handle.clone()),
window,
cx,
)
}), }),
) )
.children(self.context_menu.as_ref().map(|(menu, position, _)| { .children(self.context_menu.as_ref().map(|(menu, position, _)| {
+1
View File
@@ -21,6 +21,7 @@ gpui_macros.workspace = true
icons.workspace = true icons.workspace = true
itertools.workspace = true itertools.workspace = true
menu.workspace = true menu.workspace = true
schemars.workspace = true
serde.workspace = true serde.workspace = true
settings.workspace = true settings.workspace = true
smallvec.workspace = true smallvec.workspace = true
File diff suppressed because it is too large Load Diff