feat: updated nvim and vscode to new controller api

This commit is contained in:
əlemi 2023-07-09 03:44:39 +02:00
parent ca42874590
commit 1b747491bc
3 changed files with 73 additions and 69 deletions

View file

@ -1,9 +1,10 @@
use std::sync::Arc; use std::sync::Arc;
use std::{net::TcpStream, sync::Mutex, collections::BTreeMap}; use std::{net::TcpStream, sync::Mutex, collections::BTreeMap};
use codemp::cursor::{CursorSubscriber, CursorControllerHandle};
use codemp::operation::{OperationController, OperationFactory, OperationProcessor};
use codemp::client::CodempClient; use codemp::client::CodempClient;
use codemp::controller::buffer::{OperationControllerHandle, OperationControllerSubscriber};
use codemp::controller::cursor::{CursorControllerHandle, CursorSubscriber};
use codemp::factory::OperationFactory;
use codemp::proto::buffer_client::BufferClient; use codemp::proto::buffer_client::BufferClient;
use codemp::tokio; use codemp::tokio;
@ -16,8 +17,8 @@ use tracing::{error, warn, debug, info};
#[derive(Clone)] #[derive(Clone)]
struct NeovimHandler { struct NeovimHandler {
client: CodempClient, client: CodempClient,
factories: Arc<Mutex<BTreeMap<String, Arc<OperationController>>>>, factories: Arc<Mutex<BTreeMap<String, OperationControllerHandle>>>,
cursors: Arc<Mutex<BTreeMap<String, Arc<CursorControllerHandle>>>>, cursors: Arc<Mutex<BTreeMap<String, CursorControllerHandle>>>,
} }
fn nullable_optional_str(args: &[Value], index: usize) -> Option<String> { fn nullable_optional_str(args: &[Value], index: usize) -> Option<String> {
@ -37,11 +38,11 @@ fn default_zero_number(args: &[Value], index: usize) -> i64 {
} }
impl NeovimHandler { impl NeovimHandler {
fn buffer_controller(&self, path: &String) -> Option<Arc<OperationController>> { fn buffer_controller(&self, path: &String) -> Option<OperationControllerHandle> {
Some(self.factories.lock().unwrap().get(path)?.clone()) Some(self.factories.lock().unwrap().get(path)?.clone())
} }
fn cursor_controller(&self, path: &String) -> Option<Arc<CursorControllerHandle>> { fn cursor_controller(&self, path: &String) -> Option<CursorControllerHandle> {
Some(self.cursors.lock().unwrap().get(path)?.clone()) Some(self.cursors.lock().unwrap().get(path)?.clone())
} }
} }
@ -89,11 +90,9 @@ impl Handler for NeovimHandler {
match self.buffer_controller(&path) { match self.buffer_controller(&path) {
None => Err(Value::from("no controller for given path")), None => Err(Value::from("no controller for given path")),
Some(controller) => { Some(controller) => {
match controller.apply(controller.insert(&txt, pos as u64)) { controller.apply(controller.insert(&txt, pos as u64)).await;
Err(e) => Err(Value::from(format!("could not send insert: {}", e))), Ok(Value::Nil)
Ok(_res) => Ok(Value::Nil), },
}
}
} }
}, },
@ -107,9 +106,9 @@ impl Handler for NeovimHandler {
match self.buffer_controller(&path) { match self.buffer_controller(&path) {
None => Err(Value::from("no controller for given path")), None => Err(Value::from("no controller for given path")),
Some(controller) => match controller.apply(controller.delete(pos, count)) { Some(controller) => {
Err(e) => Err(Value::from(format!("could not send delete: {}", e))), controller.apply(controller.delete(pos, count)).await;
Ok(_res) => Ok(Value::Nil), Ok(Value::Nil)
} }
} }
}, },
@ -123,9 +122,11 @@ impl Handler for NeovimHandler {
match self.buffer_controller(&path) { match self.buffer_controller(&path) {
None => Err(Value::from("no controller for given path")), None => Err(Value::from("no controller for given path")),
Some(controller) => match controller.apply(controller.replace(&txt)) { Some(controller) => {
Err(e) => Err(Value::from(format!("could not send replace: {}", e))), if let Some(op) = controller.replace(&txt) {
Ok(_res) => Ok(Value::Nil), controller.apply(op).await;
}
Ok(Value::Nil)
} }
} }
}, },
@ -145,17 +146,15 @@ impl Handler for NeovimHandler {
match c.attach(path.clone()).await { match c.attach(path.clone()).await {
Err(e) => Err(Value::from(format!("could not attach to stream: {}", e))), Err(e) => Err(Value::from(format!("could not attach to stream: {}", e))),
Ok(controller) => { Ok(controller) => {
let _controller = controller.clone(); let mut _controller = controller.clone();
let lines : Vec<String> = _controller.content().split('\n').map(|x| x.to_string()).collect(); let lines : Vec<String> = _controller.content().split('\n').map(|x| x.to_string()).collect();
match buffer.set_lines(0, -1, false, lines).await { match buffer.set_lines(0, -1, false, lines).await {
Err(e) => Err(Value::from(format!("could not sync buffer: {}", e))), Err(e) => Err(Value::from(format!("could not sync buffer: {}", e))),
Ok(()) => { Ok(()) => {
tokio::spawn(async move { tokio::spawn(async move {
loop { while let Some(_change) = _controller.poll().await {
if !_controller.run() { break debug!("buffer updater clean exit") }
let _span = _controller.wait().await;
// TODO only change lines affected!
let lines : Vec<String> = _controller.content().split('\n').map(|x| x.to_string()).collect(); let lines : Vec<String> = _controller.content().split('\n').map(|x| x.to_string()).collect();
// TODO only change lines affected!
if let Err(e) = buffer.set_lines(0, -1, false, lines).await { if let Err(e) = buffer.set_lines(0, -1, false, lines).await {
error!("could not update buffer: {}", e); error!("could not update buffer: {}", e);
} }
@ -170,14 +169,15 @@ impl Handler for NeovimHandler {
}, },
"detach" => { "detach" => {
if args.is_empty() { Err(Value::String("not implemented".into()))
return Err(Value::from("no path given")); // if args.is_empty() {
} // return Err(Value::from("no path given"));
let path = default_empty_str(&args, 0); // }
match self.buffer_controller(&path) { // let path = default_empty_str(&args, 0);
None => Err(Value::from("no controller for given path")), // match self.buffer_controller(&path) {
Some(controller) => Ok(Value::from(controller.stop())), // None => Err(Value::from("no controller for given path")),
} // Some(controller) => Ok(Value::from(controller.stop())),
// }
}, },
"listen" => { "listen" => {
@ -185,10 +185,6 @@ impl Handler for NeovimHandler {
return Err(Value::from("no path given")); return Err(Value::from("no path given"));
} }
let path = default_empty_str(&args, 0); let path = default_empty_str(&args, 0);
let controller = match self.buffer_controller(&path) {
None => return Err(Value::from("no controller for given path")),
Some(c) => c,
};
let ns = nvim.create_namespace("Cursor").await let ns = nvim.create_namespace("Cursor").await
.map_err(|e| Value::from(format!("could not create namespace: {}", e)))?; .map_err(|e| Value::from(format!("could not create namespace: {}", e)))?;
@ -200,19 +196,25 @@ impl Handler for NeovimHandler {
match c.listen().await { match c.listen().await {
Err(e) => Err(Value::from(format!("could not listen cursors: {}", e))), Err(e) => Err(Value::from(format!("could not listen cursors: {}", e))),
Ok(mut cursor) => { Ok(mut cursor) => {
self.cursors.lock().unwrap().insert(path, cursor.clone().into()); self.cursors.lock().unwrap().insert(path, cursor.clone());
debug!("spawning cursor processing worker"); debug!("spawning cursor processing worker");
tokio::spawn(async move { tokio::spawn(async move {
while let Some(cur) = cursor.poll().await { while let Some(cur) = cursor.poll().await {
if !controller.run() { break }
if let Err(e) = buf.clear_namespace(ns, 0, -1).await { if let Err(e) = buf.clear_namespace(ns, 0, -1).await {
error!("could not clear previous cursor highlight: {}", e); error!("could not clear previous cursor highlight: {}", e);
} }
let start = cur.start();
let end = cur.end();
let end_col = if start.row == end.row {
end.col
} else {
0 // TODO what the fuck
};
if let Err(e) = buf.add_highlight( if let Err(e) = buf.add_highlight(
ns, "ErrorMsg", ns, "ErrorMsg",
(cur.start().row-1) as i64, start.row as i64 - 1,
cur.start().col as i64, start.col as i64,
(cur.start().col+1) as i64 end_col as i64
).await { ).await {
error!("could not create highlight for cursor: {}", e); error!("could not create highlight for cursor: {}", e);
} }
@ -233,11 +235,13 @@ impl Handler for NeovimHandler {
let path = default_empty_str(&args, 0); let path = default_empty_str(&args, 0);
let row = default_zero_number(&args, 1) as i32; let row = default_zero_number(&args, 1) as i32;
let col = default_zero_number(&args, 2) as i32; let col = default_zero_number(&args, 2) as i32;
let row_end = default_zero_number(&args, 3) as i32;
let col_end = default_zero_number(&args, 4) as i32;
match self.cursor_controller(&path) { match self.cursor_controller(&path) {
None => Err(Value::from("no path given")), None => Err(Value::from("no path given")),
Some(cur) => { Some(cur) => {
cur.send(&path, (row, col).into(), (0, 0).into()).await; cur.send(&path, (row, col).into(), (row_end, col_end).into()).await;
Ok(Value::Nil) Ok(Value::Nil)
} }
} }

View file

@ -92,36 +92,34 @@ async function _attach(path) {
DECORATION = null DECORATION = null
} }
const range_start = new vscode.Position(start[0] - 1, start[1]); const range_start = new vscode.Position(start[0] - 1, start[1]);
const range_end = new vscode.Position(start[0] - 1, start[1] + 1); const range_end = new vscode.Position(end[0] - 1, end[1]);
const decorationRange = new vscode.Range(range_start, range_end); const decorationRange = new vscode.Range(range_start, range_end);
DECORATION = vscode.window.createTextEditorDecorationType( DECORATION = vscode.window.createTextEditorDecorationType(
{backgroundColor: 'red', color: 'white'} {backgroundColor: 'red', color: 'white'}
) )
editor.setDecorations(DECORATION, [decorationRange]) editor.setDecorations(DECORATION, [decorationRange])
} catch (err) { } catch (err) {
vscode.window.showErrorMessage("fuck! " + err) vscode.window.showErrorMessage("error setting cursor decoration: " + err)
} }
}) })
vscode.window.onDidChangeTextEditorSelection(async (e) => { vscode.window.onDidChangeTextEditorSelection(async (e) => {
let buf = e.textEditor.document.uri.toString() let buf = e.textEditor.document.uri.toString()
let selection = e.selections[0] // TODO there may be more than one cursor!! let selection = e.selections[0] // TODO there may be more than one cursor!!
let anchor = [selection.anchor.line+1, selection.anchor.character] let anchor = [selection.anchor.line+1, selection.anchor.character]
let position = [selection.active.line+1, selection.active.character] let position = [selection.active.line+1, selection.active.character+1]
// (anchor, position) = _order_tuples(anchor, position) // (anchor, position) = _order_tuples(anchor, position)
await CURSOR.send(buf, anchor, position) await CURSOR.send(buf, anchor, position)
}) })
CONTROLLER = await CLIENT.attach(path) CONTROLLER = await CLIENT.attach(path)
CONTROLLER.callback((start, end) => { CONTROLLER.callback((start, end, text) => {
// TODO only change affected document range
let content = CONTROLLER.content()
let range = new vscode.Range(
editor.document.positionAt(0),
editor.document.positionAt(editor.document.getText().length)
)
try { try {
OP_CACHE.add((range, content)) let range = new vscode.Range(
editor.edit(editBuilder => editBuilder.replace(range, content)) editor.document.positionAt(start),
editor.document.positionAt(end)
)
OP_CACHE.add((range, text))
editor.edit(editBuilder => editBuilder.replace(range, text))
} catch (err) { } catch (err) {
vscode.window.showErrorMessage("could not set buffer: " + err) vscode.window.showErrorMessage("could not set buffer: " + err)
} }

View file

@ -3,8 +3,9 @@ use std::sync::Arc;
use neon::prelude::*; use neon::prelude::*;
use once_cell::sync::OnceCell; use once_cell::sync::OnceCell;
use codemp::{ use codemp::{
cursor::{CursorControllerHandle, CursorSubscriber}, client::CodempClient, operation::{OperationController, OperationFactory, OperationProcessor}, controller::{cursor::{CursorSubscriber, CursorControllerHandle}, buffer::{OperationControllerHandle, OperationControllerSubscriber}},
proto::buffer_client::BufferClient, client::CodempClient,
proto::buffer_client::BufferClient, factory::OperationFactory,
}; };
use codemp::tokio::{runtime::Runtime, sync::Mutex}; use codemp::tokio::{runtime::Runtime, sync::Mutex};
@ -126,7 +127,7 @@ fn attach_client(mut cx: FunctionContext) -> JsResult<JsPromise> {
Ok(controller) => { Ok(controller) => {
deferred.settle_with(&channel, move |mut cx| { deferred.settle_with(&channel, move |mut cx| {
let obj = cx.empty_object(); let obj = cx.empty_object();
let boxed_value = cx.boxed(OperationControllerHandle(controller)); let boxed_value = cx.boxed(OperationControllerJs(controller));
obj.set(&mut cx, "boxed", boxed_value)?; obj.set(&mut cx, "boxed", boxed_value)?;
let apply_method = JsFunction::new(&mut cx, apply_operation)?; let apply_method = JsFunction::new(&mut cx, apply_operation)?;
obj.set(&mut cx, "apply", apply_method)?; obj.set(&mut cx, "apply", apply_method)?;
@ -145,12 +146,12 @@ fn attach_client(mut cx: FunctionContext) -> JsResult<JsPromise> {
} }
struct OperationControllerHandle(Arc<OperationController>); struct OperationControllerJs(OperationControllerHandle);
impl Finalize for OperationControllerHandle {} impl Finalize for OperationControllerJs {}
fn apply_operation(mut cx: FunctionContext) -> JsResult<JsPromise> { fn apply_operation(mut cx: FunctionContext) -> JsResult<JsPromise> {
let this = cx.this(); let this = cx.this();
let boxed : Handle<JsBox<OperationControllerHandle>> = this.get(&mut cx, "boxed")?; let boxed : Handle<JsBox<OperationControllerJs>> = this.get(&mut cx, "boxed")?;
let skip = cx.argument::<JsNumber>(0)?.value(&mut cx).round() as usize; let skip = cx.argument::<JsNumber>(0)?.value(&mut cx).round() as usize;
let text = cx.argument::<JsString>(1)?.value(&mut cx); let text = cx.argument::<JsString>(1)?.value(&mut cx);
let tail = cx.argument::<JsNumber>(2)?.value(&mut cx).round() as usize; let tail = cx.argument::<JsNumber>(2)?.value(&mut cx).round() as usize;
@ -160,10 +161,11 @@ fn apply_operation(mut cx: FunctionContext) -> JsResult<JsPromise> {
let channel = cx.channel(); let channel = cx.channel();
runtime(&mut cx)?.spawn(async move { runtime(&mut cx)?.spawn(async move {
let op = rc.delta(skip, text.as_str(), tail); if let Some(op) = rc.delta(skip, text.as_str(), tail) {
match rc.apply(op) { rc.apply(op).await;
Err(e) => deferred.settle_with(&channel, move |mut cx| cx.throw_error::<_, Handle<JsString>>(format!("could not apply operation: {}", e))), deferred.settle_with(&channel, move |mut cx| Ok(cx.boolean(true)));
Ok(span) => deferred.settle_with(&channel, move |mut cx| tuple(&mut cx, span.start as i32, span.end as i32)), } else {
deferred.settle_with(&channel, move |mut cx| Ok(cx.undefined()));
} }
}); });
@ -172,28 +174,28 @@ fn apply_operation(mut cx: FunctionContext) -> JsResult<JsPromise> {
fn content_operation(mut cx: FunctionContext) -> JsResult<JsString> { fn content_operation(mut cx: FunctionContext) -> JsResult<JsString> {
let this = cx.this(); let this = cx.this();
let boxed : Handle<JsBox<OperationControllerHandle>> = this.get(&mut cx, "boxed")?; let boxed : Handle<JsBox<OperationControllerJs>> = this.get(&mut cx, "boxed")?;
Ok(cx.string(boxed.0.content())) Ok(cx.string(boxed.0.content()))
} }
fn callback_operation(mut cx: FunctionContext) -> JsResult<JsUndefined> { fn callback_operation(mut cx: FunctionContext) -> JsResult<JsUndefined> {
let this = cx.this(); let this = cx.this();
let boxed : Handle<JsBox<OperationControllerHandle>> = this.get(&mut cx, "boxed")?; let boxed : Handle<JsBox<OperationControllerJs>> = this.get(&mut cx, "boxed")?;
let callback = Arc::new(cx.argument::<JsFunction>(0)?.root(&mut cx)); let callback = Arc::new(cx.argument::<JsFunction>(0)?.root(&mut cx));
let rc = boxed.0.clone(); let mut rc = boxed.0.clone();
let channel = cx.channel(); let channel = cx.channel();
// TODO when garbage collecting OperationController stop this worker // TODO when garbage collecting OperationController stop this worker
runtime(&mut cx)?.spawn(async move { runtime(&mut cx)?.spawn(async move {
loop{ while let Some(edit) = rc.poll().await {
let span = rc.wait().await;
let cb = callback.clone(); let cb = callback.clone();
channel.send(move |mut cx| { channel.send(move |mut cx| {
cb.to_inner(&mut cx) cb.to_inner(&mut cx)
.call_with(&cx) .call_with(&cx)
.arg(cx.number(span.start as i32)) .arg(cx.number(edit.span.start as i32))
.arg(cx.number(span.end as i32)) .arg(cx.number(edit.span.end as i32))
.arg(cx.string(edit.content))
.apply::<JsUndefined, _>(&mut cx)?; .apply::<JsUndefined, _>(&mut cx)?;
Ok(()) Ok(())
}); });