ok-ready-go/receiver/src/gui.rs
Dorian Zedler 54a0f7f533
Some checks reported errors
continuous-integration/drone/push Build was killed
Feat: fully working gui
2023-02-17 14:14:00 +01:00

181 lines
5 KiB
Rust

use std::sync::{Mutex, Arc};
use std::sync::mpsc::{self, TryRecvError};
use std::thread::{self};
use iced::theme;
use iced::widget::{
column, row, text,
text_input, pick_list
};
use iced::widget::{Button};
use iced::{alignment, Element, Length, Sandbox};
use iced_aw::number_input::NumberInput;
use crate::{keyboard::{self, ContinueButton}, comm};
pub struct Gui {
password: String,
c: Option<Box<dyn Fn() -> ()>>,
continue_sequence: Arc<Mutex<(u32, ContinueButton)>>
}
#[derive(Debug, Clone)]
pub enum Message {
ConnectPressed,
PasswordChanged(String),
DisconnectPressed,
ContinueButtonCountChanged(u32),
ContinueButtonChanged(ContinueButton)
}
impl Sandbox for Gui {
type Message = Message;
fn new() -> Self {
Gui {
password: "".to_owned(),
c: None,
continue_sequence: Arc::new(Mutex::new((2, ContinueButton::Tab)))
}
}
fn update(&mut self, event: Message) {
match event {
Message::PasswordChanged(p) => self.password = p,
Message::ConnectPressed => {
let res = Some(connect(self, &self.password));
self.c = res;
},
Message::DisconnectPressed => {
(self.c.as_mut().unwrap())();
self.c = None;
}
Message::ContinueButtonCountChanged(count) => {
self.continue_sequence.lock().unwrap().0 = count;
}
Message::ContinueButtonChanged(b) => {
self.continue_sequence.lock().unwrap().1 = b
}
}
}
fn view(&self) -> Element<Message> {
let connected = self.c.is_some();
let content: Element<_> = column![
text("OK! .. READY! ... GO!").size(30),
if connected {
connected_content(self)
} else {
not_connected_content(self)
}
]
.width(Length::Fill)
.spacing(20)
.padding(20)
.into();
content
}
fn title(&self) -> String {
"gui".to_owned()
}
fn theme(&self) -> iced::Theme {
iced::Theme::Dark
}
}
fn not_connected_content(gui: &Gui) -> Element<Message> {
column![
"Enter the same password as on your phone to connect.",
text_input("Enter password", &gui.password, Message::PasswordChanged)
.password()
.size(30),
button("Connect")
.width(Length::Fill)
.style(theme::Button::Primary)
.on_press(Message::ConnectPressed),
].width(Length::Fill).spacing(20).padding(0).into()
}
fn connected_content(gui: &Gui) -> Element<Message> {
let seq = gui.continue_sequence.lock().unwrap();
column![
"Connected.",
button("Disconnect")
.width(Length::Fill)
.style(theme::Button::Primary)
.on_press(Message::DisconnectPressed),
row![
NumberInput::new(seq.0, 10, Message::ContinueButtonCountChanged).step(1).size(30),
pick_list(vec![ContinueButton::Tab, ContinueButton::Enter], Some(seq.1), Message::ContinueButtonChanged).padding(5)
].spacing(20).width(Length::Fill)
].width(Length::Fill).spacing(20).padding(0).into()
}
// ----------
// components
// ----------
fn button<'a, Message: Clone>(label: &str) -> Button<'a, Message> {
iced::widget::button(text(label).horizontal_alignment(alignment::Horizontal::Center))
.padding(12)
}
// -------
// helpers
// -------
fn connect(gui: &Gui, password: &str) -> Box<dyn Fn() -> ()> {
let password = password.to_owned();
let mux = gui.continue_sequence.clone();
let (tx, rx) = mpsc::channel();
let handle = thread::spawn(move || {
let c = comm::Comm::new("broker.emqx.io", &password, handle_time).unwrap();
loop {
match rx.try_recv() {
Ok(()) | Err(TryRecvError::Disconnected) => {
println!("Comm is terminating.");
break;
},
Err(TryRecvError::Empty) => {}
}
c.handle_next_event(&mux);
}
c.disconnect();
});
Box::new(move || {
tx.send(()).unwrap();
while !handle.is_finished() {};
})
}
fn millis_to_string(millis: u32) -> String {
let seconds = (millis as f64) / 1000.0;
let formatted = format!("{:.2}", seconds);
formatted.replace(".", ",")
}
fn handle_time(time: u32, mux: &Arc<Mutex<(u32, ContinueButton)>>) -> Result<(), ()> {
let (continue_button_count, continue_button) = *mux.lock().unwrap();
println!("Got time: {}, count: {}, button: {}", time, continue_button_count, continue_button);
let time_with_comma = millis_to_string(time);
println!("-> Trying to type {time_with_comma}");
keyboard::type_text(&time_with_comma)?;
for _ in 0..continue_button_count {
println!("-> Trying to click {continue_button}");
keyboard::click_button(continue_button)?;
}
Ok(())
}