Initial GPUI Wayland terminal with Alacritty core
This commit is contained in:
+473
@@ -0,0 +1,473 @@
|
||||
//! A single terminal pane. Session owns the PTY; this view only handles presentation/input.
|
||||
use async_channel::Receiver;
|
||||
use std::ops::Range;
|
||||
|
||||
use alacritty_terminal::{
|
||||
event::Event,
|
||||
grid::{Dimensions, Scroll},
|
||||
index::{Column, Line, Point as GridPoint, Side},
|
||||
selection::{Selection, SelectionType},
|
||||
term::TermMode,
|
||||
vte::ansi::{Color, CursorShape, NamedColor},
|
||||
};
|
||||
use gpui::{prelude::*, *};
|
||||
|
||||
use crate::{
|
||||
colors, input,
|
||||
render::{FONT_SIZE, LINE_HEIGHT, RenderCell, Renderer},
|
||||
session::Session,
|
||||
};
|
||||
|
||||
const PADDING: f32 = 8.;
|
||||
|
||||
pub struct TerminalView {
|
||||
session: Session,
|
||||
focus: FocusHandle,
|
||||
font: Font,
|
||||
bounds: Bounds<Pixels>,
|
||||
cell_width: f32,
|
||||
selecting: bool,
|
||||
scroll_remainder: f32,
|
||||
preedit: String,
|
||||
cursor_bounds: Bounds<Pixels>,
|
||||
renderer: Renderer,
|
||||
_events: Task<()>,
|
||||
}
|
||||
|
||||
impl TerminalView {
|
||||
pub fn new(
|
||||
session: Session,
|
||||
events: Receiver<Event>,
|
||||
window: &mut Window,
|
||||
cx: &mut Context<Self>,
|
||||
) -> Self {
|
||||
let terminal_font = crate::fonts::terminal_font(window.text_system());
|
||||
let font_id = window.text_system().resolve_font(&terminal_font);
|
||||
let cell_width = window
|
||||
.text_system()
|
||||
.advance(font_id, px(FONT_SIZE), 'M')
|
||||
.map(|advance| f32::from(advance.width))
|
||||
.unwrap_or(9.)
|
||||
.max(1.);
|
||||
let focus = cx.focus_handle();
|
||||
window.focus(&focus);
|
||||
// Wake on PTY output rather than adding a polling interval to input latency.
|
||||
let task = cx.spawn_in(window, async move |view, cx| {
|
||||
while let Ok(first) = events.recv().await {
|
||||
let pending: Vec<_> = std::iter::once(first)
|
||||
.chain(std::iter::from_fn(|| events.try_recv().ok()))
|
||||
.take(4096)
|
||||
.collect();
|
||||
if cx
|
||||
.update(|window, cx| {
|
||||
view.update(cx, |view, cx| {
|
||||
for event in pending {
|
||||
match event {
|
||||
Event::Title(title) => window.set_window_title(&title),
|
||||
Event::ResetTitle => window.set_window_title("Terminal"),
|
||||
Event::PtyWrite(text) => view.session.write(text.into_bytes()),
|
||||
Event::TextAreaSizeRequest(format) => {
|
||||
view.session.write(format(view.session.size()).into_bytes())
|
||||
}
|
||||
Event::ColorRequest(index, format) => {
|
||||
let color = (index
|
||||
< alacritty_terminal::term::color::COUNT)
|
||||
.then(|| view.session.term.lock().colors()[index])
|
||||
.flatten();
|
||||
view.session.write(
|
||||
format(color.unwrap_or_else(|| colors::palette(index)))
|
||||
.into_bytes(),
|
||||
);
|
||||
}
|
||||
Event::Exit => window.remove_window(),
|
||||
Event::Wakeup => view.session.acknowledge_wakeup(),
|
||||
// OSC 52 is deliberately not wired to the desktop clipboard.
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
cx.notify();
|
||||
})
|
||||
})
|
||||
.is_err()
|
||||
{
|
||||
break;
|
||||
}
|
||||
// Give the compositor a turn even when a child continuously writes.
|
||||
futures_lite::future::yield_now().await;
|
||||
}
|
||||
});
|
||||
Self {
|
||||
session,
|
||||
focus,
|
||||
font: terminal_font,
|
||||
bounds: Bounds::default(),
|
||||
cell_width,
|
||||
selecting: false,
|
||||
scroll_remainder: 0.,
|
||||
preedit: String::new(),
|
||||
cursor_bounds: Bounds::default(),
|
||||
renderer: Renderer::default(),
|
||||
_events: task,
|
||||
}
|
||||
}
|
||||
|
||||
fn send(&mut self, bytes: Vec<u8>, cx: &mut Context<Self>) {
|
||||
if bytes.is_empty() {
|
||||
return;
|
||||
}
|
||||
let mut changed = !self.preedit.is_empty();
|
||||
self.preedit.clear();
|
||||
{
|
||||
let mut term = self.session.term.lock();
|
||||
changed |= term.grid().display_offset() != 0 || term.selection.is_some();
|
||||
term.scroll_display(Scroll::Bottom);
|
||||
term.selection = None;
|
||||
}
|
||||
self.session.write(bytes);
|
||||
// Echo arrives through the PTY. Do not draw an unchanged frame first.
|
||||
if changed {
|
||||
cx.notify();
|
||||
}
|
||||
}
|
||||
|
||||
fn key_down(&mut self, event: &KeyDownEvent, _: &mut Window, cx: &mut Context<Self>) {
|
||||
let key = &event.keystroke;
|
||||
if key.modifiers.control
|
||||
&& key.modifiers.shift
|
||||
&& !key.modifiers.alt
|
||||
&& !key.modifiers.platform
|
||||
{
|
||||
match key.key.as_str() {
|
||||
"c" | "C" => {
|
||||
if let Some(text) = self.session.term.lock().selection_to_string() {
|
||||
cx.write_to_clipboard(ClipboardItem::new_string(text));
|
||||
}
|
||||
cx.stop_propagation();
|
||||
return;
|
||||
}
|
||||
"v" | "V" => {
|
||||
if let Some(text) = cx.read_from_clipboard().and_then(|item| item.text()) {
|
||||
let bracketed = self
|
||||
.session
|
||||
.term
|
||||
.lock()
|
||||
.mode()
|
||||
.contains(TermMode::BRACKETED_PASTE);
|
||||
let text = input::paste_text(&text, bracketed);
|
||||
self.send(text, cx);
|
||||
}
|
||||
cx.stop_propagation();
|
||||
return;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if key.modifiers.shift
|
||||
&& !key.modifiers.control
|
||||
&& !key.modifiers.alt
|
||||
&& !key.modifiers.platform
|
||||
&& !self
|
||||
.session
|
||||
.term
|
||||
.lock()
|
||||
.mode()
|
||||
.contains(TermMode::ALT_SCREEN)
|
||||
{
|
||||
let scroll = match key.key.as_str() {
|
||||
"pageup" => Some(Scroll::PageUp),
|
||||
"pagedown" => Some(Scroll::PageDown),
|
||||
"home" => Some(Scroll::Top),
|
||||
"end" => Some(Scroll::Bottom),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(scroll) = scroll {
|
||||
self.session.term.lock().scroll_display(scroll);
|
||||
cx.notify();
|
||||
cx.stop_propagation();
|
||||
return;
|
||||
}
|
||||
}
|
||||
let mode = *self.session.term.lock().mode();
|
||||
if let Some(bytes) = input::encode_key(key, mode) {
|
||||
self.send(bytes, cx);
|
||||
cx.stop_propagation();
|
||||
}
|
||||
}
|
||||
|
||||
fn grid_point(&self, position: Point<Pixels>) -> (GridPoint, Side) {
|
||||
let term = self.session.term.lock();
|
||||
let x = (f32::from(position.x - self.bounds.left()) - PADDING).max(0.) / self.cell_width;
|
||||
let y =
|
||||
((f32::from(position.y - self.bounds.top()) - PADDING).max(0.) / LINE_HEIGHT) as usize;
|
||||
let column = (x as usize).min(term.columns() - 1);
|
||||
let line = y.min(term.screen_lines() - 1) as i32 - term.grid().display_offset() as i32;
|
||||
(
|
||||
GridPoint::new(Line(line), Column(column)),
|
||||
if x.fract() < 0.5 {
|
||||
Side::Left
|
||||
} else {
|
||||
Side::Right
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
fn mouse_down(&mut self, event: &MouseDownEvent, window: &mut Window, cx: &mut Context<Self>) {
|
||||
window.focus(&self.focus);
|
||||
let (point, side) = self.grid_point(event.position);
|
||||
let ty = match event.click_count {
|
||||
2 => SelectionType::Semantic,
|
||||
3.. => SelectionType::Lines,
|
||||
_ => SelectionType::Simple,
|
||||
};
|
||||
self.session.term.lock().selection = Some(Selection::new(ty, point, side));
|
||||
self.selecting = true;
|
||||
cx.notify();
|
||||
}
|
||||
|
||||
fn mouse_move(&mut self, event: &MouseMoveEvent, _: &mut Window, cx: &mut Context<Self>) {
|
||||
if self.selecting && event.dragging() {
|
||||
let (point, side) = self.grid_point(event.position);
|
||||
if let Some(selection) = &mut self.session.term.lock().selection {
|
||||
selection.update(point, side);
|
||||
}
|
||||
cx.notify();
|
||||
}
|
||||
}
|
||||
|
||||
fn scroll(&mut self, event: &ScrollWheelEvent, _: &mut Window, cx: &mut Context<Self>) {
|
||||
self.scroll_remainder += match event.delta {
|
||||
ScrollDelta::Lines(delta) => delta.y * 3.,
|
||||
ScrollDelta::Pixels(delta) => f32::from(delta.y) / LINE_HEIGHT,
|
||||
};
|
||||
let lines = self.scroll_remainder.trunc() as i32;
|
||||
self.scroll_remainder -= lines as f32;
|
||||
if lines != 0 {
|
||||
let mode = *self.session.term.lock().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.session
|
||||
.term
|
||||
.lock()
|
||||
.scroll_display(Scroll::Delta(lines));
|
||||
cx.notify();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn prepare(&mut self, bounds: Bounds<Pixels>, window: &mut Window) {
|
||||
let prepare_started = std::time::Instant::now();
|
||||
self.bounds = bounds;
|
||||
let columns = ((f32::from(bounds.size.width) - 2. * PADDING) / self.cell_width)
|
||||
.floor()
|
||||
.max(2.) as usize;
|
||||
let lines = ((f32::from(bounds.size.height) - 2. * PADDING) / LINE_HEIGHT)
|
||||
.floor()
|
||||
.max(1.) as usize;
|
||||
self.session.resize(
|
||||
columns,
|
||||
lines,
|
||||
self.cell_width.round() as u16,
|
||||
LINE_HEIGHT as u16,
|
||||
);
|
||||
let term = self.session.term.lock();
|
||||
let content = term.renderable_content();
|
||||
let offset = content.display_offset as i32;
|
||||
let cursor = content.cursor;
|
||||
self.cursor_bounds = Bounds::new(
|
||||
bounds.origin
|
||||
+ point(
|
||||
px(PADDING + cursor.point.column.0 as f32 * self.cell_width),
|
||||
px(PADDING + (cursor.point.line.0 + offset) as f32 * LINE_HEIGHT),
|
||||
),
|
||||
size(px(self.cell_width), px(LINE_HEIGHT)),
|
||||
);
|
||||
let mut rows = vec![Vec::with_capacity(columns); lines];
|
||||
for indexed in content.display_iter {
|
||||
let (mut foreground, mut background) =
|
||||
colors::cell_colors(indexed.cell, content.colors);
|
||||
if content
|
||||
.selection
|
||||
.is_some_and(|selection| selection.contains(indexed.point))
|
||||
{
|
||||
foreground = rgb(0xffffff).into();
|
||||
background = rgb(0x3c536d).into();
|
||||
}
|
||||
let shape = if indexed.point == cursor.point {
|
||||
cursor.shape
|
||||
} else {
|
||||
CursorShape::Hidden
|
||||
};
|
||||
if shape == CursorShape::Block {
|
||||
background = colors::resolve(Color::Named(NamedColor::Cursor), content.colors);
|
||||
foreground = colors::resolve(Color::Named(NamedColor::Background), content.colors);
|
||||
}
|
||||
let row = (indexed.point.line.0 + offset) as usize;
|
||||
rows[row].push(RenderCell {
|
||||
cell: indexed.cell.clone(),
|
||||
foreground,
|
||||
background,
|
||||
cursor: shape,
|
||||
});
|
||||
}
|
||||
drop(term);
|
||||
self.renderer
|
||||
.prepare(rows, &self.font, self.cell_width, window);
|
||||
log::debug!(target: "terminal::timing", "prepare_us={} cells={}", prepare_started.elapsed().as_micros(), columns * lines);
|
||||
}
|
||||
}
|
||||
|
||||
impl Render for TerminalView {
|
||||
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
|
||||
let prepare_view = cx.entity();
|
||||
let paint_view = cx.entity();
|
||||
div()
|
||||
.size_full()
|
||||
.bg(rgb(colors::BACKGROUND))
|
||||
.overflow_hidden()
|
||||
.track_focus(&self.focus)
|
||||
.cursor(CursorStyle::IBeam)
|
||||
.on_key_down(cx.listener(Self::key_down))
|
||||
.on_mouse_down(MouseButton::Left, cx.listener(Self::mouse_down))
|
||||
.on_mouse_move(cx.listener(Self::mouse_move))
|
||||
.on_mouse_up(
|
||||
MouseButton::Left,
|
||||
cx.listener(|view, _, _, _| view.selecting = false),
|
||||
)
|
||||
.on_mouse_up_out(
|
||||
MouseButton::Left,
|
||||
cx.listener(|view, _, _, _| view.selecting = false),
|
||||
)
|
||||
.on_scroll_wheel(cx.listener(Self::scroll))
|
||||
.child(
|
||||
canvas(
|
||||
move |bounds, window, cx| {
|
||||
prepare_view.update(cx, |view, _| view.prepare(bounds, window))
|
||||
},
|
||||
move |bounds, (), window, cx| {
|
||||
let paint_started = std::time::Instant::now();
|
||||
let view = paint_view.read(cx);
|
||||
let focus = view.focus.clone();
|
||||
let base_font = view.font.clone();
|
||||
let preedit = view.preedit.clone();
|
||||
let cursor_bounds = view.cursor_bounds;
|
||||
window.handle_input(
|
||||
&focus,
|
||||
ElementInputHandler::new(bounds, paint_view.clone()),
|
||||
cx,
|
||||
);
|
||||
window.with_content_mask(Some(ContentMask { bounds }), |window| {
|
||||
let origin = bounds.origin + point(px(PADDING), px(PADDING));
|
||||
paint_view.update(cx, |view, cx| view.renderer.paint(origin, window, cx));
|
||||
if !preedit.is_empty() {
|
||||
let run = TextRun {
|
||||
len: preedit.len(),
|
||||
font: base_font.clone(),
|
||||
color: rgb(colors::FOREGROUND).into(),
|
||||
background_color: Some(rgb(colors::BACKGROUND).into()),
|
||||
underline: Some(UnderlineStyle {
|
||||
thickness: px(1.),
|
||||
color: None,
|
||||
wavy: false,
|
||||
}),
|
||||
strikethrough: None,
|
||||
};
|
||||
let shaped = window.text_system().shape_line(
|
||||
preedit.into(),
|
||||
px(FONT_SIZE),
|
||||
&[run],
|
||||
None,
|
||||
);
|
||||
let _ =
|
||||
shaped.paint(cursor_bounds.origin, px(LINE_HEIGHT), window, cx);
|
||||
}
|
||||
});
|
||||
log::debug!(target: "terminal::timing", "paint_us={}", paint_started.elapsed().as_micros());
|
||||
},
|
||||
)
|
||||
.size_full(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl EntityInputHandler for TerminalView {
|
||||
fn text_for_range(
|
||||
&mut self,
|
||||
_: Range<usize>,
|
||||
_: &mut Option<Range<usize>>,
|
||||
_: &mut Window,
|
||||
_: &mut Context<Self>,
|
||||
) -> Option<String> {
|
||||
None
|
||||
}
|
||||
fn selected_text_range(
|
||||
&mut self,
|
||||
_: bool,
|
||||
_: &mut Window,
|
||||
_: &mut Context<Self>,
|
||||
) -> Option<UTF16Selection> {
|
||||
Some(UTF16Selection {
|
||||
range: 0..0,
|
||||
reversed: false,
|
||||
})
|
||||
}
|
||||
fn marked_text_range(&self, _: &mut Window, _: &mut Context<Self>) -> Option<Range<usize>> {
|
||||
(!self.preedit.is_empty()).then(|| 0..self.preedit.encode_utf16().count())
|
||||
}
|
||||
fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
|
||||
self.preedit.clear();
|
||||
cx.notify();
|
||||
}
|
||||
fn replace_text_in_range(
|
||||
&mut self,
|
||||
_: Option<Range<usize>>,
|
||||
text: &str,
|
||||
_: &mut Window,
|
||||
cx: &mut Context<Self>,
|
||||
) {
|
||||
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<Range<usize>>,
|
||||
text: &str,
|
||||
_: Option<Range<usize>>,
|
||||
_: &mut Window,
|
||||
cx: &mut Context<Self>,
|
||||
) {
|
||||
self.preedit = text.to_owned();
|
||||
cx.notify();
|
||||
}
|
||||
fn bounds_for_range(
|
||||
&mut self,
|
||||
_: Range<usize>,
|
||||
_: Bounds<Pixels>,
|
||||
_: &mut Window,
|
||||
_: &mut Context<Self>,
|
||||
) -> Option<Bounds<Pixels>> {
|
||||
Some(self.cursor_bounds)
|
||||
}
|
||||
fn character_index_for_point(
|
||||
&mut self,
|
||||
_: Point<Pixels>,
|
||||
_: &mut Window,
|
||||
_: &mut Context<Self>,
|
||||
) -> Option<usize> {
|
||||
None
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user