diff options
Diffstat (limited to 'src')
| -rw-r--r-- | src/config.rs | 182 | ||||
| -rw-r--r-- | src/main.rs | 858 | ||||
| -rw-r--r-- | src/terminal.rs | 172 |
3 files changed, 1212 insertions, 0 deletions
diff --git a/src/config.rs b/src/config.rs new file mode 100644 index 0000000..65720e3 --- /dev/null +++ b/src/config.rs @@ -0,0 +1,182 @@ +use anyhow::{Context, Result, bail}; +use mlua::{Lua, Table}; +use std::{collections::HashMap, path::PathBuf}; + +pub const DEFAULT: &str = include_str!("../assets/config.lua"); +#[derive(Clone)] +pub struct Config { + pub font: String, + pub font_size: f32, + pub line_height: f32, + pub padding: f32, + pub background: u32, + pub foreground: u32, + pub accent: u32, + pub surface: u32, + pub muted: u32, + pub border: u32, + pub show_status_bar: bool, + pub status_bar_toggle: String, + pub width: f32, + pub height: f32, + pub scrollback: usize, + pub shell: String, + pub args: Vec<String>, + pub cwd: PathBuf, + pub env: HashMap<String, String>, + pub bindings: HashMap<String, String>, + pub palette: Vec<u32>, + pub startup: Option<String>, +} +pub fn directory() -> PathBuf { + dirs::config_dir() + .unwrap_or_else(|| PathBuf::from(".")) + .join("ducky") +} +pub fn color(s: &str) -> Result<u32> { + let s = s.strip_prefix('#').unwrap_or(s); + if s.len() != 6 { + bail!("colors must have six hexadecimal digits"); + } + Ok(u32::from_str_radix(s, 16)?) +} +impl Config { + pub fn load() -> Result<Self> { + let dir = directory(); + std::fs::create_dir_all(&dir)?; + let prompt = dir.join("shell.bash"); + if !prompt.exists() { + std::fs::write(&prompt, include_str!("../assets/shell.bash"))?; + } + let path = dir.join("config.lua"); + if !path.exists() { + std::fs::write(&path, DEFAULT)?; + } + Self::parse(&std::fs::read_to_string(&path)?, &dir) + .with_context(|| format!("loading {}", path.display())) + } + pub(crate) fn parse(source: &str, dir: &std::path::Path) -> Result<Self> { + let lua = Lua::new(); + let package: Table = lua + .globals() + .get("package") + .map_err(|e| anyhow::anyhow!(e.to_string()))?; + let old: String = package.get("path").unwrap_or_default(); + package + .set( + "path", + format!( + "{}/?.lua;{}/?/init.lua;{}", + dir.display(), + dir.display(), + old + ), + ) + .map_err(|e| anyhow::anyhow!(e.to_string()))?; + let defaults: Table = lua + .load(DEFAULT) + .eval() + .map_err(|e| anyhow::anyhow!(e.to_string()))?; + let t: Table = lua + .load(source) + .set_name("config.lua") + .eval() + .map_err(|e| anyhow::anyhow!(e.to_string()))?; + for pair in defaults.pairs::<String, mlua::Value>() { + let (key, value) = pair.map_err(|e| anyhow::anyhow!(e.to_string()))?; + if t.get::<mlua::Value>(key.as_str()) + .unwrap_or(mlua::Value::Nil) + .is_nil() + { + t.set(key, value) + .map_err(|e| anyhow::anyhow!(e.to_string()))?; + } + } + macro_rules! get { + ($key:literal) => { + t.get($key).map_err(|e| anyhow::anyhow!(e.to_string()))? + }; + } + let palette: Vec<String> = get!("palette"); + let c = Self { + font: get!("font"), + font_size: get!("font_size"), + line_height: get!("line_height"), + padding: get!("padding"), + background: color( + &t.get::<String>("background") + .map_err(|e| anyhow::anyhow!(e.to_string()))?, + )?, + foreground: color( + &t.get::<String>("foreground") + .map_err(|e| anyhow::anyhow!(e.to_string()))?, + )?, + accent: color( + &t.get::<String>("accent") + .map_err(|e| anyhow::anyhow!(e.to_string()))?, + )?, + surface: color( + &t.get::<String>("surface") + .map_err(|e| anyhow::anyhow!(e.to_string()))?, + )?, + muted: color( + &t.get::<String>("muted") + .map_err(|e| anyhow::anyhow!(e.to_string()))?, + )?, + border: color( + &t.get::<String>("border") + .map_err(|e| anyhow::anyhow!(e.to_string()))?, + )?, + show_status_bar: get!("show_status_bar"), + status_bar_toggle: get!("status_bar_toggle"), + width: get!("width"), + height: get!("height"), + scrollback: get!("scrollback"), + shell: get!("shell"), + args: get!("args"), + cwd: PathBuf::from( + t.get::<String>("cwd") + .map_err(|e| anyhow::anyhow!(e.to_string()))?, + ), + env: get!("env"), + bindings: get!("bindings"), + palette: palette.iter().map(|v| color(v)).collect::<Result<_>>()?, + startup: get!("startup"), + }; + if !(8.0..=48.0).contains(&c.font_size) + || !(c.font_size..=80.0).contains(&c.line_height) + || !(0.0..=100.0).contains(&c.padding) + || !(400.0..=4000.0).contains(&c.width) + || !(300.0..=3000.0).contains(&c.height) + || c.palette.len() != 16 + || c.scrollback > 1_000_000 + { + bail!( + "invalid font, spacing, window dimensions, scrollback, or palette (requires 16 colors)" + ); + } + Ok(c) + } +} +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn defaults_and_lua_evaluation() { + let c = Config::parse( + "return {font_size=16, accent='#abcdef', bindings={['alt-g']='echo hello\\r'}}", + std::path::Path::new("/tmp"), + ) + .unwrap(); + assert_eq!(c.font_size, 16.); + assert_eq!(c.accent, 0xabcdef); + assert_eq!(c.palette.len(), 16); + } + #[test] + fn rejects_bad_config() { + assert!(Config::parse("return {font_size=0}", std::path::Path::new("/tmp")).is_err()); + assert!(color("#ff").is_err()); + assert!(Config::parse("return {accent=false}", std::path::Path::new("/tmp")).is_err()); + assert!(Config::parse("return {palette={}}", std::path::Path::new("/tmp")).is_err()); + } +} 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 |