| 1 |
use std::{borrow::Cow, mem, time::Duration}; |
| 2 |
|
| 3 |
use nmrs::{ConnectionError, Network, NetworkInfo, SettingsPatch, WifiDevice, WifiSecurity}; |
| 4 |
use tokio::sync::mpsc::{self, UnboundedReceiver, UnboundedSender}; |
| 5 |
|
| 6 |
use crate::{ |
| 7 |
app::{App, Focus, Status}, |
| 8 |
ui::{ |
| 9 |
tabs::Tabs, |
| 10 |
toast::{Toast, Urgency}, |
| 11 |
}, |
| 12 |
}; |
| 13 |
|
| 14 |
#[derive(Debug, Clone)] |
| 15 |
pub enum Action { |
| 16 |
Quit, |
| 17 |
Tick(Duration), |
| 18 |
|
| 19 |
Refresh, |
| 20 |
|
| 21 |
Reload, |
| 22 |
SetFocus(Focus), |
| 23 |
SetStatus(Status), |
| 24 |
|
| 25 |
|
| 26 |
NetworkScanResult(Box<Result<NetworkScanResult, &'static str>>), |
| 27 |
Connect(Box<ConnectRequest>), |
| 28 |
Forget { ssid: String }, |
| 29 |
ToggleAutoconnect { ssid: String }, |
| 30 |
ToggleAirplaneMode, |
| 31 |
TogglePower, |
| 32 |
Disconnect, |
| 33 |
|
| 34 |
|
| 35 |
NextItem(Tabs), |
| 36 |
PreviousItem(Tabs), |
| 37 |
ShowToast(Box<ToastRequest>), |
| 38 |
} |
| 39 |
|
| 40 |
#[derive(Debug, Clone)] |
| 41 |
pub struct NetworkScanResult { |
| 42 |
pub known: Vec<Network>, |
| 43 |
pub available: Vec<Network>, |
| 44 |
pub devices: Vec<WifiDevice>, |
| 45 |
pub current_network: Option<Network>, |
| 46 |
pub current_network_info: Option<NetworkInfo>, |
| 47 |
} |
| 48 |
|
| 49 |
#[derive(Debug, Clone)] |
| 50 |
pub struct ConnectRequest { |
| 51 |
pub ssid: String, |
| 52 |
pub interface: Option<String>, |
| 53 |
pub credentials: WifiSecurity, |
| 54 |
} |
| 55 |
|
| 56 |
#[derive(Debug, Clone)] |
| 57 |
pub struct ToastRequest { |
| 58 |
pub title: Option<Cow<'static, str>>, |
| 59 |
pub msg: Cow<'static, str>, |
| 60 |
pub urgency: Urgency, |
| 61 |
pub duration: Option<f32>, |
| 62 |
} |
| 63 |
|
| 64 |
pub struct ActionHandler { |
| 65 |
tx: UnboundedSender<Action>, |
| 66 |
rx: UnboundedReceiver<Action>, |
| 67 |
} |
| 68 |
|
| 69 |
impl ActionHandler { |
| 70 |
pub fn new() -> Self { |
| 71 |
let (tx, rx) = mpsc::unbounded_channel::<Action>(); |
| 72 |
|
| 73 |
Self { tx, rx } |
| 74 |
} |
| 75 |
|
| 76 |
|
| 77 |
pub fn sender(&self) -> UnboundedSender<Action> { |
| 78 |
self.tx.clone() |
| 79 |
} |
| 80 |
|
| 81 |
pub fn send(&self, action: Action) { |
| 82 |
match self.tx.send(action) { |
| 83 |
Ok(_) => {} |
| 84 |
Err(e) => { |
| 85 |
error!("Action failed: {}", e) |
| 86 |
} |
| 87 |
} |
| 88 |
} |
| 89 |
|
| 90 |
pub async fn handle_actions(app: &mut App) -> anyhow::Result<()> { |
| 91 |
while let Ok(action) = app.action.rx.try_recv() { |
| 92 |
match action { |
| 93 |
|
| 94 |
Action::Quit => app.quit(), |
| 95 |
Action::Tick(delta) => Self::handle_tick(app, delta), |
| 96 |
Action::SetFocus(new_focus) => Self::set_focus(app, new_focus), |
| 97 |
Action::SetStatus(new_status) => { |
| 98 |
debug!("Set status to: {:?}!", new_status); |
| 99 |
app.status = new_status; |
| 100 |
} |
| 101 |
|
| 102 |
|
| 103 |
Action::Refresh => Self::spawn_fetch(app, true), |
| 104 |
Action::Reload => Self::spawn_fetch(app, false), |
| 105 |
Action::NetworkScanResult(box_data) => { |
| 106 |
Self::apply_scan_result(app, *box_data); |
| 107 |
} |
| 108 |
Action::Connect(box_data) => Self::spawn_connect(app, *box_data), |
| 109 |
Action::Forget { ssid } => Self::spawn_forget(app, ssid), |
| 110 |
Action::ToggleAutoconnect { ssid } => Self::spawn_toggle_autoconnect(app, ssid), |
| 111 |
Action::ToggleAirplaneMode => Self::spawn_toggle_airplane(app), |
| 112 |
Action::TogglePower => Self::spawn_toggle_power(app), |
| 113 |
Action::Disconnect => Self::spawn_disconnect(app), |
| 114 |
|
| 115 |
|
| 116 |
Action::NextItem(tab) => match tab { |
| 117 |
Tabs::KnownNetworks => app.known_networks.next(), |
| 118 |
Tabs::AvailableNetworks => app.available_networks.next(), |
| 119 |
Tabs::Devices => app.devices.next(), |
| 120 |
}, |
| 121 |
Action::PreviousItem(tab) => match tab { |
| 122 |
Tabs::KnownNetworks => app.known_networks.previous(), |
| 123 |
Tabs::AvailableNetworks => app.available_networks.previous(), |
| 124 |
Tabs::Devices => app.devices.previous(), |
| 125 |
}, |
| 126 |
Action::ShowToast(box_data) => { |
| 127 |
let toast_req = *box_data; |
| 128 |
app.toasts.push(Toast::new( |
| 129 |
&app.config.ui.toast, |
| 130 |
toast_req.title, |
| 131 |
toast_req.msg, |
| 132 |
toast_req.urgency, |
| 133 |
toast_req.duration, |
| 134 |
)); |
| 135 |
} |
| 136 |
} |
| 137 |
} |
| 138 |
Ok(()) |
| 139 |
} |
| 140 |
|
| 141 |
|
| 142 |
|
| 143 |
fn handle_tick(app: &mut App, delta: Duration) { |
| 144 |
for toast in &mut app.toasts { |
| 145 |
toast.duration = toast.duration.saturating_sub(delta); |
| 146 |
} |
| 147 |
app.toasts.retain(|toast| !toast.duration.is_zero()); |
| 148 |
|
| 149 |
let finished: Vec<Action> = app |
| 150 |
.timers_mut() |
| 151 |
.into_iter() |
| 152 |
.filter(|t| t.enabled) |
| 153 |
.filter_map(|timer| { |
| 154 |
timer.tick(delta); |
| 155 |
if timer.is_finished() { |
| 156 |
timer.reset(); |
| 157 |
Some(timer.on_finish.clone()) |
| 158 |
} else { |
| 159 |
None |
| 160 |
} |
| 161 |
}) |
| 162 |
.collect(); |
| 163 |
|
| 164 |
for action in finished { |
| 165 |
app.action.send(action); |
| 166 |
} |
| 167 |
} |
| 168 |
|
| 169 |
fn set_focus(app: &mut App, new_focus: Focus) { |
| 170 |
debug!("Set focus to: {:?}!", new_focus); |
| 171 |
match new_focus { |
| 172 |
Focus::Popup(_) => { |
| 173 |
app.scan.disable(); |
| 174 |
debug!("Scan disabled (popup is open)"); |
| 175 |
} |
| 176 |
Focus::Tab(_) => app.scan.enable(), |
| 177 |
} |
| 178 |
app.last_focus = mem::replace(&mut app.focus, new_focus); |
| 179 |
} |
| 180 |
|
| 181 |
fn apply_scan_result(app: &mut App, result: Result<NetworkScanResult, &'static str>) { |
| 182 |
app.reloading = false; |
| 183 |
|
| 184 |
match result { |
| 185 |
Ok(scan_result) => { |
| 186 |
app.network_manager.current_network = scan_result.current_network; |
| 187 |
app.network_manager.current_network_info = scan_result.current_network_info; |
| 188 |
app.known_networks.set_items(scan_result.known); |
| 189 |
app.available_networks.set_items(scan_result.available); |
| 190 |
app.devices.set_items(scan_result.devices); |
| 191 |
} |
| 192 |
Err(msg) => app.action.send(Action::toast_err(msg)), |
| 193 |
} |
| 194 |
|
| 195 |
if mem::take(&mut app.reload_pending) { |
| 196 |
app.action.send(Action::Reload); |
| 197 |
} |
| 198 |
} |
| 199 |
|
| 200 |
|
| 201 |
|
| 202 |
fn spawn_fetch(app: &mut App, scan: bool) { |
| 203 |
if !app.scan.enabled { |
| 204 |
return; |
| 205 |
} |
| 206 |
if app.reloading { |
| 207 |
app.reload_pending = true; |
| 208 |
if scan { |
| 209 |
let network_manager = app.network_manager.clone(); |
| 210 |
tokio::spawn(async move { network_manager.scan_networks().await }); |
| 211 |
} |
| 212 |
return; |
| 213 |
} |
| 214 |
app.reloading = true; |
| 215 |
let action_tx = app.action.sender(); |
| 216 |
let network_manager = app.network_manager.clone(); |
| 217 |
tokio::spawn(async move { |
| 218 |
if scan { |
| 219 |
network_manager.scan_networks().await; |
| 220 |
} |
| 221 |
let result = match tokio::try_join!( |
| 222 |
network_manager.networks_list(), |
| 223 |
network_manager.get_devices() |
| 224 |
) { |
| 225 |
Ok(((known, available), devices)) => { |
| 226 |
let current_network = network_manager.current_network().await; |
| 227 |
let current_network_info = if let Some(network) = ¤t_network { |
| 228 |
match network_manager.show_details(network).await { |
| 229 |
Ok(conn_info) => Some(conn_info), |
| 230 |
Err(_) => { |
| 231 |
_ = action_tx |
| 232 |
.send(Action::toast_err("Failed to get current network info!")); |
| 233 |
None |
| 234 |
} |
| 235 |
} |
| 236 |
} else { |
| 237 |
None |
| 238 |
}; |
| 239 |
Ok(NetworkScanResult { |
| 240 |
known, |
| 241 |
available, |
| 242 |
devices, |
| 243 |
current_network, |
| 244 |
current_network_info, |
| 245 |
}) |
| 246 |
} |
| 247 |
Err(_) => Err(if scan { |
| 248 |
"Refresh failed!" |
| 249 |
} else { |
| 250 |
"Reload failed!" |
| 251 |
}), |
| 252 |
}; |
| 253 |
_ = action_tx.send(Action::NetworkScanResult(Box::new(result))); |
| 254 |
}); |
| 255 |
} |
| 256 |
|
| 257 |
fn spawn_connect(app: &App, conn_req: ConnectRequest) { |
| 258 |
app.action |
| 259 |
.send(Action::SetStatus(Status::Connecting(conn_req.ssid.clone()))); |
| 260 |
|
| 261 |
let action_tx = app.action.sender(); |
| 262 |
let network_manager = app.network_manager.clone(); |
| 263 |
tokio::spawn(async move { |
| 264 |
let toast = match network_manager |
| 265 |
.connect(&conn_req.ssid, conn_req.interface, conn_req.credentials) |
| 266 |
.await |
| 267 |
{ |
| 268 |
Ok(Ok(_)) => Action::toast_ok("Connected!"), |
| 269 |
Ok(Err(ConnectionError::NotFound)) => { |
| 270 |
Action::toast_err("Network not visible — is it in range?") |
| 271 |
} |
| 272 |
Ok(Err(ConnectionError::AuthFailed)) => { |
| 273 |
_ = action_tx.send(Action::Forget { |
| 274 |
ssid: conn_req.ssid, |
| 275 |
}); |
| 276 |
Action::toast_err("Wrong password!") |
| 277 |
} |
| 278 |
Ok(Err(ConnectionError::Timeout)) => { |
| 279 |
Action::toast_err("Connection timed out — try increasing the timeout") |
| 280 |
} |
| 281 |
Ok(Err(ConnectionError::DhcpFailed)) => { |
| 282 |
Action::toast_err("Failed to get an IP address") |
| 283 |
} |
| 284 |
Ok(Err(_)) => Action::toast_err("Connection failed!"), |
| 285 |
Err(_) => { |
| 286 |
let msg = "Operation timed out!"; |
| 287 |
error!("{}", msg); |
| 288 |
Action::toast_err(msg) |
| 289 |
} |
| 290 |
}; |
| 291 |
_ = action_tx.send(toast); |
| 292 |
_ = action_tx.send(Action::SetStatus(Status::None)); |
| 293 |
_ = action_tx.send(Action::Refresh); |
| 294 |
}); |
| 295 |
} |
| 296 |
|
| 297 |
fn spawn_forget(app: &App, ssid: String) { |
| 298 |
let network_manager = app.network_manager.clone(); |
| 299 |
let action_tx = app.action.sender(); |
| 300 |
tokio::spawn(async move { |
| 301 |
let toast = match network_manager.forget(&ssid).await { |
| 302 |
Ok(_) => Action::toast_ok("Forgotten!"), |
| 303 |
Err(_) => Action::toast_err("Forget failed!"), |
| 304 |
}; |
| 305 |
_ = action_tx.send(toast); |
| 306 |
_ = action_tx.send(Action::Refresh); |
| 307 |
}); |
| 308 |
} |
| 309 |
|
| 310 |
fn spawn_toggle_autoconnect(app: &App, ssid: String) { |
| 311 |
let network_manager = app.network_manager.clone(); |
| 312 |
let action_tx = app.action.sender(); |
| 313 |
tokio::spawn(async move { |
| 314 |
let uuid = match network_manager.get_saved_connection_uuid(&ssid).await { |
| 315 |
Ok(Some(uuid)) => uuid, |
| 316 |
Ok(None) => return debug!("can't find uuid for {}!", ssid), |
| 317 |
Err(_) => { |
| 318 |
_ = action_tx.send(Action::toast_err("Failed to look up saved connection!")); |
| 319 |
return; |
| 320 |
} |
| 321 |
}; |
| 322 |
let saved_conn = match network_manager.get_saved_connection(&uuid).await { |
| 323 |
Ok(conn) => conn, |
| 324 |
Err(_) => { |
| 325 |
_ = action_tx.send(Action::toast_err("Failed to get the saved connection!")); |
| 326 |
return; |
| 327 |
} |
| 328 |
}; |
| 329 |
let mut patch = SettingsPatch::default(); |
| 330 |
patch.autoconnect = Some(!saved_conn.autoconnect); |
| 331 |
|
| 332 |
let toast = match network_manager.update_saved_connection(&uuid, patch).await { |
| 333 |
Ok(_) => Action::toast_ok(format!( |
| 334 |
"Auto Connect: {}", |
| 335 |
if !saved_conn.autoconnect { "On" } else { "Off" } |
| 336 |
)), |
| 337 |
Err(_) => Action::toast_err("Failed to update the saved connection!"), |
| 338 |
}; |
| 339 |
_ = action_tx.send(toast); |
| 340 |
}); |
| 341 |
} |
| 342 |
|
| 343 |
fn spawn_toggle_airplane(app: &App) { |
| 344 |
let network_manager = app.network_manager.clone(); |
| 345 |
let action_tx = app.action.sender(); |
| 346 |
tokio::spawn(async move { |
| 347 |
let enabled = match network_manager.airplane_mode_state().await { |
| 348 |
Ok(state) => state.is_airplane_mode(), |
| 349 |
Err(_) => { |
| 350 |
_ = action_tx.send(Action::toast_err("Failed to get airplane mode state!")); |
| 351 |
return; |
| 352 |
} |
| 353 |
}; |
| 354 |
|
| 355 |
let toast = match network_manager.set_airplane_mode(!enabled).await { |
| 356 |
Ok(_) => { |
| 357 |
debug!("Airplane set to {}", !enabled); |
| 358 |
Action::toast_ok(format!( |
| 359 |
"Airplane mode {}", |
| 360 |
if !enabled { "On" } else { "Off" } |
| 361 |
)) |
| 362 |
} |
| 363 |
Err(_) => Action::toast_err("Toggle airplane mode failed!"), |
| 364 |
}; |
| 365 |
_ = action_tx.send(toast); |
| 366 |
_ = action_tx.send(Action::Refresh); |
| 367 |
}); |
| 368 |
} |
| 369 |
|
| 370 |
fn spawn_toggle_power(app: &App) { |
| 371 |
let network_manager = app.network_manager.clone(); |
| 372 |
let action_tx = app.action.sender(); |
| 373 |
tokio::spawn(async move { |
| 374 |
let enabled = match network_manager.wifi_state().await { |
| 375 |
Ok(wifi_state) => wifi_state.enabled, |
| 376 |
Err(_) => { |
| 377 |
_ = action_tx.send(Action::toast_err("Failed to get wifi state!")); |
| 378 |
return; |
| 379 |
} |
| 380 |
}; |
| 381 |
|
| 382 |
let toast = match network_manager.set_wireless_enabled(!enabled).await { |
| 383 |
Ok(_) => { |
| 384 |
debug!("Wifi radio set to {}", !enabled); |
| 385 |
Action::toast_ok(format!("Wifi {}", if !enabled { "On" } else { "Off" })) |
| 386 |
} |
| 387 |
Err(_) => Action::toast_err("Toggle power failed!"), |
| 388 |
}; |
| 389 |
_ = action_tx.send(toast); |
| 390 |
_ = action_tx.send(Action::Refresh); |
| 391 |
}); |
| 392 |
} |
| 393 |
|
| 394 |
fn spawn_disconnect(app: &App) { |
| 395 |
let network_manager = app.network_manager.clone(); |
| 396 |
let action_tx = app.action.sender(); |
| 397 |
tokio::spawn(async move { |
| 398 |
let toast = match network_manager.disconnect().await { |
| 399 |
Ok(_) => Action::toast_ok("Disconnected!"), |
| 400 |
Err(_) => Action::toast_err("Disconnect failed!"), |
| 401 |
}; |
| 402 |
_ = action_tx.send(toast); |
| 403 |
_ = action_tx.send(Action::Refresh); |
| 404 |
}); |
| 405 |
} |
| 406 |
} |
| 407 |
|
| 408 |
impl Action { |
| 409 |
pub fn toast( |
| 410 |
title: Option<Cow<'static, str>>, |
| 411 |
msg: impl Into<Cow<'static, str>>, |
| 412 |
urgency: Urgency, |
| 413 |
duration: Option<f32>, |
| 414 |
) -> Self { |
| 415 |
Self::ShowToast(Box::new(ToastRequest { |
| 416 |
title, |
| 417 |
msg: msg.into(), |
| 418 |
urgency, |
| 419 |
duration, |
| 420 |
})) |
| 421 |
} |
| 422 |
|
| 423 |
pub fn toast_ok(msg: impl Into<Cow<'static, str>>) -> Self { |
| 424 |
Self::toast(None, msg, Urgency::Success, None) |
| 425 |
} |
| 426 |
|
| 427 |
pub fn toast_err(msg: impl Into<Cow<'static, str>>) -> Self { |
| 428 |
Self::toast(None, msg, Urgency::Critical, None) |
| 429 |
} |
| 430 |
} |