1use std::{
2 borrow::Cow,
3 fmt::Display,
4 ops::{
5 Mul,
6 Range,
7 },
8 time::Duration,
9};
10
11use freya_components::scrollviews::ScrollController;
12use freya_core::{
13 elements::paragraph::ParagraphHolderInner,
14 prelude::*,
15};
16use freya_edit::*;
17use ropey::Rope;
18use torin::geometry::Size2D;
19use tree_sitter::InputEdit;
20
21use crate::{
22 editor_theme::EditorSyntaxTheme,
23 languages::EditorLanguage,
24 metrics::EditorMetrics,
25 syntax::InputEditExt,
26};
27
28pub struct CodeEditorData {
29 pub(crate) history: EditorHistory,
30 pub rope: Rope,
31 pub(crate) selection: TextSelection,
32 pub(crate) last_saved_history_change: usize,
33 pub(crate) metrics: EditorMetrics,
34 pub(crate) dragging: TextDragging,
35 pub(crate) pending_edit: Option<InputEdit>,
36 pub language: Option<EditorLanguage>,
37 pub viewport: Size2D,
38 theme: EditorSyntaxTheme,
39}
40
41impl CodeEditorData {
42 pub fn new(rope: Rope, language: impl Into<Option<EditorLanguage>>) -> Self {
44 let mut data = Self {
45 rope,
46 selection: TextSelection::new_cursor(0),
47 history: EditorHistory::new(Duration::from_secs(1)),
48 last_saved_history_change: 0,
49 metrics: EditorMetrics::new(),
50 dragging: TextDragging::default(),
51 pending_edit: None,
52 language: language.into(),
53 viewport: Size2D::default(),
54 theme: EditorSyntaxTheme::default(),
55 };
56 data.configure_highlighter();
57 data
58 }
59
60 pub fn scroll_to_cursor(
64 &self,
65 mut scroll_controller: ScrollController,
66 line_height: f32,
67 ) -> bool {
68 if self.viewport.width <= 0.
69 || self.viewport.height <= 0.
70 || line_height <= 0.
71 || self.metrics.char_width <= 0.
72 {
73 return false;
74 }
75
76 let (scroll_x, scroll_y) = scroll_controller.into();
77 let scrolled_x = scroll_x as f32;
78 let scrolled_y = scroll_y as f32;
79 let cursor_left = self.cursor_col() as f32 * self.metrics.char_width;
80 let cursor_right = cursor_left + self.metrics.char_width;
81 let cursor_top = self.cursor_row() as f32 * line_height;
82 let cursor_bottom = cursor_top + line_height;
83
84 let horizontal_target = if cursor_left < scrolled_x {
85 Some(cursor_left)
86 } else if cursor_right > scrolled_x + self.viewport.width {
87 Some(cursor_right - self.viewport.width)
88 } else {
89 None
90 };
91
92 let vertical_target = if cursor_top < scrolled_y {
93 Some(cursor_top)
94 } else if cursor_bottom > scrolled_y + self.viewport.height {
95 Some(cursor_bottom - self.viewport.height)
96 } else {
97 None
98 };
99
100 let mut changed = false;
101
102 if let Some(target) = horizontal_target {
103 changed |= scroll_controller.scroll_to_x(target.into());
104 }
105
106 if let Some(target) = vertical_target {
107 changed |= scroll_controller.scroll_to_y(target.into());
108 }
109
110 changed
111 }
112
113 fn configure_highlighter(&mut self) {
115 self.metrics
116 .highlighter
117 .set_language(self.language.as_ref(), &self.theme);
118 }
119
120 pub fn set_language(&mut self, language: impl Into<Option<EditorLanguage>>) {
122 self.language = language.into();
123 self.configure_highlighter();
124 }
125
126 pub fn is_edited(&self) -> bool {
127 self.history.current_change() != self.last_saved_history_change
128 }
129
130 pub fn mark_as_saved(&mut self) {
131 self.last_saved_history_change = self.history.current_change();
132 }
133
134 pub fn parse(&mut self) {
135 let edit = self.pending_edit.take();
136 self.metrics.run_parser(&self.rope, edit, &self.theme);
137 }
138
139 pub fn measure(&mut self, font_size: f32, font_family: &str) {
140 self.metrics
141 .measure_longest_line(font_size, font_family, &self.rope);
142 }
143
144 pub fn set_theme(&mut self, theme: EditorSyntaxTheme) {
145 self.theme = theme;
146 self.configure_highlighter();
147 }
148
149 pub fn process(
150 &mut self,
151 font_size: f32,
152 font_family: &str,
153 edit_event: EditableEvent,
154 ) -> bool {
155 let mut processed = false;
156 let mut text_changed = false;
157 match edit_event {
158 EditableEvent::Down {
159 location,
160 editor_line,
161 holder,
162 } => {
163 let holder = holder.0.borrow();
164 let ParagraphHolderInner {
165 paragraph,
166 scale_factor,
167 ..
168 } = holder.as_ref().unwrap();
169
170 let current_selection = self.selection().clone();
171
172 if self.dragging.shift || self.dragging.clicked {
173 self.selection_mut().set_as_range();
174 } else {
175 self.clear_selection();
176 }
177
178 if ¤t_selection != self.selection() {
179 processed = true;
180 }
181
182 let char_position = paragraph.get_glyph_position_at_coordinate(
183 location.mul(*scale_factor).to_i32().to_tuple(),
184 );
185 let press_selection =
186 self.measure_selection(char_position.position as usize, editor_line);
187
188 let press_type = EventsCombos::<()>::pressed(location);
189 let new_selection = match press_type {
190 PressEventType::Quadruple => {
191 TextSelection::new_range((0, self.rope.len_utf16_cu()))
192 }
193 PressEventType::Triple => {
194 TextSelection::new_range(self.find_line_boundaries(press_selection.pos()))
195 }
196 PressEventType::Double => {
197 TextSelection::new_range(self.find_word_boundaries(press_selection.pos()))
198 }
199 PressEventType::Single => press_selection,
200 };
201
202 self.dragging
203 .start_selection(press_type, new_selection.clone());
204
205 if *self.selection() != new_selection {
206 *self.selection_mut() = new_selection;
207 processed = true;
208 }
209 }
210 EditableEvent::Move {
211 location,
212 editor_line,
213 holder,
214 } => {
215 if self.dragging.clicked {
216 EventsCombos::<()>::moved(location);
217
218 let paragraph = holder.0.borrow();
219 let ParagraphHolderInner {
220 paragraph,
221 scale_factor,
222 ..
223 } = paragraph.as_ref().unwrap();
224
225 let dist_position = location.mul(*scale_factor);
226
227 let dist_char = paragraph
229 .get_glyph_position_at_coordinate(dist_position.to_i32().to_tuple());
230 let to = dist_char.position as usize;
231
232 if self.get_selection().is_none() {
233 self.selection_mut().set_as_range();
234 processed = true;
235 }
236
237 let current_selection = self.selection().clone();
238
239 let new_selection = self.dragging.measure_selection(self, to, editor_line);
240
241 if current_selection != new_selection {
243 *self.selection_mut() = new_selection;
244 processed = true;
245 }
246 }
247 }
248 EditableEvent::Paste { contents } => {
249 text_changed = self.paste(contents).contains(TextEvent::TEXT_CHANGED);
250 processed = text_changed;
251 }
252 EditableEvent::Release => {
253 self.dragging.clicked = false;
254 EventsCombos::<()>::released();
255 }
256 EditableEvent::KeyDown {
257 key,
258 modifiers,
259 editor_line,
260 holder,
261 } => {
262 match key {
263 Key::Named(NamedKey::Shift) => {
265 self.dragging.shift = true;
266 }
267 _ => {
269 let event = self.process_key(
270 key,
271 &modifiers,
272 editor_line,
273 holder,
274 true,
275 true,
276 true,
277 );
278 text_changed = event.contains(TextEvent::TEXT_CHANGED);
279 if !event.is_empty() {
280 processed = true;
281 }
282 }
283 }
284 }
285 EditableEvent::KeyUp { key, .. } => {
286 if *key == Key::Named(NamedKey::Shift) {
287 self.dragging.shift = false;
288 }
289 }
290 };
291 if text_changed {
292 self.parse();
293 self.measure(font_size, font_family);
294 self.dragging = TextDragging::default();
295 }
296 processed
297 }
298}
299
300impl Display for CodeEditorData {
301 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
302 f.write_str(&self.rope.to_string())
303 }
304}
305
306impl TextEditor for CodeEditorData {
307 type LinesIterator<'a>
308 = LinesIterator<'a>
309 where
310 Self: 'a;
311
312 fn lines(&self) -> Self::LinesIterator<'_> {
313 unimplemented!("Unused.")
314 }
315
316 fn text(&self) -> Cow<'_, str> {
317 self.rope.slice(..).into()
318 }
319
320 fn insert_char(&mut self, ch: char, idx: usize) -> usize {
321 let idx_utf8 = self.utf16_cu_to_char(idx);
322 let selection = self.selection.clone();
323
324 let start_byte = self.rope.char_to_byte(idx_utf8);
326 let start_line = self.rope.char_to_line(idx_utf8);
327 let start_line_byte = self.rope.line_to_byte(start_line);
328 let start_col = start_byte - start_line_byte;
329
330 let len_before_insert = self.rope.len_utf16_cu();
331 self.rope.insert_char(idx_utf8, ch);
332 let len_after_insert = self.rope.len_utf16_cu();
333
334 let inserted_text_len = len_after_insert - len_before_insert;
335
336 let new_end_char = idx_utf8 + 1; let new_end_byte = self.rope.char_to_byte(new_end_char);
339 let new_end_line = self.rope.char_to_line(new_end_char);
340 let new_end_line_byte = self.rope.line_to_byte(new_end_line);
341 let new_end_col = new_end_byte - new_end_line_byte;
342
343 self.pending_edit = Some(InputEdit::new_edit(
344 start_byte,
345 start_byte,
346 new_end_byte,
347 (start_line, start_col),
348 (start_line, start_col),
349 (new_end_line, new_end_col),
350 ));
351
352 self.history.push_change(HistoryChange::InsertChar {
353 idx,
354 ch,
355 len: inserted_text_len,
356 selection,
357 });
358
359 inserted_text_len
360 }
361
362 fn insert(&mut self, text: &str, idx: usize) -> usize {
363 let idx_utf8 = self.utf16_cu_to_char(idx);
364 let selection = self.selection.clone();
365
366 let start_byte = self.rope.char_to_byte(idx_utf8);
368 let start_line = self.rope.char_to_line(idx_utf8);
369 let start_line_byte = self.rope.line_to_byte(start_line);
370 let start_col = start_byte - start_line_byte;
371
372 let len_before_insert = self.rope.len_utf16_cu();
373 self.rope.insert(idx_utf8, text);
374 let len_after_insert = self.rope.len_utf16_cu();
375
376 let inserted_text_len = len_after_insert - len_before_insert;
377
378 let inserted_chars = text.chars().count();
380 let new_end_char = idx_utf8 + inserted_chars;
381 let new_end_byte = self.rope.char_to_byte(new_end_char);
382 let new_end_line = self.rope.char_to_line(new_end_char);
383 let new_end_line_byte = self.rope.line_to_byte(new_end_line);
384 let new_end_col = new_end_byte - new_end_line_byte;
385
386 self.pending_edit = Some(InputEdit::new_edit(
387 start_byte,
388 start_byte,
389 new_end_byte,
390 (start_line, start_col),
391 (start_line, start_col),
392 (new_end_line, new_end_col),
393 ));
394
395 self.history.push_change(HistoryChange::InsertText {
396 idx,
397 text: text.to_owned(),
398 len: inserted_text_len,
399 selection,
400 });
401
402 inserted_text_len
403 }
404
405 fn remove(&mut self, range_utf16: Range<usize>) -> usize {
406 let range =
407 self.utf16_cu_to_char(range_utf16.start)..self.utf16_cu_to_char(range_utf16.end);
408 let text = self.rope.slice(range.clone()).to_string();
409 let selection = self.selection.clone();
410
411 let start_byte = self.rope.char_to_byte(range.start);
413 let old_end_byte = self.rope.char_to_byte(range.end);
414 let start_line = self.rope.char_to_line(range.start);
415 let start_line_byte = self.rope.line_to_byte(start_line);
416 let start_col = start_byte - start_line_byte;
417 let old_end_line = self.rope.char_to_line(range.end);
418 let old_end_line_byte = self.rope.line_to_byte(old_end_line);
419 let old_end_col = old_end_byte - old_end_line_byte;
420
421 let len_before_remove = self.rope.len_utf16_cu();
422 self.rope.remove(range);
423 let len_after_remove = self.rope.len_utf16_cu();
424
425 let removed_text_len = len_before_remove - len_after_remove;
426
427 self.pending_edit = Some(InputEdit::new_edit(
429 start_byte,
430 old_end_byte,
431 start_byte,
432 (start_line, start_col),
433 (old_end_line, old_end_col),
434 (start_line, start_col),
435 ));
436
437 self.history.push_change(HistoryChange::Remove {
438 idx: range_utf16.end - removed_text_len,
439 text,
440 len: removed_text_len,
441 selection,
442 });
443
444 removed_text_len
445 }
446
447 fn char_to_line(&self, char_idx: usize) -> usize {
448 self.rope.char_to_line(char_idx)
449 }
450
451 fn line_to_char(&self, line_idx: usize) -> usize {
452 self.rope.line_to_char(line_idx)
453 }
454
455 fn utf16_cu_to_char(&self, utf16_cu_idx: usize) -> usize {
456 self.rope.utf16_cu_to_char(utf16_cu_idx)
457 }
458
459 fn char_to_utf16_cu(&self, idx: usize) -> usize {
460 self.rope.char_to_utf16_cu(idx)
461 }
462
463 fn line(&self, line_idx: usize) -> Option<Line<'_>> {
464 let line = self.rope.get_line(line_idx);
465
466 line.map(|line| Line {
467 text: Cow::Owned(line.to_string()),
468 utf16_len: line.len_utf16_cu(),
469 })
470 }
471
472 fn len_lines(&self) -> usize {
473 self.rope.len_lines()
474 }
475
476 fn len_chars(&self) -> usize {
477 self.rope.len_chars()
478 }
479
480 fn len_utf16_cu(&self) -> usize {
481 self.rope.len_utf16_cu()
482 }
483
484 fn has_any_selection(&self) -> bool {
485 self.selection.is_range()
486 }
487
488 fn get_selection(&self) -> Option<(usize, usize)> {
489 match self.selection {
490 TextSelection::Cursor(_) => None,
491 TextSelection::Range { from, to } => Some((from, to)),
492 }
493 }
494
495 fn set(&mut self, text: &str) {
496 self.rope.remove(0..);
497 self.rope.insert(0, text);
498 self.selection.clamp(&self.rope);
499 }
500
501 fn clear_selection(&mut self) {
502 let end = self.selection().end();
503 self.selection_mut().set_as_cursor();
504 self.selection_mut().move_to(end);
505 }
506
507 fn set_selection(&mut self, (from, to): (usize, usize)) {
508 self.selection = TextSelection::Range { from, to };
509 }
510
511 fn get_selected_text(&self) -> Option<String> {
512 let (start, end) = self.get_selection_range()?;
513 let start = self.rope.try_utf16_cu_to_char(start).ok()?;
515 let end = self.rope.try_utf16_cu_to_char(end).ok()?;
516
517 Some(self.rope.get_slice(start..end)?.to_string())
518 }
519
520 fn get_selection_range(&self) -> Option<(usize, usize)> {
521 let (start, end) = match self.selection {
522 TextSelection::Cursor(_) => return None,
523 TextSelection::Range { from, to } => (from, to),
524 };
525
526 let (start, end) = if start < end {
528 (start, end)
529 } else {
530 (end, start)
531 };
532
533 Some((start, end))
534 }
535
536 fn undo(&mut self) -> Option<TextSelection> {
537 self.pending_edit = None;
539 self.metrics.highlighter.invalidate_tree();
540 self.history.undo(&mut self.rope)
541 }
542
543 fn redo(&mut self) -> Option<TextSelection> {
544 self.pending_edit = None;
546 self.metrics.highlighter.invalidate_tree();
547 self.history.redo(&mut self.rope)
548 }
549
550 fn editor_history(&self) -> &EditorHistory {
551 &self.history
552 }
553
554 fn editor_history_mut(&mut self) -> &mut EditorHistory {
555 &mut self.history
556 }
557
558 fn selection(&self) -> &TextSelection {
559 &self.selection
560 }
561
562 fn selection_mut(&mut self) -> &mut TextSelection {
563 &mut self.selection
564 }
565
566 fn get_indentation(&self) -> u8 {
567 4
568 }
569}