mod config; mod terminal; use config::Config; use gpui::{ App, Application, Bounds, ClipboardItem, Context, ElementInputHandler, EntityInputHandler, FocusHandle, FontStyle, FontWeight, KeyDownEvent, Keystroke, MouseButton, MouseDownEvent, MouseMoveEvent, Pixels, Point, ResizeEdge, ScrollWheelEvent, TextRun, TitlebarOptions, UTF16Selection, UnderlineStyle, Window, WindowBounds, WindowDecorations, WindowOptions, canvas, div, fill, font, point, prelude::*, px, rgb, size, }; use std::{ops::Range, sync::atomic::Ordering, time::Duration}; use terminal::{Terminal, ansi_color}; struct Ducky { config: Config, tabs: Vec, active: usize, focus: FocusHandle, message: Option, bounds: Bounds, cell_width: f32, selection: Option<((u16, u16), (u16, u16))>, dragging: bool, composition: String, } impl Ducky { fn new(config: Config, cx: &mut Context) -> anyhow::Result { let terminal = Terminal::new(&config)?; cx.spawn(async |this, cx| { loop { cx.background_executor() .timer(Duration::from_millis(16)) .await; if this .update(cx, |this, cx| { let changed = this .tabs .iter() .any(|t| t.dirty.swap(false, Ordering::AcqRel)); if changed { cx.notify(); } }) .is_err() { break; } } }) .detach(); Ok(Self { config, tabs: vec![terminal], active: 0, focus: cx.focus_handle(), message: None, bounds: Bounds::default(), cell_width: 9., selection: None, dragging: false, composition: String::new(), }) } fn send(&mut self, bytes: &[u8], cx: &mut Context) { self.selection = None; if let Err(e) = self.tabs[self.active].write(bytes) { self.message = Some(e.to_string()); } cx.notify(); } fn new_tab(&mut self, cx: &mut Context) { match Terminal::new(&self.config) { Ok(t) => { self.tabs.push(t); self.active = self.tabs.len() - 1; self.selection = None; } Err(e) => self.message = Some(e.to_string()), } cx.notify(); } fn close_tab(&mut self, cx: &mut Context) { self.close_tab_at(self.active, cx); } fn close_tab_at(&mut self, index: usize, cx: &mut Context) { if index >= self.tabs.len() { return; } let terminal = self.tabs.remove(index); // Waiting for an old shell to exit must never stall GPUI's event loop. std::thread::spawn(move || drop(terminal)); if self.tabs.is_empty() { cx.quit(); return; } self.active = active_after_close(self.active, index, self.tabs.len()); self.selection = None; self.dragging = false; self.composition.clear(); cx.notify(); } fn reload(&mut self, cx: &mut Context) { match Config::load() { Ok(c) => { self.config = c; self.message = Some("Configuration reloaded".into()); } Err(e) => self.message = Some(format!("{e:#}")), } cx.notify(); } fn copy(&mut self, cx: &mut Context) { let parser = self.tabs[self.active].parser.lock().unwrap(); let s = parser.screen(); let text = if let Some((a, b)) = self.selection { let (a, b) = if a <= b { (a, b) } else { (b, a) }; let mut text = String::new(); for row in a.0..=b.0 { let mut line = String::new(); for col in 0..self.tabs[self.active].dimensions.1 { if (row, col) >= a && (row, col) <= b { if let Some(c) = s.cell(row, col) { if !c.is_wide_continuation() { let content = c.contents(); line.push_str(if content.is_empty() { " " } else { &content }); } } } } text.push_str(line.trim_end()); if row < b.0 { text.push('\n'); } } text } else { s.contents() }; cx.write_to_clipboard(ClipboardItem::new_string(text)); } fn paste(&mut self, cx: &mut Context) { if let Some(text) = cx.read_from_clipboard().and_then(|c| c.text()) { let bracketed = self.tabs[self.active] .parser .lock() .unwrap() .screen() .bracketed_paste(); let text = text.replace('\x1b', ""); let data = if bracketed { format!("\x1b[200~{text}\x1b[201~") } else { text.replace('\n', "\r") }; self.send(data.as_bytes(), cx); } } fn key(&mut self, event: &KeyDownEvent, window: &mut Window, cx: &mut Context) { let key = &event.keystroke; // User byte bindings can override application actions deliberately. let stroke = key.unparse(); if let Some(data) = self.config.bindings.get(&stroke).cloned() { self.send(data.as_bytes(), cx); cx.stop_propagation(); return; } let action = self.config.action_for(key); if let Some(action) = action { match action.as_str() { "new_tab" => self.new_tab(cx), "close_tab" => self.close_tab(cx), "copy" => self.copy(cx), "paste" => self.paste(cx), "reload" => self.reload(cx), "toggle_status" => { self.config.show_status_bar = !self.config.show_status_bar; } "interrupt" => self.send(&[3], cx), "next_tab" => { self.active = (self.active + 1) % self.tabs.len(); self.selection = None; } "previous_tab" => { self.active = (self.active + self.tabs.len() - 1) % self.tabs.len(); self.selection = None; } "font_larger" => { self.config.font_size = (self.config.font_size + 1.).min(48.); self.config.line_height = self.config.font_size * 1.4; } "font_smaller" => { self.config.font_size = (self.config.font_size - 1.).max(8.); self.config.line_height = self.config.font_size * 1.4; } "scroll_up" => self.tabs[self.active].scroll(20), "scroll_down" => self.tabs[self.active].scroll(-20), _ => { if let Some(index) = action .strip_prefix("tab:") .and_then(|s| s.parse::().ok()) { if index <= self.tabs.len() { self.active = index - 1; self.selection = None; } } } } if !self.tabs.is_empty() { cx.notify(); } window.prevent_default(); cx.stop_propagation(); return; } let app_cursor = self.tabs[self.active] .parser .lock() .unwrap() .screen() .application_cursor(); if let Some(bytes) = key_bytes(key, app_cursor) { self.send(&bytes, cx); cx.stop_propagation(); } let _ = window; } fn position(&self, p: Point) -> (u16, u16) { let t = &self.tabs[self.active]; ( ((f32::from(p.y - self.bounds.top()) / self.config.line_height).max(0.) as u16) .min(t.dimensions.0 - 1), ((f32::from(p.x - self.bounds.left()) / self.cell_width).max(0.) as u16) .min(t.dimensions.1 - 1), ) } fn paint_terminal( &mut self, bounds: Bounds, window: &mut Window, cx: &mut Context, ) { self.bounds = bounds; let c = &self.config; let mut font = font(c.font.clone()); let run = TextRun { len: 1, font: font.clone(), color: rgb(c.foreground).into(), background_color: None, underline: None, strikethrough: None, }; let measure = window .text_system() .shape_line("M".into(), px(c.font_size), &[run], None); self.cell_width = f32::from(measure.width).max(1.); let rows = (f32::from(bounds.size.height) / c.line_height) .floor() .clamp(1., 500.) as u16; let cols = (f32::from(bounds.size.width) / self.cell_width) .floor() .clamp(2., 500.) as u16; if let Err(e) = self.tabs[self.active].resize(rows, cols) { self.message = Some(e.to_string()); } window.handle_input( &self.focus, ElementInputHandler::new(bounds, cx.entity()), cx, ); let parser = self.tabs[self.active].parser.lock().unwrap(); let s = parser.screen(); let cursor = s.cursor_position(); let selection = self .selection .map(|(a, b)| if a <= b { (a, b) } else { (b, a) }); for row in 0..rows { for col in 0..cols { let Some(cell) = s.cell(row, col) else { continue; }; if cell.is_wide_continuation() { continue; } let mut fg = ansi_color(cell.fgcolor(), c.foreground, &c.palette); let mut bg = ansi_color(cell.bgcolor(), c.background, &c.palette); if cell.inverse() { std::mem::swap(&mut fg, &mut bg); } if selection.is_some_and(|(a, b)| (row, col) >= a && (row, col) <= b) { bg = c.surface; fg = c.accent; } let at_cursor = (row, col) == cursor && !s.hide_cursor() && s.scrollback() == 0; if at_cursor { bg = c.accent; fg = c.background; } let origin = point( bounds.left() + px(col as f32 * self.cell_width), bounds.top() + px(row as f32 * c.line_height), ); let width = self.cell_width * if cell.is_wide() { 2. } else { 1. }; if bg != c.background { window.paint_quad(fill( Bounds::new(origin, size(px(width), px(c.line_height))), rgb(bg), )); } let text = cell.contents(); if text.is_empty() { continue; } font.weight = if cell.bold() { FontWeight::BOLD } else { FontWeight::NORMAL }; font.style = if cell.italic() { FontStyle::Italic } else { FontStyle::Normal }; let run = TextRun { len: text.len(), font: font.clone(), color: rgb(fg).into(), background_color: None, underline: cell.underline().then_some(UnderlineStyle { color: Some(rgb(fg).into()), thickness: px(1.), wavy: false, }), strikethrough: None, }; let line = window .text_system() .shape_line(text.into(), px(c.font_size), &[run], None); let _ = line.paint(origin, px(c.line_height), window, cx); } } if !self.composition.is_empty() { let run = TextRun { len: self.composition.len(), font: font.clone(), color: rgb(c.accent).into(), background_color: None, underline: Some(UnderlineStyle { color: None, thickness: px(1.), wavy: false, }), strikethrough: None, }; let line = window.text_system().shape_line( self.composition.clone().into(), px(c.font_size), &[run], None, ); let _ = line.paint( point( bounds.left() + px(cursor.1 as f32 * self.cell_width), bounds.top() + px(cursor.0 as f32 * c.line_height), ), px(c.line_height), window, cx, ); } } } fn active_after_close(active: usize, closed: usize, remaining: usize) -> usize { active .saturating_sub(usize::from(closed < active)) .min(remaining.saturating_sub(1)) } fn key_bytes(key: &Keystroke, application: bool) -> Option> { let m = key.modifiers; let code = match key.key.as_str() { "enter" => "\r", "backspace" => "\x7f", "tab" if m.shift => "\x1b[Z", "tab" => "\t", "escape" => "\x1b", "up" if application => "\x1bOA", "down" if application => "\x1bOB", "right" if application => "\x1bOC", "left" if application => "\x1bOD", "up" => "\x1b[A", "down" => "\x1b[B", "right" => "\x1b[C", "left" => "\x1b[D", "home" => "\x1b[H", "end" => "\x1b[F", "delete" => "\x1b[3~", "insert" => "\x1b[2~", "pageup" => "\x1b[5~", "pagedown" => "\x1b[6~", "f1" => "\x1bOP", "f2" => "\x1bOQ", "f3" => "\x1bOR", "f4" => "\x1bOS", "f5" => "\x1b[15~", "f6" => "\x1b[17~", "f7" => "\x1b[18~", "f8" => "\x1b[19~", "f9" => "\x1b[20~", "f10" => "\x1b[21~", "f11" => "\x1b[23~", "f12" => "\x1b[24~", _ => "", }; if !code.is_empty() { return Some(code.as_bytes().to_vec()); } if m.control { let key = key.key.to_ascii_lowercase(); let c = if key == "space" { b' ' } else { *key.as_bytes().first()? }; if key.len() == 1 || key == "space" { return Some(vec![match c { b' '..=b'_' => c & 0x1f, b'a'..=b'z' => c - b'a' + 1, _ => return None, }]); } } if m.alt { return key .key_char .as_ref() .map(|s| format!("\x1b{s}").into_bytes()); } // Printable text is delivered by GPUI's input handler, including IME commits. None } impl Render for Ducky { fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { let c = self.config.clone(); let entity = cx.entity(); let tabs = self .tabs .iter() .enumerate() .map(|(i, t)| { let parser = t.parser.lock().unwrap(); let title = parser.screen().title(); let title = if title.is_empty() { t.label.clone() } else { title.chars().take(28).collect() }; let active = i == self.active; div() .id(("tab", i)) .h(px(30.)) .px_3() .flex() .items_center() .gap_3() .rounded_md() .bg(rgb(if active { c.surface } else { c.background })) .text_color(rgb(if active { c.foreground } else { c.muted })) .text_size(px(12.)) .hover(|s| s.bg(rgb(c.surface))) .cursor_pointer() .child(div().size(px(5.)).rounded_full().bg(rgb(if active { c.accent } else { c.muted }))) .child(format!( "{} {}{}", i + 1, title, if t.exited.load(Ordering::Acquire) { " · exited" } else { "" } )) .child( div() .id(("close-tab", i)) .size(px(18.)) .rounded_sm() .flex() .items_center() .justify_center() .text_color(rgb(c.muted)) .hover(|s| s.bg(rgb(c.border)).text_color(rgb(c.foreground))) .child("×") .on_mouse_down( MouseButton::Left, cx.listener(move |this, _, window, cx| { cx.stop_propagation(); window.prevent_default(); this.close_tab_at(i, cx); window.focus(&this.focus); }), ), ) .on_mouse_down( MouseButton::Middle, cx.listener(move |this, _, window, cx| { cx.stop_propagation(); window.prevent_default(); this.close_tab_at(i, cx); window.focus(&this.focus); }), ) .on_click(cx.listener(move |this, _, window, cx| { window.focus(&this.focus); this.active = i; this.selection = None; cx.notify(); })) }) .collect::>(); let offset = self.tabs[self.active] .parser .lock() .unwrap() .screen() .scrollback(); let toggle = c.shortcut("toggle_status"); let hints = format!( "{} tab · {} copy · {} paste · {} reload", c.shortcut("new_tab"), c.shortcut("copy"), c.shortcut("paste"), c.shortcut("reload") ); div() .size_full() .flex() .flex_col() .rounded_xl() .overflow_hidden() .border_1() .border_color(rgb(c.border)) .bg(rgb(c.background)) .text_color(rgb(c.foreground)) .font_family(c.font.clone()) .track_focus(&self.focus) .on_key_down(cx.listener(Self::key)) .on_mouse_down( MouseButton::Left, cx.listener(|this, event: &MouseDownEvent, window, cx| { let p = event.position; let bounds = window.bounds(); let width = f32::from(bounds.size.width); let height = f32::from(bounds.size.height); let x = f32::from(p.x); let y = f32::from(p.y); let edge = match (x < 5., x > width - 5., y < 5., y > height - 5.) { (true, _, true, _) => Some(ResizeEdge::TopLeft), (_, true, true, _) => Some(ResizeEdge::TopRight), (true, _, _, true) => Some(ResizeEdge::BottomLeft), (_, true, _, true) => Some(ResizeEdge::BottomRight), (true, _, _, _) => Some(ResizeEdge::Left), (_, true, _, _) => Some(ResizeEdge::Right), (_, _, true, _) => Some(ResizeEdge::Top), (_, _, _, true) => Some(ResizeEdge::Bottom), _ => None, }; if let Some(edge) = edge { this.dragging = false; window.start_window_resize(edge); cx.stop_propagation(); } }), ) .child( div() .h(px(50.)) .flex_shrink_0() .px_3() .flex() .items_center() .gap_2() .when(cfg!(target_os = "macos"), |s| s.pl(px(84.))) .children(tabs) .child( div() .id("add-tab") .w(px(28.)) .h(px(28.)) .rounded_md() .flex() .items_center() .justify_center() .text_color(rgb(c.muted)) .text_size(px(18.)) .hover(|s| s.bg(rgb(c.surface)).text_color(rgb(c.accent))) .cursor_pointer() .child("+") .on_click(cx.listener(|this, _, _, cx| this.new_tab(cx))), ) .child(div().id("window-drag").flex_1().h_full().on_mouse_down( MouseButton::Left, |event, window, _| { if event.click_count == 2 { window.zoom_window(); } else { window.start_window_move(); } }, )) .when(!cfg!(target_os = "macos"), |header| { header .child( div() .id("minimize") .size(px(28.)) .rounded_md() .flex() .items_center() .justify_center() .text_size(px(14.)) .text_color(rgb(c.muted)) .hover(|s| s.bg(rgb(c.surface)).text_color(rgb(c.foreground))) .cursor_pointer() .child("−") .on_click(|_, window, _| window.minimize_window()), ) .child( div() .id("maximize") .size(px(28.)) .rounded_md() .flex() .items_center() .justify_center() .text_size(px(13.)) .text_color(rgb(c.muted)) .hover(|s| s.bg(rgb(c.surface)).text_color(rgb(c.foreground))) .cursor_pointer() .child("□") .on_click(|_, window, _| window.zoom_window()), ) .child( div() .id("close-window") .size(px(28.)) .rounded_md() .flex() .items_center() .justify_center() .text_size(px(17.)) .text_color(rgb(c.muted)) .hover(|s| s.bg(rgb(0x58333f)).text_color(rgb(0xf5a5b6))) .cursor_pointer() .child("×") .on_click(|_, window, _| window.remove_window()), ) }), ) .child( div() .id("terminal") .flex_1() .min_h_0() .p(px(c.padding)) .overflow_hidden() .on_mouse_down( MouseButton::Left, cx.listener(|this, event: &MouseDownEvent, window, cx| { window.focus(&this.focus); let p = this.position(event.position); this.selection = Some((p, p)); this.dragging = true; cx.notify(); }), ) .on_mouse_move(cx.listener(|this, event: &MouseMoveEvent, _, cx| { if this.dragging { let p = this.position(event.position); if let Some((_, b)) = &mut this.selection { *b = p; } cx.notify(); } })) .on_mouse_up( MouseButton::Left, cx.listener(|this, _, _, _| this.dragging = false), ) .on_mouse_up_out( MouseButton::Left, cx.listener(|this, _, _, _| this.dragging = false), ) .on_scroll_wheel(cx.listener(|this, event: &ScrollWheelEvent, _, cx| { let delta = event.delta.pixel_delta(px(this.config.line_height)); this.tabs[this.active] .scroll((f32::from(delta.y) / this.config.line_height).round() as i32); this.selection = None; cx.notify(); })) .child( canvas( |_, _, _| (), move |bounds, _, window, cx| { entity .update(cx, |this, cx| this.paint_terminal(bounds, window, cx)) }, ) .size_full(), ), ) .when(c.show_status_bar, |root| { root.child( div() .h(px(29.)) .flex_shrink_0() .px_5() .flex() .items_center() .justify_between() .gap_4() .text_size(px(10.)) .text_color(rgb(c.muted)) .child(div().flex_1().overflow_hidden().text_ellipsis().child( self.message.clone().unwrap_or_else(|| { if offset > 0 { format!("↑ {offset} lines") } else { config::directory().join("config.lua").display().to_string() } }), )) .child( div().flex().gap_4().child(hints).child( div() .text_color(rgb(c.accent)) .child(format!("{toggle} hide")), ), ), ) }) } } impl EntityInputHandler for Ducky { fn text_for_range( &mut self, _: Range, _: &mut Option>, _: &mut Window, _: &mut Context, ) -> Option { Some(String::new()) } 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.composition.is_empty()).then_some(0..self.composition.encode_utf16().count()) } fn unmark_text(&mut self, _: &mut Window, cx: &mut Context) { self.composition.clear(); cx.notify(); } fn replace_text_in_range( &mut self, _: Option>, text: &str, _: &mut Window, cx: &mut Context, ) { self.composition.clear(); self.send(text.as_bytes(), cx); } fn replace_and_mark_text_in_range( &mut self, _: Option>, text: &str, _: Option>, _: &mut Window, cx: &mut Context, ) { self.composition = text.into(); cx.notify(); } fn bounds_for_range( &mut self, _: Range, _: Bounds, _: &mut Window, _: &mut Context, ) -> Option> { let cursor = self.tabs[self.active] .parser .lock() .unwrap() .screen() .cursor_position(); Some(Bounds::new( point( self.bounds.left() + px(cursor.1 as f32 * self.cell_width), self.bounds.top() + px(cursor.0 as f32 * self.config.line_height), ), size(px(self.cell_width), px(self.config.line_height)), )) } fn character_index_for_point( &mut self, _: Point, _: &mut Window, _: &mut Context, ) -> Option { Some(0) } } fn main() -> anyhow::Result<()> { let args: Vec = std::env::args().collect(); if args.iter().any(|s| s == "--version") { println!("ducky {}", env!("CARGO_PKG_VERSION")); return Ok(()); } if args.iter().any(|s| s == "--help") { println!( "Ducky Shell\n\nUsage: ducky [--check-config | --config-dir | --version]\n\nCtrl+T/W: new/close tab\nAlt+1..9 / Alt+0: select tab\nCtrl+Tab: next tab\nCtrl+C/V: copy/paste\nCtrl+Alt+C: terminal interrupt\nCtrl+R: reload Lua config\nCtrl+B: toggle status bar\nCtrl+=/-: font size\nShift+PageUp/Down: scrollback" ); return Ok(()); } if args.iter().any(|s| s == "--config-dir") { println!("{}", config::directory().display()); return Ok(()); } let config = Config::load()?; if args.iter().any(|s| s == "--check-config") { println!( "Configuration OK: {}", config::directory().join("config.lua").display() ); return Ok(()); } Application::new().run(move |cx: &mut App| { let bounds = Bounds::centered(None, size(px(config.width), px(config.height)), cx); let window = cx .open_window( WindowOptions { window_bounds: Some(WindowBounds::Windowed(bounds)), window_decorations: Some(WindowDecorations::Client), titlebar: Some(TitlebarOptions { title: Some("Ducky Shell".into()), appears_transparent: true, ..Default::default() }), app_id: Some("dev.ducky.shell".into()), ..Default::default() }, move |window, cx| { cx.new(|cx| { let view = Ducky::new(config, cx).unwrap_or_else(|e| { eprintln!("Unable to start shell: {e:#}"); std::process::exit(1) }); window.focus(&view.focus); view }) }, ) .expect("open Ducky window"); let _ = window; cx.on_window_closed(|cx| { if cx.windows().is_empty() { cx.quit(); } }) .detach(); cx.activate(true); }); Ok(()) } #[cfg(test)] mod tests { use super::*; #[test] fn closing_earlier_or_inactive_tabs_preserves_selection() { assert_eq!(active_after_close(3, 0, 3), 2); assert_eq!(active_after_close(0, 2, 3), 0); assert_eq!(active_after_close(2, 2, 2), 1); assert_eq!(active_after_close(1, 1, 3), 1); } #[test] fn terminal_key_encoding() { assert_eq!( key_bytes(&Keystroke::parse("ctrl-c").unwrap(), false), Some(vec![3]) ); assert_eq!( key_bytes(&Keystroke::parse("up").unwrap(), true), Some(b"\x1bOA".to_vec()) ); } }