make plugin produce/consume events api symmetrical

This commit is contained in:
Adrian Malacoda 2017-02-13 00:55:30 -06:00
parent edef05d123
commit 9bb6887bed
4 changed files with 27 additions and 26 deletions

View File

@ -43,29 +43,26 @@ impl Tenquestionmarks {
// Plugins push events to tenquestionmarks using this channel.
let (ref sender, ref receiver) = mpsc::channel();
// Plugin event channels.
// Plugin event consumer threads.
// tenquestionmarks propagates all events to each plugin through these
// channels.
let senders: Vec<Sender<Event>> = self.plugins.values().map(|plugin| {
let (sender, receiver) = mpsc::channel();
scope.spawn(move || {
loop {
match receiver.recv() {
Ok(event) => { plugin.on_event(event) }
Err(error) => { println!("{:?}", error); }
}
}
});
scope.spawn(move || plugin.consume_events(receiver));
sender
}).collect();
// Plugin main threads.
// Plugin event producer threads.
// Each plugin will produce events which tenquestionmarks will push
// into all other plugins.
for plugin in self.plugins.values() {
let plugin_sender = sender.clone();
scope.spawn(move || plugin.run(plugin_sender));
scope.spawn(move || plugin.produce_events(plugin_sender));
}
// tenquestionmarks main event loop.
// tenquestionmarks receives events produced by plugins and pushes them
// into all other plugins
loop {
match receiver.recv() {
Ok(event) => {

View File

@ -1,6 +1,7 @@
use plugins::Plugin;
use toml::Table;
use std::sync::mpsc::Receiver;
use event::Event;
pub struct EchoPlugin {
@ -20,15 +21,22 @@ impl EchoPlugin {
}
impl Plugin for EchoPlugin {
fn on_event (&self, event: Event) {
match event {
Event::Message { content: message, channel: channel, sender: sender } => {
if message.starts_with(self.prefix.as_str()) {
let substring = String::from(&message[self.prefix.chars().count()..]);
println!("Echo: {:?}", substring);
fn consume_events (&self, receiver: Receiver<Event>) {
loop {
match receiver.recv() {
Ok(event) => {
match event {
Event::Message { content: message, channel: channel, sender: sender } => {
if message.starts_with(self.prefix.as_str()) {
let substring = String::from(&message[self.prefix.chars().count()..]);
println!("Echo: {:?}", substring);
}
}
_ => ()
}
}
Err(error) => { }
}
_ => ()
}
}
}

View File

@ -18,6 +18,6 @@ use std::sync::mpsc::{Sender, Receiver};
pub trait Plugin : Sync {
fn register (&self, tenquestionmarks: &Tenquestionmarks) {}
fn on_event (&self, event: Event) {}
fn run (&self, sender: Sender<Event>) {}
fn consume_events (&self, receiver: Receiver<Event>) {}
fn produce_events (&self, sender: Sender<Event>) {}
}

View File

@ -24,13 +24,9 @@ impl StdinPlugin {
}
impl Plugin for StdinPlugin {
fn register (&self, tenquestionmarks: &Tenquestionmarks) {
}
fn run (&self, sender: Sender<Event>) {
fn produce_events (&self, sender: Sender<Event>) {
let user = &self.user;
loop {
let mut input = String::new();
match io::stdin().read_line(&mut input) {