//! Display-only workspace and panes. All terminal and multiplexer state is remote. use crate::{ chrome, client::{Client, Updates}, colors, commands::{self, CommandAction}, cursor::CursorAnimator, fonts::{self, TerminalFont}, input, label::middle_label, palette::CommandPalette, pane_name::RenameField, protocol::{ ClientMessage, Direction, PaneSnapshot, ScrollKind, SelectionCommand, SelectionKind, SelectionSide, Snapshot, StackPaneInfo, VerticalDirection, }, render::{RenderCell, Renderer}, transition::Slide, }; use alacritty_terminal::{ term::{TermMode, color::Colors}, vte::ansi::{Color, CursorShape, NamedColor}, }; use gpui::{prelude::*, *}; use std::{ collections::HashMap, ops::Range, sync::Arc, time::{Duration, Instant}, }; const PADDING: f32 = 6.; struct TabRename { tab: u64, editor: Entity, _blur: Subscription, } pub struct Workspace { client: Client, font: TerminalFont, snapshot: Option>, panes: HashMap>, error: Option, focus: FocusHandle, palette: Option>, tab_rename: Option, outgoing: HashMap>, outgoing_snapshot: Option>, transition: Option, transition_frame_pending: bool, _updates: Task<()>, } impl Drop for Workspace { fn drop(&mut self) { // GPUI drops each window's root on close, including during app shutdown. if self.client.remote().is_some() && let Err(error) = self.client.remember_remote_detach() { log::warn!("Could not remember detached SSH session: {error:#}"); } } } impl Workspace { fn begin_tab_rename(&mut self, window: &mut Window, cx: &mut Context) { let Some(tab) = self .snapshot .as_deref() .and_then(Snapshot::active_tab) .filter(|tab| !tab.is_connecting()) else { return; }; let id = tab.id; let initial = tab.title.clone(); let owner = cx.weak_entity(); let editor = cx.new(|cx| { RenameField::new( initial, move |name, window, cx| { let _ = owner.update(cx, |view, cx| { view.tab_rename = None; if let Some(name) = name && let Err(error) = view.client.send(ClientMessage::RenameTab { tab: id, name: Some(name), }) { view.error = Some(error.to_string()); } view.restore_focus(window, cx); cx.notify(); }); }, window, cx, ) }); let focus = editor.read(cx).focus_handle(cx); let blur = cx.on_blur(&focus, window, |view, _, cx| { // Clicking elsewhere cancels the edit and keeps the clicked focus. view.tab_rename = None; cx.notify(); }); self.tab_rename = Some(TabRename { tab: id, editor, _blur: blur, }); cx.notify(); } fn focused_pane(&self) -> Option> { let snapshot = self.snapshot.as_ref()?; let tab = snapshot .tabs .iter() .find(|tab| tab.id == snapshot.active_tab)?; self.panes.get(&tab.active_pane).cloned() } fn restore_focus(&self, window: &mut Window, cx: &mut Context) { if let Some(pane) = self.focused_pane() { window.focus(&pane.read(cx).focus); } else { window.focus(&self.focus); } } fn close_palette(&mut self, window: &mut Window, cx: &mut Context) { self.palette = None; self.restore_focus(window, cx); cx.notify(); } fn open_palette(&mut self, window: &mut Window, cx: &mut Context) { if self.palette.is_some() { self.close_palette(window, cx); return; } self.tab_rename = None; for pane in self.panes.values() { pane.update(cx, |pane, cx| { pane.rename = None; pane.selecting = false; pane.preedit.clear(); cx.notify(); }); } let items = commands::root_items(self.snapshot.as_deref(), self.client.remote().is_some()); let owner = cx.weak_entity(); self.palette = Some(cx.new(|cx| { CommandPalette::new( items, move |action, window, cx| { let _ = owner.update(cx, |view, cx| { view.close_palette(window, cx); if let Some(action) = action { view.execute(action, window, cx); } }); }, window, cx, ) })); cx.notify(); } fn key_down(&mut self, event: &KeyDownEvent, window: &mut Window, cx: &mut Context) { let Some(action) = crate::bindings::action_for_key(&event.keystroke) else { return; }; // Window commands remain available while a text field has focus. if !matches!( action, CommandAction::TogglePalette | CommandAction::NewWindow | CommandAction::IncreaseFontSize | CommandAction::DecreaseFontSize ) && (self.palette.is_some() || self.tab_rename.is_some() || self .focused_pane() .is_some_and(|pane| pane.read(cx).rename.is_some())) { return; } self.execute(action, window, cx); cx.stop_propagation(); } fn open_window(&self, cx: &mut Context) { let client = self.client.clone(); let cwd = self .focused_pane() .map(|pane| pane.read(cx).data().cwd.clone()); let active_tab = self.snapshot.as_deref().and_then(Snapshot::active_tab); let remote = active_tab.and_then(|tab| tab.remote.clone().map(|host| (tab.id, host))); let launch = cx .background_executor() .spawn(async move { client.open_window(remote, cwd) }); cx.spawn(async move |view, cx| { if let Err(error) = launch.await { let _ = view.update(cx, |view, cx| { view.error = Some(format!("Could not open a new window: {error:#}")); cx.notify(); }); } }) .detach(); } fn close_tab(&mut self, id: u64, window: &mut Window, cx: &mut Context) { let Some(tab) = self .snapshot .as_ref() .and_then(|s| s.tabs.iter().find(|tab| tab.id == id)) else { return; }; let message = if tab.remote.is_some() { ClientMessage::DetachRemote { tab: id } } else if self.client.remote().is_some() { window.remove_window(); return; } else { ClientMessage::Close { id } }; if let Err(error) = self.client.send(message) { self.error = Some(error.to_string()); cx.notify(); } } fn execute(&mut self, action: CommandAction, window: &mut Window, cx: &mut Context) { use CommandAction::*; let pane = self.focused_pane(); let pane_id = pane.as_ref().map(|pane| pane.read(cx).data().id); let message = match action { TogglePalette => { self.open_palette(window, cx); None } NewWindow => { self.open_window(cx); None } IncreaseFontSize | DecreaseFontSize => { let delta = if matches!(action, IncreaseFontSize) { 1. } else { -1. }; if self.font.adjust_size(delta, window.text_system()) { for pane in self.panes.values().chain(self.outgoing.values()) { pane.update(cx, |pane, cx| { pane.renderer = Renderer::new(self.font.clone()); pane.prepared_revision = None; pane.requested_size = None; cx.notify(); }); } } None } NewTab => Some(ClientMessage::NewTab { cwd: None }), SplitPane => pane_id.map(|pane| ClientMessage::Split { pane, cwd: None }), StackAbove | StackBelow => Some(ClientMessage::NewStackPane { pane: None, direction: if matches!(action, StackAbove) { VerticalDirection::Up } else { VerticalDirection::Down }, cwd: None, }), FocusAbove | FocusBelow => Some(ClientMessage::FocusDirection { direction: if matches!(action, FocusAbove) { Direction::Up } else { Direction::Down }, }), ClosePane => pane_id.map(|id| ClientMessage::Close { id }).or_else(|| { let tab = self.snapshot.as_deref()?.active_tab()?; tab.is_connecting() .then_some(ClientMessage::DetachRemote { tab: tab.id }) }), ResetPaneName => pane_id.map(|pane| ClientMessage::RenamePane { pane, name: None }), ResetTabName => self .snapshot .as_ref() .map(|snapshot| ClientMessage::RenameTab { tab: snapshot.active_tab, name: None, }), RenameTab => { self.begin_tab_rename(window, cx); None } Copy => pane_id.map(|pane| ClientMessage::Copy { pane }), Scroll(kind) => pane_id.map(|pane| ClientMessage::Scroll { pane, kind }), FocusTab(tab) => Some(ClientMessage::FocusTab { tab }), FocusPane(pane) => Some(ClientMessage::FocusPane { pane }), PreviousTab | NextTab => Some(ClientMessage::CycleTab { forward: matches!(action, NextTab), }), PreviousPane | NextPane => Some(ClientMessage::CyclePane { forward: matches!(action, NextPane), }), FocusLeft | FocusRight => Some(ClientMessage::FocusDirection { direction: if matches!(action, FocusLeft) { Direction::Left } else { Direction::Right }, }), RenamePane => { if let Some(pane) = pane { pane.update(cx, |pane, cx| pane.begin_rename(window, cx)); } None } Paste => { if let Some(pane) = pane && let Some(text) = cx.read_from_clipboard().and_then(|item| item.text()) { pane.update(cx, |pane, cx| { pane.send( input::paste_text( &text, pane.mode().contains(TermMode::BRACKETED_PASTE), ), cx, ); }); } None } DetachRemote => { let tab = self.snapshot.as_deref().and_then(Snapshot::active_tab); if let Some(tab) = tab.filter(|tab| tab.remote.is_some()) { Some(ClientMessage::DetachRemote { tab: tab.id }) } else { if self.client.remote().is_some() { window.remove_window(); } None } } Detach => { window.remove_window(); None } }; if let Some(message) = message && let Err(error) = self.client.send(message) { self.error = Some(error.to_string()); cx.notify(); } } pub fn new( client: Client, updates: Updates, window: &mut Window, cx: &mut Context, ) -> Self { let focus = cx.focus_handle(); window.focus(&focus); // Scene transitions rebuild pane views. Keep system font discovery and // cell measurement outside that path, once per workspace. let font = fonts::terminal_font(window.text_system()); let task = cx.spawn_in(window, async move |view, cx| { while let Some(update) = updates.recv().await { if cx .update(|window, cx| { view.update(cx, |view, cx| { for text in update.clipboard.into_iter().filter(|text| !text.is_empty()) { cx.write_to_clipboard(ClipboardItem::new_string(text)); } if let Some(error) = update.error { view.error = Some(error); } if let Some(snapshot) = update.snapshot { let metadata_changed = view.snapshot.as_ref().is_none_or(|old| { old.active_tab != snapshot.active_tab || old.tabs != snapshot.tabs }); let cancelled_tab_rename = view.tab_rename.as_ref().is_some_and(|rename| { snapshot.active_tab != rename.tab || !snapshot.tabs.iter().any(|tab| tab.id == rename.tab) }); if cancelled_tab_rename { view.tab_rename = None; } let focus_allowed = view.palette.is_none() && view.tab_rename.is_none(); if let Some(direction) = view .snapshot .as_ref() .and_then(|old| scene_direction(old, &snapshot)) { view.outgoing_snapshot = view.snapshot.clone(); view.outgoing = view .snapshot .as_ref() .unwrap() .panes .iter() .filter_map(|data| { view.panes .get(&data.id) .map(|pane| (data.id, pane.clone())) }) .collect(); for pane in view.outgoing.values() { pane.update(cx, |pane, cx| { pane.read_only = true; pane.transitioning = true; pane.rename = None; pane.selecting = false; pane.preedit.clear(); pane.blink_timer = None; cx.notify(); }); } view.panes.clear(); view.transition = Some(Slide::new(direction, Instant::now())); } let active = snapshot .tabs .iter() .find(|t| t.id == snapshot.active_tab) .map(|t| t.active_pane); view.panes .retain(|id, _| snapshot.panes.iter().any(|p| p.id == *id)); for (index, data) in snapshot.panes.iter().enumerate() { if let Some(pane) = view.panes.get(&data.id) { pane.update(cx, |pane, cx| { let was_active = pane.active; pane.active = active == Some(data.id); pane.snapshot = snapshot.clone(); pane.index = index; if pane.active && !was_active && focus_allowed { if let Some(editor) = &pane.rename { editor.read(cx).focus(window); } else { window.focus(&pane.focus); } } // A stale snapshot can precede the FocusPane // acknowledgement when renaming an inactive // pane. Cancel only when focus leaves it. if was_active && !pane.active { pane.rename = None; } cx.notify(); }); } else { let client = view.client.clone(); let frame = snapshot.clone(); let pane = cx.new(|cx| { let mut pane = TerminalPane::new( client, frame, index, active == Some(data.id), view.font.clone(), window, cx, ); if pane.active && focus_allowed { window.focus(&pane.focus); } pane.transitioning = view.transition.is_some(); pane }); view.panes.insert(data.id, pane); } } let title = snapshot .tabs .iter() .find(|t| t.id == snapshot.active_tab) .map(|t| t.title.as_str()) .unwrap_or("Terminal"); window.set_window_title(&format!("psyTerm — {title}")); view.snapshot = Some(snapshot); if let Some(palette) = &view.palette { if metadata_changed { let items = commands::root_items( view.snapshot.as_deref(), view.client.remote().is_some(), ); palette .update(cx, |palette, cx| palette.set_items(items, cx)); } } else if cancelled_tab_rename { view.restore_focus(window, cx); } else if view.panes.is_empty() { window.focus(&view.focus); } } cx.notify(); }) }) .is_err() { break; } futures_lite::future::yield_now().await; } }); Self { client, font, snapshot: None, panes: HashMap::new(), error: None, focus, palette: None, tab_rename: None, outgoing: HashMap::new(), outgoing_snapshot: None, transition: None, transition_frame_pending: false, _updates: task, } } } impl Render for Workspace { fn render(&mut self, window: &mut Window, cx: &mut Context) -> impl IntoElement { let now = Instant::now(); if self .transition .as_ref() .is_some_and(|transition| transition.finished(now)) { self.transition = None; self.outgoing.clear(); self.outgoing_snapshot = None; for pane in self.panes.values() { pane.update(cx, |pane, cx| { pane.transitioning = false; cx.notify(); }); } } if self.transition.is_some() && !self.transition_frame_pending { self.transition_frame_pending = true; cx.on_next_frame(window, |view, _, cx| { view.transition_frame_pending = false; cx.notify(); }); } let tabs = self .snapshot .as_ref() .map(|s| { s.tabs .iter() .map(|tab| chrome::ChromeTab { id: tab.id, label: tab.title.clone().into(), remote: tab .remote .as_deref() .or(self.client.remote()) .map(str::to_owned), active: tab.id == s.active_tab, editor: self .tab_rename .as_ref() .filter(|rename| rename.tab == tab.id) .map(|rename| rename.editor.clone()), }) .collect() }) .unwrap_or_default(); let client = self.client.clone(); let new_client = self.client.clone(); let owner = cx.weak_entity(); let header = chrome::header( tabs, cfg!(target_os = "macos") && !window.is_fullscreen(), move |tab, _, _| { let _ = client.send(ClientMessage::FocusTab { tab }); }, move |tab, window, cx| { let _ = owner.update(cx, |view, cx| view.close_tab(tab, window, cx)); }, move |_, _| { let _ = new_client.send(ClientMessage::NewTab { cwd: None }); }, move |window, _| window.remove_window(), ); let (incoming_offset, outgoing_offset) = self .transition .as_ref() .map(|transition| transition.offsets(now)) .unwrap_or(([0., 0.], [0., 0.])); let mut body = div() .relative() .flex_1() .min_h_0() .overflow_hidden() .bg(rgb(chrome::APP_BACKGROUND)); if let Some(snapshot) = &self.outgoing_snapshot { body = body.child(pane_scene(snapshot, &self.outgoing, outgoing_offset, None)); } let mut incoming = scene(incoming_offset).id("incoming-scene"); if let Some(snapshot) = &self.snapshot { incoming = pane_scene(snapshot, &self.panes, incoming_offset, Some(&self.client)); if snapshot.panes.is_empty() { let status = match snapshot.active_tab() { Some(tab) if tab.is_connecting() => tab .remote .as_ref() .map(|host| format!("Connecting to {host}…")), Some(_) => None, // The selected tab's grid is still in transit. None => Some("No sessions. Use + to open a terminal.".to_owned()), }; if let Some(status) = status { incoming = incoming.child(div().p_4().text_color(rgb(chrome::MUTED)).child(status)); } } } else { incoming = incoming.child( div() .p_4() .text_color(rgb(chrome::MUTED)) .child("Connecting…"), ); } body = body.child(incoming); let mut root = div() .relative() .track_focus(&self.focus) .capture_key_down(cx.listener(Self::key_down)) .size_full() .flex() .flex_col() .bg(rgb(chrome::APP_BACKGROUND)) .child(header) .child(body); #[cfg(target_os = "macos")] { root = root.on_action(cx.listener(|view, _: &crate::NewWindow, _, cx| { view.open_window(cx); })); } if let Some(error) = &self.error { root = root.child( div() .flex() .items_center() .px_3() .py_1() .text_size(px(12.)) .text_color(rgb(chrome::TEXT)) .bg(rgb(chrome::BORDER)) .child(div().flex_1().min_w_0().child(error.clone())) .child( div() .id("dismiss-error") .px_2() .cursor_pointer() .child("Dismiss") .on_click(cx.listener(|view, _, _, cx| { view.error = None; cx.notify(); })), ), ); } if let Some(palette) = &self.palette { root = root.child(palette.clone()); } root } } /// Absolute positioning translates the scene without changing its layout size. fn scene(offset: [f32; 2]) -> Div { div() .absolute() .left(relative(offset[0])) .top(relative(offset[1])) .size_full() .flex() .gap(px(6.)) .p(px(chrome::CONTENT_INSET)) .bg(rgb(chrome::APP_BACKGROUND)) } fn pane_scene( snapshot: &Snapshot, panes: &HashMap>, offset: [f32; 2], client: Option<&Client>, ) -> Stateful
{ // The frozen scene can contain the same collapsed headers as the live // scene. Keep their hover, scroll, and click state in separate namespaces. let mut content = scene(offset).id(if client.is_some() { "incoming-scene" } else { "outgoing-scene" }); if let Some(tab) = snapshot .tabs .iter() .find(|tab| tab.id == snapshot.active_tab) { for stack in &tab.stacks { let Some(index) = stack .panes .iter() .position(|pane| pane.id == stack.active_pane) else { continue; }; let mut column = div() .flex_1() .min_w_0() .h_full() .flex() .flex_col() .gap(px(2.)) .overflow_hidden(); if index > 0 { column = column.child(stack_headers( &stack.panes[..index], format!("stack-above-{}", stack.active_pane), client, )); } if let Some(pane) = panes.get(&stack.active_pane) { column = column.child(pane.clone()); } if index + 1 < stack.panes.len() { column = column.child(stack_headers( &stack.panes[index + 1..], format!("stack-below-{}", stack.active_pane), client, )); } content = content.child(column); } } content } fn stack_headers(entries: &[StackPaneInfo], id: String, client: Option<&Client>) -> Stateful
{ let mut headers = div() .id(ElementId::Name(id.into())) .flex() .flex_col() .w_full() .flex_shrink_0() .max_h(relative(0.25)) .overflow_y_scroll(); for entry in entries { let pane = entry.id; let client = client.cloned(); headers = headers.child( chrome::pane_title_bar(false) .id(ElementId::Name(format!("collapsed-pane-{pane}").into())) .border_1() .border_color(rgb(chrome::PANE_INACTIVE_BORDER)) .cursor_pointer() .hover(|style| style.border_color(rgb(0xbdbdbd))) .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) .on_click(move |_, _, cx| { cx.stop_propagation(); if let Some(client) = &client { let _ = client.send(ClientMessage::FocusPane { pane }); } }) .child(middle_label(entry.title.clone().into())), ); } headers } fn scene_direction(old: &Snapshot, next: &Snapshot) -> Option<[f32; 2]> { if old.panes.is_empty() || next.panes.is_empty() { return None; } if old.active_tab != next.active_tab { let previous = old .tabs .iter() .position(|tab| tab.id == old.active_tab) .unwrap_or(0); let next_index = next .tabs .iter() .position(|tab| tab.id == next.active_tab) .unwrap_or(0); return Some([if next_index > previous { 1. } else { -1. }, 0.]); } if let (Some(old_tab), Some(next_tab)) = ( old.tabs.iter().find(|tab| tab.id == old.active_tab), next.tabs.iter().find(|tab| tab.id == next.active_tab), ) && let Some(direction) = crate::transition::stack_direction(old_tab, next_tab) { return Some([0., direction]); } next.panes .iter() .any(|pane| !old.panes.iter().any(|old| old.id == pane.id)) .then_some([1., 0.]) } struct TerminalPane { client: Client, snapshot: Arc, index: usize, active: bool, // Frozen outgoing scenes are display-only; no PTY resize, focus or input. read_only: bool, transitioning: bool, focus: FocusHandle, bounds: Bounds, selecting: bool, scroll_remainder: f32, preedit: String, cursor_bounds: Bounds, cursor: CursorAnimator, renderer: Renderer, rename: Option>, prepared_revision: Option, requested_size: Option<(u16, u16)>, next_frame_pending: bool, blink_timer: Option>, _activation: Subscription, } impl TerminalPane { fn new( client: Client, snapshot: Arc, index: usize, active: bool, font: TerminalFont, window: &mut Window, cx: &mut Context, ) -> Self { let focus = cx.focus_handle(); let activation = cx.observe_window_activation(window, |pane, window, cx| { if window.is_window_active() { // Each attached window has its own zoom and viewport. The focused // window sets the shared PTY dimensions. pane.requested_size = None; } pane.blink_timer = None; cx.notify(); }); Self { client, snapshot, index, active, read_only: false, transitioning: false, focus, bounds: Bounds::default(), selecting: false, scroll_remainder: 0., preedit: String::new(), cursor_bounds: Bounds::default(), cursor: CursorAnimator::new(), renderer: Renderer::new(font), rename: None, prepared_revision: None, requested_size: None, next_frame_pending: false, blink_timer: None, _activation: activation, } } fn data(&self) -> &PaneSnapshot { &self.snapshot.panes[self.index] } fn command(&self, command: ClientMessage) { if self.read_only { return; } if let Err(error) = self.client.send(command) { log::warn!("{error:#}"); } } fn mode(&self) -> TermMode { TermMode::from_bits_truncate(self.data().mode) } fn activity(&mut self, cx: &mut Context) { self.cursor.activity(Instant::now()); self.blink_timer = None; cx.notify(); } fn send(&mut self, bytes: Vec, cx: &mut Context) { if self.read_only || bytes.is_empty() { return; } self.preedit.clear(); self.activity(cx); if let Err(error) = self.client.input(self.data().id, bytes) { log::warn!("{error:#}"); } } fn begin_rename(&mut self, window: &mut Window, cx: &mut Context) { self.command(ClientMessage::FocusPane { pane: self.data().id, }); self.preedit.clear(); self.selecting = false; let initial = self.data().title.clone(); let owner = cx.weak_entity(); let field = cx.new(|cx| { RenameField::new( initial, move |name, window, cx| { let _ = owner.update(cx, |pane, cx| { pane.rename = None; if let Some(name) = name { pane.command(ClientMessage::RenamePane { pane: pane.data().id, name: Some(name), }); } window.focus(&pane.focus); pane.activity(cx); }); }, window, cx, ) }); self.rename = Some(field); cx.notify(); } fn pane_header(&mut self, cx: &mut Context) -> Div { let mut header = chrome::pane_title_bar(self.active) .flex() .items_center() .gap(px(8.)) .on_mouse_down( MouseButton::Left, cx.listener(|pane, _, window, cx| { cx.stop_propagation(); if pane.read_only { return; } if pane.rename.is_none() { window.focus(&pane.focus); } pane.command(ClientMessage::FocusPane { pane: pane.data().id, }); }), ); if let Some(editor) = &self.rename { header = header .child(div().flex_1().min_w_0().child(editor.clone())) .child( div() .flex_shrink_0() .text_size(px(11.)) .font_weight(FontWeight::NORMAL) .child("Enter to save · Esc to cancel"), ); } else { header = header.child( div() .flex_1() .min_w_0() .h_full() .overflow_hidden() .child(middle_label(self.data().title.clone().into())), ); } header } fn key_down(&mut self, event: &KeyDownEvent, _: &mut Window, cx: &mut Context) { if self.read_only || self.rename.is_some() { return; } let key = &event.keystroke; let pane = self.data().id; self.activity(cx); if key.modifiers.shift && !key.modifiers.control && !key.modifiers.alt && !key.modifiers.platform && !self.mode().contains(TermMode::ALT_SCREEN) { let kind = match key.key.as_str() { "pageup" => Some(ScrollKind::PageUp), "pagedown" => Some(ScrollKind::PageDown), "home" => Some(ScrollKind::Top), "end" => Some(ScrollKind::Bottom), _ => None, }; if let Some(kind) = kind { self.command(ClientMessage::Scroll { pane, kind }); cx.stop_propagation(); return; } } if let Some(bytes) = input::encode_key(key, self.mode()) { self.send(bytes, cx); cx.stop_propagation(); } } fn grid_point(&self, position: Point) -> (u16, u16, SelectionSide) { let x = ((f32::from(position.x - self.bounds.left()) - PADDING).max(0.) / self.renderer.font.cell_width) .min(f32::from(self.data().columns - 1)); let y = ((f32::from(position.y - self.bounds.top()) - PADDING).max(0.) / self.renderer.font.line_height) .min(f32::from(self.data().lines - 1)); ( x as u16, y as u16, if x.fract() < 0.5 { SelectionSide::Left } else { SelectionSide::Right }, ) } fn mouse_down(&mut self, event: &MouseDownEvent, window: &mut Window, cx: &mut Context) { if self.read_only { return; } window.focus(&self.focus); self.activity(cx); let pane = self.data().id; self.command(ClientMessage::FocusPane { pane }); let (column, row, side) = self.grid_point(event.position); let kind = match event.click_count { 2 => SelectionKind::Word, 3.. => SelectionKind::Line, _ => SelectionKind::Simple, }; self.command(ClientMessage::Selection { pane, selection: SelectionCommand::Start { column, row, side, kind, }, }); self.selecting = true; } fn mouse_move(&mut self, event: &MouseMoveEvent, _: &mut Window, _: &mut Context) { if self.selecting && event.dragging() { let (column, row, side) = self.grid_point(event.position); self.command(ClientMessage::Selection { pane: self.data().id, selection: SelectionCommand::Update { column, row, side }, }); } } fn scroll(&mut self, event: &ScrollWheelEvent, _: &mut Window, cx: &mut Context) { if self.read_only { return; } self.scroll_remainder += match event.delta { ScrollDelta::Lines(d) => d.y * 3., ScrollDelta::Pixels(d) => f32::from(d.y) / self.renderer.font.line_height, }; let lines = self.scroll_remainder.trunc() as i32; self.scroll_remainder -= lines as f32; if lines == 0 { return; } let mode = self.mode(); if mode.contains(TermMode::ALT_SCREEN | TermMode::ALTERNATE_SCROLL) && !event.modifiers.shift { let arrow = match (mode.contains(TermMode::APP_CURSOR), lines > 0) { (true, true) => b"\x1bOA", (true, false) => b"\x1bOB", (false, true) => b"\x1b[A", (false, false) => b"\x1b[B", }; self.send(arrow.repeat(lines.unsigned_abs().min(100) as usize), cx); } else { self.command(ClientMessage::Scroll { pane: self.data().id, kind: ScrollKind::Delta(lines), }); } } fn prepare(&mut self, bounds: Bounds, window: &mut Window) { let font = &self.renderer.font; let columns = ((f32::from(bounds.size.width) - 2. * PADDING) / font.cell_width) .floor() .clamp(2., 1000.) as u16; let lines = ((f32::from(bounds.size.height) - 2. * PADDING) / font.line_height) .floor() .clamp(1., 500.) as u16; if !self.read_only && window.is_window_active() && self.requested_size != Some((columns, lines)) { self.requested_size = Some((columns, lines)); self.command(ClientMessage::Resize { pane: self.data().id, columns, lines, cell_width: font.cell_width.round() as u16, cell_height: font.line_height as u16, }); } let prepare_rows = self.prepared_revision != Some(self.snapshot.revision) || self.bounds.size != bounds.size; if !prepare_rows && self.bounds.origin == bounds.origin { return; } let started = Instant::now(); self.bounds = bounds; let data = self.data(); let mut palette = Colors::default(); for (i, color) in data.colors.iter().enumerate() { palette[i] = *color; } let cursor = data.cursor; let hidden = data.exited || cursor.row < 0 || cursor.row >= i32::from(data.lines); let wide = data .cells .get( cursor.row.max(0) as usize * usize::from(data.columns) + usize::from(cursor.column), ) .is_some_and(|cell| { cell.flags .contains(alacritty_terminal::term::cell::Flags::WIDE_CHAR) }); let cursor_bounds = Bounds::new( bounds.origin + point( px(PADDING + f32::from(cursor.column) * font.cell_width), px(PADDING + cursor.row as f32 * font.line_height), ), size( px(font.cell_width * if wide { 2. } else { 1. }), px(font.line_height), ), ); let mut cursor_color = colors::resolve(Color::Named(NamedColor::Cursor), &palette); cursor_color.a = 0.55; self.cursor_bounds = cursor_bounds; self.cursor.set_target( cursor_bounds, if hidden { CursorShape::Hidden } else { cursor.shape.into() }, cursor_color, Instant::now(), ); if !prepare_rows { return; } let data = self.data(); let rows = data .cells .chunks(usize::from(data.columns)) .enumerate() .map(|(row, cells)| { cells .iter() .enumerate() .map(|(col, cell)| { let (mut foreground, mut background) = colors::cell_colors(cell, &palette); if data.selected[row * usize::from(data.columns) + col] { foreground = rgb(chrome::TEXT).into(); background = rgb(chrome::BORDER).into(); } RenderCell { cell: cell.clone(), foreground, background, cursor: CursorShape::Hidden, } }) .collect() }) .collect(); self.renderer.prepare(rows, window); self.prepared_revision = Some(self.snapshot.revision); log::debug!(target:"psyterm::timing","prepare_us={}",started.elapsed().as_micros()); } fn schedule_cursor( &mut self, delay: Option, window: &mut Window, cx: &mut Context, ) { self.blink_timer = None; match delay { Some(delay) if delay.is_zero() => { if !self.next_frame_pending { self.next_frame_pending = true; cx.on_next_frame(window, |pane, _, cx| { pane.next_frame_pending = false; cx.notify(); }); } } Some(delay) => { self.blink_timer = Some(cx.spawn_in(window, async move |pane, cx| { cx.background_executor().timer(delay).await; let _ = pane.update(cx, |_, cx| cx.notify()); })); } None => {} } } } impl Render for TerminalPane { fn render(&mut self, _: &mut Window, cx: &mut Context) -> impl IntoElement { let prepare = cx.entity(); let paint = cx.entity(); let header = self.pane_header(cx); let content = div().flex_1().min_h_0().min_w_0().overflow_hidden().cursor(CursorStyle::IBeam) .on_mouse_down(MouseButton::Left,cx.listener(|pane, event, window, cx| { pane.rename = None; pane.mouse_down(event, window, cx); })) .on_mouse_move(cx.listener(Self::mouse_move)) .on_mouse_up(MouseButton::Left,cx.listener(|pane,_,_,_|pane.selecting=false)) .on_mouse_up_out(MouseButton::Left,cx.listener(|pane,_,_,_|pane.selecting=false)) .on_scroll_wheel(cx.listener(Self::scroll)) .child(canvas(move |bounds,window,cx|prepare.update(cx,|pane,_|pane.prepare(bounds,window)), move |bounds,(),window,cx| { paint.update(cx,|pane,cx| { let started=Instant::now(); if !pane.read_only && pane.rename.is_none() { window.handle_input(&pane.focus,ElementInputHandler::new(bounds,paint.clone()),cx); } let mut delay=None; window.with_content_mask(Some(ContentMask{bounds}),|window| { let origin=bounds.origin+point(px(PADDING),px(PADDING)); let focused=window.is_window_active() && pane.active && pane.focus.is_focused(window) && pane.rename.is_none(); pane.renderer.paint_with_cursor(origin,window,cx,|window| { if !pane.transitioning { delay=pane.cursor.paint(Instant::now(),focused,window); } }); if !pane.preedit.is_empty() { let font = &pane.renderer.font; let run = TextRun { len: pane.preedit.len(), font: font.face.clone(), color: rgb(chrome::TEXT).into(), background_color: Some(rgb(chrome::TERMINAL_BACKGROUND).into()), underline: Some(UnderlineStyle { thickness: px(1.), color: None, wavy: false, }), strikethrough: None, }; let line = window.text_system().shape_line( pane.preedit.clone().into(), px(font.size), &[run], None, ); let origin = pane.cursor_bounds.origin; let height = px(font.line_height); let _ = line.paint_background(origin, height, window, cx); let _ = line.paint(origin, height, window, cx); } }); pane.schedule_cursor(delay,window,cx); log::debug!(target:"psyterm::timing","paint_us={}",started.elapsed().as_micros()); }); }).size_full()); div() .flex_1() .min_w_0() .min_h_0() .h_full() .flex() .flex_col() .bg(rgb(chrome::TERMINAL_BACKGROUND)) .border_1() .border_color(rgb(if self.active { chrome::PANE_FOCUS } else { chrome::PANE_INACTIVE_BORDER })) .overflow_hidden() .track_focus(&self.focus) .on_key_down(cx.listener(Self::key_down)) .child(header) .child(content) } } impl EntityInputHandler for TerminalPane { fn text_for_range( &mut self, _: Range, _: &mut Option>, _: &mut Window, _: &mut Context, ) -> Option { None } fn selected_text_range( &mut self, _: bool, _: &mut Window, _: &mut Context, ) -> Option { Some(UTF16Selection { range: 0..0, reversed: false, }) } fn marked_text_range(&self, _: &mut Window, _: &mut Context) -> Option> { (!self.preedit.is_empty()).then(|| 0..self.preedit.encode_utf16().count()) } fn unmark_text(&mut self, _: &mut Window, cx: &mut Context) { self.preedit.clear(); cx.notify(); } fn replace_text_in_range( &mut self, _: Option>, text: &str, _: &mut Window, cx: &mut Context, ) { if text.is_empty() { if !self.preedit.is_empty() { self.preedit.clear(); cx.notify(); } } else { self.send(text.as_bytes().to_vec(), cx); } } fn replace_and_mark_text_in_range( &mut self, _: Option>, text: &str, _: Option>, _: &mut Window, cx: &mut Context, ) { self.preedit = text.to_owned(); self.activity(cx); } fn bounds_for_range( &mut self, _: Range, _: Bounds, _: &mut Window, _: &mut Context, ) -> Option> { Some(self.cursor_bounds) } fn character_index_for_point( &mut self, _: Point, _: &mut Window, _: &mut Context, ) -> Option { None } }