Skip to content

Visual Studio Code, rebuilt in Rust

Rust
11.0 KB
Raw Blame
//! scrollLocking.ts `SyncScroll`: Toggle and Hold Locked Scrolling Across Editors and the "Scrolling Locked" status
//! bar entry, and the scroll of a visible editor moving every other visible one by as much.

use serde_json::json;

use super::Workbench;
use crate::commands::Outcome;
use crate::editor::Scroll;
use crate::main_thread_status_bar::{StatusEntry, set_or_update_entry};

const ENTRY_ID: &str = "status.scrollLockingEnabled";
const TOGGLE: &str = "workbench.action.toggleLockedScrolling";
const HOLD: &str = "workbench.action.holdLockedScrolling";

impl Workbench {
    pub(super) fn register_scroll_locking_commands(&mut self) {
        self.commands.register(TOGGLE, |workbench, _, _, cx| {
            workbench.toggle_locked_scrolling();
            cx.notify();
            Outcome::done()
        });
        // Locked while its key is held; from anywhere else it toggles.
        self.commands.register(HOLD, |workbench, _, window, cx| {
            workbench.toggle_locked_scrolling();
            workbench.enable_keybinding_hold_mode(HOLD, Workbench::toggle_locked_scrolling, window, cx);
            cx.notify();
            Outcome::done()
        });
    }

    pub(super) fn locked_scrolling(&self) -> bool {
        self.status_entries.iter().any(|entry| entry.entry_id == ENTRY_ID)
    }

    /// `toggle` and `toggleStatusbarItem`: the prominent entry at priority 102 on the right while active.
    fn toggle_locked_scrolling(&mut self) {
        if self.locked_scrolling() {
            self.status_entries.retain(|entry| entry.entry_id != ENTRY_ID);
            self.locked_scroll_panes.clear();
            return;
        }
        let entry = StatusEntry {
            entry_id: ENTRY_ID.into(),
            extension_id: None,
            id: ENTRY_ID.into(),
            name: "Scrolling Locked".into(),
            text: "Scrolling Locked".into(),
            tooltip: Some("Lock Scrolling Enabled".into()),
            command: Some(json!(TOGGLE)),
            color: None,
            background_color: None,
            kind: Some("prominent"),
            align_left: false,
            priority: 102.,
            secondary: 0,
            show_progress: false,
        };
        set_or_update_entry(&mut self.status_entries, entry);
        self.track_locked_scroll_panes();
    }

    /// `trackVisiblePanes`: while locked, each visible editor's scroll position is where its scroll counts from.
    pub(super) fn track_locked_scroll_panes(&mut self) {
        self.locked_scroll_panes.clear();
        if self.locked_scrolling() {
            self.locked_scroll_panes = self.visible_scroll_panes().into_iter().map(|(_, id, scroll)| (id, scroll)).collect();
        }
    }

    /// `onDidEditorPaneScroll`: the scrolled editor's distance from its tracked position moves every other visible
    /// editor as far from its own. The others' scroll does not sync again (`_reentrancyBarrier`).
    pub(super) fn sync_locked_scroll(&mut self) {
        let tracked = |panes: &[(u32, Scroll)], id: u32| panes.iter().find(|(pane, _)| *pane == id).map(|(_, scroll)| *scroll);
        let Some(scrolled) = self.editors.active() else { return };
        let Some(initial) = tracked(&self.locked_scroll_panes, scrolled.model_id) else { return };
        let (scrolled, top, left) = (scrolled.model_id, scrolled.scroll.top - initial.top, scrolled.scroll.left - initial.left);
        for (group, id, scroll) in self.visible_scroll_panes() {
            let Some(initial) = tracked(&self.locked_scroll_panes, id).filter(|_| id != scrolled) else { continue };
            if scroll != (Scroll { top: initial.top + top, left: initial.left + left }) {
                self.with_group(group, |workbench| {
                    let viewport = workbench.editors.viewport;
                    let editor = workbench.editors.code_editor_mut(id).expect("a visible pane's editor");
                    editor.set_scroll(initial.top + top, initial.left + left, viewport);
                });
            }
        }
    }

    /// `getAllVisiblePanes`: each grid group's code editor and a side by side editor's secondary side, as its group,
    /// model id and scroll position.
    fn visible_scroll_panes(&self) -> Vec<(u32, u32, Scroll)> {
        let mut groups = Vec::new();
        for group in self.groups_in_grid_order() {
            groups.push(group);
            let side = self.editors.group_active_tab(group).and_then(|tab| self.editors.side_by_sides.get(&tab.model_id));
            groups.extend(side.copied());
        }
        groups.into_iter().filter_map(|group| {
                let (editor, _) = self.editors.group_active(group)?;
                Some((group, editor.model_id, editor.scroll))
            })
            .collect()
    }
}

#[cfg(test)]
mod tests {
    use std::path::Path;

    use crate::host_sync::HostSync;
    use crate::languages::Languages;
    use crate::theme::load_theme;
    use crate::workbench::Workbench;

    #[gpui::test]
    fn toggling_adds_and_removes_the_status_entry(cx: &mut gpui::TestAppContext) {
        let app_root = Path::new(env!("VSCODE_SRC")).to_path_buf();
        let themes = exthost::scan::scan_extension(&app_root.join("extensions/theme-defaults"), true).unwrap();
        let theme = load_theme(&[themes], "Dark Modern").unwrap();
        let (sender, _receiver) = std::sync::mpsc::channel();
        let (workbench, cx) = cx.add_window_view(|_, cx| Workbench::new(theme, app_root.clone(), None, Languages::new(&[]), crate::default_settings(), HostSync::new(sender), cx));
        workbench.update_in(cx, |workbench, window, cx| {
            drop(workbench.execute_command("workbench.action.toggleLockedScrolling", Vec::new(), window, cx));
            assert!(workbench.locked_scrolling());
            let entry = workbench.status_entries.iter().find(|entry| entry.entry_id == "status.scrollLockingEnabled").unwrap();
            assert_eq!((entry.text.as_str(), entry.kind, entry.align_left), ("Scrolling Locked", Some("prominent"), false));
            drop(workbench.execute_command("workbench.action.toggleLockedScrolling", Vec::new(), window, cx));
            assert!(!workbench.locked_scrolling());
        });
    }

