├── .gitignore ├── .vscode └── launch.json ├── Cargo.toml ├── LICENSE ├── README.md ├── demo ├── Cargo.toml ├── Trunk.toml ├── assets │ ├── favicon.ico │ ├── icon-1024.png │ ├── icon-256.png │ ├── icon_ios_touch_192.png │ ├── manifest.json │ ├── maskable_icon_x512.png │ └── sw.js ├── index.html └── src │ ├── app.rs │ ├── clap.rs │ ├── lib.rs │ └── main.rs └── src ├── console.rs ├── lib.rs └── tab.rs /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | -------------------------------------------------------------------------------- /.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | // Use IntelliSense to learn about possible attributes. 3 | // Hover to view descriptions of existing attributes. 4 | // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 5 | "version": "0.2.0", 6 | "configurations": [ 7 | { 8 | "name": "(Windows) Launch", 9 | "type": "cppvsdbg", 10 | "request": "launch", 11 | "program": "${workspaceFolder}/target/debug/demo.exe", 12 | "args": [], 13 | "stopAtEntry": false, 14 | "cwd": "${workspaceFolder}", 15 | "environment": [], 16 | "console": "externalTerminal" 17 | } 18 | ] 19 | } -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | workspace = { members = ["demo"] } 2 | [package] 3 | name = "egui_console" 4 | version = "0.2.0" 5 | edition = "2021" 6 | exclude = [ 7 | ".vscode" 8 | ] 9 | license = "MIT" 10 | description = "A Console Window for egui" 11 | repository = "https://github.com/pm100/egui_console" 12 | readme = "README.md" 13 | keywords=["egui","widget","console"] 14 | categories=["gui"] 15 | 16 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 17 | 18 | [dependencies] 19 | 20 | eframe = "0.28.1" 21 | egui = "0.28.1" 22 | itertools = "0.13.0" 23 | 24 | serde = "1.0.204" 25 | serde_derive = "1.0.204" 26 | 27 | 28 | [features] 29 | persistence=[] 30 | 31 | 32 | 33 | 34 | 35 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2024 pm100 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # A console window for egui 2 | Provides a console window for egui. This is not a shell to the OS its simply a command shell window. Its very useful for providing a command line interface inside a GUI app. 3 | 4 | ## features 5 | - host in any container 6 | - persisted (optional) searchable history 7 | - tab completion for filesystem paths and arbitrary commands 8 | 9 | ## demo 10 | 11 | Run it with `cargo run -p demo`. Type 'help' at the command prompt. Shows integration with https://docs.rs/clap/latest/clap/ 12 | 13 | ![image](https://github.com/user-attachments/assets/de2df396-68ac-4723-ae62-2811fb81ba05) 14 | 15 | To see command completeion type 'l'. 16 | To see filesystem completion try 'cd s' 17 | 18 | ## use 19 | 20 | You need a ConsoleWindow instance in your egui App 21 | ``` 22 | pub struct ConsoleDemo { 23 | // Example stuff: 24 | label: String, 25 | #[serde(skip)] // This how you opt-out of serialization of a field 26 | value: f32, 27 | console: ConsoleWindow, 28 | } 29 | ``` 30 | 31 | And then use the builder to instantiate a ConsoleWindow 32 | 33 | ``` 34 | ConsoleBuilder::new() 35 | .prompt(">> ") 36 | .history_size(20) 37 | .tab_quote_character('\"') 38 | .build(); 39 | ``` 40 | 41 | On each ui update cycle call the draw method, passing in the Ui instance that should host the console window. Draw returns a ConsoleEvent enum, at the moment this is either None or the text of the command the user entered. 42 | ``` 43 | let console_response = self.console.draw(ui); 44 | if let ConsoleEvent::Command(command) = console_response { 45 | self.console.write(&command); 46 | self.console.prompt(); 47 | } 48 | ``` 49 | The prompt method repromts the user. The sample above simply echoes the command the user entered and then reprompts. 50 | 51 | ### command completion 52 | 53 | Tab completion for 'commands' works if the user types part of a command at the prompt; ie it must be the first thing on the line. 54 | 55 | You must supply a table of commands for tab completion to work. The console window maintains a `Vec` of commands. you can modify this table by calling the `command_table_mut` method. THis returns a mutable reference to the command table. 56 | 57 | The demo app loads this from the clap subcommands 58 | -------------------------------------------------------------------------------- /demo/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "demo" 3 | version = "0.1.0" 4 | authors = ["Emil Ernerfeldt "] 5 | edition = "2021" 6 | include = ["LICENSE-APACHE", "LICENSE-MIT", "**/*.rs", "Cargo.toml"] 7 | rust-version = "1.76" 8 | 9 | [package.metadata.docs.rs] 10 | all-features = true 11 | targets = ["x86_64-unknown-linux-gnu", "wasm32-unknown-unknown"] 12 | 13 | [dependencies] 14 | egui_console={path="..", features=["persistence"]} 15 | egui = "0.28.1" 16 | eframe = {version = "0.28.1", default-features = false, features = [ 17 | "accesskit", # Make egui compatible with screen readers. NOTE: adds a lot of dependencies. 18 | "default_fonts", # Embed the default egui fonts. 19 | "glow", # Use the glow rendering backend. Alternative: "wgpu". 20 | "persistence", # Enable restoring app state when restarting the app. 21 | ] } 22 | log = "0.4" 23 | 24 | # You only need serde if you want app persistence: 25 | serde = { version = "1", features = ["derive"] } 26 | clap = "4.5.11" 27 | anyhow = "1.0.86" 28 | shlex = "1.3.0" 29 | 30 | # native: 31 | [target.'cfg(not(target_arch = "wasm32"))'.dependencies] 32 | env_logger = "0.10" 33 | 34 | # web: 35 | [target.'cfg(target_arch = "wasm32")'.dependencies] 36 | wasm-bindgen-futures = "0.4" 37 | 38 | # to access the DOM (to hide the loading text) 39 | [target.'cfg(target_arch = "wasm32")'.dependencies.web-sys] 40 | version = "0.3.4" 41 | 42 | #[profile.release] 43 | #opt-level = 2 # fast and small wasm 44 | 45 | # Optimize all dependencies even in debug builds: 46 | #[profile.dev.package."*"] 47 | #opt-level = 2 48 | 49 | 50 | # [patch.crates-io] 51 | 52 | # If you want to use the bleeding edge version of egui and eframe: 53 | # egui = { git = "https://github.com/emilk/egui", branch = "master" } 54 | # eframe = { git = "https://github.com/emilk/egui", branch = "master" } 55 | 56 | # If you fork https://github.com/emilk/egui you can test with: 57 | # egui = { path = "../egui/crates/egui" } 58 | # eframe = { path = "../egui/crates/eframe" } 59 | [features] 60 | default=["persistence"] 61 | persistence=[] 62 | -------------------------------------------------------------------------------- /demo/Trunk.toml: -------------------------------------------------------------------------------- 1 | [build] 2 | -------------------------------------------------------------------------------- /demo/assets/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pm100/egui_console/d8311d1f9dae8cb09b5bb187b0801d929d8168bc/demo/assets/favicon.ico -------------------------------------------------------------------------------- /demo/assets/icon-1024.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pm100/egui_console/d8311d1f9dae8cb09b5bb187b0801d929d8168bc/demo/assets/icon-1024.png -------------------------------------------------------------------------------- /demo/assets/icon-256.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pm100/egui_console/d8311d1f9dae8cb09b5bb187b0801d929d8168bc/demo/assets/icon-256.png -------------------------------------------------------------------------------- /demo/assets/icon_ios_touch_192.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pm100/egui_console/d8311d1f9dae8cb09b5bb187b0801d929d8168bc/demo/assets/icon_ios_touch_192.png -------------------------------------------------------------------------------- /demo/assets/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "egui Template PWA", 3 | "short_name": "egui-template-pwa", 4 | "icons": [ 5 | { 6 | "src": "./icon-256.png", 7 | "sizes": "256x256", 8 | "type": "image/png" 9 | }, 10 | { 11 | "src": "./maskable_icon_x512.png", 12 | "sizes": "512x512", 13 | "type": "image/png", 14 | "purpose": "any maskable" 15 | }, 16 | { 17 | "src": "./icon-1024.png", 18 | "sizes": "1024x1024", 19 | "type": "image/png" 20 | } 21 | ], 22 | "lang": "en-US", 23 | "id": "/index.html", 24 | "start_url": "./index.html", 25 | "display": "standalone", 26 | "background_color": "white", 27 | "theme_color": "white" 28 | } 29 | -------------------------------------------------------------------------------- /demo/assets/maskable_icon_x512.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pm100/egui_console/d8311d1f9dae8cb09b5bb187b0801d929d8168bc/demo/assets/maskable_icon_x512.png -------------------------------------------------------------------------------- /demo/assets/sw.js: -------------------------------------------------------------------------------- 1 | var cacheName = 'egui-template-pwa'; 2 | var filesToCache = [ 3 | './', 4 | './index.html', 5 | './eframe_template.js', 6 | './eframe_template_bg.wasm', 7 | ]; 8 | 9 | /* Start the service worker and cache all of the app's content */ 10 | self.addEventListener('install', function (e) { 11 | e.waitUntil( 12 | caches.open(cacheName).then(function (cache) { 13 | return cache.addAll(filesToCache); 14 | }) 15 | ); 16 | }); 17 | 18 | /* Serve cached content when offline */ 19 | self.addEventListener('fetch', function (e) { 20 | e.respondWith( 21 | caches.match(e.request).then(function (response) { 22 | return response || fetch(e.request); 23 | }) 24 | ); 25 | }); 26 | -------------------------------------------------------------------------------- /demo/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | eframe template 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 136 | 137 | 138 | 139 | 140 | 141 | -------------------------------------------------------------------------------- /demo/src/app.rs: -------------------------------------------------------------------------------- 1 | use crate::clap::syntax; 2 | use anyhow::Result; 3 | /// We derive Deserialize/Serialize so we can persist app state on shutdown. 4 | //use egui_console::console::{ConsoleBuilder, ConsoleEvent, ConsoleWindow}; 5 | use egui_console::{ConsoleBuilder, ConsoleEvent, ConsoleWindow}; 6 | #[cfg_attr(feature = "persistence", derive(serde::Deserialize, serde::Serialize))] 7 | //#[derive(serde::Deserialize, serde::Serialize)] 8 | #[cfg_attr(feature = "persistence", serde(default))] // if we add new fields, give them default values when deserializing old state 9 | pub struct ConsoleDemo { 10 | // Example stuff: 11 | label: String, 12 | #[cfg_attr(feature = "persistence", serde(skip))] 13 | // This how you opt-out of serialization of a field 14 | value: f32, 15 | console_win: ConsoleWindow, 16 | } 17 | 18 | impl Default for ConsoleDemo { 19 | fn default() -> Self { 20 | Self { 21 | // Example stuff: 22 | label: "Hello World!".to_owned(), 23 | value: 2.7, 24 | console_win: ConsoleBuilder::new() 25 | .prompt(">> ") 26 | .history_size(20) 27 | .tab_quote_character('\"') 28 | .build(), 29 | } 30 | } 31 | } 32 | 33 | impl ConsoleDemo { 34 | /// Called once before the first frame. 35 | pub fn new(cc: &eframe::CreationContext<'_>) -> Self { 36 | // This is also where you can customize the look and feel of egui using 37 | // `cc.egui_ctx.set_visuals` and `cc.egui_ctx.set_fonts`. 38 | 39 | // Load previous app state (if any). 40 | // Note that you must enable the `persistence` feature for this to work. 41 | #[cfg(feature = "persistence")] 42 | let mut app = if let Some(storage) = cc.storage { 43 | eframe::get_value(storage, eframe::APP_KEY).unwrap_or_default() 44 | } else { 45 | Self::default() 46 | }; 47 | for cmd in syntax().get_subcommands() { 48 | app.console_win 49 | .command_table_mut() 50 | .push(cmd.get_name().to_string()); 51 | } 52 | 53 | app 54 | } 55 | } 56 | 57 | impl eframe::App for ConsoleDemo { 58 | /// Called by the frame work to save state before shutdown. 59 | fn save(&mut self, storage: &mut dyn eframe::Storage) { 60 | #[cfg(feature = "persistence")] 61 | eframe::set_value(storage, eframe::APP_KEY, self); 62 | } 63 | 64 | /// Called each time the UI needs repainting, which may be many times per second. 65 | fn update(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) { 66 | // Put your widgets into a `SidePanel`, `TopBottomPanel`, `CentralPanel`, `Window` or `Area`. 67 | // For inspiration and more examples, go to https://emilk.github.io/egui 68 | 69 | egui::TopBottomPanel::top("top_panel").show(ctx, |ui| { 70 | // The top panel is often a good place for a menu bar: 71 | 72 | egui::menu::bar(ui, |ui| { 73 | // NOTE: no File->Quit on web pages! 74 | let is_web = cfg!(target_arch = "wasm32") | true; 75 | if !is_web { 76 | ui.menu_button("File", |ui| { 77 | if ui.button("Quit").clicked() { 78 | ctx.send_viewport_cmd(egui::ViewportCommand::Close); 79 | } 80 | }); 81 | ui.add_space(16.0); 82 | } 83 | 84 | egui::widgets::global_dark_light_mode_buttons(ui); 85 | }); 86 | }); 87 | // egui::SidePanel::left("left_panel") 88 | // .resizable(true) 89 | // .default_width(150.0) 90 | // .width_range(80.0..=200.0) 91 | // .show(ctx, |ui| { 92 | // ui.vertical_centered(|ui| { 93 | // ui.heading("Left Panel"); 94 | // }); 95 | // }); 96 | egui::CentralPanel::default().show(ctx, |ui| { 97 | let mut console_response: ConsoleEvent = ConsoleEvent::None; 98 | egui::Window::new("Console Window") 99 | .default_height(500.0) 100 | .resizable(true) 101 | .show(ctx, |ui| { 102 | console_response = self.console_win.draw(ui); 103 | }); 104 | if let ConsoleEvent::Command(command) = console_response { 105 | let resp = match self.dispatch(&command, ctx) { 106 | Err(e) => { 107 | if let Some(original_error) = e.downcast_ref::() { 108 | format!("{}", original_error) 109 | } else if e.backtrace().status() 110 | == std::backtrace::BacktraceStatus::Captured 111 | { 112 | format!("{} {}", e, e.backtrace()) 113 | } else { 114 | format!("{}", e) 115 | } 116 | } 117 | 118 | Ok(string) => string, // continue 119 | }; 120 | if !resp.is_empty() { 121 | self.console_win.write(&resp); 122 | } 123 | self.console_win.prompt(); 124 | } 125 | 126 | if ui.button("click for console output").clicked() { 127 | self.console_win.write("clicked"); 128 | self.console_win.prompt(); 129 | } 130 | }); 131 | } 132 | } 133 | impl ConsoleDemo { 134 | pub fn dispatch(&mut self, line: &str, ctx: &egui::Context) -> Result { 135 | // let args = line.split_whitespace(); 136 | let args = shlex::split(line).ok_or(anyhow::anyhow!("cannot parse"))?; 137 | // parse with clap 138 | let matches = syntax().try_get_matches_from(args)?; 139 | // execute the command 140 | match matches.subcommand() { 141 | Some(("cd", args)) => { 142 | let dir = args.get_one::("directory").unwrap(); 143 | std::env::set_current_dir(dir)?; 144 | let cwd = std::env::current_dir()?; 145 | Ok(format!("Current working directory: {}", cwd.display())) 146 | } 147 | Some(("dark", _)) => { 148 | // let ctx = egui::Context::default(); 149 | ctx.set_visuals(egui::Visuals::dark()); 150 | Ok("Dark mode enabled".to_string()) 151 | } 152 | Some(("light", _)) => { 153 | // let ctx = egui::Context::default(); 154 | ctx.set_visuals(egui::Visuals::light()); 155 | Ok("Light mode enabled".to_string()) 156 | } 157 | Some(("quit", _)) => { 158 | // let ctx = egui::Context::default(); 159 | ctx.send_viewport_cmd(egui::ViewportCommand::Close); 160 | Ok("Bye".to_string()) 161 | } 162 | Some(("clear_screen", _)) => { 163 | self.console_win.clear(); 164 | Ok("".to_string()) 165 | } 166 | Some(("dir", args)) => { 167 | let filter = if let Some(filter) = args.get_one::("filter") { 168 | filter.clone() 169 | } else { 170 | "".to_string() 171 | }; 172 | let entries = std::fs::read_dir(".")?; 173 | let mut result = String::new(); 174 | for entry in entries { 175 | let entry = entry?; 176 | let path = entry.path(); 177 | if path.display().to_string().contains(filter.as_str()) { 178 | result.push_str(&format!("{}\n", path.display())); 179 | } 180 | } 181 | Ok(result) 182 | } 183 | Some(("history", _)) => { 184 | let history = self.console_win.get_history(); 185 | let mut result = String::new(); 186 | for (i, line) in history.iter().enumerate() { 187 | result.push_str(&format!("{}: {}\n", i, line)); 188 | } 189 | Ok(result) 190 | } 191 | Some(("clear_history", _)) => { 192 | self.console_win.clear_history(); 193 | Ok("".to_string()) 194 | } 195 | _ => Ok("Unknown command".to_string()), 196 | } 197 | } 198 | } 199 | -------------------------------------------------------------------------------- /demo/src/clap.rs: -------------------------------------------------------------------------------- 1 | use clap::Command; 2 | use clap::{arg, Arg}; 3 | 4 | // Clap sub command syntax defintions 5 | pub fn syntax() -> Command { 6 | // strip out usage 7 | const PARSER_TEMPLATE: &str = "\ 8 | {all-args} 9 | "; 10 | // strip out name/version 11 | const APPLET_TEMPLATE: &str = "\ 12 | {about-with-newline}\n\ 13 | {usage-heading}\n {usage}\n\ 14 | \n\ 15 | {all-args}{after-help}\ 16 | "; 17 | 18 | Command::new("xxx") 19 | .multicall(true) 20 | .arg_required_else_help(true) 21 | .subcommand_required(true) 22 | .subcommand_value_name("Command") 23 | .subcommand_help_heading("Commands") 24 | .help_template(PARSER_TEMPLATE) 25 | .subcommand( 26 | Command::new("quit") 27 | .visible_aliases(["exit", "q"]) 28 | .about("Quit demo") 29 | .help_template(APPLET_TEMPLATE), 30 | ) 31 | .subcommand( 32 | Command::new("dir") 33 | .about("Directory list of current directory") 34 | .arg(arg!([filter])) 35 | .help_template(APPLET_TEMPLATE), 36 | ) 37 | .subcommand( 38 | Command::new("dark") 39 | .about("Set dark mode") 40 | .help_template(APPLET_TEMPLATE), 41 | ) 42 | .subcommand( 43 | Command::new("light") 44 | .about("Set light mode") 45 | .help_template(APPLET_TEMPLATE), 46 | ) 47 | .subcommand( 48 | Command::new("clear_screen") 49 | .visible_aliases(["cls"]) 50 | .about("Clear the screen") 51 | .help_template(APPLET_TEMPLATE), 52 | ) 53 | .subcommand( 54 | Command::new("history") 55 | .about("dump command history") 56 | .help_template(APPLET_TEMPLATE), 57 | ) 58 | .subcommand( 59 | Command::new("clear_history") 60 | .help_template(APPLET_TEMPLATE) 61 | .visible_aliases(["clh"]), 62 | ) 63 | .subcommand( 64 | Command::new("cd") 65 | .about("change current dir") 66 | .arg(Arg::new("directory").required(true)) 67 | .arg_required_else_help(true) 68 | .help_template(APPLET_TEMPLATE), 69 | ) 70 | } 71 | -------------------------------------------------------------------------------- /demo/src/lib.rs: -------------------------------------------------------------------------------- 1 | #![warn(clippy::all, rust_2018_idioms)] 2 | #![allow(missing_docs)] 3 | 4 | mod app; 5 | pub mod clap; 6 | pub use app::ConsoleDemo; 7 | -------------------------------------------------------------------------------- /demo/src/main.rs: -------------------------------------------------------------------------------- 1 | #![warn(clippy::all, rust_2018_idioms)] 2 | #![cfg_attr(not(debug_assertions), windows_subsystem = "windows")] // hide console window on Windows in release 3 | #![allow(missing_docs)] 4 | // When compiling natively: 5 | #[cfg(not(target_arch = "wasm32"))] 6 | fn main() -> eframe::Result { 7 | env_logger::init(); // Log to stderr (if you run with `RUST_LOG=debug`). 8 | 9 | let native_options = eframe::NativeOptions { 10 | viewport: egui::ViewportBuilder::default() 11 | .with_inner_size([400.0, 300.0]) 12 | .with_min_inner_size([300.0, 220.0]) 13 | .with_icon( 14 | // NOTE: Adding an icon is optional 15 | eframe::icon_data::from_png_bytes(&include_bytes!("../assets/icon-256.png")[..]) 16 | .expect("Failed to load icon"), 17 | ), 18 | ..Default::default() 19 | }; 20 | eframe::run_native( 21 | "eframe template", 22 | native_options, 23 | Box::new(|cc| Ok(Box::new(demo::ConsoleDemo::new(cc)))), 24 | ) 25 | } 26 | 27 | // When compiling to web using trunk: 28 | #[cfg(target_arch = "wasm32")] 29 | fn main() { 30 | // Redirect `log` message to `console.log` and friends: 31 | eframe::WebLogger::init(log::LevelFilter::Debug).ok(); 32 | 33 | let web_options = eframe::WebOptions::default(); 34 | 35 | wasm_bindgen_futures::spawn_local(async { 36 | let start_result = eframe::WebRunner::new() 37 | .start( 38 | "the_canvas_id", 39 | web_options, 40 | Box::new(|cc| Ok(Box::new(demo::ConsoleDemo::new(cc)))), 41 | ) 42 | .await; 43 | 44 | // Remove the loading text and spinner: 45 | let loading_text = web_sys::window() 46 | .and_then(|w| w.document()) 47 | .and_then(|d| d.get_element_by_id("loading_text")); 48 | if let Some(loading_text) = loading_text { 49 | match start_result { 50 | Ok(_) => { 51 | loading_text.remove(); 52 | } 53 | Err(e) => { 54 | loading_text.set_inner_html( 55 | "

