Skip to content

Instantly share code, notes, and snippets.

@knopp

knopp/plugin.rs Secret

Created June 13, 2021 19:34
Show Gist options
  • Save knopp/139f7b2b02ce4f59e2649bc1560276c3 to your computer and use it in GitHub Desktop.
Save knopp/139f7b2b02ce4f59e2649bc1560276c3 to your computer and use it in GitHub Desktop.
pub trait MethodCallHandler {
fn on_method_call(
&mut self,
call: MethodCall<Value>,
reply: MethodCallReply<Value>,
engine: EngineHandle,
);
// keep the method invoker provider if you want to call methods on engines
fn set_method_invoker_provider(&mut self, _provider: MethodInvokerProvider) {}
}
// Example handler
pub struct ExampleHandler {
// sender i used to schedule responde on main thread
sender: RunLoopSender,
}
impl ExampleHandler {
pub fn new(sender: RunLoopSender) -> Self {
Self { sender }
}
}
impl MethodCallHandler for ExampleHandler {
fn on_method_call(
&mut self,
call: MethodCall<Value>,
reply: MethodCallReply<Value>,
_engine: EngineHandle,
) {
match call.method.as_str() {
"echo" => {
reply.send_ok(call.args);
}
"backgroundTask" => {
// reply is not thread safe and can not be sent between threads directly;
// use capsule to move it between threads
let mut reply = Capsule::new(reply);
let sender = self.sender.clone();
thread::spawn(move || {
// simulate long running task on background thread
thread::sleep(Duration::from_secs(1));
let value = 3.141592;
// jump back to platform thread to send the reply
sender.send(move || {
// capsule will only let us take the stored value on thread where
// it was created
let reply = reply.take().unwrap();
reply.send_ok(Value::F64(value));
});
});
}
_ => {}
}
}
}
//
// in main.rs
//
// handler is active until plugin gets dropped
let _example_plugin = Plugin::new(
context.clone(),
"example_channel",
ExampleHandler::new(context.run_loop.borrow().new_sender()),
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment