use runact::{Actor, ActorContext, ActorError};
use std::any::Any;
#[allow(dead_code)]
pub struct BufferActor {
lines: Vec<String>,
cursor_row: usize,
cursor_col: usize,
modified: bool,
file_path: Option<String>,
pub read_only: bool,
pub state: Option<Box<dyn Any + Send + Sync>>,
history: Vec<BufferEdit>,
history_index: usize,
}
#[derive(Clone, Debug)]
#[allow(dead_code)]
pub enum BufferEdit {
InsertChar {
row: usize,
col: usize,
ch: char,
},
DeleteChar {
row: usize,
col: usize,
ch: char,
},
InsertLine {
row: usize,
split_at: usize,
rest: String,
},
DeleteLine {
row: usize,
content: String,
},
}
#[derive(Clone)]
pub enum BufferMessage {
InsertChar(char),
InsertLine,
DeleteChar,
DeleteLine,
MoveUp,
MoveDown,
MoveLeft,
MoveRight,
MoveToStart,
MoveToEnd,
MoveToNextWord,
MoveToPrevWord,
MoveToEndOfWord,
MoveToLine(usize),
MoveToLastLine,
GetContent,
GetCursorPosition,
GetFilePath,
SetFilePath(Option<String>),
LoadContent(String),
Undo,
Redo,
Echo(String),
#[allow(dead_code)]
AppendLine(String),
#[allow(dead_code)]
GetLines,
#[allow(dead_code)]
Clear,
#[allow(dead_code)]
IsModified,
}
impl Actor for BufferActor {
type Message = BufferMessage;
fn handle(&mut self, msg: BufferMessage, ctx: &mut ActorContext) -> Result<(), ActorError> {
match msg {
BufferMessage::InsertChar(_)
| BufferMessage::InsertLine
| BufferMessage::DeleteChar
| BufferMessage::DeleteLine
if self.read_only =>
{
return Ok(());
}
BufferMessage::InsertChar(ch) => {
if self.cursor_row < self.lines.len() {
let line = &mut self.lines[self.cursor_row];
let prev_col = self.cursor_col;
line.insert(self.cursor_col, ch);
self.cursor_col += 1;
self.modified = true;
self.push_edit(BufferEdit::InsertChar {
row: self.cursor_row,
col: prev_col,
ch,
});
}
}
BufferMessage::InsertLine => {
let line = if self.cursor_row < self.lines.len() {
self.lines[self.cursor_row][self.cursor_col..].to_string()
} else {
String::new()
};
let old_col = self.cursor_col;
let old_row = self.cursor_row;
if self.cursor_row < self.lines.len() {
self.lines[self.cursor_row] =
self.lines[self.cursor_row][..self.cursor_col].to_string();
}
self.cursor_row += 1;
self.cursor_col = 0;
self.lines.insert(self.cursor_row, line);
self.modified = true;
self.push_edit(BufferEdit::InsertLine {
row: old_row,
split_at: old_col,
rest: String::new(),
});
}
BufferMessage::DeleteChar => {
if self.cursor_col > 0 {
let line = &mut self.lines[self.cursor_row];
self.cursor_col -= 1;
let ch = line.remove(self.cursor_col);
self.modified = true;
self.push_edit(BufferEdit::DeleteChar {
row: self.cursor_row,
col: self.cursor_col,
ch,
});
} else if self.cursor_row > 0 {
let current_line = self.lines.remove(self.cursor_row);
self.cursor_row -= 1;
self.cursor_col = self.lines[self.cursor_row].len();
self.lines[self.cursor_row].push_str(¤t_line);
self.modified = true;
}
}
BufferMessage::DeleteLine => {
if self.lines.len() > 1 {
let content = self.lines.remove(self.cursor_row);
if self.cursor_row >= self.lines.len() {
self.cursor_row = self.lines.len() - 1;
}
self.cursor_col = 0;
self.modified = true;
self.push_edit(BufferEdit::DeleteLine {
row: self.cursor_row,
content,
});
} else {
self.lines[0].clear();
self.cursor_col = 0;
self.modified = true;
}
}
BufferMessage::MoveUp => {
if self.cursor_row > 0 {
self.cursor_row -= 1;
self.cursor_col = self.cursor_col.min(self.lines[self.cursor_row].len());
}
}
BufferMessage::MoveDown => {
if self.cursor_row < self.lines.len() - 1 {
self.cursor_row += 1;
self.cursor_col = self.cursor_col.min(self.lines[self.cursor_row].len());
}
}
BufferMessage::MoveLeft => {
if self.cursor_col > 0 {
self.cursor_col -= 1;
} else if self.cursor_row > 0 {
self.cursor_row -= 1;
self.cursor_col = self.lines[self.cursor_row].len();
}
}
BufferMessage::MoveRight => {
if self.cursor_col < self.lines[self.cursor_row].len() {
self.cursor_col += 1;
} else if self.cursor_row < self.lines.len() - 1 {
self.cursor_row += 1;
self.cursor_col = 0;
}
}
BufferMessage::MoveToStart => self.cursor_col = 0,
BufferMessage::MoveToEnd => self.cursor_col = self.lines[self.cursor_row].len(),
BufferMessage::MoveToNextWord => {
let line = &self.lines[self.cursor_row];
let mut col = self.cursor_col;
while col < line.len() && !is_word_char(line[col..].chars().next().unwrap()) {
col += 1;
}
while col < line.len() && is_word_char(line[col..].chars().next().unwrap()) {
col += 1;
}
self.cursor_col = col;
}
BufferMessage::MoveToPrevWord => {
let line = &self.lines[self.cursor_row];
let mut col = self.cursor_col;
while col > 0 && is_word_char(line[col.saturating_sub(1)..].chars().next().unwrap())
{
col -= 1;
}
while col > 0
&& !is_word_char(line[col.saturating_sub(1)..].chars().next().unwrap())
{
col -= 1;
}
self.cursor_col = col;
}
BufferMessage::MoveToEndOfWord => {
let line = &self.lines[self.cursor_row];
let mut col = self.cursor_col;
while col < line.len()
&& !is_word_char(line[col..].chars().next().unwrap())
&& !line[col..].chars().next().unwrap().is_whitespace()
{
col += 1;
}
while col < line.len() && is_word_char(line[col..].chars().next().unwrap()) {
col += 1;
}
if col > self.cursor_col {
self.cursor_col = col.saturating_sub(1).min(line.len());
}
}
BufferMessage::MoveToLine(row) => {
let target = row.saturating_sub(1);
self.cursor_row = target.min(self.lines.len().saturating_sub(1));
self.cursor_col = self.cursor_col.min(self.lines[self.cursor_row].len());
}
BufferMessage::MoveToLastLine => {
self.cursor_row = self.lines.len().saturating_sub(1);
self.cursor_col = self.lines[self.cursor_row].len();
}
BufferMessage::GetContent => {
let _ = ctx.reply(self.lines.join("\n"));
}
BufferMessage::GetCursorPosition => {
let _ = ctx.reply((self.cursor_row, self.cursor_col));
}
BufferMessage::GetFilePath => {
let _ = ctx.reply(self.file_path.clone());
}
BufferMessage::SetFilePath(path) => {
self.file_path = path;
}
BufferMessage::LoadContent(content) => {
self.lines = content_to_lines(&content);
if self.lines.is_empty() {
self.lines.push(String::new());
}
self.cursor_row = 0;
self.cursor_col = 0;
self.modified = false;
self.history.clear();
self.history_index = 0;
}
BufferMessage::Undo => {
if self.history_index > 0 {
self.history_index -= 1;
if let Some(edit) = self.history.get(self.history_index).cloned() {
self.apply_undo(&edit);
}
}
}
BufferMessage::Redo => {
if self.history_index < self.history.len() {
if let Some(edit) = self.history.get(self.history_index).cloned() {
self.apply_redo(&edit);
}
self.history_index += 1;
}
}
BufferMessage::Echo(msg) => {
self.lines.push(msg);
while self.lines.len() > 50 {
self.lines.remove(0);
}
self.cursor_row = self.lines.len().saturating_sub(1);
}
BufferMessage::AppendLine(msg) => {
if let Some(last) = self.lines.last_mut() {
last.push_str(&msg);
} else {
self.lines.push(msg);
}
}
BufferMessage::GetLines => {
let _ = ctx.reply(self.lines.join("\n"));
}
BufferMessage::Clear => {
self.lines.clear();
self.lines.push(String::new());
self.cursor_row = 0;
self.cursor_col = 0;
}
BufferMessage::IsModified => {
let _ = ctx.reply(self.modified);
}
}
Ok(())
}
}
fn is_word_char(c: char) -> bool {
c.is_alphanumeric() || c == '_'
}
pub fn content_to_lines(content: &str) -> Vec<String> {
let mut lines: Vec<String> = content.split('\n').map(String::from).collect();
if lines.len() == 1 && lines[0].is_empty() && content.is_empty() {
return lines;
}
for line in lines.iter_mut() {
if line.ends_with('\r') {
line.pop();
}
}
if lines.is_empty() {
lines.push(String::new());
}
lines
}
#[allow(dead_code)]
impl Default for BufferActor {
fn default() -> Self {
Self::new()
}
}
impl BufferActor {
pub fn new() -> Self {
Self {
lines: vec![String::new()],
cursor_row: 0,
cursor_col: 0,
modified: false,
file_path: None,
read_only: false,
state: None,
history: Vec::new(),
history_index: 0,
}
}
pub fn new_read_only() -> Self {
Self {
read_only: true,
..Self::new()
}
}
#[allow(dead_code)]
pub fn new_with_content(content: &str) -> Self {
let mut a = Self::new();
a.lines = content_to_lines(content);
if a.lines.is_empty() {
a.lines.push(String::new());
}
a
}
#[allow(dead_code)]
pub fn lines(&self) -> &[String] {
&self.lines
}
#[allow(dead_code)]
pub fn cursor_pos(&self) -> (usize, usize) {
(self.cursor_row, self.cursor_col)
}
#[allow(dead_code)]
pub fn is_modified(&self) -> bool {
self.modified
}
#[allow(dead_code)]
pub fn file_path(&self) -> Option<&str> {
self.file_path.as_deref()
}
fn push_edit(&mut self, edit: BufferEdit) {
self.history.truncate(self.history_index);
self.history.push(edit);
self.history_index += 1;
}
fn apply_undo(&mut self, edit: &BufferEdit) {
match edit {
BufferEdit::InsertChar { row, col, ch: _ } => {
if *row < self.lines.len() {
let line = &mut self.lines[*row];
if *col <= line.len() {
line.remove(*col);
}
self.cursor_row = *row;
self.cursor_col = *col;
}
self.modified = true;
}
BufferEdit::DeleteChar { row, col, ch } => {
if *row < self.lines.len() {
let line = &mut self.lines[*row];
if *col <= line.len() {
line.insert(*col, *ch);
}
self.cursor_row = *row;
self.cursor_col = *col + 1;
}
self.modified = true;
}
BufferEdit::InsertLine {
row,
split_at: _,
rest: _,
} => {
if *row < self.lines.len() {
let current = self.lines.remove(*row + 1);
self.lines[*row].push_str(¤t);
self.cursor_row = *row;
self.cursor_col = self.lines[*row].len();
}
self.modified = true;
}
BufferEdit::DeleteLine { row, content } => {
self.lines.insert(*row + 1, content.clone());
self.cursor_row = *row + 1;
self.cursor_col = 0;
self.modified = true;
}
}
}
fn apply_redo(&mut self, edit: &BufferEdit) {
match edit {
BufferEdit::InsertChar { row, col, ch } => {
if *row < self.lines.len() {
let line = &mut self.lines[*row];
if *col <= line.len() {
line.insert(*col, *ch);
}
self.cursor_row = *row;
self.cursor_col = *col + 1;
}
self.modified = true;
}
BufferEdit::DeleteChar { row, col, ch: _ } => {
if *row < self.lines.len() {
let line = &mut self.lines[*row];
if *col <= line.len() {
line.remove(*col);
}
self.cursor_row = *row;
self.cursor_col = *col;
}
self.modified = true;
}
BufferEdit::InsertLine {
row,
split_at,
rest,
} => {
let current = if *row < self.lines.len() {
self.lines[self.cursor_row][*split_at..].to_string()
} else {
rest.clone()
};
if *row < self.lines.len() {
self.lines[*row] =
self.lines[*row][..*split_at.min(&self.lines[*row].len())].to_string();
}
self.lines.insert(*row + 1, current);
self.cursor_row = *row + 1;
self.cursor_col = 0;
self.modified = true;
}
BufferEdit::DeleteLine { row, content: _ } => {
if self.lines.len() > 1 {
self.lines.remove(*row);
if *row >= self.lines.len() {
self.cursor_row = self.lines.len() - 1;
} else {
self.cursor_row = *row;
}
self.cursor_col = 0;
} else {
self.lines[0].clear();
self.cursor_col = 0;
}
self.modified = true;
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_content_to_lines_preserves_trailing_newline() {
let lines = content_to_lines("hello\n");
assert_eq!(lines, vec!["hello".to_string(), String::new()]);
}
#[test]
fn test_content_to_lines_no_trailing_newline() {
let lines = content_to_lines("hello");
assert_eq!(lines, vec!["hello".to_string()]);
}
#[test]
fn test_content_to_lines_empty() {
let lines = content_to_lines("");
assert_eq!(lines, vec![String::new()]);
}
#[test]
fn test_content_to_lines_multiple() {
let lines = content_to_lines("a\nb\nc\n");
assert_eq!(
lines,
vec![
"a".to_string(),
"b".to_string(),
"c".to_string(),
String::new()
]
);
}
#[test]
fn test_content_to_lines_crlf() {
let lines = content_to_lines("a\r\nb\r\n");
assert_eq!(lines, vec!["a".to_string(), "b".to_string(), String::new()]);
}
#[test]
fn test_new_with_content_preserves_trailing_line() {
let actor = BufferActor::new_with_content("hello\n");
assert_eq!(actor.lines().len(), 2);
assert_eq!(actor.lines()[1], "");
}
}