♻️ refactor: extract GuiClient struct

main
_ 2021-10-10 17:56:13 +00:00
parent 07fa3b97c3
commit 11ee6292ba
1 changed files with 58 additions and 23 deletions

View File

@ -10,6 +10,7 @@ use fltk::{
window::Window
};
use structopt::StructOpt;
use tokio::runtime::Runtime;
use quic_demo::{
client_proxy::*,
@ -35,9 +36,50 @@ enum Message {
ClosePort (usize),
}
struct GuiClient <'a> {
rt: &'a Runtime,
frame_status: Frame,
forwarding_instances: Vec <Option <ForwardingInstance>>,
gui_ports: Vec <GuiPort>,
}
impl GuiClient <'_> {
pub fn open_port (
&mut self,
connection_p2_p3: quinn::Connection,
port_idx: usize,
) -> anyhow::Result <()>
{
let params = self.gui_ports [port_idx].get_params ()?;
let _guard = self.rt.enter ();
self.forwarding_instances [port_idx].replace (ForwardingInstance::new (
connection_p2_p3,
params,
));
self.gui_ports [port_idx].set_forwarding (true);
self.frame_status.set_label ("Forwarding 1 port");
Ok (())
}
pub fn close_port (&mut self, port_idx: usize) -> anyhow::Result <()> {
if let Some (old_instance) = self.forwarding_instances [port_idx].take () {
self.rt.block_on (old_instance.close ())?;
}
self.gui_ports [port_idx].set_forwarding (false);
self.frame_status.set_label ("Forwarding 0 ports");
Ok (())
}
}
fn main () -> anyhow::Result <()> {
tracing_subscriber::fmt::init ();
let rt = tokio::runtime::Runtime::new ()?;
let rt = Runtime::new ()?;
let opt = Opt::from_args ();
@ -53,7 +95,7 @@ fn main () -> anyhow::Result <()> {
let mut x = margin;
let mut y = margin;
let mut frame_status = Frame::new (x, y, 800 - 20, h, "Forwarding 0 ports");
let frame_status = Frame::new (x, y, 800 - 20, h, "Forwarding 0 ports");
y += h + margin;
x = margin;
@ -87,18 +129,25 @@ fn main () -> anyhow::Result <()> {
// y += h + margin;
// x = margin;
let mut gui_ports = vec! [
let gui_ports = vec! [
gui_port_0,
gui_port_1,
gui_port_2,
];
let mut forwarding_instances = vec! [
let forwarding_instances = vec! [
None,
None,
None,
];
let mut gui_client = GuiClient {
rt: &rt,
frame_status,
forwarding_instances,
gui_ports,
};
// y += h + margin;
wind.end ();
@ -132,27 +181,13 @@ fn main () -> anyhow::Result <()> {
while app.wait () {
match fltk_rx.recv () {
Some (Message::OpenPort (port_idx)) => {
if let Ok (params) = gui_ports [port_idx].get_params () {
let connection_p2_p3 = connection_p2_p3.clone ();
let _guard = rt.enter ();
forwarding_instances [port_idx].replace (ForwardingInstance::new (
connection_p2_p3,
params,
));
gui_ports [port_idx].set_forwarding (true);
frame_status.set_label ("Forwarding 1 port");
}
match gui_client.open_port (connection_p2_p3.clone (), port_idx) {
Err (e) => error! ("{:?}", e),
_ => (),
};
},
Some (Message::ClosePort (port_idx)) => {
if let Some (old_instance) = forwarding_instances [port_idx].take () {
rt.block_on (old_instance.close ())?;
}
gui_ports [port_idx].set_forwarding (false);
frame_status.set_label ("Forwarding 0 ports");
gui_client.close_port (port_idx)?;
},
None => (),
}