use iced::widget::operation::{RelativeOffset, snap_to};
use iced::widget::{Id, canvas};
use std::cell::{Cell, RefCell};
use std::collections::HashSet;
use std::ops::Range;
use std::rc::Rc;
use std::sync::atomic::{AtomicU64, Ordering};
#[cfg(not(target_arch = "wasm32"))]
use std::time::Instant;
use crate::buffer::TextBuffer;
use crate::i18n::Translations;
use crate::theme::Style;
use caches::{
BracketDepthCache, HighlightCache, MaxContentWidthCache, ResolvedSyntax,
VisualLinesCache,
};
use editing::cursor_set;
pub use editing::history::CommandHistory;
use features::{command_palette, folding, goto_line, search, vim};
use metrics::{
CACHE_WINDOW_MARGIN_MULTIPLIER, CHAR_WIDTH, CURSOR_BLINK_INTERVAL,
FONT_SIZE, GUTTER_WIDTH, HIGHLIGHT_LINES_PER_FRAME, LINE_HEIGHT, TAB_WIDTH,
compare_floats, indent_width, measure_char_width, measure_text_width,
};
#[cfg(target_arch = "wasm32")]
use web_time::Instant;
static EDITOR_ID_COUNTER: AtomicU64 = AtomicU64::new(1);
static FOCUSED_EDITOR_ID: AtomicU64 = AtomicU64::new(0);
#[cfg(feature = "bench")]
#[doc(hidden)]
pub mod bench_support;
mod bool_options;
mod caches;
mod config;
mod editing;
pub(crate) mod features;
mod focus;
mod input;
pub mod lsp;
mod metrics;
mod render;
pub use features::context_menu::{ContextMenuEntry, ContextMenuItem};
pub use features::vim::VimMode;
#[derive(Debug, Clone)]
pub(crate) struct ImePreedit {
pub(crate) content: String,
pub(crate) selection: Option<Range<usize>>,
}
pub(crate) struct LspEditSnapshot {
pub(crate) start_line: usize,
pub(crate) old_end_exclusive: usize,
pub(crate) old_line_count: usize,
pub(crate) old_end: lsp::LspPosition,
}
pub struct CodeEditor {
pub(crate) editor_id: u64,
pub(crate) buffer: TextBuffer,
pub(crate) cursors: cursor_set::CursorSet,
pub(crate) horizontal_scroll_offset: f32,
pub(crate) style: Style,
pub(crate) syntax: String,
pub(crate) last_blink: Instant,
pub(crate) cursor_visible: bool,
pub(crate) is_dragging: bool,
pub(crate) drag_viewport_point: Option<iced::Point>,
pub(crate) content_cache: canvas::Cache,
pub(crate) overlay_cache: canvas::Cache,
pub(crate) scrollable_id: Id,
pub(crate) horizontal_scrollable_id: Id,
pub(crate) max_content_width_cache: RefCell<Option<MaxContentWidthCache>>,
pub(crate) viewport_scroll: f32,
pub(crate) viewport_height: f32,
pub(crate) viewport_width: f32,
pub(crate) last_canvas_width: Cell<f32>,
pub(crate) history: CommandHistory,
pub(crate) is_grouping: bool,
pub(crate) wrap_enabled: bool,
pub(crate) auto_indent_enabled: bool,
pub(crate) auto_close_brackets: bool,
pub(crate) indent_style: IndentStyle,
pub(crate) wrap_column: Option<usize>,
pub(crate) folding_enabled: bool,
pub(crate) collapsed_folds: HashSet<usize>,
pub(crate) fold_revision: u64,
pub(crate) foldable_regions_cache:
RefCell<Option<(u64, Rc<Vec<folding::FoldRegion>>)>>,
pub(crate) search_state: search::SearchState,
custom_context_menu_entries: Vec<ContextMenuEntry>,
default_context_menu_enabled: bool,
reveal_in_file_manager_enabled: bool,
pub(crate) goto_line_state: goto_line::GotoLineState,
pub(crate) command_palette_state: command_palette::CommandPaletteState,
custom_command_palette_entries: Vec<ContextMenuItem>,
default_command_palette_enabled: bool,
pub(crate) command_palette_enabled: bool,
vim_enabled: bool,
pub(crate) vim_state: vim::VimState,
pub(crate) translations: Translations,
pub(crate) search_replace_enabled: bool,
pub(crate) line_numbers_enabled: bool,
pub(crate) show_whitespace: bool,
pub(crate) show_indent_guides: bool,
pub(crate) show_color_previews: bool,
pub(crate) bracket_match_highlight_enabled: bool,
pub(crate) bracket_pair_colorization_enabled: bool,
pub(crate) sticky_scroll_enabled: bool,
pub(crate) lsp_enabled: bool,
pub(crate) lsp_client: Option<Box<dyn lsp::LspClient>>,
pub(crate) lsp_document: Option<lsp::LspDocument>,
pub(crate) lsp_pending_changes: Vec<lsp::LspTextChange>,
pub(crate) lsp_shadow_text: String,
pub(crate) lsp_shadow_is_current: bool,
pub(crate) lsp_synced_line_count: usize,
pub(crate) lsp_synced_last_line_len: usize,
pub(crate) lsp_edit_snapshot: Option<LspEditSnapshot>,
pub(crate) lsp_auto_flush: bool,
pub(crate) has_canvas_focus: bool,
pub(crate) focus_locked: bool,
pub(crate) show_cursor: bool,
pub(crate) modifiers: Cell<iced::keyboard::Modifiers>,
pub(crate) last_click: Cell<Option<(Instant, iced::Point, u8)>>,
pub(crate) font: iced::Font,
pub(crate) ime_preedit: Option<ImePreedit>,
pub(crate) font_size: f32,
pub(crate) full_char_width: f32,
pub(crate) line_height: f32,
pub(crate) char_width: f32,
pub(crate) last_first_visible_line: usize,
pub(crate) cache_window_start_line: usize,
pub(crate) cache_window_end_line: usize,
pub(crate) buffer_revision: u64,
visual_lines_cache: RefCell<Option<VisualLinesCache>>,
pub(crate) resolved_syntax: RefCell<Option<ResolvedSyntax>>,
pub(crate) highlight_cache: RefCell<Option<HighlightCache>>,
pub(crate) highlight_lines_remaining: Cell<usize>,
pub(crate) bracket_depth_cache: RefCell<BracketDepthCache>,
pub(crate) pre_edit_line: usize,
pub(crate) pre_edit_last_line: usize,
}
#[derive(Debug, Clone)]
pub enum Message {
CharacterInput(char),
VimKey(char),
ToggleVimMode,
WriteRequested,
Backspace,
Delete,
Enter,
Tab,
Backtab,
ArrowKey(ArrowDirection, bool),
MouseClick(iced::Point),
MouseDrag(iced::Point),
MouseHover(iced::Point),
MouseRelease,
SelectionAutoScroll(f32),
DoubleClick(iced::Point),
TripleClick(iced::Point),
ContextMenuRequested(iced::Point),
CustomContextMenuAction(String),
RevealInFileManager,
Cut,
Copy,
Paste(String),
DeleteSelection,
SelectAll,
Tick,
PageUp(bool),
PageDown(bool),
Home(bool),
End(bool),
CtrlHome,
CtrlEnd,
WordLeft(bool),
WordRight(bool),
DeleteWordBack,
DeleteWordForward,
GotoPosition(usize, usize),
OpenGotoLine,
CloseGotoLine,
GotoLineChanged(String),
SubmitGotoLine,
OpenCommandPalette,
CloseCommandPalette,
CommandPaletteChanged(String),
CommandPaletteNavigate(bool),
CommandPaletteSelected(usize),
SubmitCommandPalette,
CommandPaletteAction(String),
Scrolled(iced::widget::scrollable::Viewport),
HorizontalScrolled(iced::widget::scrollable::Viewport),
Undo,
Redo,
OpenSearch,
OpenSearchReplace,
CloseSearch,
SearchQueryChanged(String),
ReplaceQueryChanged(String),
ToggleCaseSensitive,
FindNext,
FindPrevious,
ReplaceNext,
ReplaceAll,
SearchDialogTab,
SearchDialogShiftTab,
CanvasFocusGained,
CanvasFocusLost,
JumpClick(iced::Point),
ImeOpened,
ImePreedit(String, Option<Range<usize>>),
ImeCommit(String),
ImeClosed,
AltClick(iced::Point),
AddCursorAbove,
AddCursorBelow,
SelectNextOccurrence,
ToggleFold(usize),
ToggleFoldAtCursor,
FoldAll,
UnfoldAll,
MoveLineUp,
MoveLineDown,
DuplicateLineUp,
DuplicateLineDown,
ToggleComment,
StickyScrollJump(usize),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum IndentStyle {
Spaces(u8),
Tab,
}
impl IndentStyle {
pub const ALL: [IndentStyle; 4] = [
IndentStyle::Spaces(2),
IndentStyle::Spaces(4),
IndentStyle::Spaces(8),
IndentStyle::Tab,
];
}
impl std::fmt::Display for IndentStyle {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
IndentStyle::Spaces(1) => write!(f, "1 space"),
IndentStyle::Spaces(n) => write!(f, "{n} spaces"),
IndentStyle::Tab => write!(f, "Tab"),
}
}
}
#[derive(Debug, Clone, Copy)]
pub enum ArrowDirection {
Up,
Down,
Left,
Right,
}
impl CodeEditor {
pub fn new(content: &str, syntax: &str) -> Self {
let editor_id = EDITOR_ID_COUNTER.fetch_add(1, Ordering::Relaxed);
if editor_id == 1 {
FOCUSED_EDITOR_ID.store(editor_id, Ordering::Relaxed);
}
let mut editor = Self {
editor_id,
buffer: TextBuffer::new(content),
cursors: cursor_set::CursorSet::new((0, 0)),
horizontal_scroll_offset: 0.0,
style: crate::theme::from_iced_theme(&iced::Theme::TokyoNightStorm),
syntax: syntax.to_string(),
last_blink: Instant::now(),
cursor_visible: true,
is_dragging: false,
drag_viewport_point: None,
content_cache: canvas::Cache::default(),
overlay_cache: canvas::Cache::default(),
scrollable_id: Id::unique(),
horizontal_scrollable_id: Id::unique(),
max_content_width_cache: RefCell::new(None),
viewport_scroll: 0.0,
viewport_height: 600.0, viewport_width: 800.0, last_canvas_width: Cell::new(800.0),
history: CommandHistory::new(100),
is_grouping: false,
wrap_enabled: true,
auto_indent_enabled: true,
auto_close_brackets: true,
indent_style: IndentStyle::Spaces(4),
wrap_column: None,
folding_enabled: true,
collapsed_folds: HashSet::new(),
fold_revision: 0,
foldable_regions_cache: RefCell::new(None),
search_state: search::SearchState::new(),
custom_context_menu_entries: Vec::new(),
default_context_menu_enabled: true,
reveal_in_file_manager_enabled: false,
goto_line_state: goto_line::GotoLineState::new(),
command_palette_state: command_palette::CommandPaletteState::new(),
custom_command_palette_entries: Vec::new(),
default_command_palette_enabled: true,
command_palette_enabled: true,
vim_enabled: false,
vim_state: vim::VimState::default(),
translations: Translations::default(),
search_replace_enabled: true,
line_numbers_enabled: true,
show_whitespace: true,
show_indent_guides: true,
show_color_previews: true,
bracket_match_highlight_enabled: true,
bracket_pair_colorization_enabled: true,
sticky_scroll_enabled: true,
lsp_enabled: true,
lsp_client: None,
lsp_document: None,
lsp_pending_changes: Vec::new(),
lsp_shadow_text: String::new(),
lsp_shadow_is_current: true,
lsp_synced_line_count: 1,
lsp_synced_last_line_len: 0,
lsp_edit_snapshot: None,
lsp_auto_flush: true,
has_canvas_focus: false,
focus_locked: false,
show_cursor: false,
modifiers: Cell::new(iced::keyboard::Modifiers::default()),
last_click: Cell::new(None),
font: iced::Font::MONOSPACE,
ime_preedit: None,
font_size: FONT_SIZE,
full_char_width: CHAR_WIDTH * 2.0,
line_height: LINE_HEIGHT,
char_width: CHAR_WIDTH,
last_first_visible_line: 0,
cache_window_start_line: 0,
cache_window_end_line: 0,
buffer_revision: 0,
visual_lines_cache: RefCell::new(None),
resolved_syntax: RefCell::new(None),
highlight_cache: RefCell::new(None),
highlight_lines_remaining: Cell::new(usize::MAX),
bracket_depth_cache: RefCell::new(BracketDepthCache::new()),
pre_edit_line: 0,
pre_edit_last_line: 0,
};
editor.recalculate_char_dimensions(false);
editor
}
pub fn content(&self) -> String {
self.buffer.to_string()
}
#[must_use]
pub fn is_dialog_open(&self) -> bool {
self.search_state.is_open
|| self.goto_line_state.is_open
|| self.command_palette_state.is_open
}
pub fn reset(&mut self, content: &str) -> iced::Task<Message> {
self.buffer = TextBuffer::new(content);
self.cursors.set_single((0, 0));
self.vim_state.reset();
self.horizontal_scroll_offset = 0.0;
self.is_dragging = false;
self.viewport_scroll = 0.0;
self.history = CommandHistory::new(100);
self.is_grouping = false;
self.last_blink = Instant::now();
self.cursor_visible = true;
self.content_cache = canvas::Cache::default();
self.overlay_cache = canvas::Cache::default();
self.buffer_revision = self.buffer_revision.wrapping_add(1);
*self.visual_lines_cache.borrow_mut() = None;
self.pre_edit_line = 0;
self.pre_edit_last_line = usize::MAX;
self.invalidate_highlight_from(0);
*self.bracket_depth_cache.borrow_mut() = BracketDepthCache::new();
self.enqueue_lsp_change();
snap_to(self.scrollable_id.clone(), RelativeOffset::START)
}
pub(crate) fn reset_cursor_blink(&mut self) {
self.last_blink = Instant::now();
self.cursor_visible = true;
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_is_dialog_open_tracks_every_built_in_dialog() {
let mut editor = CodeEditor::new("one\ntwo", "rs");
assert!(!editor.is_dialog_open());
let _ = editor.open_search_dialog();
assert!(editor.is_dialog_open());
let _ = editor.close_search_dialog();
assert!(!editor.is_dialog_open());
let _ = editor.open_goto_line_dialog();
assert!(editor.is_dialog_open());
let _ = editor.close_goto_line_dialog();
assert!(!editor.is_dialog_open());
let _ = editor.open_command_palette();
assert!(editor.is_dialog_open());
let _ = editor.close_command_palette();
assert!(!editor.is_dialog_open());
}
}