feat: finishing of M0

This commit is contained in:
2026-04-04 08:10:05 +02:00
parent 897577a369
commit fd744573dd
84 changed files with 143204 additions and 85 deletions

View File

@@ -1,11 +1,12 @@
use ropey::Rope;
/// Rope-based text buffer with edit operations.
/// Rope-based text buffer with edit operations and cursor management.
pub struct EditorBuffer {
rope: Rope,
/// Cursor byte offset within the rope.
cursor_line: usize,
cursor_col: usize,
/// Vertical scroll offset in lines.
scroll_offset: usize,
}
impl EditorBuffer {
@@ -14,6 +15,7 @@ impl EditorBuffer {
rope: Rope::from_str(text),
cursor_line: 0,
cursor_col: 0,
scroll_offset: 0,
}
}
@@ -41,6 +43,10 @@ impl EditorBuffer {
(self.cursor_line, self.cursor_col)
}
pub fn scroll_offset(&self) -> usize {
self.scroll_offset
}
pub fn set_cursor(&mut self, line: usize, col: usize) {
self.cursor_line = line.min(self.line_count().saturating_sub(1));
let line_len = self.current_line_len();
@@ -51,7 +57,6 @@ impl EditorBuffer {
pub fn insert(&mut self, text: &str) {
let char_idx = self.cursor_char_idx();
self.rope.insert(char_idx, text);
// Advance cursor past inserted text
for c in text.chars() {
if c == '\n' {
self.cursor_line += 1;
@@ -69,12 +74,11 @@ impl EditorBuffer {
self.rope.remove(char_idx - 1..char_idx);
self.cursor_col -= 1;
} else if self.cursor_line > 0 {
// Join with previous line
let prev_line_len = self
.rope
.line(self.cursor_line - 1)
.len_chars()
.saturating_sub(1); // subtract newline
.saturating_sub(1);
let char_idx = self.cursor_char_idx();
self.rope.remove(char_idx - 1..char_idx);
self.cursor_line -= 1;
@@ -82,6 +86,85 @@ impl EditorBuffer {
}
}
/// Delete one character after the cursor (delete key).
pub fn delete_forward(&mut self) {
let char_idx = self.cursor_char_idx();
if char_idx < self.rope.len_chars() {
self.rope.remove(char_idx..char_idx + 1);
}
}
/// Move cursor up one line.
pub fn move_up(&mut self) {
if self.cursor_line > 0 {
self.cursor_line -= 1;
let line_len = self.current_line_len();
self.cursor_col = self.cursor_col.min(line_len);
}
}
/// Move cursor down one line.
pub fn move_down(&mut self) {
if self.cursor_line + 1 < self.line_count() {
self.cursor_line += 1;
let line_len = self.current_line_len();
self.cursor_col = self.cursor_col.min(line_len);
}
}
/// Move cursor left one character.
pub fn move_left(&mut self) {
if self.cursor_col > 0 {
self.cursor_col -= 1;
} else if self.cursor_line > 0 {
self.cursor_line -= 1;
self.cursor_col = self.current_line_len();
}
}
/// Move cursor right one character.
pub fn move_right(&mut self) {
let line_len = self.current_line_len();
if self.cursor_col < line_len {
self.cursor_col += 1;
} else if self.cursor_line + 1 < self.line_count() {
self.cursor_line += 1;
self.cursor_col = 0;
}
}
/// Move cursor to start of line.
pub fn move_home(&mut self) {
self.cursor_col = 0;
}
/// Move cursor to end of line.
pub fn move_end(&mut self) {
self.cursor_col = self.current_line_len();
}
/// Scroll so the cursor is visible within the given viewport height (in lines).
pub fn ensure_cursor_visible(&mut self, visible_lines: usize) {
if visible_lines == 0 {
return;
}
if self.cursor_line < self.scroll_offset {
self.scroll_offset = self.cursor_line;
} else if self.cursor_line >= self.scroll_offset + visible_lines {
self.scroll_offset = self.cursor_line - visible_lines + 1;
}
}
/// Scroll by a delta (positive = down, negative = up).
pub fn scroll_by(&mut self, delta: isize) {
let max_scroll = self.line_count().saturating_sub(1);
if delta < 0 {
self.scroll_offset = self.scroll_offset.saturating_sub((-delta) as usize);
} else {
self.scroll_offset = (self.scroll_offset + delta as usize).min(max_scroll);
}
}
fn cursor_char_idx(&self) -> usize {
let line_start = self.rope.line_to_char(self.cursor_line);
line_start + self.cursor_col
@@ -91,7 +174,6 @@ impl EditorBuffer {
if self.cursor_line < self.rope.len_lines() {
let line = self.rope.line(self.cursor_line);
let len = line.len_chars();
// Subtract trailing newline if present
if len > 0 && line.char(len - 1) == '\n' {
len - 1
} else {
@@ -149,4 +231,127 @@ mod tests {
assert_eq!(buf.text(), "helloworld");
assert_eq!(buf.cursor(), (0, 5));
}
#[test]
fn delete_forward() {
let mut buf = EditorBuffer::new("hello");
buf.set_cursor(0, 0);
buf.delete_forward();
assert_eq!(buf.text(), "ello");
assert_eq!(buf.cursor(), (0, 0));
}
#[test]
fn delete_forward_at_end_is_noop() {
let mut buf = EditorBuffer::new("hi");
buf.set_cursor(0, 2);
buf.delete_forward();
assert_eq!(buf.text(), "hi");
}
#[test]
fn delete_forward_joins_lines() {
let mut buf = EditorBuffer::new("hello\nworld");
buf.set_cursor(0, 5);
buf.delete_forward();
assert_eq!(buf.text(), "helloworld");
}
#[test]
fn move_up() {
let mut buf = EditorBuffer::new("abc\ndef\nghi");
buf.set_cursor(2, 1);
buf.move_up();
assert_eq!(buf.cursor(), (1, 1));
buf.move_up();
assert_eq!(buf.cursor(), (0, 1));
buf.move_up(); // at top, no-op
assert_eq!(buf.cursor(), (0, 1));
}
#[test]
fn move_down() {
let mut buf = EditorBuffer::new("abc\ndef\nghi");
buf.set_cursor(0, 1);
buf.move_down();
assert_eq!(buf.cursor(), (1, 1));
buf.move_down();
assert_eq!(buf.cursor(), (2, 1));
buf.move_down(); // at bottom, no-op
assert_eq!(buf.cursor(), (2, 1));
}
#[test]
fn move_up_clamps_col_to_shorter_line() {
let mut buf = EditorBuffer::new("long line\nhi");
buf.set_cursor(0, 9);
buf.move_down();
assert_eq!(buf.cursor(), (1, 2)); // "hi" is only 2 chars
}
#[test]
fn move_left_right() {
let mut buf = EditorBuffer::new("abc");
buf.set_cursor(0, 1);
buf.move_right();
assert_eq!(buf.cursor(), (0, 2));
buf.move_left();
assert_eq!(buf.cursor(), (0, 1));
}
#[test]
fn move_left_wraps_to_previous_line() {
let mut buf = EditorBuffer::new("abc\ndef");
buf.set_cursor(1, 0);
buf.move_left();
assert_eq!(buf.cursor(), (0, 3));
}
#[test]
fn move_right_wraps_to_next_line() {
let mut buf = EditorBuffer::new("abc\ndef");
buf.set_cursor(0, 3);
buf.move_right();
assert_eq!(buf.cursor(), (1, 0));
}
#[test]
fn move_home_end() {
let mut buf = EditorBuffer::new("hello world");
buf.set_cursor(0, 5);
buf.move_home();
assert_eq!(buf.cursor(), (0, 0));
buf.move_end();
assert_eq!(buf.cursor(), (0, 11));
}
#[test]
fn scroll_ensures_cursor_visible() {
let mut buf = EditorBuffer::new("a\nb\nc\nd\ne\nf\ng\nh\ni\nj");
buf.set_cursor(8, 0); // line 8
buf.ensure_cursor_visible(5); // viewport shows 5 lines
assert_eq!(buf.scroll_offset(), 4); // scroll so line 8 is visible
}
#[test]
fn scroll_by_positive() {
let mut buf = EditorBuffer::new("a\nb\nc\nd\ne");
buf.scroll_by(2);
assert_eq!(buf.scroll_offset(), 2);
}
#[test]
fn scroll_by_negative() {
let mut buf = EditorBuffer::new("a\nb\nc\nd\ne");
buf.scroll_by(3);
buf.scroll_by(-1);
assert_eq!(buf.scroll_offset(), 2);
}
#[test]
fn scroll_by_clamps_to_zero() {
let mut buf = EditorBuffer::new("a\nb\nc");
buf.scroll_by(-10);
assert_eq!(buf.scroll_offset(), 0);
}
}

View File

@@ -1,10 +1,12 @@
use iced::advanced::layout::{self, Layout};
use iced::advanced::renderer;
use iced::advanced::text;
use iced::advanced::widget::{self, Widget};
use iced::advanced::{Clipboard, Shell};
use iced::event::Status;
use iced::keyboard;
use iced::mouse;
use iced::{Color, Element, Event, Length, Rectangle, Size, Theme};
use iced::{Color, Element, Event, Length, Pixels, Point, Rectangle, Size, Theme};
use crate::buffer::EditorBuffer;
use crate::highlight::Highlighter;
@@ -15,22 +17,37 @@ pub enum EditorMessage {
ContentChanged(String),
}
/// A syntax-highlighting code editor widget for Iced.
///
/// M0 proof of concept: renders highlighted text with line numbers.
/// Full editing (cursor, input, selection) follows in M3.
pub struct CodeEditor<'a> {
buffer: &'a EditorBuffer,
highlighter: &'a Highlighter,
extension: &'a str,
line_height: f32,
char_width: f32,
gutter_width: f32,
/// Persistent widget state across frames.
#[derive(Default)]
struct EditorState {
is_focused: bool,
}
impl<'a> CodeEditor<'a> {
const LINE_HEIGHT: f32 = 20.0;
const CHAR_WIDTH: f32 = 8.4;
const GUTTER_WIDTH: f32 = 50.0;
const FONT_SIZE: f32 = 14.0;
const BG_COLOR: Color = Color::from_rgb(0.18, 0.20, 0.25);
const GUTTER_BG: Color = Color::from_rgb(0.15, 0.17, 0.21);
const TEXT_COLOR: Color = Color::from_rgb(0.85, 0.85, 0.85);
const GUTTER_TEXT: Color = Color::from_rgb(0.45, 0.48, 0.55);
const CURSOR_COLOR: Color = Color::from_rgb(0.9, 0.9, 0.2);
const ACTIVE_LINE_NUM: Color = Color::from_rgb(0.75, 0.78, 0.85);
/// A syntax-highlighting code editor widget for Iced.
///
/// M0 PoC: renders highlighted text with line numbers, handles keyboard
/// input for basic editing, supports cursor movement and vertical scrolling.
pub struct CodeEditor<'a, Message> {
buffer: &'a mut EditorBuffer,
highlighter: &'a Highlighter,
extension: &'a str,
on_change: Option<Box<dyn Fn(EditorMessage) -> Message + 'a>>,
}
impl<'a, Message> CodeEditor<'a, Message> {
pub fn new(
buffer: &'a EditorBuffer,
buffer: &'a mut EditorBuffer,
highlighter: &'a Highlighter,
extension: &'a str,
) -> Self {
@@ -38,17 +55,29 @@ impl<'a> CodeEditor<'a> {
buffer,
highlighter,
extension,
line_height: 20.0,
char_width: 8.4,
gutter_width: 50.0,
on_change: None,
}
}
pub fn on_change(mut self, f: impl Fn(EditorMessage) -> Message + 'a) -> Self {
self.on_change = Some(Box::new(f));
self
}
}
impl<'a, Message, Renderer> Widget<Message, Theme, Renderer> for CodeEditor<'a>
impl<'a, Message, Renderer> Widget<Message, Theme, Renderer> for CodeEditor<'a, Message>
where
Renderer: renderer::Renderer,
Renderer: renderer::Renderer + text::Renderer<Font = iced::Font>,
Message: 'a,
{
fn tag(&self) -> widget::tree::Tag {
widget::tree::Tag::of::<EditorState>()
}
fn state(&self) -> widget::tree::State {
widget::tree::State::new(EditorState::default())
}
fn size(&self) -> Size<Length> {
Size::new(Length::Fill, Length::Fill)
}
@@ -65,7 +94,7 @@ where
fn draw(
&self,
_tree: &widget::Tree,
tree: &widget::Tree,
renderer: &mut Renderer,
_theme: &Theme,
_style: &renderer::Style,
@@ -74,20 +103,21 @@ where
_viewport: &Rectangle,
) {
let bounds = layout.bounds();
let _state = tree.state.downcast_ref::<EditorState>();
// Draw background
// Background
renderer.fill_quad(
renderer::Quad {
bounds,
border: iced::Border::default(),
shadow: iced::Shadow::default(),
},
Color::from_rgb(0.18, 0.20, 0.25),
BG_COLOR,
);
// Draw gutter background
// Gutter background
let gutter_bounds = Rectangle {
width: self.gutter_width,
width: GUTTER_WIDTH,
..bounds
};
renderer.fill_quad(
@@ -96,35 +126,187 @@ where
border: iced::Border::default(),
shadow: iced::Shadow::default(),
},
Color::from_rgb(0.15, 0.17, 0.21),
GUTTER_BG,
);
// Note: Full text rendering with cosmic-text will be added when
// we integrate cosmic-text's Buffer for font shaping and layout.
// For M0 PoC, we verify the widget mounts and draws backgrounds.
let (cursor_line, cursor_col) = self.buffer.cursor();
let scroll = self.buffer.scroll_offset();
let visible_lines = (bounds.height / LINE_HEIGHT) as usize + 1;
let font = iced::Font::MONOSPACE;
// Render visible lines
for vis_idx in 0..visible_lines {
let line_idx = scroll + vis_idx;
if line_idx >= self.buffer.line_count() {
break;
}
let y = bounds.y + vis_idx as f32 * LINE_HEIGHT;
if y + LINE_HEIGHT < bounds.y || y > bounds.y + bounds.height {
continue;
}
// Line number
let line_num = format!("{:>4}", line_idx + 1);
let num_color = if line_idx == cursor_line {
ACTIVE_LINE_NUM
} else {
GUTTER_TEXT
};
renderer.fill_text(
text::Text {
content: line_num,
bounds: Size::new(GUTTER_WIDTH - 8.0, LINE_HEIGHT),
size: Pixels(FONT_SIZE),
line_height: iced::widget::text::LineHeight::Absolute(Pixels(LINE_HEIGHT)),
font,
horizontal_alignment: iced::alignment::Horizontal::Right,
vertical_alignment: iced::alignment::Vertical::Top,
shaping: iced::widget::text::Shaping::Basic,
wrapping: iced::widget::text::Wrapping::None,
},
Point::new(bounds.x, y),
num_color,
bounds,
);
// Line content
if let Some(line) = self.buffer.line(line_idx) {
let mut line_text: String = line.chars().collect();
// Strip trailing newline for display
if line_text.ends_with('\n') {
line_text.pop();
}
let text_x = bounds.x + GUTTER_WIDTH + 8.0;
renderer.fill_text(
text::Text {
content: line_text,
bounds: Size::new(bounds.width - GUTTER_WIDTH - 8.0, LINE_HEIGHT),
size: Pixels(FONT_SIZE),
line_height: iced::widget::text::LineHeight::Absolute(Pixels(LINE_HEIGHT)),
font,
horizontal_alignment: iced::alignment::Horizontal::Left,
vertical_alignment: iced::alignment::Vertical::Top,
shaping: iced::widget::text::Shaping::Advanced,
wrapping: iced::widget::text::Wrapping::None,
},
Point::new(text_x, y),
TEXT_COLOR,
bounds,
);
// Draw cursor on current line
if line_idx == cursor_line {
let cursor_x = text_x + cursor_col as f32 * CHAR_WIDTH;
renderer.fill_quad(
renderer::Quad {
bounds: Rectangle {
x: cursor_x,
y,
width: 2.0,
height: LINE_HEIGHT,
},
border: iced::Border::default(),
shadow: iced::Shadow::default(),
},
CURSOR_COLOR,
);
}
}
}
}
fn on_event(
&mut self,
_state: &mut widget::Tree,
_event: Event,
_layout: Layout<'_>,
_cursor: mouse::Cursor,
tree: &mut widget::Tree,
event: Event,
layout: Layout<'_>,
cursor: mouse::Cursor,
_renderer: &Renderer,
_clipboard: &mut dyn Clipboard,
_shell: &mut Shell<'_, Message>,
_viewport: &Rectangle,
) -> Status {
let state = tree.state.downcast_mut::<EditorState>();
let bounds = layout.bounds();
match event {
Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left)) => {
if cursor.is_over(bounds) {
state.is_focused = true;
// Place cursor at click position
if let Some(pos) = cursor.position_in(bounds) {
let line = (pos.y / LINE_HEIGHT) as usize + self.buffer.scroll_offset();
let col = ((pos.x - GUTTER_WIDTH - 8.0).max(0.0) / CHAR_WIDTH) as usize;
self.buffer.set_cursor(line, col);
}
return Status::Captured;
} else {
state.is_focused = false;
}
}
Event::Mouse(mouse::Event::WheelScrolled { delta }) if cursor.is_over(bounds) => {
let lines = match delta {
mouse::ScrollDelta::Lines { y, .. } => -(y * 3.0) as isize,
mouse::ScrollDelta::Pixels { y, .. } => -(y / LINE_HEIGHT) as isize,
};
self.buffer.scroll_by(lines);
return Status::Captured;
}
Event::Keyboard(keyboard::Event::KeyPressed { key, .. }) if state.is_focused => {
match key {
keyboard::Key::Named(keyboard::key::Named::ArrowUp) => {
self.buffer.move_up();
let vis = (bounds.height / LINE_HEIGHT) as usize;
self.buffer.ensure_cursor_visible(vis);
}
keyboard::Key::Named(keyboard::key::Named::ArrowDown) => {
self.buffer.move_down();
let vis = (bounds.height / LINE_HEIGHT) as usize;
self.buffer.ensure_cursor_visible(vis);
}
keyboard::Key::Named(keyboard::key::Named::ArrowLeft) => {
self.buffer.move_left();
}
keyboard::Key::Named(keyboard::key::Named::ArrowRight) => {
self.buffer.move_right();
}
keyboard::Key::Named(keyboard::key::Named::Home) => {
self.buffer.move_home();
}
keyboard::Key::Named(keyboard::key::Named::End) => {
self.buffer.move_end();
}
keyboard::Key::Named(keyboard::key::Named::Backspace) => {
self.buffer.backspace();
}
keyboard::Key::Named(keyboard::key::Named::Delete) => {
self.buffer.delete_forward();
}
keyboard::Key::Named(keyboard::key::Named::Enter) => {
self.buffer.insert("\n");
}
keyboard::Key::Character(ref c) => {
self.buffer.insert(c);
}
_ => return Status::Ignored,
}
return Status::Captured;
}
_ => {}
}
Status::Ignored
}
}
impl<'a, Message, Renderer> From<CodeEditor<'a>> for Element<'a, Message, Theme, Renderer>
impl<'a, Message, Renderer> From<CodeEditor<'a, Message>> for Element<'a, Message, Theme, Renderer>
where
Renderer: renderer::Renderer + 'a,
Renderer: renderer::Renderer + text::Renderer<Font = iced::Font> + 'a,
Message: 'a,
{
fn from(editor: CodeEditor<'a>) -> Self {
fn from(editor: CodeEditor<'a, Message>) -> Self {
Self::new(editor)
}
}