    /// keybindingService.ts `enableKeybindingHoldMode`: a key bound to Hold Locked Scrolling locks while it is down,
    /// ignores its repeats, and unlocks on its key up; run from elsewhere, Hold toggles.
    #[gpui::test]
    fn a_held_key_locks_scrolling_until_it_goes_up(cx: &mut gpui::TestAppContext) {
        use gpui::{KeyDownEvent, KeyUpEvent, Keystroke};
        let app_root = Path::new(env!("VSCODE_SRC")).to_path_buf();
        let themes = exthost::scan::scan_extension(&app_root.join("extensions/theme-defaults"), true).unwrap();
        let theme = load_theme(&[themes], "Dark Modern").unwrap();
        let (workbench, cx) = cx.add_window_view(|_, cx| {
            let mut workbench = Workbench::new(theme, app_root.clone(), None, Languages::new(&[]), crate::default_settings(), HostSync::new(std::sync::mpsc::channel().0), cx);
            let hold = crate::keybindings::Item::new(crate::keybindings::parse_keybinding("ctrl+alt+l"), super::HOLD, None, None, true);
            workbench.set_default_keybindings(vec![hold]);
            workbench.set_user_keybindings(Vec::new());
            workbench
        });
        workbench.update_in(cx, |workbench, window, cx| window.focus(&workbench.action_bar_focus("activity", "workbench.view.explorer", cx), cx));
        cx.run_until_parked();
        let keystroke = Keystroke::parse("ctrl-alt-l").unwrap();
        let locked = |cx: &mut gpui::VisualTestContext| workbench.read_with(cx, |workbench, _| workbench.locked_scrolling());
        cx.simulate_event(KeyDownEvent { keystroke: keystroke.clone(), is_held: false, prefer_character_input: false });
        assert!(locked(cx), "the key down locks");
        cx.simulate_event(KeyDownEvent { keystroke: keystroke.clone(), is_held: true, prefer_character_input: false });
        assert!(locked(cx), "a repeat is ignored");
        cx.simulate_event(KeyUpEvent { keystroke });
        assert!(!locked(cx), "the key up unlocks");
        workbench.update_in(cx, |workbench, window, cx| drop(workbench.execute_command(super::HOLD, Vec::new(), window, cx)));
        assert!(locked(cx), "the command palette's Hold toggles");
        workbench.update(cx, |workbench, cx| workbench.reset_keybinding_hold_mode(cx));
        assert!(locked(cx), "without a held key there is no hold mode");
    }

    /// `onDidEditorPaneScroll`: while locked, a wheel over one group's editor moves the other group's editor as far
    /// from where it was when the lock was turned on.
    #[gpui::test]
    fn a_locked_scroll_moves_every_other_visible_editor(cx: &mut gpui::TestAppContext) {
        let app_root = Path::new(env!("VSCODE_SRC")).to_path_buf();
        let themes = exthost::scan::scan_extension(&app_root.join("extensions/theme-defaults"), true).unwrap();
        let theme = load_theme(&[themes], "Dark Modern").unwrap();
        let dir = std::env::temp_dir().join(format!("code-gpui-scroll-locking-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        let file = dir.join("a.txt");
        std::fs::write(&file, (0..400).map(|line| format!("line {line}\n")).collect::<String>()).unwrap();
        let (workbench, cx) = cx.add_window_view(|window, cx| {
            let mut workbench = Workbench::new(theme, app_root.clone(), None, Languages::new(&[]), crate::default_settings(), HostSync::new(std::sync::mpsc::channel().0), cx);
            workbench.open_file(file.clone(), true, window, cx);
            workbench
        });
        cx.run_until_parked();
        workbench.update_in(cx, |workbench, window, cx| drop(workbench.execute_command("workbench.action.splitEditor", vec![], window, cx)));
        cx.update(|window, _| window.refresh());
        cx.run_until_parked();
        let (left, left_id) = workbench.update_in(cx, |workbench, window, cx| {
            let viewport = workbench.editors.viewport;
            assert!(workbench.editors.active_mut().unwrap().set_scroll(100., 0., viewport));
            drop(workbench.execute_command("workbench.action.toggleLockedScrolling", vec![], window, cx));
            let left = workbench.groups_in_grid_order()[0];
            (left, workbench.with_group(left, |workbench| workbench.editors.active().unwrap().model_id))
        });
        let bounds = cx.debug_bounds(format!("text-area-{left_id}").leak()).unwrap();
        cx.simulate_event(gpui::ScrollWheelEvent { position: bounds.center(), delta: gpui::ScrollDelta::Pixels(gpui::point(gpui::px(0.), gpui::px(-60.))), ..Default::default() });
        cx.run_until_parked();
        let (left_top, focused_top) = workbench.update(cx, |workbench, _| {
            (workbench.with_group(left, |workbench| workbench.editors.active().unwrap().scroll.top), workbench.editors.active().unwrap().scroll.top)
        });
        assert!(left_top > 0., "the wheel scrolled the left group's editor");
        assert_eq!(focused_top, 100. + left_top, "the other editor moved as far from where it was locked");
        std::fs::remove_dir_all(dir).unwrap();
    }
}