implement the new event system, things are still really messy

This commit is contained in:
lumi 2017-05-10 00:13:54 +02:00
commit 917b14b5d2
11 changed files with 403 additions and 156 deletions

View file

@ -1,10 +1,10 @@
//! Provides the plugin infrastructure.
use event::{Event, AbstractEvent};
use event::{Event, EventHandler, Dispatcher, SendElement, Priority};
use std::any::Any;
use std::sync::mpsc::Sender;
use std::sync::{Arc, Mutex};
use std::mem;
@ -12,14 +12,12 @@ use minidom::Element;
#[derive(Clone)]
pub struct PluginProxyBinding {
sender: Sender<Element>,
dispatcher: Sender<AbstractEvent>,
dispatcher: Arc<Mutex<Dispatcher>>,
}
impl PluginProxyBinding {
pub fn new(sender: Sender<Element>, dispatcher: Sender<AbstractEvent>) -> PluginProxyBinding {
pub fn new(dispatcher: Arc<Mutex<Dispatcher>>) -> PluginProxyBinding {
PluginProxyBinding {
sender: sender,
dispatcher: dispatcher,
}
}
@ -58,46 +56,44 @@ impl PluginProxy {
/// Dispatches an event.
pub fn dispatch<E: Event>(&self, event: E) {
self.with_binding(move |binding| {
binding.dispatcher.send(AbstractEvent::new(event))
.unwrap(); // TODO: may want to return the error
// TODO: proper error handling
binding.dispatcher.lock().unwrap().dispatch(event);
});
}
/// Registers an event handler.
pub fn register_handler<E, H>(&self, priority: Priority, handler: H) where E: Event, H: EventHandler<E> {
self.with_binding(move |binding| {
// TODO: proper error handling
binding.dispatcher.lock().unwrap().register(priority, handler);
});
}
/// Sends a stanza.
pub fn send(&self, elem: Element) {
self.with_binding(move |binding| {
binding.sender.send(elem).unwrap(); // TODO: as above, may want to return the error
});
self.dispatch(SendElement(elem));
}
}
/// A plugin handler return value.
///
/// The `Continue` variant means to do nothing, the `Unload` variant means to unload the plugin.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum PluginReturn {
Continue,
Unload,
}
/// A trait whch all plugins should implement.
pub trait Plugin: Any + PluginAny {
/// Gets a mutable reference to the inner `PluginProxy`.
fn get_proxy(&mut self) -> &mut PluginProxy;
/// Handles a received stanza.
fn handle(&mut self, elem: &Element) -> PluginReturn;
#[doc(hidden)]
fn bind(&mut self, inner: PluginProxyBinding) {
self.get_proxy().bind(inner);
}
}
pub trait PluginInit {
fn init(dispatcher: &mut Dispatcher, me: Arc<Box<Plugin>>);
}
pub trait PluginAny {
fn as_any(&self) -> &Any;
}
impl<T: Any + Sized> PluginAny for T {
impl<T: Any + Sized + Plugin> PluginAny for T {
fn as_any(&self) -> &Any { self }
}