codemp/src/ffi/js/cursor.rs

58 lines
1.8 KiB
Rust
Raw Normal View History

use crate::api::controller::{AsyncReceiver, AsyncSender};
use crate::cursor::controller::CursorController;
2024-10-01 00:42:57 +02:00
use napi::threadsafe_function::ErrorStrategy::Fatal;
use napi::threadsafe_function::{
ThreadSafeCallContext, ThreadsafeFunction, ThreadsafeFunctionCallMode,
};
use napi_derive::napi;
2024-03-10 12:42:56 +01:00
#[napi]
impl CursorController {
2024-09-27 23:34:48 +02:00
/// Register a callback to be called on receive.
/// There can only be one callback registered at any given time.
2024-10-01 00:42:57 +02:00
#[napi(
js_name = "callback",
ts_args_type = "fun: (event: CursorController) => void"
)]
pub fn js_callback(&self, fun: napi::JsFunction) -> napi::Result<()> {
let tsfn: ThreadsafeFunction<crate::cursor::controller::CursorController, Fatal> = fun
.create_threadsafe_function(
0,
|ctx: ThreadSafeCallContext<crate::cursor::controller::CursorController>| {
Ok(vec![ctx.value])
},
)?;
self.callback(move |controller: CursorController| {
2024-09-27 23:34:48 +02:00
tsfn.call(controller.clone(), ThreadsafeFunctionCallMode::Blocking);
//check this with tracing also we could use Ok(event) to get the error
// If it blocks the main thread too many time we have to change this
2024-03-10 12:42:56 +01:00
});
2024-03-10 12:42:56 +01:00
Ok(())
}
2024-09-27 23:34:48 +02:00
/// Clear the registered callback
#[napi(js_name = "clear_callback")]
pub fn js_clear_callback(&self) {
self.clear_callback();
}
2024-09-27 23:34:48 +02:00
/// Send a new cursor event to remote
#[napi(js_name = "send")]
2024-10-10 12:14:44 +02:00
pub fn js_send(&self, sel: crate::api::Selection) -> napi::Result<()> {
Ok(self.send(sel)?)
2024-03-10 12:42:56 +01:00
}
2024-09-27 23:34:48 +02:00
/// Get next cursor event if available without blocking
2024-10-01 00:42:57 +02:00
#[napi(js_name = "try_recv")]
pub async fn js_try_recv(&self) -> napi::Result<Option<crate::api::Cursor>> {
Ok(self.try_recv().await?.map(crate::api::Cursor::from))
2024-03-10 12:42:56 +01:00
}
2024-08-21 17:14:19 +02:00
2024-10-01 00:42:57 +02:00
/// Block until next
#[napi(js_name = "recv")]
pub async fn js_recv(&self) -> napi::Result<crate::api::Cursor> {
2024-08-21 17:14:19 +02:00
Ok(self.recv().await?.into())
}
2024-03-10 12:42:56 +01:00
}