terminal: Add scrollbar (#23256)

Closes #4798

This PR implements a scrollbar for the terminal by turning
`ScrollableHandle` into a trait, allowing us to implement a custom
scroll handle, `TerminalScrollHandle`. It works by converting terminal
lines into pixels that `ScrollableHandle` understands. When
`ScrollableHandle` provides a changed offset (e.g., when you drag the
scrollbar), we convert this pixel offset back into the number of lines
to scroll and update the terminal content accordingly.

While the current version works as expected, I believe the scrollbar's
offset updates could potentially be turned into an event. This event
could then be subscribed to in `TerminalView`, not needing to update the
terminal's offset in the `render` method as it might have performance
implications. Further ideas on this are welcome.

Preview:


https://github.com/user-attachments/assets/560f0aac-4544-4007-8f0b-8833386f608f

Todo:

- [x] Experiment with custom scrollbar responding to terminal mouse
scroll
- [x] Refactor existing scrollbar handle into a trait  
- [x] Update terminal to use the scrollbar trait instead of a custom
scrollbar implementation
- [x] Figure out how scrollbar events like mouse drag should notify the
terminal to update its state
- [x] Code clean up
- [x] Scrollbar hide setting for terminal

Release Notes:

- Added scrollbar to the terminal
This commit is contained in:
tims 2025-01-18 22:06:41 +05:30 committed by GitHub
parent 728a874b1e
commit 8c92da45a9
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
7 changed files with 412 additions and 91 deletions

View file

@ -0,0 +1,91 @@
use std::{
any::Any,
cell::{Cell, RefCell},
rc::Rc,
};
use gpui::{size, Bounds, Point};
use terminal::Terminal;
use ui::{px, ContentSize, Pixels, ScrollableHandle};
#[derive(Debug)]
struct ScrollHandleState {
line_height: Pixels,
total_lines: usize,
viewport_lines: usize,
display_offset: usize,
}
impl ScrollHandleState {
fn new(terminal: &Terminal) -> Self {
Self {
line_height: terminal.last_content().size.line_height,
total_lines: terminal.total_lines(),
viewport_lines: terminal.viewport_lines(),
display_offset: terminal.last_content().display_offset,
}
}
}
#[derive(Debug, Clone)]
pub struct TerminalScrollHandle {
state: Rc<RefCell<ScrollHandleState>>,
pub future_display_offset: Rc<Cell<Option<usize>>>,
}
impl TerminalScrollHandle {
pub fn new(terminal: &Terminal) -> Self {
Self {
state: Rc::new(RefCell::new(ScrollHandleState::new(terminal))),
future_display_offset: Rc::new(Cell::new(None)),
}
}
pub fn update(&self, terminal: &Terminal) {
*self.state.borrow_mut() = ScrollHandleState::new(terminal);
}
}
impl ScrollableHandle for TerminalScrollHandle {
fn content_size(&self) -> Option<ContentSize> {
let state = self.state.borrow();
Some(ContentSize {
size: size(px(0.), px(state.total_lines as f32 * state.line_height.0)),
scroll_adjustment: Some(Point::new(px(0.), px(0.))),
})
}
fn offset(&self) -> Point<Pixels> {
let state = self.state.borrow();
let scroll_offset = state.total_lines - state.viewport_lines - state.display_offset;
Point::new(
px(0.),
-px(scroll_offset as f32 * self.state.borrow().line_height.0),
)
}
fn set_offset(&self, point: Point<Pixels>) {
let state = self.state.borrow();
let offset_delta = (point.y.0 / state.line_height.0).round() as i32;
let max_offset = state.total_lines - state.viewport_lines;
let display_offset = ((max_offset as i32 + offset_delta) as usize).min(max_offset);
self.future_display_offset.set(Some(display_offset));
}
fn viewport(&self) -> Bounds<Pixels> {
let state = self.state.borrow();
Bounds::new(
Point::new(px(0.), px(0.)),
size(
px(0.),
px(state.viewport_lines as f32 * state.line_height.0),
),
)
}
fn as_any(&self) -> &dyn Any {
self
}
}

View file

@ -1,15 +1,20 @@
mod persistence;
pub mod terminal_element;
pub mod terminal_panel;
pub mod terminal_scrollbar;
pub mod terminal_tab_tooltip;
use collections::HashSet;
use editor::{actions::SelectAll, scroll::Autoscroll, Editor};
use editor::{
actions::SelectAll,
scroll::{Autoscroll, ScrollbarAutoHide},
Editor, EditorSettings,
};
use futures::{stream::FuturesUnordered, StreamExt};
use gpui::{
anchored, deferred, div, impl_actions, AnyElement, AppContext, DismissEvent, EventEmitter,
FocusHandle, FocusableView, KeyContext, KeyDownEvent, Keystroke, Model, MouseButton,
MouseDownEvent, Pixels, Render, ScrollWheelEvent, Styled, Subscription, Task, View,
MouseDownEvent, Pixels, Render, ScrollWheelEvent, Stateful, Styled, Subscription, Task, View,
VisualContext, WeakModel, WeakView,
};
use language::Bias;
@ -21,15 +26,18 @@ use terminal::{
index::Point,
term::{search::RegexSearch, TermMode},
},
terminal_settings::{CursorShape, TerminalBlink, TerminalSettings, WorkingDirectory},
terminal_settings::{self, CursorShape, TerminalBlink, TerminalSettings, WorkingDirectory},
Clear, Copy, Event, MaybeNavigationTarget, Paste, ScrollLineDown, ScrollLineUp, ScrollPageDown,
ScrollPageUp, ScrollToBottom, ScrollToTop, ShowCharacterPalette, TaskStatus, Terminal,
TerminalSize, ToggleViMode,
};
use terminal_element::{is_blank, TerminalElement};
use terminal_panel::TerminalPanel;
use terminal_scrollbar::TerminalScrollHandle;
use terminal_tab_tooltip::TerminalTooltip;
use ui::{h_flex, prelude::*, ContextMenu, Icon, IconName, Label, Tooltip};
use ui::{
h_flex, prelude::*, ContextMenu, Icon, IconName, Label, Scrollbar, ScrollbarState, Tooltip,
};
use util::{
paths::{PathWithPosition, SanitizedPath},
ResultExt,
@ -120,6 +128,10 @@ pub struct TerminalView {
show_breadcrumbs: bool,
block_below_cursor: Option<Rc<BlockProperties>>,
scroll_top: Pixels,
scrollbar_state: ScrollbarState,
scroll_handle: TerminalScrollHandle,
show_scrollbar: bool,
hide_scrollbar_task: Option<Task<()>>,
_subscriptions: Vec<Subscription>,
_terminal_subscriptions: Vec<Subscription>,
}
@ -167,6 +179,8 @@ impl TerminalView {
.cursor_shape
.unwrap_or_default();
let scroll_handle = TerminalScrollHandle::new(terminal.read(cx));
Self {
terminal,
workspace: workspace_handle,
@ -184,6 +198,10 @@ impl TerminalView {
show_breadcrumbs: TerminalSettings::get_global(cx).toolbar.breadcrumbs,
block_below_cursor: None,
scroll_top: Pixels::ZERO,
scrollbar_state: ScrollbarState::new(scroll_handle.clone()),
scroll_handle,
show_scrollbar: !Self::should_autohide_scrollbar(cx),
hide_scrollbar_task: None,
_subscriptions: vec![
focus_in,
focus_out,
@ -619,6 +637,136 @@ impl TerminalView {
subscribe_for_terminal_events(&terminal, self.workspace.clone(), cx);
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: &AppContext) -> 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: &AppContext) -> 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 ViewContext<Self>) {
const SCROLLBAR_SHOW_INTERVAL: Duration = Duration::from_secs(1);
if !Self::should_autohide_scrollbar(cx) {
return;
}
self.hide_scrollbar_task = Some(cx.spawn(|panel, mut cx| async move {
cx.background_executor()
.timer(SCROLLBAR_SHOW_INTERVAL)
.await;
panel
.update(&mut cx, |panel, cx| {
panel.show_scrollbar = false;
cx.notify();
})
.log_err();
}))
}
fn render_scrollbar(&self, cx: &mut ViewContext<Self>) -> Option<Stateful<Div>> {
if !Self::should_show_scrollbar(cx)
|| !(self.show_scrollbar || self.scrollbar_state.is_dragging())
{
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(|_, _, 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(|terminal_view, _, cx| {
if !terminal_view.scrollbar_state.is_dragging()
&& !terminal_view.focus_handle.contains_focused(cx)
{
terminal_view.hide_scrollbar(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.scrollbar_state.clone())),
)
}
}
fn subscribe_for_terminal_events(
@ -933,6 +1081,7 @@ impl TerminalView {
terminal.focus_out();
terminal.set_cursor_shape(CursorShape::Hollow);
});
self.hide_scrollbar(cx);
cx.notify();
}
}
@ -945,6 +1094,8 @@ impl Render for TerminalView {
let focused = self.focus_handle.is_focused(cx);
div()
.occlude()
.id("terminal-view")
.size_full()
.relative()
.track_focus(&self.focus_handle(cx))
@ -973,18 +1124,32 @@ impl Render for TerminalView {
}
}),
)
.on_hover(cx.listener(|this, hovered, cx| {
if *hovered {
this.show_scrollbar = true;
this.hide_scrollbar_task.take();
cx.notify();
} else if !this.focus_handle.contains_focused(cx) {
this.hide_scrollbar(cx);
}
}))
.child(
// TODO: Oddly this wrapper div is needed for TerminalElement to not steal events from the context menu
div().size_full().child(TerminalElement::new(
terminal_handle,
terminal_view_handle,
self.workspace.clone(),
self.focus_handle.clone(),
focused,
self.should_show_cursor(focused, cx),
self.can_navigate_to_selected_word,
self.block_below_cursor.clone(),
)),
div()
.size_full()
.child(TerminalElement::new(
terminal_handle,
terminal_view_handle,
self.workspace.clone(),
self.focus_handle.clone(),
focused,
self.should_show_cursor(focused, cx),
self.can_navigate_to_selected_word,
self.block_below_cursor.clone(),
))
.when_some(self.render_scrollbar(cx), |div, scrollbar| {
div.child(scrollbar)
}),
)
.children(self.context_menu.as_ref().map(|(menu, position, _)| {
deferred(