xmpp-rs-mirror/src/plugin.rs

100 lines
2.5 KiB
Rust
Raw Normal View History

2017-02-21 16:38:29 +00:00
//! Provides the plugin infrastructure.
use event::{Event, EventHandler, Dispatcher, SendElement, Priority};
2017-02-20 15:28:51 +00:00
use std::any::Any;
use std::sync::{Arc, Mutex};
2017-02-20 15:28:51 +00:00
use std::mem;
use minidom::Element;
#[derive(Clone)]
pub struct PluginProxyBinding {
dispatcher: Arc<Mutex<Dispatcher>>,
2017-02-20 15:28:51 +00:00
}
impl PluginProxyBinding {
pub fn new(dispatcher: Arc<Mutex<Dispatcher>>) -> PluginProxyBinding {
2017-02-20 15:28:51 +00:00
PluginProxyBinding {
dispatcher: dispatcher,
}
}
}
pub enum PluginProxy {
Unbound,
BoundTo(PluginProxyBinding),
}
impl PluginProxy {
/// Returns a new `PluginProxy`.
2017-02-20 15:28:51 +00:00
pub fn new() -> PluginProxy {
PluginProxy::Unbound
}
/// Binds the `PluginProxy` to a `PluginProxyBinding`.
2017-02-20 15:28:51 +00:00
pub fn bind(&mut self, inner: PluginProxyBinding) {
if let PluginProxy::BoundTo(_) = *self {
panic!("trying to bind an already bound plugin proxy!");
}
mem::replace(self, PluginProxy::BoundTo(inner));
}
fn with_binding<R, F: FnOnce(&PluginProxyBinding) -> R>(&self, f: F) -> R {
match *self {
PluginProxy::Unbound => {
panic!("trying to use an unbound plugin proxy!");
},
PluginProxy::BoundTo(ref binding) => {
f(binding)
},
}
}
/// Dispatches an event.
2017-02-20 15:28:51 +00:00
pub fn dispatch<E: Event>(&self, event: E) {
self.with_binding(move |binding| {
// TODO: proper error handling
binding.dispatcher.lock().unwrap().dispatch(event);
2017-02-20 15:28:51 +00:00
});
}
/// Registers an event handler.
pub fn register_handler<E, H>(&self, priority: Priority, handler: H) where E: Event, H: EventHandler<E> {
2017-02-20 15:28:51 +00:00
self.with_binding(move |binding| {
// TODO: proper error handling
binding.dispatcher.lock().unwrap().register(priority, handler);
2017-02-20 15:28:51 +00:00
});
}
/// Sends a stanza.
pub fn send(&self, elem: Element) {
self.dispatch(SendElement(elem));
}
2017-02-20 15:28:51 +00:00
}
/// A trait whch all plugins should implement.
2017-02-20 15:28:51 +00:00
pub trait Plugin: Any + PluginAny {
/// Gets a mutable reference to the inner `PluginProxy`.
2017-02-20 15:28:51 +00:00
fn get_proxy(&mut self) -> &mut PluginProxy;
#[doc(hidden)]
2017-02-20 15:28:51 +00:00
fn bind(&mut self, inner: PluginProxyBinding) {
self.get_proxy().bind(inner);
}
}
pub trait PluginInit {
fn init(dispatcher: &mut Dispatcher, me: Arc<Box<Plugin>>);
}
2017-02-20 15:28:51 +00:00
pub trait PluginAny {
fn as_any(&self) -> &Any;
}
impl<T: Any + Sized + Plugin> PluginAny for T {
2017-02-20 15:28:51 +00:00
fn as_any(&self) -> &Any { self }
}