1use std::path::{Path, PathBuf};
4
5use crate::assembler::{BuildOutcome, Diagnostic};
6use crate::command::Command;
7use crate::config::{Keymap, Settings};
8use crate::debugger::breakpoints::{BreakpointSet, Location};
9use crate::debugger::memory::MemoryBlock;
10use crate::debugger::registers::{Format, RegisterFile};
11use crate::debugger::state::{DebuggerState, StateMachine, Transition};
12use crate::disassembler::{DisassemblyLine, Syntax};
13use crate::editor::{Movement, Position, Range, SelectionMode, SymbolKind, Workspace};
14use crate::instruction::Database as InstructionDatabase;
15use crate::process::ProcessOutput;
16use crate::project::Project;
17use crate::syscall::Database as SyscallDatabase;
18use crate::ui::Theme;
19
20use super::mode::{Mode, Palette, PickItem, Picker, PickerKind, Prompt, PromptKind};
21use super::page::Page;
22use super::panel::Panel;
23use super::scroll::ScrollState;
24use super::terminal::TerminalScreen;
25
26fn watch_expression(text: &str) -> String {
27 let text = text.trim();
28 let register = text.to_ascii_lowercase();
29 if crate::instruction::registers::is_register(®ister) {
30 format!("${register}")
31 } else {
32 text.to_owned()
33 }
34}
35
36#[derive(Debug, Clone, PartialEq, Eq)]
38pub enum Effect {
39 None,
41 Quit,
43 Build {
45 debug: bool,
47 },
48 Run,
50 StopProgram,
52 DebugStart,
54 DebugContinue,
56 DebugInterrupt,
58 DebugStop,
60 Step(StepKind),
62 SyncBreakpoints,
64 ReadMemory(u64),
66 SaveFile(PathBuf),
68 SaveAndClose(PathBuf),
70 SaveAll,
72 SaveProject,
74 OpenFile(PathBuf),
76 RunScratchpad,
78 Make(String),
80 CreateFile(PathBuf),
82 RenameFile {
84 from: PathBuf,
86 to: PathBuf,
88 },
89 DeleteFile(PathBuf),
91 SetRegister(String),
93 SetSystemClipboard(String),
95}
96
97#[derive(Debug, Clone, Copy, PartialEq, Eq)]
99pub enum StepKind {
100 Instruction,
102 Over,
104 Line,
106 Out,
108 Back,
110 BackOver,
112 ReverseContinue,
114}
115
116#[derive(Debug, Clone, Copy, PartialEq, Eq)]
118pub enum Severity {
119 Info,
121 Warning,
123 Error,
125 Success,
127}
128
129#[derive(Debug, Clone, PartialEq, Eq)]
131pub struct Status {
132 pub text: String,
134 pub severity: Severity,
136}
137
138impl Status {
139 pub fn info(text: impl Into<String>) -> Self {
141 Self {
142 text: text.into(),
143 severity: Severity::Info,
144 }
145 }
146
147 pub fn success(text: impl Into<String>) -> Self {
149 Self {
150 text: text.into(),
151 severity: Severity::Success,
152 }
153 }
154
155 pub fn warning(text: impl Into<String>) -> Self {
157 Self {
158 text: text.into(),
159 severity: Severity::Warning,
160 }
161 }
162
163 pub fn error(text: impl Into<String>) -> Self {
165 Self {
166 text: text.into(),
167 severity: Severity::Error,
168 }
169 }
170}
171
172impl Default for Status {
173 fn default() -> Self {
174 Status::info("Ready. Ctrl+P for commands, F6 to build, F5 to run.")
175 }
176}
177
178pub struct App {
180 pub workspace: Workspace,
182 pub project: Project,
184 pub settings: Settings,
186 pub keymap: Keymap,
188 pub theme: Theme,
190 pub page: Page,
192 pub focus: Panel,
194 pub scroll: ScrollState,
196 pub project_files: Vec<PathBuf>,
198 pub explorer_selected: usize,
200 pub mode: Mode,
202 pub status: Status,
204
205 pub debugger: StateMachine,
207 pub registers: RegisterFile,
209 pub breakpoints: BreakpointSet,
211 pub memory: MemoryBlock,
213 pub memory_address: Option<u64>,
215 pub stack: MemoryBlock,
217 pub recording: bool,
219 pub at_exit: bool,
221 pub frames: Vec<crate::debugger::frames::Frame>,
223 pub frame_selected: usize,
225 pub disassembly: Vec<DisassemblyLine>,
227 pub current_address: Option<u64>,
229 pub current_line: Option<(PathBuf, usize)>,
231
232 pub build: Option<BuildOutcome>,
234 pub last_run: Option<ProcessOutput>,
236 pub output: Vec<String>,
238 pub terminal: Option<TerminalScreen>,
240 pub diagnostics: Vec<Diagnostic>,
242
243 pub register_format: Format,
245 pub disassembly_syntax: Syntax,
247 pub ide_page: Page,
249 pub scratchpad: crate::scratchpad::Scratchpad,
251 pub scratchpad_result: Option<Result<crate::scratchpad::Outcome, String>>,
253 pub learning: crate::learning::Progress,
255 pub clipboard: String,
257
258 pub instructions: InstructionDatabase,
260 pub syscalls: SyscallDatabase,
262 pub syscall_query: String,
264 pub syscall_selected: usize,
266 pub breakpoint_selected: usize,
268
269 pub search_query: String,
271 pending_prompt: Option<PromptKind>,
273 pub should_quit: bool,
275}
276
277impl App {
278 pub fn new(project: Project, settings: Settings) -> Result<Self, serde_json::Error> {
280 let (keymap, _) = settings.keymap();
281 let theme = settings.theme();
282
283 Ok(Self {
284 workspace: Workspace::new(),
285 project,
286 keymap,
287 theme,
288 page: Page::default(),
289 focus: Page::default().default_panel(),
290 scroll: ScrollState::default(),
291 project_files: Vec::new(),
292 explorer_selected: 0,
293 mode: Mode::default(),
294 status: Status::default(),
295
296 debugger: StateMachine::new(),
297 registers: RegisterFile::new(),
298 breakpoints: BreakpointSet::new(),
299 memory: MemoryBlock::default(),
300 memory_address: None,
301 stack: MemoryBlock::default(),
302 recording: false,
303 at_exit: false,
304 frames: Vec::new(),
305 frame_selected: 0,
306 disassembly: Vec::new(),
307 current_address: None,
308 current_line: None,
309
310 build: None,
311 last_run: None,
312 output: Vec::new(),
313 terminal: None,
314 diagnostics: Vec::new(),
315
316 register_format: Format::default(),
317 disassembly_syntax: Syntax::default(),
318 ide_page: Page::Code,
319 scratchpad: crate::scratchpad::Scratchpad::new(),
320 scratchpad_result: None,
321 learning: crate::learning::Progress::new(),
322 clipboard: String::new(),
323
324 instructions: InstructionDatabase::load()?,
325 syscalls: SyscallDatabase::load()?,
326 syscall_query: String::new(),
327 syscall_selected: 0,
328 breakpoint_selected: 0,
329
330 search_query: String::new(),
331 pending_prompt: None,
332 should_quit: false,
333 settings,
334 })
335 }
336
337 pub fn open_page(&mut self, page: Page) {
339 if self.page == page {
340 return;
341 }
342 if page.is_study() && !self.page.is_study() {
343 self.ide_page = self.page;
344 }
345 self.page = page;
346 self.focus = page.default_panel();
347 }
348
349 pub fn focus_panel(&mut self, panel: Panel) {
351 if !self.page.contains(panel) {
352 let page = Page::for_panel(panel);
353 if page.is_study() && !self.page.is_study() {
354 self.ide_page = self.page;
355 }
356 self.page = page;
357 }
358 self.focus = panel;
359 }
360
361 fn copy(&mut self, remove: bool) -> Effect {
363 let document = self.workspace.active_mut();
364 let selected = document.has_selection();
365
366 let text = if selected {
367 document.selected_text()
368 } else {
369 let line = document.cursor().line;
370 format!("{}\n", document.buffer().line_or_empty(line))
371 };
372
373 if text.trim().is_empty() && !selected {
374 self.status = Status::info("The line is empty");
375 return Effect::None;
376 }
377
378 if remove && !document.delete_selection() {
379 let line = document.cursor().line;
380 let buffer = document.buffer();
381 let end = if line + 1 < buffer.line_count() {
382 Position::new(line + 1, 0)
383 } else {
384 Position::new(line, buffer.line_len(line))
385 };
386 document.replace_range(Range::new(Position::new(line, 0), end), "");
387 }
388
389 self.clipboard = text.clone();
390 self.status = Status::info(format!(
391 "{} {}",
392 if remove { "Cut" } else { "Copied" },
393 describe(&text)
394 ));
395 Effect::SetSystemClipboard(text)
396 }
397
398 pub fn apply(&mut self, command: &Command) -> Effect {
400 match command {
401 Command::NewFile => self.open_prompt(PromptKind::NewFile),
402 Command::OpenFile => self.open_prompt(PromptKind::OpenFile),
403 Command::SaveFile => match self.workspace.active().path() {
404 Some(path) => Effect::SaveFile(path.to_path_buf()),
405 None => self.open_prompt(PromptKind::SaveAs),
406 },
407 Command::SaveFileAs => self.open_prompt(PromptKind::SaveAs),
408 Command::SaveAll => Effect::SaveAll,
409 Command::AddToProject => self.add_active_to_project(),
410 Command::CloseFile => {
411 if self.workspace.active().is_modified() {
412 self.open_prompt(PromptKind::ConfirmClose)
413 } else {
414 self.close_active_document();
415 Effect::None
416 }
417 }
418 Command::Quit => {
419 if self.workspace.has_unsaved_changes() {
420 self.mode = Mode::Prompt(Prompt::new(PromptKind::ConfirmQuit, ""));
421 self.pending_prompt = Some(PromptKind::ConfirmQuit);
422 Effect::None
423 } else {
424 self.should_quit = true;
425 Effect::Quit
426 }
427 }
428
429 Command::Undo => {
430 if !self.workspace.active_mut().undo() {
431 self.status = Status::info("Nothing to undo");
432 }
433 Effect::None
434 }
435 Command::Redo => {
436 if !self.workspace.active_mut().redo() {
437 self.status = Status::info("Nothing to redo");
438 }
439 Effect::None
440 }
441 Command::SelectAll => {
442 self.workspace.active_mut().select_all();
443 Effect::None
444 }
445 Command::Indent => {
446 self.workspace.active_mut().indent();
447 Effect::None
448 }
449 Command::Dedent => {
450 self.workspace.active_mut().dedent();
451 Effect::None
452 }
453 Command::Copy => self.copy(false),
454 Command::Cut => self.copy(true),
455 Command::Paste => {
456 if self.clipboard.is_empty() {
457 self.status = Status::info("Nothing has been copied yet");
458 return Effect::None;
459 }
460 let text = self.clipboard.clone();
461 self.workspace.active_mut().insert(&text);
462 self.status = Status::info(format!("Pasted {}", describe(&text)));
463 Effect::None
464 }
465
466 Command::GoToPage(page) if page.within(self.page) == self.page => {
467 self.focus = self.page.next_panel(self.focus);
468 Effect::None
469 }
470 Command::GoToPage(page) => {
471 self.open_page(page.within(self.page));
472 Effect::None
473 }
474 Command::NextPage => {
475 self.open_page(self.page.next());
476 Effect::None
477 }
478 Command::PreviousPage => {
479 self.open_page(self.page.previous());
480 Effect::None
481 }
482 Command::NextPanel => {
483 self.focus = self.page.next_panel(self.focus);
484 Effect::None
485 }
486 Command::PreviousPanel => {
487 self.focus = self.page.previous_panel(self.focus);
488 Effect::None
489 }
490 Command::FocusPanel(panel) => {
491 self.focus_panel(*panel);
492 Effect::None
493 }
494 Command::NextDocument => {
495 self.workspace.next_document();
496 Effect::None
497 }
498 Command::ScrollUp => self.scroll_focused(-(crate::app::scroll::STEP as isize)),
499 Command::ScrollDown => self.scroll_focused(crate::app::scroll::STEP as isize),
500 Command::ScrollPageUp => {
501 self.scroll.page(self.focus, false);
502 Effect::None
503 }
504 Command::ScrollPageDown => {
505 self.scroll.page(self.focus, true);
506 Effect::None
507 }
508 Command::ScrollToTop => {
509 self.scroll.to_start(self.focus);
510 Effect::None
511 }
512 Command::ScrollToEnd => {
513 self.scroll.to_end(self.focus);
514 Effect::None
515 }
516 Command::PreviousDocument => {
517 self.workspace.previous_document();
518 Effect::None
519 }
520 Command::GoToLine => self.open_prompt(PromptKind::GoToLine),
521 Command::GoToAddress => self.open_prompt(PromptKind::GoToAddress),
522 Command::GoToSymbol => self.open_picker(PickerKind::Symbols),
523 Command::SearchFiles => self.open_picker(PickerKind::Search),
524 Command::RenameFile => match self.workspace.active().path() {
525 Some(path) => {
526 let text = crate::editor::workspace::display_path(path);
527 self.open_prompt(PromptKind::RenameFile);
528 if let Mode::Prompt(prompt) = &mut self.mode {
529 prompt.set_text(text);
530 }
531 Effect::None
532 }
533 None => {
534 self.status = Status::warning("The buffer has no file to rename");
535 Effect::None
536 }
537 },
538 Command::DeleteFile => {
539 if self.workspace.active().path().is_none() {
540 self.status = Status::warning("The buffer has no file to delete");
541 return Effect::None;
542 }
543 self.open_prompt(PromptKind::DeleteFile)
544 }
545 Command::GoToDefinition => {
546 self.go_to_definition();
547 Effect::None
548 }
549 Command::GoToFirstError => {
550 self.go_to_first_error();
551 Effect::None
552 }
553
554 Command::Search => self.open_prompt(PromptKind::Search),
555 Command::Replace => self.open_prompt(PromptKind::Replace),
556 Command::SearchNext => {
557 self.find(true);
558 Effect::None
559 }
560 Command::SearchPrevious => {
561 self.find(false);
562 Effect::None
563 }
564
565 Command::Build => self.start_build(false),
566 Command::BuildWithDebugInfo => self.start_build(true),
567 Command::Run => {
568 if self.debugger.state() == DebuggerState::Paused {
569 return self.apply(&Command::DebugContinue);
570 }
571 Effect::Run
572 }
573 Command::Stop => Effect::StopProgram,
574 Command::MakeTarget => {
575 if crate::assembler::make::makefile(&self.project).is_none() {
576 self.status = Status::warning("This project has no Makefile");
577 return Effect::None;
578 }
579 self.open_picker(PickerKind::MakeTargets)
580 }
581
582 Command::DebugStart => {
583 if self.debugger.state().can_launch() || self.debugger.state().can_build() {
584 self.open_page(Page::Debug);
585 Effect::DebugStart
586 } else {
587 self.status = Status::warning(format!(
588 "Cannot start a session while {}",
589 self.debugger.state()
590 ));
591 Effect::None
592 }
593 }
594 Command::DebugContinue => self.require_paused(Effect::DebugContinue),
595 Command::DebugInterrupt => {
596 if self.debugger.state().can_interrupt() {
597 Effect::DebugInterrupt
598 } else {
599 self.status = Status::warning("The program is not running");
600 Effect::None
601 }
602 }
603 Command::StepInstruction => self.require_paused(Effect::Step(StepKind::Instruction)),
604 Command::StepOver => self.require_paused(Effect::Step(StepKind::Over)),
605 Command::StepLine => self.require_paused(Effect::Step(StepKind::Line)),
606 Command::StepOut => self.require_paused(Effect::Step(StepKind::Out)),
607 Command::StepBack => self.require_recording(StepKind::Back),
608 Command::StepBackOver => self.require_recording(StepKind::BackOver),
609 Command::ReverseContinue => self.require_recording(StepKind::ReverseContinue),
610 Command::DebugStop => {
611 if self.debugger.state().can_stop() {
612 Effect::DebugStop
613 } else {
614 self.status = Status::info("No debug session is running");
615 Effect::None
616 }
617 }
618 Command::ToggleBreakpoint => self.toggle_breakpoint(),
619 Command::AddWatchpoint => self.open_prompt(PromptKind::Watch),
620 Command::SetBreakpointCondition => {
621 let Some(breakpoint) = self.breakpoints.all().get(self.breakpoint_selected) else {
622 self.status = Status::warning("Select a breakpoint in the Breakpoints panel");
623 return Effect::None;
624 };
625 let condition = breakpoint.condition.clone().unwrap_or_default();
626 self.open_prompt(PromptKind::BreakpointCondition);
627 if let Mode::Prompt(prompt) = &mut self.mode {
628 prompt.set_text(condition);
629 }
630 Effect::None
631 }
632 Command::SetRegister => {
633 if !self.debugger.state().can_step() {
634 return self.require_paused(Effect::None);
635 }
636 self.open_prompt(PromptKind::SetRegister)
637 }
638 Command::ClearBreakpoints => {
639 self.breakpoints.clear();
640 self.breakpoint_selected = 0;
641 self.status = Status::info("All breakpoints cleared");
642 Effect::SyncBreakpoints
643 }
644
645 Command::CycleRegisterFormat => {
646 self.register_format = self.register_format.next();
647 self.status = Status::info(format!(
648 "Registers shown as {}",
649 self.register_format.label()
650 ));
651 Effect::None
652 }
653 Command::ToggleDisassemblySyntax => {
654 self.disassembly_syntax = self.disassembly_syntax.toggled();
655 self.status = Status::info(format!(
656 "Disassembly in {} syntax",
657 self.disassembly_syntax.label()
658 ));
659 Effect::None
660 }
661 Command::CycleTheme => {
662 let next = self.theme.kind().next();
663 self.theme.set_kind(next);
664 self.settings.appearance.theme = next;
665 self.status = Status::info(format!("Theme: {}", next.description()));
666 Effect::None
667 }
668 Command::ToggleLearningMode => {
669 if self.page.is_study() {
670 self.open_page(self.ide_page);
671 self.status = Status::default();
672 } else {
673 self.open_page(Page::Learn);
674 self.status = Status::info(
675 "Learn: ←→ moves through the material, ? jumps to the questions, F1 goes back",
676 );
677 }
678 Effect::None
679 }
680
681 Command::OpenPalette => {
682 self.mode = Mode::Palette(Palette::open());
683 Effect::None
684 }
685 Command::OpenSyscallFinder => {
686 self.focus_panel(Panel::Syscalls);
687 Effect::None
688 }
689 Command::OpenScratchpad => {
690 self.focus_panel(Panel::Scratchpad);
691 Effect::None
692 }
693 Command::ShowKeybindings => {
694 self.focus_panel(Panel::Output);
695 self.output.clear();
696 self.output.push("Keyboard shortcuts".to_owned());
697 self.output.push(String::new());
698 for (binding, command) in self.keymap.sorted_bindings() {
699 self.output
700 .push(format!(" {:<14} {}", binding.to_string(), command.title()));
701 }
702 Effect::None
703 }
704 Command::ShowStatusDetails => {
705 let message = self.status.text.clone();
706 self.output.push(message);
707 self.focus_panel(Panel::Output);
708 Effect::None
709 }
710 }
711 }
712
713 fn open_prompt(&mut self, kind: PromptKind) -> Effect {
715 let prefill = match kind {
716 PromptKind::Search => self.search_query.clone(),
717 PromptKind::SaveAs | PromptKind::SaveAsAndClose => self
718 .workspace
719 .active()
720 .path()
721 .map(|path| path.display().to_string())
722 .unwrap_or_default(),
723 _ => String::new(),
724 };
725 self.mode = Mode::Prompt(Prompt::new(kind, prefill));
726 self.pending_prompt = Some(kind);
727 Effect::None
728 }
729
730 fn require_paused(&mut self, effect: Effect) -> Effect {
732 if self.debugger.state().can_step() {
733 effect
734 } else {
735 self.status = Status::warning(match self.debugger.state() {
736 DebuggerState::Idle | DebuggerState::Ready => {
737 "Start a debug session first (F12)".to_owned()
738 }
739 DebuggerState::Running => "The program is running; interrupt it first".to_owned(),
740 other => format!("Cannot step while {other}"),
741 });
742 Effect::None
743 }
744 }
745
746 fn require_recording(&mut self, kind: StepKind) -> Effect {
748 if !self.settings.debugger.record {
749 self.status =
750 Status::warning("Stepping backwards needs recording; set debugger.record = true");
751 return Effect::None;
752 }
753 self.require_paused(Effect::Step(kind))
754 }
755
756 pub fn cancel_overlay(&mut self) {
758 self.mode = Mode::Normal;
759 self.pending_prompt = None;
760 }
761
762 pub fn accept_prompt(&mut self) -> Effect {
764 let Mode::Prompt(prompt) = &self.mode else {
765 return Effect::None;
766 };
767 let text = prompt.text().trim().to_owned();
768 let Some(kind) = self.pending_prompt else {
769 self.cancel_overlay();
770 return Effect::None;
771 };
772
773 match kind {
774 PromptKind::ConfirmQuit => {
775 self.cancel_overlay();
776 if text.eq_ignore_ascii_case("y") || text.eq_ignore_ascii_case("yes") {
777 self.should_quit = true;
778 return Effect::Quit;
779 }
780 self.status = Status::info("Quit cancelled");
781 Effect::None
782 }
783 PromptKind::ConfirmClose => {
784 self.cancel_overlay();
785 if text.eq_ignore_ascii_case("s") || text.eq_ignore_ascii_case("save") {
786 return match self.workspace.active().path() {
787 Some(path) => Effect::SaveAndClose(path.to_path_buf()),
788 None => self.open_prompt(PromptKind::SaveAsAndClose),
789 };
790 }
791 if text.eq_ignore_ascii_case("d") || text.eq_ignore_ascii_case("discard") {
792 self.close_active_document();
793 } else {
794 self.status = Status::info("Close cancelled");
795 }
796 Effect::None
797 }
798 PromptKind::GoToLine => match text.parse::<usize>() {
799 Ok(line) => {
800 self.cancel_overlay();
801 self.workspace.active_mut().go_to_line(line);
802 self.focus_panel(Panel::Editor);
803 Effect::None
804 }
805 Err(_) => {
806 self.status = Status::error(format!("'{text}' is not a line number"));
807 Effect::None
808 }
809 },
810 PromptKind::GoToAddress => {
811 match crate::debugger::memory::evaluate_address(&text, &self.registers) {
812 Ok(address) => {
813 self.cancel_overlay();
814 self.memory_address = Some(address);
815 self.focus_panel(Panel::Memory);
816 Effect::ReadMemory(address)
817 }
818 Err(error) => {
819 self.status = Status::error(error.to_string());
820 Effect::None
821 }
822 }
823 }
824 PromptKind::Search => {
825 self.cancel_overlay();
826 self.search_query = text;
827 self.find(true);
828 Effect::None
829 }
830 PromptKind::Replace => {
831 self.cancel_overlay();
832 self.replace_all(&text);
833 Effect::None
834 }
835 PromptKind::OpenFile => {
836 if text.is_empty() {
837 self.status = Status::error("Enter a file name");
838 return Effect::None;
839 }
840 self.cancel_overlay();
841 Effect::OpenFile(PathBuf::from(text))
842 }
843 PromptKind::RenameFile => {
844 let Some(from) = self.workspace.active().path().map(Path::to_path_buf) else {
845 self.cancel_overlay();
846 return Effect::None;
847 };
848 if text.is_empty() {
849 self.status = Status::error("Enter a file name");
850 return Effect::None;
851 }
852 self.cancel_overlay();
853 let to = self.project.resolve(Path::new(&text));
854 if crate::editor::workspace::same_target(&from, &to) {
855 return Effect::None;
856 }
857 Effect::RenameFile { from, to }
858 }
859 PromptKind::DeleteFile => {
860 self.cancel_overlay();
861 match (
862 text.eq_ignore_ascii_case("yes"),
863 self.workspace.active().path(),
864 ) {
865 (true, Some(path)) => Effect::DeleteFile(path.to_path_buf()),
866 _ => {
867 self.status = Status::info("Nothing was deleted");
868 Effect::None
869 }
870 }
871 }
872 PromptKind::Watch => {
873 self.cancel_overlay();
874 if text.is_empty() {
875 return Effect::None;
876 }
877 if !self.debugger.state().can_edit_breakpoints() {
878 self.status =
879 Status::warning("Cannot change breakpoints while the program runs");
880 return Effect::None;
881 }
882 let expression = watch_expression(&text);
883 if self.breakpoints.add_watch(&expression) {
884 self.status = Status::info(format!("Watching {expression}"));
885 Effect::SyncBreakpoints
886 } else {
887 self.status = Status::info(format!("{expression} is already watched"));
888 Effect::None
889 }
890 }
891 PromptKind::BreakpointCondition => {
892 self.cancel_overlay();
893 if !self.debugger.state().can_edit_breakpoints() {
894 self.status =
895 Status::warning("Cannot change breakpoints while the program runs");
896 return Effect::None;
897 }
898 let condition = (!text.is_empty()).then(|| watch_expression(&text));
899 self.breakpoints
900 .set_condition(self.breakpoint_selected, condition.clone());
901 self.status = Status::info(match condition {
902 Some(condition) => format!("Stops only if {condition}"),
903 None => "Condition removed".to_owned(),
904 });
905 Effect::SyncBreakpoints
906 }
907 PromptKind::SetRegister => {
908 let Some((name, value)) = text.split_once('=') else {
909 self.status = Status::error("Write it as rax=0x10");
910 return Effect::None;
911 };
912 let name = name.trim().to_ascii_lowercase();
913 if !crate::instruction::registers::is_register(&name) {
914 self.status = Status::error(format!("'{name}' is not a register"));
915 return Effect::None;
916 }
917 let Some(value) = crate::learning::parse_answer(value.trim()) else {
918 self.status = Status::error(format!("'{}' is not a number", value.trim()));
919 return Effect::None;
920 };
921 self.cancel_overlay();
922 Effect::SetRegister(format!("${name} = {value}"))
923 }
924 PromptKind::NewFile => {
925 self.cancel_overlay();
926 if text.is_empty() {
927 return Effect::None;
928 }
929 Effect::CreateFile(self.project.resolve(Path::new(&text)))
930 }
931 PromptKind::SaveAs => {
932 if text.is_empty() {
933 self.status = Status::error("Enter a file name");
934 return Effect::None;
935 }
936 self.cancel_overlay();
937 Effect::SaveFile(PathBuf::from(text))
938 }
939 PromptKind::SaveAsAndClose => {
940 if text.is_empty() {
941 self.status = Status::error("Enter a file name");
942 return Effect::None;
943 }
944 self.cancel_overlay();
945 Effect::SaveAndClose(PathBuf::from(text))
946 }
947 }
948 }
949
950 fn open_picker(&mut self, kind: PickerKind) -> Effect {
951 self.mode = Mode::Picker(Picker::new(kind));
952 self.refresh_picker();
953 Effect::None
954 }
955
956 pub fn refresh_picker(&mut self) {
958 let Mode::Picker(picker) = &self.mode else {
959 return;
960 };
961 let query = picker.prompt().text().trim().to_owned();
962 let items = match picker.kind() {
963 PickerKind::Symbols => self.symbol_items(&query),
964 PickerKind::Search => self.search_items(&query),
965 PickerKind::MakeTargets => self.make_target_items(&query),
966 };
967 if let Mode::Picker(picker) = &mut self.mode {
968 picker.set_items(items);
969 }
970 }
971
972 fn project_texts(&self) -> Vec<(PathBuf, String)> {
973 self.project_files
974 .iter()
975 .filter_map(|path| {
976 let text = match self.index_of_document(path) {
977 Some(index) => self.workspace.documents()[index].buffer().to_text(),
978 None => std::fs::read_to_string(path).ok()?,
979 };
980 Some((path.clone(), text))
981 })
982 .collect()
983 }
984
985 fn symbol_items(&self, query: &str) -> Vec<PickItem> {
986 let mut items = Vec::new();
987 for (path, text) in self.project_texts() {
988 let buffer = crate::editor::TextBuffer::from_text(&text);
989 for symbol in crate::editor::symbols::extract(&buffer) {
990 if !symbol.kind.is_definition() && symbol.kind != SymbolKind::Section {
991 continue;
992 }
993 items.push(PickItem {
994 label: symbol.qualified_name.clone(),
995 detail: format!(
996 "{} {}:{}",
997 symbol.kind.description(),
998 crate::editor::workspace::display_path(&path),
999 symbol.position.line + 1
1000 ),
1001 path: path.clone(),
1002 line: symbol.position.line + 1,
1003 });
1004 }
1005 }
1006 let ranked =
1007 crate::command::palette::rank(query, items.iter().map(|item| item.label.as_str()));
1008 ranked
1009 .into_iter()
1010 .filter_map(|(index, _)| items.get(index).cloned())
1011 .collect()
1012 }
1013
1014 fn make_target_items(&self, query: &str) -> Vec<PickItem> {
1015 let Some(makefile) = crate::assembler::make::makefile(&self.project) else {
1016 return Vec::new();
1017 };
1018 let text = std::fs::read_to_string(&makefile).unwrap_or_default();
1019 let items: Vec<PickItem> = crate::assembler::make::targets(&text)
1020 .into_iter()
1021 .map(|(name, line)| PickItem {
1022 detail: format!("Makefile:{line}"),
1023 label: name,
1024 path: makefile.clone(),
1025 line,
1026 })
1027 .collect();
1028 crate::command::palette::rank(query, items.iter().map(|item| item.label.as_str()))
1029 .into_iter()
1030 .filter_map(|(index, _)| items.get(index).cloned())
1031 .collect()
1032 }
1033
1034 fn search_items(&self, query: &str) -> Vec<PickItem> {
1035 const LIMIT: usize = 500;
1036 if query.chars().count() < 2 {
1037 return Vec::new();
1038 }
1039 let needle = query.to_lowercase();
1040 let mut items = Vec::new();
1041 for (path, text) in self.project_texts() {
1042 for (index, line) in text.lines().enumerate() {
1043 if line.to_lowercase().contains(&needle) {
1044 items.push(PickItem {
1045 label: line.split_whitespace().collect::<Vec<_>>().join(" "),
1046 detail: format!(
1047 "{}:{}",
1048 crate::editor::workspace::display_path(&path),
1049 index + 1
1050 ),
1051 path: path.clone(),
1052 line: index + 1,
1053 });
1054 if items.len() == LIMIT {
1055 return items;
1056 }
1057 }
1058 }
1059 }
1060 items
1061 }
1062
1063 pub fn accept_picker(&mut self) -> Effect {
1065 let Mode::Picker(picker) = &self.mode else {
1066 return Effect::None;
1067 };
1068 let kind = picker.kind();
1069 let Some(item) = picker.selected_item().cloned() else {
1070 self.cancel_overlay();
1071 return Effect::None;
1072 };
1073 self.cancel_overlay();
1074 if kind == PickerKind::MakeTargets {
1075 return self.start_make_target(item.label);
1076 }
1077 if self.show_file(&item.path) {
1078 self.workspace.active_mut().reveal(item.line - 1);
1079 }
1080 self.focus_panel(Panel::Editor);
1081 Effect::None
1082 }
1083
1084 pub fn close_active_document(&mut self) {
1086 let index = self.workspace.active_index();
1087 match self.workspace.close(index) {
1088 Ok(_) => self.status = Status::info("Closed"),
1089 Err(error) => self.status = Status::error(error.to_string()),
1090 }
1091 }
1092
1093 pub fn accept_palette(&mut self) -> Effect {
1095 let Mode::Palette(palette) = &self.mode else {
1096 return Effect::None;
1097 };
1098 let Some(command) = palette.selected_command().cloned() else {
1099 self.cancel_overlay();
1100 return Effect::None;
1101 };
1102 self.cancel_overlay();
1103 self.apply(&command)
1104 }
1105
1106 fn start_make_target(&mut self, target: String) -> Effect {
1107 if !self.debugger.state().can_build() {
1108 self.status = Status::warning("Stop the debug session before running make");
1109 return Effect::None;
1110 }
1111 let _ = self.debugger.apply(Transition::BuildStarted);
1112 self.status = Status::info(format!("make {target}…"));
1113 Effect::Make(target)
1114 }
1115
1116 fn start_build(&mut self, debug: bool) -> Effect {
1118 if !self.debugger.state().can_build() {
1119 self.status = Status::warning("Stop the debug session before rebuilding");
1120 return Effect::None;
1121 }
1122 let _ = self.debugger.apply(Transition::BuildStarted);
1123 self.status = Status::info("Building…");
1124 Effect::Build { debug }
1125 }
1126
1127 pub fn finish_build(&mut self, outcome: BuildOutcome) {
1129 self.diagnostics.clone_from(&outcome.diagnostics);
1130 self.output = outcome.raw_output().lines().map(str::to_owned).collect();
1131
1132 if outcome.success {
1133 let _ = self.debugger.apply(Transition::BuildSucceeded);
1134 self.status = Status::success(outcome.summary());
1135 } else {
1136 let _ = self
1137 .debugger
1138 .fail(Transition::BuildFailed, outcome.summary());
1139 self.status = Status::error(outcome.summary());
1140 self.focus_panel(Panel::Output);
1141 self.go_to_first_error();
1142 }
1143 self.build = Some(outcome);
1144 }
1145
1146 pub fn fail_build(&mut self, message: impl Into<String>) {
1148 let message = message.into();
1149 let _ = self.debugger.fail(Transition::BuildFailed, message.clone());
1150 self.output = vec![message.clone()];
1151 self.status = Status::error(message);
1152 self.focus_panel(Panel::Output);
1153 }
1154
1155 pub fn finish_run(&mut self, output: ProcessOutput) {
1157 self.finish_terminal();
1158 if self.output.is_empty() && !output.stdout.is_empty() {
1159 self.output.extend(output.stdout.lines().map(str::to_owned));
1160 }
1161 if !output.stderr.is_empty() {
1162 self.output.extend(output.stderr.lines().map(str::to_owned));
1163 }
1164 self.output.push(String::new());
1165 self.output.push(format!(
1166 "Program {} in {} ms",
1167 output.outcome.description(),
1168 output.duration.as_millis()
1169 ));
1170
1171 self.status = match output.outcome {
1172 crate::process::Outcome::Exited(0) => {
1173 Status::success(format!("Program {}", output.outcome.description()))
1174 }
1175 crate::process::Outcome::Stopped => Status::warning("Program stopped"),
1176 _ => Status::error(format!("Program {}", output.outcome.description())),
1177 };
1178 self.focus_panel(Panel::Output);
1179 self.last_run = Some(output);
1180 }
1181
1182 pub fn finish_terminal(&mut self) {
1184 if let Some(terminal) = self.terminal.take() {
1185 self.output = terminal.into_lines();
1186 self.scroll.reset(Panel::Output);
1187 }
1188 }
1189
1190 fn go_to_definition(&mut self) {
1192 use crate::editor::symbols;
1193
1194 let document = self.workspace.active();
1195 let cursor = document.cursor();
1196 let line = document.buffer().line_or_empty(cursor.line).to_owned();
1197 let byte_offset = line
1198 .char_indices()
1199 .nth(cursor.column)
1200 .map_or(line.len(), |(offset, _)| offset);
1201
1202 if let Some(target) = crate::editor::syntax::include_target(&line) {
1203 let target = target.to_owned();
1204 self.follow_include(&target);
1205 return;
1206 }
1207
1208 let Some((_, word)) = crate::editor::syntax::word_at(&line, byte_offset) else {
1209 self.status = Status::info("No symbol under the cursor");
1210 return;
1211 };
1212 let word = word.to_owned();
1213
1214 let all = symbols::extract(document.buffer());
1215 let local = symbols::find_definition(&all, document.buffer(), &word, cursor)
1216 .map(|symbol| (symbol.position, symbol.kind));
1217
1218 if let Some((position, kind)) = local {
1219 if kind.is_definition() {
1220 self.workspace
1221 .active_mut()
1222 .move_cursor(Movement::To(position), SelectionMode::Collapse);
1223 self.focus_panel(Panel::Editor);
1224 self.status = Status::info(format!("{word} defined on line {}", position.line + 1));
1225 return;
1226 }
1227 }
1228
1229 if self.definition_in_another_file(&word) {
1230 return;
1231 }
1232
1233 if let Some((position, kind)) = local {
1234 self.workspace
1235 .active_mut()
1236 .move_cursor(Movement::To(position), SelectionMode::Collapse);
1237 self.focus_panel(Panel::Editor);
1238 self.status = Status::warning(format!(
1239 "only the {} for {word} is here, on line {}",
1240 kind.description(),
1241 position.line + 1
1242 ));
1243 return;
1244 }
1245 self.status = Status::warning(format!("'{word}' is not defined in this project"));
1246 }
1247
1248 fn follow_include(&mut self, target: &str) {
1250 let mut candidates = Vec::new();
1251 if let Some(directory) = self
1252 .workspace
1253 .active()
1254 .path()
1255 .and_then(|path| path.parent().map(Path::to_path_buf))
1256 {
1257 candidates.push(directory.join(target));
1258 }
1259 for directory in &self.project.config().project.include_directories {
1260 candidates.push(self.project.resolve(directory).join(target));
1261 }
1262 candidates.push(self.project.root().join(target));
1263
1264 for candidate in candidates {
1265 if candidate.is_file() && self.show_file(&candidate) {
1266 self.focus_panel(Panel::Editor);
1267 self.status =
1268 Status::info(format!("Opened {}", self.workspace.active().display_name()));
1269 return;
1270 }
1271 }
1272 self.status = Status::warning(format!("cannot find {target}"));
1273 }
1274
1275 fn definition_in_another_file(&mut self, name: &str) -> bool {
1277 use crate::editor::symbols;
1278
1279 if name.starts_with('.') {
1280 return false;
1281 }
1282
1283 let active = self.workspace.active_index();
1284 for index in 0..self.workspace.len() {
1285 if index == active {
1286 continue;
1287 }
1288 let buffer = self.workspace.documents()[index].buffer();
1289 let found = symbols::extract(buffer)
1290 .into_iter()
1291 .find(|symbol| symbol.kind.is_definition() && symbol.matches_name(name));
1292 if let Some(symbol) = found {
1293 self.workspace.set_active(index);
1294 self.jump_to_definition(name, symbol.position);
1295 return true;
1296 }
1297 }
1298
1299 for path in self.project.source_paths() {
1300 if self.index_of_document(&path).is_some() {
1301 continue;
1302 }
1303 let Ok(text) = crate::editor::workspace::read_file(&path) else {
1304 continue;
1305 };
1306 let buffer = crate::editor::TextBuffer::from_text(&text);
1307 let found = symbols::extract(&buffer)
1308 .into_iter()
1309 .find(|symbol| symbol.kind.is_definition() && symbol.matches_name(name));
1310 let Some(symbol) = found else { continue };
1311
1312 if self.show_file(&path) {
1313 self.jump_to_definition(name, symbol.position);
1314 return true;
1315 }
1316 }
1317 false
1318 }
1319
1320 fn jump_to_definition(&mut self, name: &str, position: Position) {
1322 self.workspace
1323 .active_mut()
1324 .move_cursor(Movement::To(position), SelectionMode::Collapse);
1325 self.focus_panel(Panel::Editor);
1326 self.status = Status::info(format!(
1327 "{name} defined in {} on line {}",
1328 self.workspace.active().display_name(),
1329 position.line + 1
1330 ));
1331 }
1332
1333 fn go_to_first_error(&mut self) {
1335 let Some(diagnostic) = crate::assembler::diagnostics::first_navigable(&self.diagnostics)
1336 else {
1337 self.status = Status::info("No errors to jump to");
1338 return;
1339 };
1340 let Some(line) = diagnostic.buffer_line() else {
1341 return;
1342 };
1343 let column = diagnostic.buffer_column();
1344 let message = diagnostic.message.clone();
1345 let file = diagnostic.file.clone();
1346
1347 if let Some(file) = file {
1348 if !self.show_file(&file) {
1349 self.status = Status::error(format!(
1350 "{}: {message}",
1351 crate::editor::workspace::display_path(&file)
1352 ));
1353 return;
1354 }
1355 }
1356
1357 self.workspace.active_mut().move_cursor(
1358 Movement::To(crate::editor::Position::new(line, column)),
1359 SelectionMode::Collapse,
1360 );
1361 self.focus_panel(Panel::Editor);
1362 self.status = Status::error(message);
1363 }
1364
1365 pub fn refresh_project_files(&mut self) {
1367 self.project.rescan();
1368 let mut files = crate::project::project_files_under(
1369 self.project.root(),
1370 &self.project.output_directory(),
1371 );
1372
1373 for path in self.project.source_paths() {
1374 if !files.contains(&path) {
1375 files.push(path);
1376 }
1377 }
1378 for document in self.workspace.documents() {
1379 if let Some(path) = document.path() {
1380 if !files.iter().any(|known| known == path) {
1381 files.push(path.to_path_buf());
1382 }
1383 }
1384 }
1385
1386 files.sort();
1387 files.dedup();
1388 self.explorer_selected = self.explorer_selected.min(files.len().saturating_sub(1));
1389 self.project_files = files;
1390 }
1391
1392 pub fn move_explorer_selection(&mut self, rows: isize) {
1394 if self.project_files.is_empty() {
1395 return;
1396 }
1397 let last = self.project_files.len() - 1;
1398 let target = self.explorer_selected as isize + rows;
1399 self.explorer_selected = target.clamp(0, last as isize) as usize;
1400 }
1401
1402 pub fn open_selected_file(&mut self) -> Effect {
1404 match self.project_files.get(self.explorer_selected) {
1405 Some(path) => Effect::OpenFile(path.clone()),
1406 None => Effect::None,
1407 }
1408 }
1409
1410 fn scroll_focused(&mut self, rows: isize) -> Effect {
1412 if ScrollState::is_scrollable(self.focus) {
1413 self.scroll.scroll_by(self.focus, rows);
1414 }
1415 Effect::None
1416 }
1417
1418 fn add_active_to_project(&mut self) -> Effect {
1420 let Some(path) = self.workspace.active().path().map(Path::to_path_buf) else {
1421 self.status = Status::warning("Save the buffer first; a source needs a file name");
1422 return Effect::None;
1423 };
1424
1425 match self.project.add_source(&path) {
1426 Ok(false) => {
1427 self.status = Status::info(format!(
1428 "{} is already built with the project",
1429 crate::editor::workspace::display_path(&path)
1430 ));
1431 Effect::None
1432 }
1433 Ok(true) => Effect::SaveProject,
1434 Err(error) => {
1435 self.status = Status::error(error.to_string());
1436 Effect::None
1437 }
1438 }
1439 }
1440
1441 pub fn show_file(&mut self, path: &std::path::Path) -> bool {
1443 if let Some(index) = self.index_of_document(path) {
1444 self.workspace.set_active(index);
1445 return true;
1446 }
1447 let resolved = self.resolve_reported_path(path);
1448 match self.workspace.open(&resolved) {
1449 Ok(index) => {
1450 self.workspace.set_active(index);
1451 self.workspace
1452 .active_mut()
1453 .set_indent_width(self.settings.indent_width());
1454 true
1455 }
1456 Err(_) => false,
1457 }
1458 }
1459
1460 fn find(&mut self, forward: bool) {
1462 use crate::editor::search::{self, SearchOptions};
1463
1464 if self.search_query.is_empty() {
1465 self.status = Status::info("Nothing to search for");
1466 return;
1467 }
1468
1469 let document = self.workspace.active();
1470 let cursor = document.cursor();
1471 let options = SearchOptions::new();
1472 let found = if forward {
1473 let from = document.buffer().position_after(cursor).unwrap_or(cursor);
1474 search::find_next(document.buffer(), &self.search_query, from, options)
1475 } else {
1476 search::find_previous(document.buffer(), &self.search_query, cursor, options)
1477 };
1478
1479 if let Some(hit) = found {
1480 let range = hit.range;
1481 self.workspace.active_mut().select_range(range);
1482 self.focus_panel(Panel::Editor);
1483 self.status = Status::info(format!(
1484 "'{}' on line {}",
1485 self.search_query,
1486 range.start.line + 1
1487 ));
1488 return;
1489 }
1490
1491 if self.find_in_another_document(forward) {
1492 return;
1493 }
1494 self.status = Status::warning(format!("'{}' not found", self.search_query));
1495 }
1496
1497 fn find_in_another_document(&mut self, forward: bool) -> bool {
1499 use crate::editor::search::{self, SearchOptions};
1500
1501 let count = self.workspace.len();
1502 if count < 2 {
1503 return false;
1504 }
1505 let options = SearchOptions::new();
1506 let active = self.workspace.active_index();
1507
1508 for step in 1..count {
1509 let index = if forward {
1510 (active + step) % count
1511 } else {
1512 (active + count - step) % count
1513 };
1514
1515 let buffer = self.workspace.documents()[index].buffer();
1516 let matches = search::find_all(buffer, &self.search_query, options);
1517 let hit = if forward {
1518 matches.first()
1519 } else {
1520 matches.last()
1521 };
1522 let Some(hit) = hit.map(|hit| hit.range) else {
1523 continue;
1524 };
1525
1526 self.workspace.set_active(index);
1527 self.workspace.active_mut().select_range(hit);
1528 self.focus_panel(Panel::Editor);
1529 self.status = Status::info(format!(
1530 "'{}' in {} on line {}",
1531 self.search_query,
1532 self.workspace.active().display_name(),
1533 hit.start.line + 1
1534 ));
1535 return true;
1536 }
1537 false
1538 }
1539
1540 fn replace_all(&mut self, replacement: &str) {
1542 use crate::editor::search::{self, SearchOptions};
1543
1544 if self.search_query.is_empty() {
1545 self.status = Status::info("Search for something first");
1546 return;
1547 }
1548
1549 let edits = search::replace_all(
1550 self.workspace.active().buffer(),
1551 &self.search_query,
1552 replacement,
1553 SearchOptions::new(),
1554 );
1555 let count = edits.len();
1556
1557 for (range, text) in edits {
1558 self.workspace.active_mut().replace_range(range, &text);
1559 }
1560
1561 self.status = if count == 0 {
1562 Status::warning(format!("'{}' not found", self.search_query))
1563 } else {
1564 Status::success(format!("Replaced {count} occurrence(s)"))
1565 };
1566 }
1567
1568 fn toggle_breakpoint(&mut self) -> Effect {
1570 let Some(path) = self.workspace.active().path().map(PathBuf::from) else {
1571 self.status = Status::warning("Save the file before setting a breakpoint");
1572 return Effect::None;
1573 };
1574 let line = self.workspace.active().cursor().line + 1;
1575 self.toggle_breakpoint_in(&path, line)
1576 }
1577
1578 pub fn toggle_breakpoint_in(&mut self, path: &Path, line: usize) -> Effect {
1580 if !self.debugger.state().can_edit_breakpoints() {
1581 self.status = Status::warning("Cannot change breakpoints while the program runs");
1582 return Effect::None;
1583 }
1584 if !self.show_file(path) {
1585 self.status = Status::error(format!("cannot open {}", path.display()));
1586 return Effect::None;
1587 }
1588 let path = path.to_path_buf();
1589 self.workspace.active_mut().reveal(line - 1);
1590 let added = self.breakpoints.toggle_line(&path, line);
1591 self.status = Status::info(if added {
1592 format!("Breakpoint set on line {line}")
1593 } else {
1594 format!("Breakpoint removed from line {line}")
1595 });
1596 Effect::SyncBreakpoints
1597 }
1598
1599 pub fn diagnostic_at(&self, path: &Path, line: usize) -> Option<&Diagnostic> {
1601 self.diagnostics.iter().find(|diagnostic| {
1602 diagnostic.line == Some(line)
1603 && diagnostic.file.as_deref().is_some_and(|file| {
1604 let reported = self.resolve_reported_path(file);
1605 crate::editor::workspace::same_target(&reported, path)
1606 || crate::editor::workspace::same_file(path, &reported)
1607 })
1608 })
1609 }
1610
1611 pub fn pending_breakpoints(&self) -> Vec<Location> {
1613 self.breakpoints
1614 .pending()
1615 .into_iter()
1616 .map(|breakpoint| breakpoint.location.clone())
1617 .collect()
1618 }
1619
1620 pub fn matching_syscalls(&self) -> Vec<&crate::syscall::Syscall> {
1622 self.syscalls.search(&self.syscall_query)
1623 }
1624
1625 pub fn current_explanation(&self) -> Option<crate::instruction::Explanation> {
1627 let explanation = self.explanation_source()?;
1628 Some(if self.debugger.state().can_inspect() {
1629 explanation.with_values(&self.registers)
1630 } else {
1631 explanation
1632 })
1633 }
1634
1635 fn explanation_source(&self) -> Option<crate::instruction::Explanation> {
1637 let explain = |line: &str| crate::instruction::explain_line(&self.instructions, line);
1638
1639 if self.page == Page::Reference {
1640 if let Some(explanation) = explain(&self.syscall_query) {
1641 return Some(explanation);
1642 }
1643 }
1644
1645 if self.page == Page::Learn {
1646 if !self.scratchpad.snippet.trim().is_empty() {
1647 return explain(&self.scratchpad.snippet);
1648 }
1649 if let Some(question) = self.learning.current_question() {
1650 return explain(question.instruction);
1651 }
1652 return None;
1653 }
1654
1655 if self.debugger.state().can_inspect() {
1656 if let Some((file, line)) = &self.current_line {
1657 if let Some(document) = self.document_for(file) {
1658 let text = document.buffer().line_or_empty(line.saturating_sub(1));
1659 return explain(text);
1660 }
1661 }
1662
1663 if let Some(address) = self.current_address {
1664 if let Some(line) = self
1665 .disassembly
1666 .iter()
1667 .find(|line| line.instruction.address == address)
1668 {
1669 return explain(&line.instruction.text());
1670 }
1671 }
1672 return None;
1673 }
1674
1675 let document = self.workspace.active();
1676 explain(document.buffer().line_or_empty(document.cursor().line))
1677 }
1678
1679 pub fn show_execution(&mut self) {
1681 self.open_page(Page::Debug);
1682 self.follow_execution();
1683 }
1684
1685 pub fn follow_execution(&mut self) -> bool {
1687 let Some((file, line)) = self.current_line.clone() else {
1688 return false;
1689 };
1690
1691 if !self.show_file(&file) {
1692 return false;
1693 }
1694 self.workspace.active_mut().go_to_line(line);
1695 true
1696 }
1697
1698 pub fn resolve_reported_path(&self, reported: &std::path::Path) -> PathBuf {
1700 if reported.is_absolute() || reported.is_file() {
1701 return reported.to_path_buf();
1702 }
1703 let rooted = self.project.root().join(reported);
1704 if rooted.is_file() {
1705 rooted
1706 } else {
1707 reported.to_path_buf()
1708 }
1709 }
1710
1711 pub fn index_of_document(&self, path: &std::path::Path) -> Option<usize> {
1713 let documents = self.workspace.documents();
1714 documents
1715 .iter()
1716 .position(|document| {
1717 document
1718 .path()
1719 .is_some_and(|open| crate::editor::workspace::same_target(open, path))
1720 })
1721 .or_else(|| {
1722 let rooted = self.project.root().join(path);
1723 documents
1724 .iter()
1725 .position(|document| document.path() == Some(rooted.as_path()))
1726 })
1727 .or_else(|| {
1728 documents.iter().position(|document| {
1729 document
1730 .path()
1731 .is_some_and(|open| crate::editor::workspace::same_file(open, path))
1732 })
1733 })
1734 }
1735
1736 fn document_for(&self, path: &std::path::Path) -> Option<&crate::editor::Document> {
1737 self.index_of_document(path)
1738 .and_then(|index| self.workspace.documents().get(index))
1739 }
1740}
1741
1742fn describe(text: &str) -> String {
1744 let lines = text.lines().count().max(1);
1745 if lines > 1 {
1746 format!("{lines} lines")
1747 } else {
1748 let characters = text.trim_end_matches('\n').chars().count();
1749 format!(
1750 "{characters} character{}",
1751 if characters == 1 { "" } else { "s" }
1752 )
1753 }
1754}
1755
1756#[cfg(test)]
1757mod tests {
1758 use super::*;
1759
1760 fn app() -> App {
1761 let dir = tempfile::tempdir().expect("temp dir");
1762 let project = Project::for_file(&dir.path().join("main.asm"));
1763 App::new(project, Settings::default()).expect("databases load")
1764 }
1765
1766 fn app_with_source(text: &str) -> App {
1767 let mut app = app();
1768 app.workspace.active_mut().insert(text);
1769 app.workspace
1770 .active_mut()
1771 .move_cursor(Movement::DocumentStart, SelectionMode::Collapse);
1772 app
1773 }
1774
1775 #[test]
1776 fn a_new_app_starts_in_the_editor_doing_nothing() {
1777 let app = app();
1778 assert_eq!(app.focus, Panel::Editor);
1779 assert_eq!(app.mode, Mode::Normal);
1780 assert_eq!(app.debugger.state(), DebuggerState::Idle);
1781 assert!(!app.should_quit);
1782 assert!(app.breakpoints.is_empty());
1783 }
1784
1785 #[test]
1786 fn panel_focus_cycles_within_the_page() {
1787 let mut app = app();
1788 assert_eq!(app.page, Page::Code);
1789
1790 assert_eq!(app.apply(&Command::NextPanel), Effect::None);
1791 assert_eq!(app.focus, Panel::Explorer);
1792 app.apply(&Command::PreviousPanel);
1793 assert_eq!(app.focus, Panel::Editor);
1794
1795 for _ in 0..Page::Code.panels().len() {
1796 app.apply(&Command::NextPanel);
1797 assert_eq!(app.page, Page::Code, "Tab must not change page");
1798 }
1799 assert_eq!(app.focus, Panel::Editor, "the cycle closed");
1800 }
1801
1802 #[test]
1803 fn focusing_a_panel_opens_a_page_that_shows_it() {
1804 let mut app = app();
1805 app.apply(&Command::FocusPanel(Panel::Memory));
1806
1807 assert_eq!(app.focus, Panel::Memory);
1808 assert_eq!(app.page, Page::Debug, "memory is not on the code page");
1809 assert!(app.page.contains(app.focus));
1810 }
1811
1812 #[test]
1813 fn focusing_a_panel_the_page_already_shows_stays_put() {
1814 let mut app = app();
1815 app.apply(&Command::GoToPage(Page::Debug));
1816 app.apply(&Command::FocusPanel(Panel::Output));
1817
1818 assert_eq!(app.page, Page::Debug);
1819 assert_eq!(app.focus, Panel::Output);
1820 }
1821
1822 #[test]
1823 fn the_open_page_s_number_moves_to_its_next_panel() {
1824 let mut app = app();
1825 let before = app.focus;
1826 app.apply(&Command::GoToPage(app.page));
1827 assert_ne!(app.focus, before);
1828 assert!(app.page.contains(app.focus));
1829 }
1830
1831 #[test]
1832 fn changing_page_moves_focus_onto_it() {
1833 let mut app = app();
1834 for page in Page::ALL {
1835 app.open_page(page);
1836 assert_eq!(app.page, page);
1837 assert!(
1838 page.contains(app.focus),
1839 "{page} left focus on {}",
1840 app.focus
1841 );
1842 }
1843
1844 app.apply(&Command::NextPage);
1845 assert_eq!(app.page, Page::Learn, "pages wrap within their group");
1846 app.apply(&Command::PreviousPage);
1847 assert_eq!(app.page, Page::Reference);
1848 }
1849
1850 #[test]
1851 fn every_command_leaves_focus_on_the_current_page() {
1852 for command in Command::all() {
1853 let mut app = app();
1854 app.apply(&command);
1855 assert!(
1856 app.page.contains(app.focus),
1857 "{command} left focus on {} while showing {}",
1858 app.focus,
1859 app.page
1860 );
1861 }
1862 }
1863
1864 #[test]
1865 fn stopping_shows_the_machine_and_the_line_it_stopped_on() {
1866 let mut app = app_with_source("one\ntwo\nthree\nfour\nfive\nsix\n");
1867 app.workspace
1868 .active_mut()
1869 .set_path("/tmp/ratasm-test/main.asm");
1870 app.current_line = Some((PathBuf::from("/tmp/ratasm-test/main.asm"), 5));
1871
1872 app.show_execution();
1873
1874 assert_eq!(app.page, Page::Debug, "the registers are on the debug page");
1875 assert_eq!(
1876 app.workspace.active().cursor().line,
1877 4,
1878 "the editor should be on the stopped line"
1879 );
1880 }
1881
1882 #[test]
1883 fn following_execution_into_a_missing_file_does_nothing() {
1884 let mut app = app();
1885 app.current_line = Some((PathBuf::from("/nowhere/other.asm"), 3));
1886
1887 assert!(!app.follow_execution(), "there is no such file to open");
1888 }
1889
1890 #[test]
1891 fn following_execution_opens_a_second_source_that_is_not_yet_open() {
1892 let dir = tempfile::tempdir().expect("temp dir");
1893 let other = dir.path().join("util.asm");
1894 std::fs::write(&other, "one\ntwo\nthree\nfour\n").expect("write");
1895
1896 let mut app = app();
1897 app.current_line = Some((other.clone(), 3));
1898
1899 assert!(app.follow_execution(), "stepping into a file must open it");
1900 assert_eq!(app.workspace.active().path(), Some(other.as_path()));
1901 assert_eq!(app.workspace.active().cursor().line, 2);
1902 }
1903
1904 #[test]
1905 fn two_open_files_sharing_a_name_are_not_confused() {
1906 let dir = tempfile::tempdir().expect("temp dir");
1907 let first = dir.path().join("src");
1908 let second = dir.path().join("lib");
1909 std::fs::create_dir_all(&first).expect("mkdir");
1910 std::fs::create_dir_all(&second).expect("mkdir");
1911 std::fs::write(first.join("main.asm"), "a\n").expect("write");
1912 std::fs::write(second.join("main.asm"), "b\n").expect("write");
1913
1914 let mut app = app();
1915 app.workspace.open(&first.join("main.asm")).expect("open");
1916 let wanted = app.workspace.open(&second.join("main.asm")).expect("open");
1917
1918 assert_eq!(
1919 app.index_of_document(&second.join("main.asm")),
1920 Some(wanted)
1921 );
1922 }
1923
1924 #[test]
1925 fn following_execution_with_no_stop_does_nothing() {
1926 let mut app = app();
1927 assert!(!app.follow_execution());
1928 }
1929
1930 #[test]
1931 fn the_learn_page_explains_the_instruction_being_asked_about() {
1932 let mut app = app();
1933 app.open_page(Page::Learn);
1934 app.learning.jump_to_questions();
1935
1936 let question = app
1937 .learning
1938 .current_question()
1939 .expect("jumping lands on a question");
1940 let explanation = app
1941 .current_explanation()
1942 .expect("the question names an instruction");
1943
1944 assert!(
1945 question
1946 .instruction
1947 .to_lowercase()
1948 .contains(&explanation.mnemonic.to_lowercase()),
1949 "explained {} for the question {}",
1950 explanation.mnemonic,
1951 question.instruction
1952 );
1953 }
1954
1955 #[test]
1956 fn the_reference_page_explains_an_instruction_typed_into_the_search_box() {
1957 let mut app = app();
1958 app.open_page(Page::Reference);
1959 app.syscall_query = "imul".to_owned();
1960
1961 let explanation = app
1962 .current_explanation()
1963 .expect("imul is an instruction ratasm knows");
1964 assert_eq!(explanation.mnemonic.to_lowercase(), "imul");
1965 }
1966
1967 #[test]
1968 fn a_search_that_is_not_an_instruction_leaves_the_panel_alone() {
1969 let mut app = app();
1970 app.open_page(Page::Reference);
1971 app.syscall_query = "write".to_owned();
1972
1973 assert!(app.current_explanation().is_none());
1974 }
1975
1976 #[test]
1977 fn a_typed_snippet_takes_precedence_over_the_question() {
1978 let mut app = app();
1979 app.open_page(Page::Learn);
1980 app.learning.jump_to_questions();
1981 app.scratchpad.snippet = "xor rcx, rcx".to_owned();
1982
1983 let explanation = app.current_explanation().expect("the snippet is explained");
1984 assert_eq!(explanation.mnemonic.to_lowercase(), "xor");
1985 }
1986
1987 #[test]
1988 fn starting_a_session_opens_the_debug_page() {
1989 let mut app = app();
1990 assert_eq!(app.page, Page::Code);
1991 app.apply(&Command::DebugStart);
1992 assert_eq!(app.page, Page::Debug);
1993 }
1994
1995 #[test]
1996 fn quitting_with_no_changes_exits_immediately() {
1997 let mut app = app();
1998 assert_eq!(app.apply(&Command::Quit), Effect::Quit);
1999 assert!(app.should_quit);
2000 }
2001
2002 #[test]
2003 fn quitting_with_unsaved_changes_asks_first() {
2004 let mut app = app();
2005 app.workspace.active_mut().insert_char('x');
2006
2007 assert_eq!(app.apply(&Command::Quit), Effect::None);
2008 assert!(!app.should_quit, "must not quit yet");
2009 assert!(app.mode.is_overlay());
2010 }
2011
2012 #[test]
2013 fn confirming_the_quit_prompt_exits_and_declining_does_not() {
2014 let mut app = app();
2015 app.workspace.active_mut().insert_char('x');
2016 app.apply(&Command::Quit);
2017
2018 if let Mode::Prompt(prompt) = &mut app.mode {
2019 prompt.insert('n');
2020 }
2021 assert_eq!(app.accept_prompt(), Effect::None);
2022 assert!(!app.should_quit, "declining must not quit");
2023
2024 app.apply(&Command::Quit);
2025 if let Mode::Prompt(prompt) = &mut app.mode {
2026 prompt.insert('y');
2027 }
2028 assert_eq!(app.accept_prompt(), Effect::Quit);
2029 assert!(app.should_quit);
2030 }
2031
2032 #[test]
2033 fn closing_a_modified_buffer_asks_before_discarding_it() {
2034 let mut app = app_with_source("mov rax, 1\n");
2035
2036 assert_eq!(app.apply(&Command::CloseFile), Effect::None);
2037 assert!(matches!(
2038 app.mode,
2039 Mode::Prompt(ref prompt) if prompt.kind() == Some(PromptKind::ConfirmClose)
2040 ));
2041 assert_eq!(app.workspace.active().buffer().to_text(), "mov rax, 1\n");
2042
2043 if let Mode::Prompt(prompt) = &mut app.mode {
2044 prompt.insert('d');
2045 }
2046 assert_eq!(app.accept_prompt(), Effect::None);
2047 assert!(app.workspace.active().buffer().is_empty());
2048 }
2049
2050 #[test]
2051 fn closing_a_modified_buffer_can_save_first() {
2052 let mut app = app_with_source("ret\n");
2053 let path = app.project.root().join("saved.asm");
2054 app.workspace.active_mut().set_path(&path);
2055 app.apply(&Command::CloseFile);
2056
2057 if let Mode::Prompt(prompt) = &mut app.mode {
2058 prompt.insert('s');
2059 }
2060 assert_eq!(app.accept_prompt(), Effect::SaveAndClose(path));
2061 assert_eq!(
2062 app.workspace.active().buffer().to_text(),
2063 "ret\n",
2064 "the buffer stays open until the save effect succeeds"
2065 );
2066 }
2067
2068 #[test]
2069 fn stepping_without_a_session_explains_rather_than_failing_silently() {
2070 let mut app = app();
2071 assert_eq!(app.apply(&Command::StepInstruction), Effect::None);
2072 assert_eq!(app.status.severity, Severity::Warning);
2073 assert!(
2074 app.status.text.contains("debug session"),
2075 "{}",
2076 app.status.text
2077 );
2078 }
2079
2080 #[test]
2081 fn stepping_while_paused_produces_the_right_effect() {
2082 let mut app = app();
2083 app.debugger.apply(Transition::BuildStarted).expect("build");
2084 app.debugger.apply(Transition::BuildSucceeded).expect("ok");
2085 app.debugger
2086 .apply(Transition::LaunchRequested)
2087 .expect("launch");
2088 app.debugger
2089 .apply(Transition::LaunchSucceeded)
2090 .expect("running");
2091 app.debugger.apply(Transition::Stopped).expect("paused");
2092
2093 assert_eq!(
2094 app.apply(&Command::StepInstruction),
2095 Effect::Step(StepKind::Instruction)
2096 );
2097 assert_eq!(app.apply(&Command::StepOver), Effect::Step(StepKind::Over));
2098 assert_eq!(app.apply(&Command::StepLine), Effect::Step(StepKind::Line));
2099 assert_eq!(app.apply(&Command::StepOut), Effect::Step(StepKind::Out));
2100 }
2101
2102 #[test]
2103 fn run_continues_when_the_program_is_paused() {
2104 let mut app = app();
2105 assert_eq!(app.apply(&Command::Run), Effect::Run);
2106
2107 app.debugger.apply(Transition::BuildStarted).expect("build");
2108 app.debugger.apply(Transition::BuildSucceeded).expect("ok");
2109 app.debugger
2110 .apply(Transition::LaunchRequested)
2111 .expect("launch");
2112 app.debugger
2113 .apply(Transition::LaunchSucceeded)
2114 .expect("running");
2115 app.debugger.apply(Transition::Stopped).expect("paused");
2116
2117 assert_eq!(app.apply(&Command::Run), Effect::DebugContinue);
2118 }
2119
2120 #[test]
2121 fn building_is_refused_while_a_session_holds_the_executable() {
2122 let mut app = app();
2123 app.debugger.apply(Transition::BuildStarted).expect("build");
2124 app.debugger.apply(Transition::BuildSucceeded).expect("ok");
2125 app.debugger
2126 .apply(Transition::LaunchRequested)
2127 .expect("launch");
2128 app.debugger
2129 .apply(Transition::LaunchSucceeded)
2130 .expect("running");
2131
2132 assert_eq!(app.apply(&Command::Build), Effect::None);
2133 assert_eq!(app.status.severity, Severity::Warning);
2134 }
2135
2136 #[test]
2137 fn a_build_moves_the_state_machine_and_reports() {
2138 let mut app = app();
2139 assert_eq!(app.apply(&Command::Build), Effect::Build { debug: false });
2140 assert_eq!(app.debugger.state(), DebuggerState::Building);
2141
2142 assert_eq!(
2143 app.apply(&Command::BuildWithDebugInfo),
2144 Effect::None,
2145 "already building"
2146 );
2147 }
2148
2149 #[test]
2150 fn a_breakpoint_needs_a_saved_file() {
2151 let mut app = app();
2152 assert_eq!(app.apply(&Command::ToggleBreakpoint), Effect::None);
2153 assert!(
2154 app.status.text.contains("Save the file"),
2155 "{}",
2156 app.status.text
2157 );
2158 assert!(app.breakpoints.is_empty());
2159 }
2160
2161 #[test]
2162 fn a_diagnostic_is_found_however_the_paths_are_spelled() {
2163 let dir = tempfile::tempdir().expect("temp dir");
2164 let file = dir.path().join("src/main.asm");
2165 std::fs::create_dir_all(file.parent().expect("parent")).expect("mkdir");
2166 std::fs::write(&file, "ret\n").expect("write");
2167 let mut app = App::new(Project::for_file(&file), Settings::default()).expect("app");
2168 app.diagnostics = vec![Diagnostic {
2169 file: Some(file.clone()),
2170 line: Some(1),
2171 column: None,
2172 severity: crate::assembler::Severity::Error,
2173 message: "bad".into(),
2174 producer: crate::assembler::Producer::Assembler,
2175 raw: String::new(),
2176 }];
2177 let dotted = dir.path().join(".").join("src/main.asm");
2178 assert!(app.diagnostic_at(&dotted, 1).is_some());
2179 assert!(app.diagnostic_at(&file, 2).is_none());
2180 }
2181
2182 #[test]
2183 fn the_pickers_find_symbols_and_text_across_the_project() {
2184 let dir = tempfile::tempdir().expect("temp dir");
2185 std::fs::write(dir.path().join("a.asm"), "_start:\n call helper\n").expect("write");
2186 std::fs::write(dir.path().join("b.asm"), "nop\nhelper:\n ret\n").expect("write");
2187 let mut app = App::new(
2188 Project::for_file(&dir.path().join("a.asm")),
2189 Settings::default(),
2190 )
2191 .expect("app");
2192 app.refresh_project_files();
2193
2194 app.apply(&Command::GoToSymbol);
2195 if let Mode::Picker(picker) = &mut app.mode {
2196 picker.prompt_mut().set_text("helpr");
2197 }
2198 app.refresh_picker();
2199 let Mode::Picker(picker) = &app.mode else {
2200 panic!("picker open");
2201 };
2202 let item = picker.selected_item().expect("a match").clone();
2203 assert_eq!((item.label.as_str(), item.line), ("helper", 2));
2204 assert!(item.path.ends_with("b.asm"));
2205 assert_eq!(app.accept_picker(), Effect::None);
2206 assert!(app
2207 .workspace
2208 .active()
2209 .path()
2210 .expect("open")
2211 .ends_with("b.asm"));
2212 assert_eq!(app.workspace.active().cursor().line, 1);
2213
2214 app.apply(&Command::SearchFiles);
2215 if let Mode::Picker(picker) = &mut app.mode {
2216 picker.prompt_mut().set_text("HELPER");
2217 }
2218 app.refresh_picker();
2219 let Mode::Picker(picker) = &app.mode else {
2220 panic!("picker open");
2221 };
2222 assert_eq!(picker.items().len(), 2);
2223 }
2224
2225 #[test]
2226 fn deleting_asks_for_yes() {
2227 let mut app = app();
2228 app.workspace.active_mut().set_path("/tmp/x.asm");
2229 app.apply(&Command::DeleteFile);
2230 if let Mode::Prompt(prompt) = &mut app.mode {
2231 prompt.set_text("no");
2232 }
2233 assert_eq!(app.accept_prompt(), Effect::None);
2234 app.apply(&Command::DeleteFile);
2235 if let Mode::Prompt(prompt) = &mut app.mode {
2236 prompt.set_text("YES");
2237 }
2238 assert_eq!(
2239 app.accept_prompt(),
2240 Effect::DeleteFile(PathBuf::from("/tmp/x.asm"))
2241 );
2242 }
2243
2244 #[test]
2245 fn toggling_a_breakpoint_adds_then_removes_it() {
2246 let mut app = app();
2247 app.workspace.active_mut().set_path("/tmp/main.asm");
2248
2249 assert_eq!(
2250 app.apply(&Command::ToggleBreakpoint),
2251 Effect::SyncBreakpoints
2252 );
2253 assert_eq!(app.breakpoints.len(), 1);
2254 assert!(app.status.text.contains("set"));
2255
2256 app.apply(&Command::ToggleBreakpoint);
2257 assert!(app.breakpoints.is_empty());
2258 assert!(app.status.text.contains("removed"));
2259 }
2260
2261 #[test]
2262 fn breakpoints_cannot_be_changed_while_the_program_runs() {
2263 let mut app = app();
2264 app.workspace.active_mut().set_path("/tmp/main.asm");
2265 app.debugger.apply(Transition::BuildStarted).expect("build");
2266 app.debugger.apply(Transition::BuildSucceeded).expect("ok");
2267 app.debugger
2268 .apply(Transition::LaunchRequested)
2269 .expect("launch");
2270 app.debugger
2271 .apply(Transition::LaunchSucceeded)
2272 .expect("running");
2273
2274 assert_eq!(app.apply(&Command::ToggleBreakpoint), Effect::None);
2275 assert!(app.breakpoints.is_empty());
2276 }
2277
2278 #[test]
2279 fn the_palette_opens_filters_and_runs_a_command() {
2280 let mut app = app();
2281 app.apply(&Command::OpenPalette);
2282 assert!(app.mode.palette().is_some());
2283
2284 if let Mode::Palette(palette) = &mut app.mode {
2285 for ch in "next panel".chars() {
2286 palette.prompt_mut().insert(ch);
2287 }
2288 palette.refresh();
2289 }
2290
2291 let effect = app.accept_palette();
2292 assert_eq!(effect, Effect::None);
2293 assert_eq!(app.focus, Panel::Explorer, "the command actually ran");
2294 assert_eq!(app.mode, Mode::Normal, "the palette closed");
2295 }
2296
2297 #[test]
2298 fn cancelling_an_overlay_returns_to_editing() {
2299 let mut app = app();
2300 app.apply(&Command::OpenPalette);
2301 app.cancel_overlay();
2302 assert_eq!(app.mode, Mode::Normal);
2303
2304 app.apply(&Command::GoToLine);
2305 app.cancel_overlay();
2306 assert_eq!(app.mode, Mode::Normal);
2307 }
2308
2309 #[test]
2310 fn go_to_line_moves_the_cursor() {
2311 let mut app = app_with_source("one\ntwo\nthree\nfour");
2312 app.apply(&Command::GoToLine);
2313 if let Mode::Prompt(prompt) = &mut app.mode {
2314 prompt.insert('3');
2315 }
2316
2317 assert_eq!(app.accept_prompt(), Effect::None);
2318 assert_eq!(app.workspace.active().cursor().line, 2);
2319 assert_eq!(app.mode, Mode::Normal);
2320 }
2321
2322 #[test]
2323 fn a_bad_line_number_keeps_the_prompt_open_and_says_why() {
2324 let mut app = app_with_source("one\ntwo");
2325 app.apply(&Command::GoToLine);
2326 if let Mode::Prompt(prompt) = &mut app.mode {
2327 for ch in "abc".chars() {
2328 prompt.insert(ch);
2329 }
2330 }
2331
2332 app.accept_prompt();
2333 assert!(app.mode.is_overlay(), "the prompt stays open");
2334 assert_eq!(app.status.severity, Severity::Error);
2335 }
2336
2337 #[test]
2338 fn a_bad_address_expression_reports_the_reason() {
2339 let mut app = app();
2340 app.apply(&Command::GoToAddress);
2341 if let Mode::Prompt(prompt) = &mut app.mode {
2342 for ch in "rsp".chars() {
2343 prompt.insert(ch);
2344 }
2345 }
2346
2347 assert_eq!(app.accept_prompt(), Effect::None);
2348 assert_eq!(app.status.severity, Severity::Error);
2349 assert!(app.status.text.contains("paused"), "{}", app.status.text);
2350 }
2351
2352 #[test]
2353 fn a_valid_address_asks_for_the_memory_and_focuses_the_panel() {
2354 let mut app = app();
2355 app.apply(&Command::GoToAddress);
2356 if let Mode::Prompt(prompt) = &mut app.mode {
2357 for ch in "0x4000b0".chars() {
2358 prompt.insert(ch);
2359 }
2360 }
2361
2362 assert_eq!(app.accept_prompt(), Effect::ReadMemory(0x0040_00b0));
2363 assert_eq!(app.focus, Panel::Memory);
2364 assert_eq!(app.memory_address, Some(0x0040_00b0));
2365 }
2366
2367 #[test]
2368 fn search_finds_a_match_and_selects_it() {
2369 let mut app = app_with_source("mov rax, 1\nadd rbx, 2\n");
2370 app.apply(&Command::Search);
2371 if let Mode::Prompt(prompt) = &mut app.mode {
2372 for ch in "rbx".chars() {
2373 prompt.insert(ch);
2374 }
2375 }
2376 app.accept_prompt();
2377
2378 assert_eq!(app.workspace.active().selected_text(), "rbx");
2379 assert_eq!(app.focus, Panel::Editor);
2380 }
2381
2382 #[test]
2383 fn searching_for_something_absent_says_so() {
2384 let mut app = app_with_source("mov rax, 1\n");
2385 app.search_query = "zzz".to_owned();
2386 app.apply(&Command::SearchNext);
2387 assert_eq!(app.status.severity, Severity::Warning);
2388 }
2389
2390 #[test]
2391 fn replace_rewrites_every_match() {
2392 let mut app = app_with_source("mov rax, rax\nadd rax, 1\n");
2393 app.search_query = "rax".to_owned();
2394 app.apply(&Command::Replace);
2395 if let Mode::Prompt(prompt) = &mut app.mode {
2396 for ch in "r10".chars() {
2397 prompt.insert(ch);
2398 }
2399 }
2400 app.accept_prompt();
2401
2402 assert_eq!(
2403 app.workspace.active().buffer().to_text(),
2404 "mov r10, r10\nadd r10, 1\n"
2405 );
2406 assert_eq!(app.status.severity, Severity::Success);
2407 }
2408
2409 #[test]
2410 fn go_to_definition_jumps_to_the_label() {
2411 let source = "_start:\n nop\n jmp _start\n";
2412 let mut app = app_with_source(source);
2413 app.workspace.active_mut().move_cursor(
2414 Movement::To(crate::editor::Position::new(2, 9)),
2415 SelectionMode::Collapse,
2416 );
2417
2418 app.apply(&Command::GoToDefinition);
2419 assert_eq!(app.workspace.active().cursor().line, 0);
2420 assert!(app.status.text.contains("_start"));
2421 }
2422
2423 #[test]
2424 fn go_to_definition_follows_an_extern_into_another_open_file() {
2425 let dir = tempfile::tempdir().expect("temp dir");
2426 let other = dir.path().join("util.asm");
2427 std::fs::write(&other, "section .text\nhelper:\n ret\n").expect("write");
2428
2429 let mut app = app_with_source("extern helper\n_start:\n call helper\n");
2430 app.workspace.active_mut().set_path("main.asm");
2431 app.workspace.open(&other).expect("open");
2432 app.workspace.set_active(0);
2433 app.workspace.active_mut().move_cursor(
2434 Movement::To(crate::editor::Position::new(2, 10)),
2435 SelectionMode::Collapse,
2436 );
2437
2438 app.apply(&Command::GoToDefinition);
2439 assert_eq!(app.workspace.active().path(), Some(other.as_path()));
2440 assert_eq!(app.workspace.active().cursor().line, 1);
2441 assert!(app.status.text.contains("util.asm"), "{}", app.status.text);
2442 }
2443
2444 #[test]
2445 fn the_explorer_finds_the_project_s_files_on_disk() {
2446 let dir = tempfile::tempdir().expect("temp dir");
2447 let project = Project::create(dir.path(), "listed").expect("create");
2448 std::fs::write(dir.path().join("src/util.asm"), "ret\n").expect("write");
2449 std::fs::create_dir_all(dir.path().join("build")).expect("mkdir");
2450 std::fs::write(dir.path().join("build/stray.asm"), "ret\n").expect("write");
2451
2452 let mut app = App::new(project, Settings::default()).expect("databases load");
2453 app.refresh_project_files();
2454
2455 let names: Vec<String> = app
2456 .project_files
2457 .iter()
2458 .filter_map(|path| path.file_name())
2459 .map(|name| name.to_string_lossy().into_owned())
2460 .collect();
2461
2462 assert!(names.contains(&"main.asm".to_owned()), "{names:?}");
2463 assert!(names.contains(&"util.asm".to_owned()), "not yet a source");
2464 assert!(
2465 !names.contains(&"stray.asm".to_owned()),
2466 "the build output is not source: {names:?}"
2467 );
2468 }
2469
2470 #[test]
2471 fn the_explorer_selection_stays_inside_the_list() {
2472 let dir = tempfile::tempdir().expect("temp dir");
2473 let project = Project::create(dir.path(), "select").expect("create");
2474 std::fs::write(dir.path().join("src/util.asm"), "ret\n").expect("write");
2475
2476 let mut app = App::new(project, Settings::default()).expect("databases load");
2477 app.refresh_project_files();
2478 let count = app.project_files.len();
2479 assert!(count >= 2);
2480
2481 app.move_explorer_selection(-5);
2482 assert_eq!(app.explorer_selected, 0);
2483 app.move_explorer_selection(100);
2484 assert_eq!(app.explorer_selected, count - 1);
2485
2486 assert!(matches!(app.open_selected_file(), Effect::OpenFile(_)));
2487 }
2488
2489 #[test]
2490 fn an_empty_file_list_has_nothing_to_open() {
2491 let mut app = app();
2492 app.project_files.clear();
2493 app.move_explorer_selection(1);
2494 assert_eq!(app.open_selected_file(), Effect::None);
2495 }
2496
2497 #[test]
2498 fn go_to_definition_on_an_include_opens_the_included_file() {
2499 let dir = tempfile::tempdir().expect("temp dir");
2500 let included = dir.path().join("macros.inc");
2501 std::fs::write(&included, "%define WIDTH 8\n").expect("write");
2502
2503 let mut app = app_with_source("%include \"macros.inc\"\n");
2504 app.workspace
2505 .active_mut()
2506 .set_path(dir.path().join("main.asm"));
2507 app.workspace.active_mut().move_cursor(
2508 Movement::To(crate::editor::Position::new(0, 2)),
2509 SelectionMode::Collapse,
2510 );
2511
2512 app.apply(&Command::GoToDefinition);
2513 assert_eq!(app.workspace.active().path(), Some(included.as_path()));
2514 }
2515
2516 #[test]
2517 fn an_include_that_is_nowhere_says_which_file_is_missing() {
2518 let mut app = app_with_source("%include \"absent.inc\"\n");
2519 app.workspace.active_mut().set_path("main.asm");
2520 app.workspace.active_mut().move_cursor(
2521 Movement::To(crate::editor::Position::new(0, 2)),
2522 SelectionMode::Collapse,
2523 );
2524
2525 app.apply(&Command::GoToDefinition);
2526 assert_eq!(app.status.severity, Severity::Warning);
2527 assert!(
2528 app.status.text.contains("absent.inc"),
2529 "{}",
2530 app.status.text
2531 );
2532 }
2533
2534 #[test]
2535 fn go_to_definition_opens_a_project_source_that_is_not_open_yet() {
2536 let dir = tempfile::tempdir().expect("temp dir");
2537 let mut project = Project::create(dir.path(), "cross").expect("create");
2538 let other = dir.path().join("src/util.asm");
2539 std::fs::write(&other, "section .text\nhelper:\n ret\n").expect("write");
2540 project.add_source(&other).expect("add");
2541
2542 let mut app = App::new(project, Settings::default()).expect("databases load");
2543 app.workspace.active_mut().insert(" call helper\n");
2544 app.workspace.active_mut().set_path("main.asm");
2545 app.workspace.active_mut().move_cursor(
2546 Movement::To(crate::editor::Position::new(0, 10)),
2547 SelectionMode::Collapse,
2548 );
2549
2550 app.apply(&Command::GoToDefinition);
2551 assert_eq!(app.workspace.active().path(), Some(other.as_path()));
2552 }
2553
2554 #[test]
2555 fn a_declaration_is_not_mistaken_for_a_definition() {
2556 let dir = tempfile::tempdir().expect("temp dir");
2557 let other = dir.path().join("util.asm");
2558 std::fs::write(&other, "global helper\nextern helper\n").expect("write");
2559
2560 let mut app = app_with_source(" call helper\n");
2561 app.workspace.active_mut().set_path("main.asm");
2562 app.workspace.open(&other).expect("open");
2563 app.workspace.set_active(0);
2564 app.workspace.active_mut().move_cursor(
2565 Movement::To(crate::editor::Position::new(0, 10)),
2566 SelectionMode::Collapse,
2567 );
2568
2569 app.apply(&Command::GoToDefinition);
2570 assert_eq!(app.status.severity, Severity::Warning);
2571 }
2572
2573 #[test]
2574 fn search_carries_on_into_the_next_open_document() {
2575 let dir = tempfile::tempdir().expect("temp dir");
2576 let other = dir.path().join("util.asm");
2577 std::fs::write(&other, "one\ntwo\nneedle here\n").expect("write");
2578
2579 let mut app = app_with_source("nothing\nto see\n");
2580 app.workspace.active_mut().set_path("main.asm");
2581 app.workspace.open(&other).expect("open");
2582 app.workspace.set_active(0);
2583 app.search_query = "needle".to_owned();
2584
2585 app.apply(&Command::SearchNext);
2586 assert_eq!(app.workspace.active().path(), Some(other.as_path()));
2587 assert_eq!(app.workspace.active().cursor().line, 2);
2588 assert_eq!(app.status.severity, Severity::Info);
2589 }
2590
2591 #[test]
2592 fn a_query_in_no_open_document_is_still_reported_missing() {
2593 let mut app = app_with_source("nothing\n");
2594 app.search_query = "needle".to_owned();
2595 app.apply(&Command::SearchNext);
2596 assert_eq!(app.status.severity, Severity::Warning);
2597 }
2598
2599 #[test]
2600 fn go_to_definition_on_nothing_says_so() {
2601 let mut app = app_with_source(" nop\n");
2602 app.workspace.active_mut().move_cursor(
2603 Movement::To(crate::editor::Position::new(0, 0)),
2604 SelectionMode::Collapse,
2605 );
2606 app.apply(&Command::GoToDefinition);
2607 assert!(matches!(
2608 app.status.severity,
2609 Severity::Info | Severity::Warning
2610 ));
2611 }
2612
2613 #[test]
2614 fn view_settings_cycle_and_report() {
2615 let mut app = app();
2616 let before = app.register_format;
2617 app.apply(&Command::CycleRegisterFormat);
2618 assert_ne!(app.register_format, before);
2619
2620 let syntax = app.disassembly_syntax;
2621 app.apply(&Command::ToggleDisassemblySyntax);
2622 assert_ne!(app.disassembly_syntax, syntax);
2623
2624 let theme = app.theme.kind();
2625 app.apply(&Command::CycleTheme);
2626 assert_ne!(app.theme.kind(), theme);
2627 assert_eq!(app.settings.appearance.theme, app.theme.kind());
2628
2629 app.apply(&Command::ToggleLearningMode);
2630 assert_eq!(app.page, Page::Learn);
2631 app.apply(&Command::GoToPage(Page::Debug));
2632 assert_eq!(
2633 app.page,
2634 Page::Reference,
2635 "the second page of the open group"
2636 );
2637 app.apply(&Command::ToggleLearningMode);
2638 assert_eq!(app.page, Page::Code);
2639 }
2640
2641 #[test]
2642 fn undo_and_redo_report_when_there_is_nothing_to_do() {
2643 let mut app = app();
2644 app.apply(&Command::Undo);
2645 assert!(app.status.text.contains("Nothing to undo"));
2646 app.apply(&Command::Redo);
2647 assert!(app.status.text.contains("Nothing to redo"));
2648 }
2649
2650 #[test]
2651 fn the_shortcut_list_shows_every_binding() {
2652 let mut app = app();
2653 app.apply(&Command::ShowKeybindings);
2654 assert_eq!(app.focus, Panel::Output);
2655 assert!(app.output.iter().any(|line| line.contains("ctrl+s")));
2656 assert!(app.output.iter().any(|line| line.contains("F5")));
2657 }
2658
2659 #[test]
2660 fn status_details_put_the_complete_message_in_output() {
2661 let mut app = app();
2662 let message = "a diagnostic too long for the status bar";
2663 app.status = Status::error(message);
2664
2665 app.apply(&Command::ShowStatusDetails);
2666
2667 assert_eq!(app.focus, Panel::Output);
2668 assert_eq!(app.output.last().map(String::as_str), Some(message));
2669 assert_eq!(app.status.text, message, "the command remains repeatable");
2670 }
2671
2672 #[test]
2673 fn copying_a_selection_offers_it_to_the_terminal_too() {
2674 let mut app = app_with_source("mov rax, 1\nmov rdi, 0\n");
2675 app.workspace
2676 .active_mut()
2677 .select_range(Range::new(Position::new(0, 0), Position::new(0, 3)));
2678
2679 let effect = app.apply(&Command::Copy);
2680 assert_eq!(app.clipboard, "mov");
2681 assert_eq!(effect, Effect::SetSystemClipboard("mov".to_owned()));
2682 }
2683
2684 #[test]
2685 fn copying_with_no_selection_takes_the_whole_line() {
2686 let mut app = app_with_source("mov rax, 1\nmov rdi, 0\n");
2687 app.apply(&Command::Copy);
2688 assert_eq!(app.clipboard, "mov rax, 1\n");
2689 }
2690
2691 #[test]
2692 fn cutting_removes_what_it_copied() {
2693 let mut app = app_with_source("mov rax, 1\nmov rdi, 0\n");
2694 app.apply(&Command::Cut);
2695
2696 assert_eq!(app.clipboard, "mov rax, 1\n");
2697 assert_eq!(
2698 app.workspace.active().buffer().to_text(),
2699 "mov rdi, 0\n",
2700 "the line itself must be gone, not just copied"
2701 );
2702 }
2703
2704 #[test]
2705 fn pasting_puts_back_exactly_what_was_cut() {
2706 let mut app = app_with_source("mov rax, 1\nmov rdi, 0\n");
2707 let before = app.workspace.active().buffer().to_text();
2708
2709 app.apply(&Command::Cut);
2710 app.apply(&Command::Paste);
2711
2712 assert_eq!(app.workspace.active().buffer().to_text(), before);
2713 }
2714
2715 #[test]
2716 fn pasting_an_empty_clipboard_says_so_rather_than_doing_nothing() {
2717 let mut app = app_with_source("mov rax, 1\n");
2718 let effect = app.apply(&Command::Paste);
2719
2720 assert_eq!(effect, Effect::None);
2721 assert_eq!(app.status.severity, Severity::Info);
2722 assert!(app.status.text.contains("copied"));
2723 }
2724
2725 #[test]
2726 fn cutting_the_last_line_does_not_run_off_the_end() {
2727 let mut app = app_with_source("only line");
2728 app.apply(&Command::Cut);
2729 assert_eq!(app.workspace.active().buffer().to_text(), "");
2730 }
2731
2732 #[test]
2733 fn an_amount_of_text_is_described_for_the_status_bar() {
2734 assert_eq!(describe("x"), "1 character");
2735 assert_eq!(describe("mov"), "3 characters");
2736 assert_eq!(describe("mov rax, 1\n"), "10 characters");
2737 assert_eq!(describe("one\ntwo\n"), "2 lines");
2738 }
2739
2740 #[test]
2741 fn a_failed_build_focuses_the_output_and_jumps_to_the_error() {
2742 use crate::assembler::diagnostics;
2743
2744 let mut app = app_with_source("one\ntwo\nthree\nfour\nfive\n");
2745 app.workspace.active_mut().set_path("main.asm");
2746 app.apply(&Command::Build);
2747
2748 let diagnostics =
2749 diagnostics::parse_assembler_output("main.asm:3: error: symbol undefined\n");
2750 app.diagnostics = diagnostics;
2751 app.fail_build("Build failed: 1 error(s)");
2752
2753 assert_eq!(app.focus, Panel::Output);
2754 assert_eq!(app.debugger.state(), DebuggerState::Failed);
2755 assert_eq!(app.status.severity, Severity::Error);
2756
2757 app.apply(&Command::GoToFirstError);
2758 assert_eq!(app.workspace.active().cursor().line, 2, "line 3 is index 2");
2759 }
2760
2761 #[test]
2762 fn an_error_in_another_source_jumps_to_that_source() {
2763 use crate::assembler::diagnostics;
2764
2765 let mut app = app_with_source("one\ntwo\nthree\nfour\nfive\n");
2766 app.workspace.active_mut().set_path("main.asm");
2767
2768 let dir = tempfile::tempdir().expect("temp dir");
2769 let other = dir.path().join("util.asm");
2770 std::fs::write(&other, "a\nb\nc\nd\ne\nf\n").expect("write");
2771 app.workspace.open(&other).expect("open");
2772 app.workspace.set_active(0);
2773
2774 app.diagnostics = diagnostics::parse_assembler_output(&format!(
2775 "{}:4: error: symbol undefined\n",
2776 other.display()
2777 ));
2778 app.apply(&Command::GoToFirstError);
2779
2780 assert_eq!(
2781 app.workspace.active().path(),
2782 Some(other.as_path()),
2783 "the jump must land in the file the diagnostic names"
2784 );
2785 assert_eq!(app.workspace.active().cursor().line, 3);
2786 }
2787
2788 #[test]
2789 fn an_error_in_a_file_that_cannot_be_opened_still_names_it() {
2790 use crate::assembler::diagnostics;
2791
2792 let mut app = app_with_source("one\ntwo\n");
2793 app.diagnostics = diagnostics::parse_assembler_output("/nowhere/gone.asm:2: error: bad\n");
2794 app.apply(&Command::GoToFirstError);
2795
2796 assert_eq!(app.status.severity, Severity::Error);
2797 assert!(app.status.text.contains("gone.asm"), "{}", app.status.text);
2798 }
2799
2800 #[test]
2801 fn a_finished_run_summarises_the_outcome() {
2802 use crate::process::Outcome;
2803
2804 let mut app = app();
2805 app.finish_run(ProcessOutput {
2806 outcome: Outcome::Signalled(11),
2807 stdout: "partial\n".to_owned(),
2808 stderr: String::new(),
2809 duration: std::time::Duration::from_millis(7),
2810 command: "./main".to_owned(),
2811 });
2812
2813 assert_eq!(app.status.severity, Severity::Error);
2814 assert!(app.status.text.contains("SIGSEGV"), "{}", app.status.text);
2815 assert!(app.output.iter().any(|line| line.contains("partial")));
2816 assert_eq!(app.focus, Panel::Output);
2817 }
2818
2819 #[test]
2820 fn the_explanation_follows_the_cursor_when_not_debugging() {
2821 let mut app = app_with_source(" add rax, rbx\n ret\n");
2822 app.workspace.active_mut().move_cursor(
2823 Movement::To(crate::editor::Position::new(0, 4)),
2824 SelectionMode::Collapse,
2825 );
2826
2827 let explanation = app.current_explanation().expect("an explanation");
2828 assert_eq!(explanation.effect, "RAX ← RAX + RBX");
2829 }
2830
2831 fn stopped_at(app: &mut App, file: &str, line: usize) {
2833 app.debugger.apply(Transition::BuildStarted).expect("build");
2834 app.debugger.apply(Transition::BuildSucceeded).expect("ok");
2835 app.debugger
2836 .apply(Transition::LaunchRequested)
2837 .expect("launch");
2838 app.debugger
2839 .apply(Transition::LaunchSucceeded)
2840 .expect("running");
2841 app.debugger.apply(Transition::Stopped).expect("paused");
2842 app.current_line = Some((PathBuf::from(file), line));
2843 }
2844
2845 #[test]
2846 fn while_stopped_the_explanation_follows_the_program_counter() {
2847 let mut app = app_with_source(" nop\n add rax, rbx\n");
2848 app.workspace.active_mut().set_path("/tmp/main.asm");
2849 stopped_at(&mut app, "main.asm", 2);
2850
2851 let explanation = app.current_explanation().expect("an explanation");
2852 assert_eq!(explanation.mnemonic, "add");
2853 }
2854
2855 #[test]
2856 fn the_explanation_comes_from_the_file_execution_stopped_in() {
2857 let mut app = app_with_source(" nop\n add rax, rbx\n");
2858 app.workspace.active_mut().set_path("/tmp/main.asm");
2859
2860 let other = crate::editor::Document::from_file_contents(
2861 "/tmp/other.asm",
2862 " xor rcx, rcx\n mul rdx\n",
2863 );
2864 app.workspace.add_document(other);
2865 assert_eq!(app.workspace.active().display_name(), "other.asm");
2866
2867 stopped_at(&mut app, "main.asm", 2);
2868 let explanation = app.current_explanation().expect("an explanation");
2869 assert_eq!(
2870 explanation.mnemonic, "add",
2871 "it must explain main.asm, not the document being viewed"
2872 );
2873 }
2874
2875 #[test]
2876 fn without_the_source_the_disassembly_is_explained_instead() {
2877 use crate::disassembler::{decode, DisassemblyLine, Syntax};
2878
2879 let mut app = app();
2880 stopped_at(&mut app, "not-open.asm", 1);
2881 app.current_address = Some(0x1000);
2882 app.disassembly = decode(&[0x31, 0xff], 0x1000, Syntax::Intel)
2883 .into_iter()
2884 .map(DisassemblyLine::bare)
2885 .collect();
2886
2887 let explanation = app.current_explanation().expect("an explanation");
2888 assert_eq!(explanation.mnemonic, "xor");
2889 }
2890
2891 #[test]
2892 fn with_neither_source_nor_disassembly_there_is_no_explanation() {
2893 let mut app = app();
2894 stopped_at(&mut app, "not-open.asm", 1);
2895 assert!(app.current_explanation().is_none());
2896 }
2897
2898 #[test]
2899 fn a_line_with_no_instruction_has_no_explanation() {
2900 let app = app_with_source("; just a comment\n");
2901 assert!(app.current_explanation().is_none());
2902 }
2903
2904 #[test]
2905 fn syscall_search_narrows_as_the_query_changes() {
2906 let mut app = app();
2907 assert_eq!(app.matching_syscalls().len(), app.syscalls.len());
2908
2909 app.syscall_query = "write".to_owned();
2910 let found = app.matching_syscalls();
2911 assert!(found.len() < app.syscalls.len());
2912 assert_eq!(found.first().map(|call| call.name.as_str()), Some("write"));
2913 }
2914
2915 #[test]
2916 fn clearing_breakpoints_empties_the_list_and_syncs() {
2917 let mut app = app();
2918 app.workspace.active_mut().set_path("/tmp/main.asm");
2919 app.apply(&Command::ToggleBreakpoint);
2920 assert_eq!(app.breakpoints.len(), 1);
2921
2922 assert_eq!(
2923 app.apply(&Command::ClearBreakpoints),
2924 Effect::SyncBreakpoints
2925 );
2926 assert!(app.breakpoints.is_empty());
2927 }
2928
2929 #[test]
2930 fn every_command_can_be_applied_without_panicking() {
2931 for command in Command::all() {
2932 let mut app = app();
2933 app.workspace.active_mut().set_path("/tmp/main.asm");
2934 let _ = app.apply(&command);
2935 }
2936 }
2937}