The app has crashed. See the developer console for details.

", 56 | ); 57 | panic!("Failed to start eframe: {e:?}"); 58 | } 59 | } 60 | } 61 | }); 62 | } 63 | -------------------------------------------------------------------------------- /src/console.rs: -------------------------------------------------------------------------------- 1 | use std::{collections::VecDeque, str::Lines, sync::atomic::AtomicU16}; 2 | 3 | use egui::{ 4 | text::CCursorRange, Align, Context, Event, EventFilter, Id, Key, Modifiers, TextEdit, Ui, 5 | }; 6 | 7 | static SEARCH_PROMPT: &str = "(reverse-i-search) :"; 8 | const SEARCH_PROMPT_SLOT_OFF: usize = 18; 9 | static INSTANCE_COUNT: AtomicU16 = AtomicU16::new(0); 10 | 11 | /// The event that was generated by the console 12 | /// 13 | /// 14 | pub enum ConsoleEvent { 15 | /// A command was entered 16 | Command(String), 17 | 18 | /// Nothing 19 | None, 20 | } 21 | /// Console Window 22 | /// 23 | /// 24 | #[derive(Debug)] 25 | #[cfg_attr(feature = "persistence", derive(serde::Serialize, serde::Deserialize))] 26 | pub struct ConsoleWindow { 27 | #[cfg_attr(feature = "persistence", serde(skip))] 28 | pub(crate) text: String, 29 | #[cfg_attr(feature = "persistence", serde(skip))] 30 | pub(crate) force_cursor_to_end: bool, 31 | history_size: usize, 32 | pub(crate) scrollback_size: usize, 33 | command_history: VecDeque, 34 | #[cfg_attr(feature = "persistence", serde(skip))] 35 | history_cursor: Option, 36 | pub(crate) prompt: String, 37 | prompt_len: usize, 38 | id: Id, 39 | save_prompt: Option, 40 | #[cfg_attr(feature = "persistence", serde(skip))] 41 | search_partial: Option, 42 | // enable running stuff after serde reload 43 | #[cfg_attr(feature = "persistence", serde(skip))] 44 | init_done: bool, 45 | 46 | // tab completion 47 | #[cfg_attr(feature = "persistence", serde(skip))] 48 | pub(crate) tab_string: String, 49 | #[cfg_attr(feature = "persistence", serde(skip))] 50 | pub(crate) tab_nth: usize, 51 | pub(crate) tab_quote: char, 52 | #[cfg_attr(feature = "persistence", serde(skip))] 53 | pub(crate) tab_quoted: bool, 54 | #[cfg_attr(feature = "persistence", serde(skip))] 55 | pub(crate) tab_offset: usize, 56 | pub(crate) tab_command_table: Vec, 57 | } 58 | 59 | impl ConsoleWindow { 60 | pub(crate) fn new(prompt: &str) -> Self { 61 | Self { 62 | text: String::new(), 63 | force_cursor_to_end: false, 64 | command_history: VecDeque::new(), 65 | history_cursor: None, 66 | history_size: 100, 67 | scrollback_size: 1000, 68 | prompt: prompt.to_string(), 69 | prompt_len: prompt.chars().count(), 70 | id: Id::new(format!( 71 | "console_text_{}", 72 | INSTANCE_COUNT.fetch_add(1, std::sync::atomic::Ordering::Relaxed) 73 | )), 74 | save_prompt: None, 75 | search_partial: None, 76 | init_done: false, 77 | 78 | tab_string: String::new(), 79 | tab_nth: 0, 80 | tab_quote: '"', 81 | tab_quoted: false, 82 | tab_offset: usize::MAX, 83 | tab_command_table: Vec::new(), 84 | } 85 | } 86 | /// Draw the console window 87 | /// # Arguments 88 | /// * `ui` - the egui Ui context 89 | /// 90 | /// # Returns 91 | /// * `ConsoleEvent` - the event that was generated by the console 92 | /// 93 | 94 | pub fn draw(&mut self, ui: &mut Ui) -> ConsoleEvent { 95 | if !self.init_done { 96 | self.init_done = true; 97 | if let Some(prompt) = &self.save_prompt { 98 | self.prompt.clone_from(prompt); 99 | self.save_prompt = None; 100 | } 101 | self.draw_prompt(); 102 | } 103 | // do we need to handle keyboard events? 104 | let msg = if ui.ctx().memory(|mem| mem.has_focus(self.id)) { 105 | self.handle_kb(ui.ctx()) 106 | } else { 107 | ConsoleEvent::None 108 | }; 109 | { 110 | let text_len = self.text.len(); 111 | self.ui(ui); 112 | 113 | // did somebody type? 114 | if self.text.len() != text_len { 115 | // yes - need to update partial search? 116 | if self.search_partial.is_some() { 117 | self.search_partial = Some(self.get_search_text().to_string()); 118 | self.prompt = SEARCH_PROMPT.to_string(); 119 | self.prompt.insert_str( 120 | SEARCH_PROMPT_SLOT_OFF + 1, 121 | self.search_partial.as_ref().unwrap(), 122 | ); 123 | self.history_cursor = None; 124 | self.history_back(); 125 | } 126 | self.tab_string.clear(); 127 | self.tab_nth = 0; 128 | } 129 | } 130 | 131 | // this is all so that we get the escape key (to exit search) 132 | let event_filter = EventFilter { 133 | escape: true, 134 | horizontal_arrows: true, 135 | vertical_arrows: true, 136 | tab: true, // we need the tab key for tab completion 137 | }; 138 | if ui.ctx().memory(|mem| mem.has_focus(self.id)) { 139 | ui.ctx() 140 | .memory_mut(|mem| mem.set_focus_lock_filter(self.id, event_filter)); 141 | } 142 | 143 | msg 144 | } 145 | /// Write a line to the console 146 | /// # Arguments 147 | /// * `data` - the string to write 148 | /// 149 | /// Note that you can call this without the user having typed anything. 150 | /// 151 | pub fn write(&mut self, data: &str) { 152 | self.text.push_str(&format!("\n{}", data)); 153 | self.truncate_scroll_back(); 154 | self.force_cursor_to_end = true; 155 | } 156 | 157 | /// Loads the history from an iterator of strings 158 | /// # Arguments 159 | /// * `history` - an iterator of strings 160 | /// 161 | /// 162 | pub fn load_history(&mut self, history: Lines<'_>) { 163 | self.command_history = history.into_iter().map(|s| s.to_string()).collect(); 164 | self.history_cursor = None; 165 | } 166 | 167 | /// Get the history of the console 168 | /// # Returns 169 | /// * `VecDeque` - the history of the console 170 | /// 171 | /// 172 | pub fn get_history(&self) -> VecDeque { 173 | self.command_history.clone() 174 | } 175 | /// Clear the history of the console 176 | /// 177 | pub fn clear_history(&mut self) { 178 | self.command_history.clear(); 179 | self.history_cursor = None; 180 | } 181 | 182 | /// Clear the console 183 | pub fn clear(&mut self) { 184 | self.text.clear(); 185 | self.force_cursor_to_end = false; 186 | } 187 | /// Prompt the user for input 188 | pub fn prompt(&mut self) { 189 | self.draw_prompt(); 190 | } 191 | /// get mut ref to tab completion table for commands 192 | pub fn command_table_mut(&mut self) -> &mut Vec { 193 | &mut self.tab_command_table 194 | } 195 | 196 | fn cursor_at_end(&self) -> CCursorRange { 197 | egui::text::CCursorRange::one(egui::text::CCursor::new(self.text.chars().count())) 198 | } 199 | fn cursor_at(&self, loc: usize) -> CCursorRange { 200 | if loc >= self.text.chars().count() { 201 | return self.cursor_at_end(); 202 | } 203 | egui::text::CCursorRange::one(egui::text::CCursor::new(loc)) 204 | } 205 | fn ui(&mut self, ui: &mut egui::Ui) { 206 | egui::ScrollArea::both().show(ui, |ui| { 207 | ui.add_sized(ui.available_size(), |ui: &mut Ui| { 208 | let widget = egui::TextEdit::multiline(&mut self.text) 209 | .font(egui::TextStyle::Monospace) 210 | .frame(false) 211 | .code_editor() 212 | .lock_focus(true) 213 | .desired_width(f32::INFINITY) 214 | .id(self.id); 215 | let output = widget.show(ui); 216 | let mut new_cursor = None; 217 | 218 | // fix up cursor position 219 | // different logic depending on normal vs search mode 220 | // scroll, mouse move etc 221 | // cursor might not be in a good location 222 | 223 | match self.search_partial { 224 | Some(_) => { 225 | if let Some(cursor) = output.state.cursor.char_range() { 226 | let last_off = self.last_line_offset(); 227 | if cursor.primary.index < (last_off + SEARCH_PROMPT_SLOT_OFF + 1) { 228 | new_cursor = 229 | Some(self.cursor_at(last_off + SEARCH_PROMPT_SLOT_OFF + 1)); 230 | } else { 231 | let search_text = self.get_search_text(); 232 | if cursor.primary.index 233 | > (last_off + SEARCH_PROMPT.len() + search_text.len()) 234 | { 235 | new_cursor = Some(self.cursor_at( 236 | last_off + SEARCH_PROMPT_SLOT_OFF + search_text.len() + 1, 237 | )); 238 | } 239 | } 240 | } 241 | } 242 | None => { 243 | if let Some(cursor) = output.state.cursor.char_range() { 244 | let last_off = self.last_line_offset(); 245 | if cursor.primary.index < last_off + self.prompt_len - 1 { 246 | new_cursor = Some(self.cursor_at_end()); 247 | } 248 | } 249 | 250 | // we need a new line (user pressed enter) 251 | if self.force_cursor_to_end { 252 | new_cursor = Some(self.cursor_at_end()); 253 | self.force_cursor_to_end = false; 254 | } 255 | } 256 | }; 257 | 258 | if new_cursor.is_some() { 259 | let text_edit_id = output.response.id; 260 | 261 | if let Some(mut state) = TextEdit::load_state(ui.ctx(), text_edit_id) { 262 | state.cursor.set_char_range(new_cursor); 263 | state.store(ui.ctx(), text_edit_id); 264 | } 265 | ui.scroll_to_cursor(Some(Align::BOTTOM)); 266 | } 267 | output.response 268 | }); 269 | }); 270 | } 271 | 272 | pub(crate) fn get_last_line(&self) -> &str { 273 | self.text 274 | .lines() 275 | .last() 276 | .unwrap_or("") 277 | .strip_prefix(&self.prompt) 278 | .unwrap_or("") 279 | } 280 | fn truncate_scroll_back(&mut self) { 281 | let line_count = self.text.lines().count(); 282 | if line_count < self.scrollback_size { 283 | return; 284 | } 285 | let mut scrollback = String::with_capacity(self.text.len()); 286 | 287 | for (i, line) in self.text.lines().enumerate() { 288 | if i > line_count - self.scrollback_size { 289 | scrollback.push_str(line); 290 | scrollback.push('\n'); 291 | } 292 | } 293 | self.text = scrollback; 294 | } 295 | fn get_search_text(&self) -> &str { 296 | let last = self.text.lines().last().unwrap_or(""); 297 | let mut iter = last.char_indices(); 298 | let (start, _) = iter.nth(SEARCH_PROMPT_SLOT_OFF + 1).unwrap_or((0, ' ')); 299 | for (end, ch) in iter { 300 | // TODO - this will fail if the search text contains ':' 301 | if ch == ':' { 302 | return &last[start..end]; 303 | } 304 | } 305 | "" 306 | } 307 | fn consume_key(ctx: &Context, modifiers: Modifiers, logical_key: Key) { 308 | ctx.input_mut(|inp| inp.consume_key(modifiers, logical_key)); 309 | } 310 | 311 | fn handle_key( 312 | &mut self, 313 | key: &Key, 314 | modifiers: Modifiers, 315 | cursor: usize, 316 | ) -> (bool, Option) { 317 | // return value is (consume_key, command) 318 | 319 | let return_value = match (modifiers, key) { 320 | (Modifiers::NONE, Key::ArrowDown) => { 321 | // down arrow only means something if we are in search mode 322 | if self.search_partial.is_some() { 323 | self.exit_search_mode() 324 | }; 325 | if let Some(mut hc) = self.history_cursor { 326 | let last = self.get_last_line(); 327 | self.text = self.text.strip_suffix(last).unwrap_or("").to_string(); 328 | if hc == self.command_history.len() - 1 { 329 | self.history_cursor = None; 330 | } else { 331 | if hc < self.command_history.len() - 1 { 332 | hc += 1; 333 | self.text.push_str(self.command_history[hc].as_str()); 334 | } 335 | self.history_cursor = Some(hc); 336 | } 337 | } 338 | (true, None) 339 | } 340 | (Modifiers::NONE, Key::ArrowUp) => { 341 | if self.command_history.is_empty() { 342 | return (true, None); 343 | } 344 | if self.search_partial.is_some() { 345 | self.exit_search_mode() 346 | }; 347 | 348 | self.history_back(); 349 | (true, None) 350 | } 351 | (Modifiers::NONE, Key::Enter) => { 352 | let last = self.get_last_line().to_string(); 353 | if self.search_partial.is_some() { 354 | self.exit_search_mode() 355 | }; 356 | if self.command_history.len() >= self.history_size { 357 | self.command_history.pop_front(); 358 | } 359 | self.command_history.push_back(last.clone()); 360 | 361 | self.force_cursor_to_end = true; 362 | self.history_cursor = None; 363 | self.truncate_scroll_back(); 364 | (true, Some(last)) 365 | } 366 | 367 | // in search mode the cursor is constrained to the inside of the 368 | // search prompt. In mormal mode the cursor is constrained to the 369 | // right of the prompt 370 | (Modifiers::NONE, Key::Delete) => { 371 | if let Some(search_partial) = &self.search_partial { 372 | let last_off = self.last_line_offset(); 373 | if cursor > (last_off + SEARCH_PROMPT.len() - 2 + search_partial.len()) { 374 | return (true, None); 375 | } 376 | } 377 | (false, None) 378 | } 379 | (Modifiers::NONE, Key::ArrowRight) => { 380 | // nothing to do in normal mode. In search mode we need to 381 | // constrain the cursor to the search prompt 382 | if let Some(search_partial) = &self.search_partial { 383 | let last_off = self.last_line_offset(); 384 | 385 | if cursor > (last_off + SEARCH_PROMPT.len() - 2 + search_partial.len()) { 386 | return (true, None); 387 | } 388 | } 389 | (false, None) 390 | } 391 | (Modifiers::NONE, Key::ArrowLeft) | (Modifiers::NONE, Key::Backspace) => { 392 | // in either mode dont allow motion (or deleting) into prompt 393 | 394 | let last_off = self.last_line_offset(); 395 | match self.search_partial { 396 | Some(_) => { 397 | if cursor < (last_off + SEARCH_PROMPT_SLOT_OFF + 2) { 398 | return (true, None); 399 | } 400 | } 401 | None => { 402 | if cursor < (last_off + self.prompt.len() + 1) { 403 | return (true, None); 404 | } 405 | } 406 | } 407 | 408 | (false, None) 409 | } 410 | (Modifiers::NONE, Key::Escape) => { 411 | if self.search_partial.is_some() { 412 | self.exit_search_mode() 413 | }; 414 | self.history_cursor = None; 415 | (true, None) 416 | } 417 | 418 | // ctrl-r reverse search history 419 | ( 420 | Modifiers { 421 | alt: false, 422 | ctrl: true, 423 | shift: false, 424 | mac_cmd: false, 425 | command: true, 426 | }, 427 | Key::R, 428 | ) => { 429 | if self.search_partial.is_none() { 430 | self.search_partial = Some(String::new()); 431 | self.enter_search_mode(); 432 | } else { 433 | self.history_back(); 434 | } 435 | (true, None) 436 | } 437 | (Modifiers::NONE, Key::Tab) => { 438 | // off to tab completion land 439 | self.tab_complete(); 440 | (true, None) 441 | } 442 | 443 | _ => (false, None), 444 | }; 445 | 446 | return_value 447 | } 448 | 449 | fn history_back(&mut self) { 450 | let hc = match self.history_cursor { 451 | Some(hc) => hc, 452 | None => self.command_history.len(), 453 | }; 454 | 455 | let mut hist_line = String::new(); 456 | for i in (0..hc).rev() { 457 | match &self.search_partial { 458 | Some(search) => { 459 | if search.is_empty() { 460 | self.history_cursor = None; 461 | break; 462 | } 463 | 464 | if self.command_history[i].contains(search) { 465 | hist_line = self.command_history[i].clone(); 466 | self.history_cursor = Some(i); 467 | break; 468 | } 469 | } 470 | None => { 471 | hist_line = self.command_history[i].clone(); 472 | self.history_cursor = Some(i); 473 | break; 474 | } 475 | } 476 | } 477 | 478 | if !hist_line.is_empty() { 479 | let last = self.get_last_line(); 480 | self.text = self.text.strip_suffix(last).unwrap_or("").to_string(); 481 | self.text.push_str(&hist_line); 482 | } 483 | } 484 | 485 | fn last_line_offset(&self) -> usize { 486 | // offset in buffer of start of last line 487 | self.text.rfind('\n').map_or(0, |off| off + 1) 488 | } 489 | fn enter_search_mode(&mut self) { 490 | self.save_prompt = Some(self.prompt.clone()); 491 | self.prompt = SEARCH_PROMPT.to_string(); 492 | self.search_partial = Some(String::new()); 493 | let last_off = self.last_line_offset(); 494 | self.text.truncate(last_off); 495 | self.draw_prompt(); 496 | self.force_cursor_to_end = true; 497 | } 498 | fn exit_search_mode(&mut self) { 499 | self.prompt = self.save_prompt.take().unwrap(); 500 | 501 | let last_off = self.last_line_offset(); 502 | self.text.truncate(last_off); 503 | self.draw_prompt(); 504 | self.search_partial = None; 505 | self.force_cursor_to_end = true; 506 | } 507 | fn draw_prompt(&mut self) { 508 | if !self.text.is_empty() && !self.text.ends_with('\n') { 509 | self.text.push('\n'); 510 | } 511 | self.text.push_str(&self.prompt); 512 | } 513 | 514 | fn handle_kb(&mut self, ctx: &egui::Context) -> ConsoleEvent { 515 | // process all the key events in the queue 516 | // if they are meaningful to the console then use them and consume them 517 | // otherwise pass along to the textedit widget 518 | 519 | // current cursor position 520 | 521 | let cursor = if let Some(state) = egui::TextEdit::load_state(ctx, self.id) { 522 | state.cursor.char_range().unwrap().primary.index 523 | } else { 524 | 0 525 | }; 526 | 527 | // a list of keys to consume 528 | 529 | let mut kill_list = vec![]; 530 | let mut command = None; 531 | ctx.input(|input| { 532 | for event in &input.events { 533 | if let Event::Key { 534 | key, 535 | physical_key: _, 536 | pressed, 537 | modifiers, 538 | repeat: _, 539 | } = event 540 | { 541 | if *pressed { 542 | let (kill, msg) = self.handle_key(key, *modifiers, cursor); 543 | if kill { 544 | kill_list.push((*modifiers, *key)); 545 | } 546 | command = msg; 547 | // if the user pressed enter we are done 548 | if command.is_some() { 549 | break; 550 | } 551 | } 552 | } 553 | } 554 | }); 555 | 556 | // consume the keys we used 557 | for (modifiers, key) in kill_list { 558 | Self::consume_key(ctx, modifiers, key); 559 | } 560 | 561 | if let Some(command) = command { 562 | return ConsoleEvent::Command(command); 563 | } 564 | ConsoleEvent::None 565 | } 566 | } 567 | /// A builder for the console window 568 | /// 569 | pub struct ConsoleBuilder { 570 | prompt: String, 571 | history_size: usize, 572 | scrollback_size: usize, 573 | tab_quote_character: char, 574 | } 575 | 576 | impl Default for ConsoleBuilder { 577 | fn default() -> Self { 578 | Self::new() 579 | } 580 | } 581 | 582 | impl ConsoleBuilder { 583 | /// Create a new console builder 584 | /// # Returns 585 | /// * `ConsoleBuilder` - the console builder 586 | /// 587 | pub fn new() -> Self { 588 | Self { 589 | prompt: ">> ".to_string(), 590 | history_size: 100, 591 | scrollback_size: 1000, 592 | tab_quote_character: '\'', 593 | } 594 | } 595 | /// Set the prompt for the console 596 | /// # Arguments 597 | /// * `prompt` - the prompt string 598 | /// 599 | /// # Returns 600 | /// * `ConsoleBuilder` - the console builder 601 | /// 602 | pub fn prompt(mut self, prompt: &str) -> Self { 603 | self.prompt = prompt.to_string(); 604 | self 605 | } 606 | /// Set the history size for the console 607 | /// # Arguments 608 | /// * `size` - the size of the history 609 | /// 610 | /// # Returns 611 | /// * `ConsoleBuilder` - the console builder 612 | /// 613 | pub fn history_size(mut self, size: usize) -> Self { 614 | self.history_size = size; 615 | self 616 | } 617 | /// Set the scrollback size for the console 618 | /// # Arguments 619 | /// * `size` - the size of the scrollback 620 | /// 621 | /// # Returns 622 | /// * `ConsoleBuilder` - the console builder 623 | /// 624 | pub fn scrollback_size(mut self, size: usize) -> Self { 625 | self.scrollback_size = size; 626 | self 627 | } 628 | 629 | /// Set the character used to quote tab completed 630 | /// path containing spaces 631 | /// # Arguments 632 | /// * `quote` - character to use 633 | /// 634 | /// # Returns 635 | /// * `ConsoleBuilder` - the console builder 636 | /// 637 | pub fn tab_quote_character(mut self, quote: char) -> Self { 638 | self.tab_quote_character = quote; 639 | self 640 | } 641 | /// Build the console window 642 | /// # Returns 643 | /// * `ConsoleWindow` - the console window 644 | /// 645 | /// 646 | pub fn build(self) -> ConsoleWindow { 647 | let mut cons = ConsoleWindow::new(&self.prompt); 648 | cons.history_size = self.history_size; 649 | cons.scrollback_size = self.scrollback_size; 650 | cons.tab_quote = self.tab_quote_character; 651 | cons 652 | } 653 | } 654 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | /// A console window for egui / eframe applications 2 | /// 3 | /// [Egui / eframe ]: 4 | /// 5 | /// # Example 6 | /// 7 | /// You need a [`ConsoleWindow`] instance in your egui App 8 | /// ```ignore 9 | ///pub struct ConsoleDemo { 10 | /// ... 11 | /// console: ConsoleWindow, 12 | ///} 13 | /// ``` 14 | /// Then in the construction phase use [`ConsoleBuilder`] to create a new ConsoleWindow 15 | /// ```ignore 16 | /// impl Default for ConsoleDemo { 17 | /// fn default() -> Self { 18 | /// Self { 19 | /// ... 20 | /// console: ConsoleBuilder::new().prompt(">> ").history_size(20).build() 21 | /// } 22 | /// } 23 | /// } 24 | /// ``` 25 | /// 26 | /// Now in the egui update callback you must [`ConsoleWindow::draw`] the console in a host container, typically an egui Window 27 | /// 28 | /// ```ignore 29 | /// let mut console_response: ConsoleEvent = ConsoleEvent::None; 30 | /// egui::Window::new("Console Window") 31 | /// .default_height(500.0) 32 | /// .resizable(true) 33 | /// .show(ctx, |ui| { 34 | /// console_response = self.console.draw(ui); 35 | /// }); 36 | ///``` 37 | /// 38 | /// The draw method returns a [`ConsoleEvent`] that you can use to respond to user input. If the user entered a command then you can hndle that command as you like. 39 | /// The code here simply echos the command back to the user and reissues the prompt. 40 | /// 41 | ///```ignore 42 | /// if let ConsoleEvent::Command(command) = console_response { 43 | /// self.console.print(format!("You entered: {}", command)); 44 | /// self.console.prompt(); 45 | /// } 46 | /// 47 | ///``` 48 | /// 49 | /// 50 | ///# Command history 51 | /// 52 | /// - ctrl-r searches the command history 53 | /// - up and down arrow walk though the command history 54 | /// 55 | /// If you want the command history to be automatically persisted you need to enable the persistence feature. This will use the eframe storage to save the command history between sessions. 56 | /// 57 | /// Alternatively you can use [`ConsoleWindow::load_history`] and [`ConsoleWindow::get_history`] to manually save and load the command history. 58 | #[warn(missing_docs)] 59 | pub mod console; 60 | mod tab; 61 | pub use crate::console::ConsoleBuilder; 62 | pub use crate::console::ConsoleEvent; 63 | pub use crate::console::ConsoleWindow; 64 | -------------------------------------------------------------------------------- /src/tab.rs: -------------------------------------------------------------------------------- 1 | use std::path::PathBuf; 2 | 3 | use itertools::Itertools; 4 | 5 | use crate::ConsoleWindow; 6 | 7 | impl ConsoleWindow { 8 | pub(crate) fn tab_complete(&mut self) { 9 | let last = self.get_last_line().to_string(); 10 | 11 | let args = ConsoleWindow::digest_line(&last); 12 | if args.is_empty() { 13 | return; 14 | } 15 | let last_arg = &args[args.len() - 1]; 16 | let is_command_arg = args.len() == 1; 17 | let mut quote_char = self.tab_quote; 18 | if self.tab_string.is_empty() { 19 | // means we are entering tab search mode 20 | 21 | // the main fiddling here is for path with spaces in them on mac and windows 22 | // the user can enter a partial path with quotes, which we have to strip before passing to the 23 | // fs tabber and reinstate after an answer comes back 24 | // else if we get a path with spaces in it from the fs tabber we have to add quotes 25 | 26 | self.tab_quoted = false; 27 | 28 | if last_arg.is_empty() { 29 | return; 30 | } 31 | 32 | if &last_arg[0..1] == "\'" || &last_arg[0..1] == "\"" { 33 | self.tab_string = last_arg[1..].to_string(); 34 | quote_char = last_arg.chars().next().unwrap(); 35 | } else { 36 | self.tab_string = last_arg.to_string() 37 | }; 38 | self.tab_nth = 0; 39 | self.tab_offset = self.text.len() - last_arg.len(); 40 | } else { 41 | // otherwise move to the next match 42 | self.tab_nth += 1; 43 | } 44 | // the loop gets us back to the first match once fs tabber returns no match 45 | loop { 46 | if let Some(mut path) = if is_command_arg { 47 | cmd_tab_complete(&self.tab_string, self.tab_nth, &self.tab_command_table) 48 | } else { 49 | fs_tab_complete(&self.tab_string, self.tab_nth) 50 | } { 51 | let mut added_quotes = false; 52 | 53 | if path.display().to_string().contains(' ') { 54 | path = PathBuf::from(format!("{}{}{}", quote_char, path.display(), quote_char)); 55 | added_quotes = true; 56 | } 57 | 58 | self.text.truncate(self.tab_offset); 59 | self.force_cursor_to_end = true; 60 | self.text.push_str(path.to_str().unwrap()); 61 | 62 | self.tab_quoted = added_quotes; 63 | break; 64 | } else { 65 | // exit if there were no matches at all 66 | if self.tab_nth == 0 { 67 | break; 68 | } 69 | // force wrap around to first match 70 | self.tab_nth = 0; 71 | } 72 | } 73 | } 74 | // chop up input line input arguments honoring quotes 75 | 76 | fn digest_line(line: &str) -> Vec<&str> { 77 | enum State { 78 | InQuotes(char), 79 | InWhite, 80 | InWord, 81 | NotSure, 82 | } 83 | 84 | let mut state = State::InWord; 85 | 86 | let mut res: Vec<&str> = Vec::new(); 87 | let mut start = 0; 88 | 89 | for (idx, ch) in line.char_indices() { 90 | match state { 91 | State::InWord => match ch { 92 | ' ' => { 93 | res.push(&line[start..idx]); 94 | state = State::InWhite; 95 | } 96 | '"' | '\'' => { 97 | state = State::InQuotes(ch); 98 | start = idx; 99 | } 100 | _ => {} 101 | }, 102 | State::InWhite => match ch { 103 | ' ' => {} 104 | '"' | '\'' => { 105 | state = State::InQuotes(ch); 106 | start = idx; 107 | } 108 | _ => { 109 | start = idx; 110 | state = State::InWord; 111 | } 112 | }, 113 | State::InQuotes(qc) => { 114 | if ch == qc { 115 | res.push(&line[start..idx + 1]); 116 | state = State::NotSure; 117 | start = idx; 118 | } 119 | } 120 | State::NotSure => { 121 | if ch == ' ' { 122 | state = State::InWhite; 123 | } else { 124 | state = State::InWord; 125 | } 126 | start = idx; 127 | } 128 | } 129 | } 130 | 131 | match state { 132 | State::InWord => res.push(&line[start..]), 133 | State::InWhite => res.push(""), 134 | State::InQuotes(_) => res.push(&line[start..]), 135 | State::NotSure => {} 136 | } 137 | 138 | res 139 | } 140 | } 141 | pub(crate) fn cmd_tab_complete(search: &str, nth: usize, commands: &[String]) -> Option { 142 | commands 143 | .iter() 144 | .filter(|c| c.starts_with(search)) 145 | .nth(nth) 146 | .map(PathBuf::from) 147 | //None 148 | } 149 | // return the nth matching path, or None if there isnt one 150 | pub(crate) fn fs_tab_complete(search: &str, nth: usize) -> Option { 151 | let dot_slash = if cfg!(target_os = "windows") && search.find('\\').is_some() { 152 | ".\\" 153 | } else { 154 | "./" 155 | }; 156 | let search_path = PathBuf::from(search); 157 | 158 | let mut nth = nth; 159 | let mut added_dot = false; 160 | 161 | // were we given a real path to start with? 162 | 163 | let mut base_search = if search_path.is_dir() { 164 | search_path 165 | } else { 166 | // no - look at the parent (ie we got "cd dir/f") 167 | let parent = search_path.parent(); 168 | if parent.is_none() { 169 | return None; 170 | } else { 171 | let p = parent.unwrap().to_path_buf(); 172 | // if empty parent then search "." (remember we added the dot so remove it later) 173 | if p.display().to_string().is_empty() { 174 | added_dot = true; 175 | PathBuf::from(dot_slash) 176 | } else if p.display().to_string() == "." { 177 | // we were given . as a dir 178 | PathBuf::from(dot_slash) 179 | } else { 180 | p 181 | } 182 | } 183 | }; 184 | // convert .. to ../ or ..\ 185 | if base_search.display().to_string() == ".." { 186 | base_search = PathBuf::from(format!(".{}", dot_slash)); 187 | } 188 | 189 | let dir = std::fs::read_dir(&base_search); 190 | 191 | if let Ok(entries) = dir { 192 | // deal with platform oddities, also unwrap everything 193 | 194 | // mac retruns things in random order - so sort 195 | #[cfg(target_os = "macos")] 196 | let entries = entries 197 | .filter(|e| e.is_ok()) 198 | .map(|e| e.unwrap()) 199 | .sorted_by(|a, b| Ord::cmp(&a.file_name(), &b.file_name())); 200 | 201 | // windows returns things in ascii case sensitive order 202 | // this is a surprise to windows users 203 | #[cfg(target_os = "windows")] 204 | let entries = entries 205 | .filter(|e| e.is_ok()) 206 | .map(|e| e.unwrap()) 207 | .sorted_by(|a, b| { 208 | Ord::cmp( 209 | &a.file_name().to_ascii_lowercase(), 210 | &b.file_name().to_ascii_lowercase(), 211 | ) 212 | }); 213 | 214 | // linux is well behaved! 215 | #[cfg(target_os = "linux")] 216 | let entries = entries.filter(|e| e.is_ok()).map(|e| e.unwrap()); 217 | 218 | for ent in entries { 219 | let mut ret_path = ent.path(); 220 | if added_dot { 221 | ret_path = ret_path.strip_prefix(dot_slash).ok()?.to_path_buf(); 222 | } 223 | #[cfg(target_os = "windows")] 224 | if ret_path 225 | .display() 226 | .to_string() 227 | .to_ascii_lowercase() 228 | .starts_with(search) 229 | { 230 | if nth == 0 { 231 | return Some(ret_path); 232 | } else { 233 | nth -= 1; 234 | } 235 | } 236 | #[cfg(not(target_os = "windows"))] 237 | if ret_path.display().to_string().starts_with(search) { 238 | if nth == 0 { 239 | return Some(ret_path); 240 | } else { 241 | nth -= 1; 242 | } 243 | } 244 | } 245 | } 246 | None 247 | } 248 | #[test] 249 | fn test_digest_line() { 250 | let mut console = ConsoleWindow::new(">> "); 251 | let result = console.digest_line("cd foo"); 252 | assert_eq!(result, vec!["cd", "foo"]); 253 | let result = console.digest_line("cd \"foo bar\""); 254 | assert_eq!(result, vec!["cd", "\"foo bar\""]); 255 | let result = console.digest_line("cd \"foo bar"); 256 | assert_eq!(result, vec!["cd", "\"foo", "bar"]); 257 | let result = console.digest_line("cd foo bar\""); 258 | assert_eq!(result, vec!["cd", "foo", "bar\""]); 259 | let result = console.digest_line("\"cd foo bar\""); 260 | assert_eq!(result, vec!["\"cd", "foo", "bar\""]); 261 | let result = console.digest_line("cd\" foo bar\""); 262 | assert_eq!(result, vec!["cd\"", "foo", "bar\""]); 263 | } 264 | #[test] 265 | fn test_digest_line2() { 266 | // let mut console = ConsoleWindow::new(">> "); 267 | let result = ConsoleWindow::digest_line("cd foo"); 268 | assert_eq!(result, vec!["cd", "foo"]); 269 | let result = ConsoleWindow::digest_line("cd foo "); 270 | assert_eq!(result, vec!["cd", "foo", ""]); 271 | let result = ConsoleWindow::digest_line("cd \"foo bar\""); 272 | assert_eq!(result, vec!["cd", "\"foo bar\""]); 273 | let result = ConsoleWindow::digest_line("cd \"foo bar"); 274 | assert_eq!(result, vec!["cd", "\"foo bar"]); 275 | // let result = console.digest_line("cd foo bar\""); 276 | // assert_eq!(result, vec!["cd", "foo", "bar\""]); 277 | // let result = console.digest_line("\"cd foo bar\""); 278 | // assert_eq!(result, vec!["\"cd", "foo", "bar\""]); 279 | // let result = console.digest_line("cd\" foo bar\""); 280 | // assert_eq!(result, vec!["cd\"", "foo", "bar\""]); 281 | } 282 | --------------------------------------------------------------------------------