use crate::command::Command;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PromptKind {
NewFile,
OpenFile,
SaveAs,
SaveAsAndClose,
GoToLine,
GoToAddress,
RenameFile,
DeleteFile,
Watch,
BreakpointCondition,
SetRegister,
Search,
Replace,
ConfirmQuit,
ConfirmClose,
}
impl PromptKind {
pub const fn label(self) -> &'static str {
match self {
PromptKind::NewFile => "New file",
PromptKind::OpenFile => "Open file",
PromptKind::SaveAs => "Save as",
PromptKind::SaveAsAndClose => "Save and close as",
PromptKind::GoToLine => "Go to line",
PromptKind::GoToAddress => "Go to address",
PromptKind::RenameFile => "Rename to",
PromptKind::DeleteFile => "Delete the file? Type yes",
PromptKind::Watch => "Watch",
PromptKind::BreakpointCondition => "Stop only if",
PromptKind::SetRegister => "Set register",
PromptKind::Search => "Find",
PromptKind::Replace => "Replace with",
PromptKind::ConfirmQuit => "Unsaved changes. Quit anyway? (y/n)",
PromptKind::ConfirmClose => {
"Unsaved changes. Save and close, discard, or cancel? (s/d/c)"
}
}
}
pub const fn hint(self) -> &'static str {
match self {
PromptKind::NewFile => "path in the project, such as src/util.asm",
PromptKind::OpenFile => "path to an .asm file",
PromptKind::SaveAs => "path to write to",
PromptKind::SaveAsAndClose => "path to write to",
PromptKind::GoToLine => "line number",
PromptKind::GoToAddress => "0x4000b0, rsp-0x20, rbp+8",
PromptKind::RenameFile => "new path",
PromptKind::DeleteFile => "yes",
PromptKind::Watch => "$rax, (int)counter, *(long *)0x402000",
PromptKind::BreakpointCondition => "$rcx == 3; empty removes it",
PromptKind::SetRegister => "rax=0x10",
PromptKind::Search => "text to find",
PromptKind::Replace => "replacement text",
PromptKind::ConfirmQuit => "y or n",
PromptKind::ConfirmClose => "s, d, or c",
}
}
pub const fn is_confirmation(self) -> bool {
matches!(self, PromptKind::ConfirmQuit | PromptKind::ConfirmClose)
}
pub const fn completes_paths(self) -> bool {
matches!(
self,
PromptKind::OpenFile
| PromptKind::NewFile
| PromptKind::RenameFile
| PromptKind::SaveAs
| PromptKind::SaveAsAndClose
)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Prompt {
kind: Option<PromptKind>,
text: String,
cursor: usize,
}
impl Prompt {
pub fn new(kind: PromptKind, text: impl Into<String>) -> Self {
let text = text.into();
let cursor = text.chars().count();
Self {
kind: Some(kind),
text,
cursor,
}
}
pub fn kind(&self) -> Option<PromptKind> {
self.kind
}
pub fn text(&self) -> &str {
&self.text
}
pub fn cursor(&self) -> usize {
self.cursor
}
pub fn set_text(&mut self, text: impl Into<String>) {
self.text = text.into();
self.cursor = self.text.chars().count();
}
pub fn insert(&mut self, ch: char) {
let offset = self.byte_offset(self.cursor);
self.text.insert(offset, ch);
self.cursor += 1;
}
pub fn backspace(&mut self) {
if self.cursor == 0 {
return;
}
let offset = self.byte_offset(self.cursor - 1);
self.text.remove(offset);
self.cursor -= 1;
}
pub fn delete(&mut self) {
if self.cursor >= self.text.chars().count() {
return;
}
let offset = self.byte_offset(self.cursor);
self.text.remove(offset);
}
pub fn move_left(&mut self) {
self.cursor = self.cursor.saturating_sub(1);
}
pub fn move_right(&mut self) {
self.cursor = (self.cursor + 1).min(self.text.chars().count());
}
pub fn move_home(&mut self) {
self.cursor = 0;
}
pub fn move_end(&mut self) {
self.cursor = self.text.chars().count();
}
pub fn clear(&mut self) {
self.text.clear();
self.cursor = 0;
}
pub fn is_empty(&self) -> bool {
self.text.is_empty()
}
fn byte_offset(&self, index: usize) -> usize {
self.text
.char_indices()
.nth(index)
.map_or(self.text.len(), |(offset, _)| offset)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Palette {
prompt: Prompt,
matches: Vec<Command>,
selected: usize,
}
impl Palette {
pub fn open() -> Self {
let mut palette = Self {
prompt: Prompt::default(),
matches: Vec::new(),
selected: 0,
};
palette.refresh();
palette
}
pub fn prompt(&self) -> &Prompt {
&self.prompt
}
pub fn prompt_mut(&mut self) -> &mut Prompt {
&mut self.prompt
}
pub fn matches(&self) -> &[Command] {
&self.matches
}
pub fn selected(&self) -> usize {
self.selected
}
pub fn selected_command(&self) -> Option<&Command> {
self.matches.get(self.selected)
}
pub fn refresh(&mut self) {
let commands = Command::all();
let texts: Vec<String> = commands.iter().map(Command::search_text).collect();
let ranked =
crate::command::palette::rank(self.prompt.text(), texts.iter().map(String::as_str));
self.matches = ranked
.into_iter()
.filter_map(|(index, _)| commands.get(index).cloned())
.collect();
self.selected = 0;
}
pub fn select_next(&mut self) {
if self.matches.is_empty() {
return;
}
self.selected = (self.selected + 1) % self.matches.len();
}
pub fn select_previous(&mut self) {
if self.matches.is_empty() {
return;
}
self.selected = (self.selected + self.matches.len() - 1) % self.matches.len();
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PickerKind {
Symbols,
Search,
MakeTargets,
}
impl PickerKind {
pub const fn title(self) -> &'static str {
match self {
PickerKind::Symbols => "Go to symbol",
PickerKind::Search => "Search in files",
PickerKind::MakeTargets => "Run a make target",
}
}
pub const fn hint(self) -> &'static str {
match self {
PickerKind::Symbols => "type part of a label, constant or macro",
PickerKind::Search => "type at least two characters",
PickerKind::MakeTargets => "type to filter the targets",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PickItem {
pub label: String,
pub detail: String,
pub path: std::path::PathBuf,
pub line: usize,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Picker {
kind: PickerKind,
prompt: Prompt,
items: Vec<PickItem>,
selected: usize,
}
impl Picker {
pub fn new(kind: PickerKind) -> Self {
Self {
kind,
prompt: Prompt::default(),
items: Vec::new(),
selected: 0,
}
}
pub fn kind(&self) -> PickerKind {
self.kind
}
pub fn prompt(&self) -> &Prompt {
&self.prompt
}
pub fn prompt_mut(&mut self) -> &mut Prompt {
&mut self.prompt
}
pub fn items(&self) -> &[PickItem] {
&self.items
}
pub fn set_items(&mut self, items: Vec<PickItem>) {
self.items = items;
self.selected = 0;
}
pub fn selected(&self) -> usize {
self.selected
}
pub fn selected_item(&self) -> Option<&PickItem> {
self.items.get(self.selected)
}
pub fn select_next(&mut self) {
if !self.items.is_empty() {
self.selected = (self.selected + 1) % self.items.len();
}
}
pub fn select_previous(&mut self) {
if !self.items.is_empty() {
self.selected = (self.selected + self.items.len() - 1) % self.items.len();
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub enum Mode {
#[default]
Normal,
Palette(Palette),
Prompt(Prompt),
Picker(Picker),
}
impl Mode {
pub fn is_overlay(&self) -> bool {
!matches!(self, Mode::Normal)
}
pub fn prompt(&self) -> Option<&Prompt> {
match self {
Mode::Prompt(prompt) => Some(prompt),
Mode::Palette(palette) => Some(palette.prompt()),
Mode::Picker(picker) => Some(picker.prompt()),
Mode::Normal => None,
}
}
pub fn palette(&self) -> Option<&Palette> {
match self {
Mode::Palette(palette) => Some(palette),
_ => None,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_new_prompt_puts_the_cursor_after_the_prefilled_text() {
let prompt = Prompt::new(PromptKind::Search, "rax");
assert_eq!(prompt.text(), "rax");
assert_eq!(prompt.cursor(), 3);
}
#[test]
fn typing_inserts_at_the_cursor() {
let mut prompt = Prompt::new(PromptKind::Search, "rax");
prompt.move_home();
prompt.insert('e');
assert_eq!(prompt.text(), "erax");
assert_eq!(prompt.cursor(), 1);
}
#[test]
fn backspace_and_delete_remove_the_right_character() {
let mut prompt = Prompt::new(PromptKind::Search, "abc");
prompt.backspace();
assert_eq!(prompt.text(), "ab");
prompt.move_home();
prompt.delete();
assert_eq!(prompt.text(), "b");
}
#[test]
fn editing_at_the_edges_does_nothing_rather_than_panicking() {
let mut prompt = Prompt::default();
prompt.backspace();
prompt.delete();
prompt.move_left();
prompt.move_right();
assert!(prompt.is_empty());
assert_eq!(prompt.cursor(), 0);
}
#[test]
fn multibyte_text_is_edited_by_character_not_byte() {
let mut prompt = Prompt::new(PromptKind::Search, "ölçüm");
prompt.backspace();
assert_eq!(prompt.text(), "ölçü");
prompt.move_home();
prompt.delete();
assert_eq!(prompt.text(), "lçü");
prompt.insert('ÅŸ');
assert_eq!(prompt.text(), "şlçü");
}
#[test]
fn cursor_movement_is_clamped_to_the_text() {
let mut prompt = Prompt::new(PromptKind::Search, "ab");
for _ in 0..10 {
prompt.move_right();
}
assert_eq!(prompt.cursor(), 2);
for _ in 0..10 {
prompt.move_left();
}
assert_eq!(prompt.cursor(), 0);
}
#[test]
fn every_prompt_kind_has_a_label_and_a_hint() {
for kind in [
PromptKind::OpenFile,
PromptKind::SaveAs,
PromptKind::SaveAsAndClose,
PromptKind::GoToLine,
PromptKind::GoToAddress,
PromptKind::Search,
PromptKind::Replace,
PromptKind::ConfirmQuit,
PromptKind::ConfirmClose,
] {
assert!(!kind.label().is_empty());
assert!(!kind.hint().is_empty());
}
}
#[test]
fn destructive_prompts_are_confirmations() {
assert!(PromptKind::ConfirmQuit.is_confirmation());
assert!(PromptKind::ConfirmClose.is_confirmation());
assert!(!PromptKind::Search.is_confirmation());
}
#[test]
fn an_open_palette_lists_every_command() {
let palette = Palette::open();
assert_eq!(palette.matches().len(), Command::all().len());
assert_eq!(palette.selected(), 0);
assert!(palette.selected_command().is_some());
}
#[test]
fn typing_narrows_the_palette() {
let mut palette = Palette::open();
for ch in "step over".chars() {
palette.prompt_mut().insert(ch);
}
palette.refresh();
assert!(palette.matches().len() < Command::all().len());
assert_eq!(
palette.selected_command().map(Command::id),
Some("debug.step-over".to_owned())
);
}
#[test]
fn a_query_matching_nothing_leaves_no_selection() {
let mut palette = Palette::open();
for ch in "zzzznothing".chars() {
palette.prompt_mut().insert(ch);
}
palette.refresh();
assert!(palette.matches().is_empty());
assert!(palette.selected_command().is_none());
}
#[test]
fn selection_wraps_in_both_directions() {
let mut palette = Palette::open();
let count = palette.matches().len();
palette.select_previous();
assert_eq!(palette.selected(), count - 1, "wraps to the end");
palette.select_next();
assert_eq!(palette.selected(), 0, "wraps back to the start");
}
#[test]
fn moving_the_selection_in_an_empty_palette_does_nothing() {
let mut palette = Palette::open();
for ch in "zzzz".chars() {
palette.prompt_mut().insert(ch);
}
palette.refresh();
palette.select_next();
palette.select_previous();
assert_eq!(palette.selected(), 0);
}
#[test]
fn refreshing_resets_the_selection_to_the_best_match() {
let mut palette = Palette::open();
palette.select_next();
palette.select_next();
assert_ne!(palette.selected(), 0);
palette.prompt_mut().insert('r');
palette.refresh();
assert_eq!(palette.selected(), 0);
}
#[test]
fn the_default_mode_is_editing() {
let mode = Mode::default();
assert_eq!(mode, Mode::Normal);
assert!(!mode.is_overlay());
assert!(mode.prompt().is_none());
assert!(mode.palette().is_none());
}
#[test]
fn overlays_report_themselves_and_expose_their_prompt() {
let mode = Mode::Prompt(Prompt::new(PromptKind::GoToLine, "42"));
assert!(mode.is_overlay());
assert_eq!(mode.prompt().map(Prompt::text), Some("42"));
assert!(mode.palette().is_none());
let mode = Mode::Palette(Palette::open());
assert!(mode.is_overlay());
assert!(mode.palette().is_some());
assert!(mode.prompt().is_some(), "the palette has a query prompt");
}
}