Update active networks without needing to poll every 5 seconds

This commit is contained in:
Lucy 2022-02-10 14:25:25 -05:00
parent 9b60cc758b
commit fc8e6e4d4d
No known key found for this signature in database
GPG key ID: EBC517FAD666BBF1

View file

@ -1,10 +1,15 @@
// SPDX-License-Identifier: LGPL-3.0-or-later // SPDX-License-Identifier: LGPL-3.0-or-later
use cosmic_dbus_networkmanager::{ use cosmic_dbus_networkmanager::{
active_connection::ActiveConnection,
device::SpecificDevice, device::SpecificDevice,
interface::enums::{ApFlags, ApSecurityFlags}, interface::{
active_connection::ActiveConnectionProxy,
enums::{ApFlags, ApSecurityFlags},
},
nm::NetworkManager, nm::NetworkManager,
}; };
use futures_util::StreamExt;
use gtk4::{ use gtk4::{
glib::{self, clone, source::PRIORITY_DEFAULT, MainContext, Sender}, glib::{self, clone, source::PRIORITY_DEFAULT, MainContext, Sender},
prelude::*, prelude::*,
@ -127,8 +132,29 @@ fn render_vpn(name: String, ip_addresses: Vec<IpAddr>) -> gtk4::Box {
async fn handle_devices(tx: Sender<Vec<ActiveConnectionInfo>>) -> zbus::Result<()> { async fn handle_devices(tx: Sender<Vec<ActiveConnectionInfo>>) -> zbus::Result<()> {
let conn = Connection::system().await?; let conn = Connection::system().await?;
let network_manager = NetworkManager::new(&conn).await?; let network_manager = NetworkManager::new(&conn).await?;
loop { handle_active_connections(tx.clone(), network_manager.active_connections().await?).await?;
let active_connections = network_manager.active_connections().await?; let mut active_connections_changed = network_manager.receive_active_connections_changed().await;
while let Some(active_connection_objects) = active_connections_changed.next().await {
let active_connection_objects = active_connection_objects.get().await?;
let mut active_connections = Vec::with_capacity(active_connection_objects.len());
for object in active_connection_objects {
active_connections.push(
ActiveConnectionProxy::builder(&conn)
.path(object)?
.build()
.await
.map(ActiveConnection::from)?,
);
}
handle_active_connections(tx.clone(), active_connections).await?;
}
Ok(())
}
async fn handle_active_connections(
tx: Sender<Vec<ActiveConnectionInfo>>,
active_connections: Vec<ActiveConnection<'_>>,
) -> zbus::Result<()> {
let mut info = Vec::<ActiveConnectionInfo>::with_capacity(active_connections.len()); let mut info = Vec::<ActiveConnectionInfo>::with_capacity(active_connections.len());
for connection in active_connections { for connection in active_connections {
if connection.vpn().await? { if connection.vpn().await? {
@ -191,8 +217,7 @@ async fn handle_devices(tx: Sender<Vec<ActiveConnectionInfo>>) -> zbus::Result<(
} }
tx.send(info) tx.send(info)
.expect("failed to send active connections back to main thread"); .expect("failed to send active connections back to main thread");
tokio::time::sleep(std::time::Duration::from_secs(5)).await; Ok(())
}
} }
enum ActiveConnectionInfo { enum ActiveConnectionInfo {