aboutsummaryrefslogtreecommitdiffstats
path: root/src/main.rs
diff options
context:
space:
mode:
authorduckyriley <[email protected]>2026-11-23 20:45:44 +0800
committerduckyriley <[email protected]>2026-11-23 20:45:44 +0800
commit24d7f554d00901841810b856b44d5763cbc5bd76 (patch)
tree740eb685f70937a014a6c5e5a7fa09b51f19bac0 /src/main.rs
downloadducky-24d7f554d00901841810b856b44d5763cbc5bd76.tar.gz
ducky-24d7f554d00901841810b856b44d5763cbc5bd76.zip
Build native GPUI shell with Lua customization and riced defaults
Diffstat (limited to '')
-rw-r--r--src/main.rs858
1 files changed, 858 insertions, 0 deletions
diff --git a/src/main.rs b/src/main.rs
new file mode 100644
index 0000000..34117c3
--- /dev/null
+++ b/src/main.rs
@@ -0,0 +1,858 @@
+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<Terminal>,
+ active: usize,
+ focus: FocusHandle,
+ message: Option<String>,
+ bounds: Bounds<Pixels>,
+ cell_width: f32,
+ selection: Option<((u16, u16), (u16, u16))>,
+ dragging: bool,
+ composition: String,
+}
+impl Ducky {
+ fn new(config: Config, cx: &mut Context<Self>) -> anyhow::Result<Self> {
+ 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>) {
+ 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<Self>) {
+ 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>) {
+ self.tabs.remove(self.active);
+ if self.tabs.is_empty() {
+ cx.quit();
+ return;
+ }
+ self.active = self.active.min(self.tabs.len() - 1);
+ self.selection = None;
+ cx.notify();
+ }
+ fn reload(&mut self, cx: &mut Context<Self>) {
+ 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<Self>) {
+ 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<Self>) {
+ 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<Self>) {
+ let key = &event.keystroke;
+ let m = key.modifiers;
+ if key.unparse() == self.config.status_bar_toggle {
+ self.config.show_status_bar = !self.config.show_status_bar;
+ cx.notify();
+ cx.stop_propagation();
+ return;
+ }
+ if m.control && m.shift {
+ match key.key.to_lowercase().as_str() {
+ "t" => self.new_tab(cx),
+ "w" => self.close_tab(cx),
+ "r" => self.reload(cx),
+ "c" => self.copy(cx),
+ "v" => self.paste(cx),
+ "tab" => {
+ self.active = (self.active + self.tabs.len() - 1) % self.tabs.len();
+ self.selection = None;
+ cx.notify();
+ }
+ "=" | "+" => {
+ self.config.font_size = (self.config.font_size + 1.).min(48.);
+ self.config.line_height = self.config.font_size * 1.4;
+ cx.notify();
+ }
+ "-" => {
+ self.config.font_size = (self.config.font_size - 1.).max(8.);
+ self.config.line_height = self.config.font_size * 1.4;
+ cx.notify();
+ }
+ _ => {
+ if let Some(data) = self.config.bindings.get(&key.unparse()).cloned() {
+ self.send(data.as_bytes(), cx);
+ } else {
+ return;
+ }
+ }
+ }
+ cx.stop_propagation();
+ return;
+ }
+ if m.control && key.key == "tab" {
+ self.active = (self.active + 1) % self.tabs.len();
+ self.selection = None;
+ cx.notify();
+ cx.stop_propagation();
+ return;
+ }
+ if let Some(data) = self.config.bindings.get(&key.unparse()).cloned() {
+ self.send(data.as_bytes(), cx);
+ cx.stop_propagation();
+ return;
+ }
+ if m.shift && (key.key == "pageup" || key.key == "pagedown") {
+ self.tabs[self.active].scroll(if key.key == "pageup" { 20 } else { -20 });
+ cx.notify();
+ 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<Pixels>) -> (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<Pixels>,
+ window: &mut Window,
+ cx: &mut Context<Self>,
+ ) {
+ 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 key_bytes(key: &Keystroke, application: bool) -> Option<Vec<u8>> {
+ 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<Self>) -> 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 {
+ ""
+ }
+ ))
+ .on_click(cx.listener(move |this, _, _, cx| {
+ this.active = i;
+ this.selection = None;
+ cx.notify();
+ }))
+ })
+ .collect::<Vec<_>>();
+ let offset = self.tabs[self.active]
+ .parser
+ .lock()
+ .unwrap()
+ .screen()
+ .scrollback();
+ let toggle = c
+ .status_bar_toggle
+ .replace('-', "+")
+ .replace("ctrl", "Ctrl")
+ .replace("shift", "Shift");
+ 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()
+ .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();
+ }
+ },
+ ))
+ .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("Ctrl+Shift T tab · C copy · V paste · R reload")
+ .child(
+ div()
+ .text_color(rgb(c.accent))
+ .child(format!("{toggle} hide")),
+ ),
+ ),
+ )
+ })
+ }
+}
+impl EntityInputHandler for Ducky {
+ fn text_for_range(
+ &mut self,
+ _: Range<usize>,
+ _: &mut Option<Range<usize>>,
+ _: &mut Window,
+ _: &mut Context<Self>,
+ ) -> Option<String> {
+ Some(String::new())
+ }
+ 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.composition.is_empty()).then_some(0..self.composition.encode_utf16().count())
+ }
+ fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
+ self.composition.clear();
+ cx.notify();
+ }
+ fn replace_text_in_range(
+ &mut self,
+ _: Option<Range<usize>>,
+ text: &str,
+ _: &mut Window,
+ cx: &mut Context<Self>,
+ ) {
+ self.composition.clear();
+ self.send(text.as_bytes(), 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.composition = text.into();
+ cx.notify();
+ }
+ fn bounds_for_range(
+ &mut self,
+ _: Range<usize>,
+ _: Bounds<Pixels>,
+ _: &mut Window,
+ _: &mut Context<Self>,
+ ) -> Option<Bounds<Pixels>> {
+ 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<Pixels>,
+ _: &mut Window,
+ _: &mut Context<Self>,
+ ) -> Option<usize> {
+ Some(0)
+ }
+}
+fn main() -> anyhow::Result<()> {
+ let args: Vec<String> = 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+Shift+T/W: new/close tab\nCtrl+Tab: next tab\nCtrl+Shift+C/V: copy/paste\nCtrl+Shift+R: reload Lua config\nCtrl+Shift+B: toggle status bar\nCtrl+Shift++/-: 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 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())
+ );
+ }
+}