♻️ refactor: use FLTK's event loop to simplify

main
_ 2021-07-11 23:57:18 +00:00
parent 04975ee6c0
commit ef27c0443d
1 changed files with 42 additions and 43 deletions

View File

@ -1,17 +1,13 @@
use std::{
sync::Arc,
};
use fltk::{
app,
app,
button::Button,
enums::CallbackTrigger,
frame::Frame,
prelude::*,
window::Window
};
use tokio::{
sync::Mutex,
sync::oneshot,
};
@ -20,39 +16,49 @@ struct ServerInstance {
shutdown_tx: oneshot::Sender <()>,
}
#[derive (Clone, Copy)]
enum Message {
RunServer,
StopServer,
}
fn main ()
{
let rt = tokio::runtime::Runtime::new ().unwrap ();
let rt_handle = rt.handle ();
tracing_subscriber::fmt::init ();
let stopped_msg = "PTTH server: Stopped";
let started_msg = "PTTH server: Running";
let server_instance = Arc::new (Mutex::new (None));
let mut server_instance = None;
// let shutdown_rx = ptth_core::graceful_shutdown::init ();
let app = app::App::default();
let mut wind = Window::new(100, 100, 400, 300, "Hello from rust");
let frame = Frame::new(0, 0, 400, 200, stopped_msg);
let mut but_run = Button::new (120, 210, 80, 40, "Run");
let mut but_stop = Button::new (200, 210, 80, 40, "Stop");
wind.end();
wind.show();
let (fltk_tx, fltk_rx) = app::channel::<Message> ();
{
let server_instance = Arc::clone (&server_instance);
let mut frame = frame.clone ();
let rt_handle = rt_handle.clone ();
let app = app::App::default();
let mut wind = Window::new (100, 100, 400, 300, "PTTH server");
let mut frame = Frame::new (0, 0, 400, 200, stopped_msg);
let mut but_run = Button::new (120, 210, 80, 40, "Run");
but_run.set_trigger (CallbackTrigger::Changed);
but_run.emit (fltk_tx, Message::RunServer);
but_run.set_callback (move |_| {
rt_handle.block_on (async {
let mut server_instance = server_instance.lock ().await;
let mut but_stop = Button::new (200, 210, 80, 40, "Stop");
but_stop.set_trigger (CallbackTrigger::Changed);
but_stop.emit (fltk_tx, Message::StopServer);
but_stop.deactivate ();
wind.end ();
wind.show ();
while app.wait () {
match fltk_rx.recv () {
Some (Message::RunServer) => {
let (shutdown_tx, shutdown_rx) = tokio::sync::oneshot::channel ();
let task = tokio::spawn (async {
let task = rt.spawn (async {
let config_file = ptth_server::ConfigFile {
name: "ptth_server".into (),
api_key: ptth_core::gen_key (),
@ -76,26 +82,19 @@ fn main ()
task,
shutdown_tx,
}));
});
frame.set_label (started_msg);
});
}
{
let server_instance = Arc::clone (&server_instance);
let mut frame = frame.clone ();
let rt_handle = rt_handle.clone ();
but_stop.set_callback (move |_| {
rt_handle.block_on (async {
let mut server_instance = server_instance.lock ().await;
frame.set_label (started_msg);
but_run.deactivate ();
but_stop.activate ();
},
Some (Message::StopServer) => {
server_instance.replace (None);
});
frame.set_label (stopped_msg);
});
frame.set_label (stopped_msg);
but_run.activate ();
but_stop.deactivate ();
},
None => (),
}
}
app.run ().unwrap ();
}