feat: merge subscriptions crate into cosmic-settings repo

This commit is contained in:
Michael Aaron Murphy 2025-10-08 08:19:35 +02:00 committed by Michael Murphy
parent a2f53f2239
commit 600720b7d1
47 changed files with 8399 additions and 63 deletions

View file

@ -0,0 +1,18 @@
[package]
name = "cosmic-settings-network-manager-subscription"
version = "0.1.0"
edition = "2024"
license = "MPL-2.0"
rust-version.workspace = true
publish = true
[dependencies]
cosmic-dbus-networkmanager = { git = "https://github.com/pop-os/dbus-settings-bindings" }
futures = "0.3.31"
iced_futures = { git = "https://github.com/pop-os/libcosmic" }
itertools = "0.14.0"
secure-string = "0.3.0"
thiserror = "2.0.17"
tokio = "1.47.1"
tracing = "0.1.41"
zbus = "5.11.0"

View file

@ -0,0 +1,359 @@
Mozilla Public License Version 2.0
==================================
## 1. Definitions
### 1.1. "Contributor"
means each individual or legal entity that creates, contributes to
the creation of, or owns Covered Software.
### 1.2. "Contributor Version"
means the combination of the Contributions of others (if any) used
by a Contributor and that particular Contributor's Contribution.
### 1.3. "Contribution"
means Covered Software of a particular Contributor.
### 1.4. "Covered Software"
means Source Code Form to which the initial Contributor has attached
the notice in Exhibit A, the Executable Form of such Source Code
Form, and Modifications of such Source Code Form, in each case
including portions thereof.
### 1.5. "Incompatible With Secondary Licenses"
means
+ (a) that the initial Contributor has attached the notice described
in Exhibit B to the Covered Software; or
+ (b) that the Covered Software was made available under the terms of
version 1.1 or earlier of the License, but not also under the
terms of a Secondary License.
### 1.6. "Executable Form"
means any form of the work other than Source Code Form.
### 1.7. "Larger Work"
means a work that combines Covered Software with other material, in
a separate file or files, that is not Covered Software.
### 1.8. "License"
means this document.
### 1.9. "Licensable"
means having the right to grant, to the maximum extent possible,
whether at the time of the initial grant or subsequently, any and
all of the rights conveyed by this License.
### 1.10. "Modifications"
means any of the following:
+ (a) any file in Source Code Form that results from an addition to,
deletion from, or modification of the contents of Covered
Software; or
+ (b) any new file in Source Code Form that contains any Covered
Software.
### 1.11. "Patent Claims" of a Contributor
means any patent claim(s), including without limitation, method,
process, and apparatus claims, in any patent Licensable by such
Contributor that would be infringed, but for the grant of the
License, by the making, using, selling, offering for sale, having
made, import, or transfer of either its Contributions or its
Contributor Version.
### 1.12. "Secondary License"
means either the GNU General Public License, Version 2.0, the GNU
Lesser General Public License, Version 2.1, the GNU Affero General
Public License, Version 3.0, or any later versions of those
licenses.
### 1.13. "Source Code Form"
means the form of the work preferred for making modifications.
### 1.14. "You" (or "Your")
means an individual or a legal entity exercising rights under this
License. For legal entities, "You" includes any entity that
controls, is controlled by, or is under common control with You. For
purposes of this definition, "control" means (a) the power, direct
or indirect, to cause the direction or management of such entity,
whether by contract or otherwise, or (b) ownership of more than
fifty percent (50%) of the outstanding shares or beneficial
ownership of such entity.
## 2. License Grants and Conditions
### 2.1. Grants
Each Contributor hereby grants You a world-wide, royalty-free,
non-exclusive license:
+ (a) under intellectual property rights (other than patent or trademark)
Licensable by such Contributor to use, reproduce, make available,
modify, display, perform, distribute, and otherwise exploit its
Contributions, either on an unmodified basis, with Modifications, or
as part of a Larger Work; and
+ (b) under Patent Claims of such Contributor to make, use, sell, offer
for sale, have made, import, and otherwise transfer either its
Contributions or its Contributor Version.
### 2.2. Effective Date
The licenses granted in Section 2.1 with respect to any Contribution
become effective for each Contribution on the date the Contributor first
distributes such Contribution.
### 2.3. Limitations on Grant Scope
The licenses granted in this Section 2 are the only rights granted under
this License. No additional rights or licenses will be implied from the
distribution or licensing of Covered Software under this License.
Notwithstanding Section 2.1(b) above, no patent license is granted by a
Contributor:
+ (a) for any code that a Contributor has removed from Covered Software;
or
+ (b) for infringements caused by: (i) Your and any other third party's
modifications of Covered Software, or (ii) the combination of its
Contributions with other software (except as part of its Contributor
Version); or
+ (c) under Patent Claims infringed by Covered Software in the absence of
its Contributions.
This License does not grant any rights in the trademarks, service marks,
or logos of any Contributor (except as may be necessary to comply with
the notice requirements in Section 3.4).
### 2.4. Subsequent Licenses
No Contributor makes additional grants as a result of Your choice to
distribute the Covered Software under a subsequent version of this
License (see Section 10.2) or under the terms of a Secondary License (if
permitted under the terms of Section 3.3).
### 2.5. Representation
Each Contributor represents that the Contributor believes its
Contributions are its original creation(s) or it has sufficient rights
to grant the rights to its Contributions conveyed by this License.
### 2.6. Fair Use
This License is not intended to limit any rights You have under
applicable copyright doctrines of fair use, fair dealing, or other
equivalents.
### 2.7. Conditions
Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
in Section 2.1.
## 3. Responsibilities
### 3.1. Distribution of Source Form
All distribution of Covered Software in Source Code Form, including any
Modifications that You create or to which You contribute, must be under
the terms of this License. You must inform recipients that the Source
Code Form of the Covered Software is governed by the terms of this
License, and how they can obtain a copy of this License. You may not
attempt to alter or restrict the recipients' rights in the Source Code
Form.
### 3.2. Distribution of Executable Form
If You distribute Covered Software in Executable Form then:
+ (a) such Covered Software must also be made available in Source Code
Form, as described in Section 3.1, and You must inform recipients of
the Executable Form how they can obtain a copy of such Source Code
Form by reasonable means in a timely manner, at a charge no more
than the cost of distribution to the recipient; and
+ (b) You may distribute such Executable Form under the terms of this
License, or sublicense it under different terms, provided that the
license for the Executable Form does not attempt to limit or alter
the recipients' rights in the Source Code Form under this License.
### 3.3. Distribution of a Larger Work
You may create and distribute a Larger Work under terms of Your choice,
provided that You also comply with the requirements of this License for
the Covered Software. If the Larger Work is a combination of Covered
Software with a work governed by one or more Secondary Licenses, and the
Covered Software is not Incompatible With Secondary Licenses, this
License permits You to additionally distribute such Covered Software
under the terms of such Secondary License(s), so that the recipient of
the Larger Work may, at their option, further distribute the Covered
Software under the terms of either this License or such Secondary
License(s).
### 3.4. Notices
You may not remove or alter the substance of any license notices
(including copyright notices, patent notices, disclaimers of warranty,
or limitations of liability) contained within the Source Code Form of
the Covered Software, except that You may alter any license notices to
the extent required to remedy known factual inaccuracies.
### 3.5. Application of Additional Terms
You may choose to offer, and to charge a fee for, warranty, support,
indemnity or liability obligations to one or more recipients of Covered
Software. However, You may do so only on Your own behalf, and not on
behalf of any Contributor. You must make it absolutely clear that any
such warranty, support, indemnity, or liability obligation is offered by
You alone, and You hereby agree to indemnify every Contributor for any
liability incurred by such Contributor as a result of warranty, support,
indemnity or liability terms You offer. You may include additional
disclaimers of warranty and limitations of liability specific to any
jurisdiction.
## 4. Inability to Comply Due to Statute or Regulation
If it is impossible for You to comply with any of the terms of this
License with respect to some or all of the Covered Software due to
statute, judicial order, or regulation then You must: (a) comply with
the terms of this License to the maximum extent possible; and (b)
describe the limitations and the code they affect. Such description must
be placed in a text file included with all distributions of the Covered
Software under this License. Except to the extent prohibited by statute
or regulation, such description must be sufficiently detailed for a
recipient of ordinary skill to be able to understand it.
## 5. Termination
5.1. The rights granted under this License will terminate automatically
if You fail to comply with any of its terms. However, if You become
compliant, then the rights granted under this License from a particular
Contributor are reinstated (a) provisionally, unless and until such
Contributor explicitly and finally terminates Your grants, and (b) on an
ongoing basis, if such Contributor fails to notify You of the
non-compliance by some reasonable means prior to 60 days after You have
come back into compliance. Moreover, Your grants from a particular
Contributor are reinstated on an ongoing basis if such Contributor
notifies You of the non-compliance by some reasonable means, this is the
first time You have received notice of non-compliance with this License
from such Contributor, and You become compliant prior to 30 days after
Your receipt of the notice.
5.2. If You initiate litigation against any entity by asserting a patent
infringement claim (excluding declaratory judgment actions,
counter-claims, and cross-claims) alleging that a Contributor Version
directly or indirectly infringes any patent, then the rights granted to
You by any and all Contributors for the Covered Software under Section
2.1 of this License shall terminate.
5.3. In the event of termination under Sections 5.1 or 5.2 above, all
end user license agreements (excluding distributors and resellers) which
have been validly granted by You or Your distributors under this License
prior to termination shall survive termination.
## 6. Disclaimer of Warranty
**Covered Software is provided under this License on an "as is"
basis, without warranty of any kind, either expressed, implied, or
statutory, including, without limitation, warranties that the
Covered Software is free of defects, merchantable, fit for a
particular purpose or non-infringing. The entire risk as to the
quality and performance of the Covered Software is with You.
Should any Covered Software prove defective in any respect, You
(not any Contributor) assume the cost of any necessary servicing,
repair, or correction. This disclaimer of warranty constitutes an
essential part of this License. No use of any Covered Software is
authorized under this License except under this disclaimer.**
#7. Limitation of Liability
**Under no circumstances and under no legal theory, whether tort
(including negligence), contract, or otherwise, shall any
Contributor, or anyone who distributes Covered Software as
permitted above, be liable to You for any direct, indirect,
special, incidental, or consequential damages of any character
including, without limitation, damages for lost profits, loss of
goodwill, work stoppage, computer failure or malfunction, or any
and all other commercial damages or losses, even if such party
shall have been informed of the possibility of such damages. This
limitation of liability shall not apply to liability for death or
personal injury resulting from such party's negligence to the
extent applicable law prohibits such limitation. Some
jurisdictions do not allow the exclusion or limitation of
incidental or consequential damages, so this exclusion and
limitation may not apply to You.**
## 8. Litigation
Any litigation relating to this License may be brought only in the
courts of a jurisdiction where the defendant maintains its principal
place of business and such litigation shall be governed by laws of that
jurisdiction, without reference to its conflict-of-law provisions.
Nothing in this Section shall prevent a party's ability to bring
cross-claims or counter-claims.
## 9. Miscellaneous
This License represents the complete agreement concerning the subject
matter hereof. If any provision of this License is held to be
unenforceable, such provision shall be reformed only to the extent
necessary to make it enforceable. Any law or regulation which provides
that the language of a contract shall be construed against the drafter
shall not be used to construe this License against a Contributor.
## 10. Versions of the License
### 10.1. New Versions
Mozilla Foundation is the license steward. Except as provided in Section
10.3, no one other than the license steward has the right to modify or
publish new versions of this License. Each version will be given a
distinguishing version number.
### 10.2. Effect of New Versions
You may distribute the Covered Software under the terms of the version
of the License under which You originally received the Covered Software,
or under the terms of any subsequent version published by the license
steward.
### 10.3. Modified Versions
If you create software not governed by this License, and you want to
create a new license for such software, you may create and use a
modified version of this License if you rename the license and remove
any references to the name of the license steward (except to note that
such modified license differs from this License).
### 10.4. Distributing Source Code Form that is Incompatible With Secondary
Licenses
If You choose to distribute Source Code Form that is Incompatible With
Secondary Licenses under the terms of this version of the License, the
notice described in Exhibit B of this License must be attached.
## Exhibit A - Source Code Form License Notice
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
If it is not possible or desirable to put the notice in a particular
file, then You may include the notice in a location (such as a LICENSE
file in a relevant directory) where a recipient would be likely to look
for such a notice.
You may add additional accurate notices of copyright ownership.
## Exhibit B - "Incompatible With Secondary Licenses" Notice
This Source Code Form is "Incompatible With Secondary Licenses", as
defined by the Mozilla Public License, v. 2.0.

View file

@ -0,0 +1,67 @@
// Copyright 2024 System76 <info@system76.com>
// SPDX-License-Identifier: MPL-2.0
use super::Event;
use cosmic_dbus_networkmanager::nm::NetworkManager;
use futures::{SinkExt, StreamExt};
use iced_futures::{Subscription, stream};
use std::{fmt::Debug, hash::Hash};
use zbus::Connection;
#[derive(Debug, Clone)]
pub enum State {
Continue(Connection),
Error,
}
pub fn active_conns_subscription<I: 'static + Hash + Copy + Send + Sync + Debug>(
id: I,
conn: Connection,
) -> iced_futures::Subscription<Event> {
Subscription::run_with_id(
id,
stream::channel(50, move |output| async move {
watch(conn, output).await;
futures::future::pending().await
}),
)
}
pub async fn watch(conn: zbus::Connection, mut output: futures::channel::mpsc::Sender<Event>) {
let mut state = State::Continue(conn);
loop {
state = start_listening(state, &mut output).await;
}
}
async fn start_listening(
state: State,
output: &mut futures::channel::mpsc::Sender<Event>,
) -> State {
let conn = match state {
State::Continue(conn) => conn,
State::Error => futures::future::pending().await,
};
let network_manager = match NetworkManager::new(&conn).await {
Ok(n) => n,
Err(why) => {
tracing::error!(why = why.to_string(), "Failed to connect to NetworkManager");
return State::Error;
}
};
let mut active_conns_changed = network_manager.receive_active_connections_changed().await;
active_conns_changed.next().await;
while let (Some(_change), _) = futures::future::join(
active_conns_changed.next(),
tokio::time::sleep(tokio::time::Duration::from_secs(1)),
)
.await
{
_ = output.send(Event::ActiveConns).await;
}
State::Continue(conn)
}

View file

@ -0,0 +1,120 @@
// Copyright 2024 System76 <info@system76.com>
// SPDX-License-Identifier: MPL-2.0
use cosmic_dbus_networkmanager::{
device::wireless::WirelessDevice,
interface::enums::{ApFlags, ApSecurityFlags, DeviceState},
};
use futures::StreamExt;
use itertools::Itertools;
use std::{collections::HashMap, sync::Arc};
use zbus::zvariant::ObjectPath;
use super::hw_address::HwAddress;
pub async fn handle_wireless_device(
device: WirelessDevice<'_>,
hw_address: Option<String>,
) -> zbus::Result<Vec<AccessPoint>> {
device.request_scan(HashMap::new()).await?;
let mut scan_changed = device.receive_last_scan_changed().await;
if let Some(t) = scan_changed.next().await {
match t.get().await {
Ok(-1) => {
tracing::error!("wireless device scan errored");
return Ok(Default::default());
}
_ => (),
}
}
let access_points = device.get_access_points().await?;
let state: DeviceState = device
.upcast()
.await
.and_then(|dev| dev.cached_state())
.unwrap_or_default()
.map(|s| s.into())
.unwrap_or_else(|| DeviceState::Unknown);
// Sort by strength and remove duplicates
let mut aps = HashMap::<String, AccessPoint>::new();
for ap in access_points {
let (ssid_res, strength_res) = futures::join!(ap.ssid(), ap.strength());
if let Some((ssid, strength)) = ssid_res.ok().zip(strength_res.ok()) {
let ssid = String::from_utf8_lossy(&ssid.clone()).into_owned();
if let Some(access_point) = aps.get(&ssid) {
if access_point.strength > strength {
continue;
}
}
let Ok(flags) = ap.rsn_flags().await else {
continue;
};
let network_type = if flags.intersects(ApSecurityFlags::KEY_MGMT_802_1X) {
NetworkType::EAP
} else if flags.intersects(ApSecurityFlags::KEY_MGMTPSK) {
NetworkType::PSK
} else if flags.is_empty() {
NetworkType::Open
} else {
continue;
};
aps.insert(
ssid.clone(),
AccessPoint {
ssid: Arc::from(ssid),
strength,
state,
working: false,
path: ap.inner().path().to_owned(),
secured: !ap.wpa_flags().await?.is_empty(),
wps_push: ap.flags().await?.contains(ApFlags::WPS_PBC),
network_type,
hw_address: hw_address
.as_ref()
.and_then(|str_addr| HwAddress::from_str(str_addr))
.unwrap_or_default(),
},
);
}
}
let aps = aps
.into_values()
.sorted_by(|a, b| b.strength.cmp(&a.strength))
.collect();
Ok(aps)
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AccessPoint {
pub ssid: Arc<str>,
pub strength: u8,
pub state: DeviceState,
pub working: bool,
pub path: ObjectPath<'static>,
pub hw_address: HwAddress,
pub secured: bool,
pub wps_push: bool,
pub network_type: NetworkType,
}
// TODO do we want to support eap methods other than peap in the applet?
// Then we'd need a dropdown for the eap method,
// and tls requires a cert instead of a password
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NetworkType {
Open,
PSK,
EAP,
}

View file

@ -0,0 +1,112 @@
// Copyright 2024 System76 <info@system76.com>
// SPDX-License-Identifier: MPL-2.0
use cosmic_dbus_networkmanager::{
active_connection::ActiveConnection, device::SpecificDevice,
interface::enums::ActiveConnectionState,
};
use std::net::Ipv4Addr;
pub async fn active_connections(
active_connections: Vec<ActiveConnection<'_>>,
) -> zbus::Result<Vec<ActiveConnectionInfo>> {
let mut info = Vec::<ActiveConnectionInfo>::with_capacity(active_connections.len());
for connection in active_connections {
let ipv4 = connection
.ip4_config()
.await?
.address_data()
.await
.unwrap_or_default();
let addresses: Vec<_> = ipv4.iter().map(|d| d.address).collect();
let state = connection
.state()
.await
.unwrap_or(ActiveConnectionState::Unknown);
if connection.vpn().await.unwrap_or_default() {
info.push(ActiveConnectionInfo::Vpn {
name: connection.id().await?,
ip_addresses: addresses.clone(),
});
continue;
}
for device in connection.devices().await.unwrap_or_default() {
match device
.downcast_to_device()
.await
.ok()
.and_then(|inner| inner)
{
Some(SpecificDevice::Wired(wired_device)) => {
info.push(ActiveConnectionInfo::Wired {
name: connection.id().await?,
hw_address: wired_device.hw_address().await?,
speed: wired_device.speed().await?,
ip_addresses: addresses.clone(),
});
}
Some(SpecificDevice::Wireless(wireless_device)) => {
if let Ok(access_point) = wireless_device.active_access_point().await {
info.push(ActiveConnectionInfo::WiFi {
name: String::from_utf8_lossy(&access_point.ssid().await?).into_owned(),
ip_addresses: addresses.clone(),
hw_address: wireless_device.hw_address().await?,
state,
strength: access_point.strength().await.unwrap_or_default(),
});
}
}
Some(SpecificDevice::WireGuard(_)) => {
info.push(ActiveConnectionInfo::Vpn {
name: connection.id().await?,
ip_addresses: addresses.clone(),
});
}
_ => {}
}
}
}
info.sort_by(|a, b| {
let helper = |conn: &ActiveConnectionInfo| match conn {
ActiveConnectionInfo::Vpn { name, .. } => format!("0{name}"),
ActiveConnectionInfo::Wired { name, .. } => format!("1{name}"),
ActiveConnectionInfo::WiFi { name, .. } => format!("2{name}"),
};
helper(a).cmp(&helper(b))
});
Ok(info)
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ActiveConnectionInfo {
Wired {
name: String,
hw_address: String,
speed: u32,
ip_addresses: Vec<Ipv4Addr>,
},
WiFi {
name: String,
ip_addresses: Vec<Ipv4Addr>,
hw_address: String,
state: ActiveConnectionState,
strength: u8,
},
Vpn {
name: String,
ip_addresses: Vec<Ipv4Addr>,
},
}
impl ActiveConnectionInfo {
pub fn name(&self) -> String {
match &self {
Self::Wired { name, .. } => name.clone(),
Self::WiFi { name, .. } => name.clone(),
Self::Vpn { name, .. } => name.clone(),
}
}
}

View file

@ -0,0 +1,230 @@
// Copyright 2024 System76 <info@system76.com>
// SPDX-License-Identifier: MPL-2.0
use super::Event;
pub use cosmic_dbus_networkmanager::interface::enums::{
ActiveConnectionState, DeviceState, DeviceType,
};
use cosmic_dbus_networkmanager::nm::NetworkManager;
use futures::{SinkExt, StreamExt};
use iced_futures::{self, Subscription, stream};
use std::{fmt::Debug, hash::Hash, sync::Arc};
use zbus::{Connection, zvariant::ObjectPath};
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct DeviceInfo {
pub path: ObjectPath<'static>,
pub device_type: DeviceType,
pub interface: String,
pub state: DeviceState,
pub active_connection: Option<(DeviceConnection, ActiveConnectionState)>,
pub available_connections: Vec<DeviceConnection>,
pub known_connections: Vec<KnownDeviceConnection>,
}
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct DeviceConnection {
pub path: ObjectPath<'static>,
pub id: String,
pub uuid: Arc<str>,
}
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct KnownDeviceConnection {
pub id: String,
pub uuid: Arc<str>,
}
pub async fn list<'a>(
conn: &'a zbus::Connection,
device_type_filter: fn(DeviceType) -> bool,
) -> zbus::Result<Vec<DeviceInfo>> {
let nm = NetworkManager::new(conn).await?;
let (devices, nm_settings) = futures::try_join!(nm.devices(), nm.settings())?;
let connection_settings: &Vec<_> = &futures::stream::FuturesOrdered::from_iter(
nm_settings
.list_connections()
.await?
.into_iter()
.map(|connection| async move { connection.get_settings().await }),
)
.filter_map(|res| async move { res.ok() })
.collect()
.await;
let device_iter = devices.into_iter().map(|device| async move {
let (interface, hw_address, device_type, state, available_connections) =
futures::try_join!(
device.interface(),
device.hw_address(),
device.device_type(),
device.state(),
device.available_connections()
)
.ok()?;
if !device_type_filter(device_type) {
return None;
}
if hw_address.is_empty() {
return None;
}
let (active_connection, available_connections) = futures::join!(
async {
let connection = device.active_connection().await?;
let (id, uuid, state) =
futures::try_join!(connection.id(), connection.uuid(), connection.state())?;
Ok::<_, zbus::Error>((
DeviceConnection {
id,
uuid: Arc::from(uuid),
path: connection.inner().path().to_owned(),
},
state,
))
},
futures::stream::FuturesOrdered::from_iter(available_connections.into_iter().map(
|conn| async move {
let path = conn.inner().path().to_owned();
let settings = conn.get_settings().await.ok()?;
let id = settings
.get("connection")?
.get("id")?
.downcast_ref::<String>()
.ok()?;
let uuid = settings["connection"]
.get("uuid")?
.downcast_ref::<String>()
.ok()?;
Some(DeviceConnection {
id,
uuid: Arc::from(uuid),
path,
})
}
),)
.filter_map(|res| async move { res })
.collect::<Vec<_>>()
);
let known_connections = connection_settings
.iter()
.flat_map(|conn_settings| {
let connection = conn_settings.get("connection")?;
let interface_name = connection
.get("interface-name")?
.downcast_ref::<String>()
.ok()?;
if interface_name != interface {
return None;
}
let id = connection.get("id")?.downcast_ref::<String>().ok()?;
let uuid = connection.get("uuid")?.downcast_ref::<String>().ok()?;
Some(KnownDeviceConnection {
uuid: Arc::from(uuid),
id,
})
})
.collect();
Some(DeviceInfo {
path: device.inner().path().to_owned(),
device_type,
interface,
state,
active_connection: active_connection.ok(),
known_connections,
available_connections,
})
});
let devices_info = futures::stream::FuturesOrdered::from_iter(device_iter)
.filter_map(|res| async move { res })
.collect::<Vec<DeviceInfo>>()
.await;
Ok(devices_info)
}
pub fn subscription<I: 'static + Hash + Copy + Send + Sync + Debug>(
id: I,
has_popup: bool,
conn: Connection,
) -> iced_futures::Subscription<Event> {
Subscription::run_with_id(
(id, has_popup),
stream::channel(50, move |output| async move {
watch(conn, has_popup, output).await;
futures::future::pending().await
}),
)
}
pub async fn watch(
conn: zbus::Connection,
has_popup: bool,
mut output: futures::channel::mpsc::Sender<Event>,
) {
let mut state = State::Continue(conn);
loop {
state = start_listening(state, has_popup, &mut output).await;
}
}
#[derive(Debug, Clone)]
pub enum State {
Continue(Connection),
Error,
}
async fn start_listening(
state: State,
has_popup: bool,
output: &mut futures::channel::mpsc::Sender<Event>,
) -> State {
let conn = match state {
State::Continue(conn) => conn,
State::Error => futures::future::pending().await,
};
let network_manager = match NetworkManager::new(&conn).await {
Ok(n) => n,
Err(why) => {
tracing::error!(
why = why.to_string(),
"failed to connect to network_manager"
);
return State::Error;
}
};
let mut devices_changed = network_manager.receive_devices_changed().await;
let secs = if has_popup { 4 } else { 60 };
while let (Some(_change), _) = futures::future::join(
devices_changed.next(),
tokio::time::sleep(tokio::time::Duration::from_secs(secs)),
)
.await
{
_ = output.send(Event::Devices).await;
}
State::Continue(conn)
}

View file

@ -0,0 +1,34 @@
#[derive(Copy, Clone, PartialEq, Eq, Default, Debug, PartialOrd, Ord)]
pub struct HwAddress {
address: u64,
}
impl HwAddress {
pub fn from_str(arg: &str) -> Option<Self> {
let columnless_vec = arg.split(":").collect::<Vec<&str>>();
if columnless_vec.len() * 3 - 1 != arg.len() {
return None;
}
for byte in &columnless_vec {
if byte.len() != 2 {
return None;
}
}
u64::from_str_radix(columnless_vec.join("").as_str(), 16)
.ok()
.and_then(|address| Some(HwAddress { address }))
}
pub fn from_string(arg: &String) -> Option<Self> {
HwAddress::from_str(arg.as_str())
}
pub fn to_string(&self) -> String {
format!("{:#x}", self.address)
.trim_start_matches("0x")
.chars()
.collect::<Vec<_>>()
.chunks(2)
.map(|chunk| chunk.iter().cloned().collect::<String>())
.collect::<Vec<String>>()
.join(":")
}
}

View file

@ -0,0 +1,889 @@
// Copyright 2024 System76 <info@system76.com>
// SPDX-License-Identifier: MPL-2.0
pub mod active_conns;
pub mod available_wifi;
pub mod current_networks;
pub mod devices;
pub mod hw_address;
pub mod wireless_enabled;
use std::{collections::HashMap, fmt::Debug, sync::Arc, time::Duration};
use available_wifi::NetworkType;
pub use cosmic_dbus_networkmanager as dbus;
pub use dbus::settings::connection::Settings;
use cosmic_dbus_networkmanager::{
active_connection::ActiveConnection,
device::SpecificDevice,
interface::{
active_connection::ActiveConnectionProxy,
enums::{self, ActiveConnectionState, DeviceType, NmConnectivityState},
},
nm::NetworkManager,
settings::NetworkManagerSettings,
};
use futures::{
FutureExt, SinkExt, StreamExt,
channel::mpsc::{UnboundedReceiver, UnboundedSender, unbounded},
};
use hw_address::HwAddress;
use iced_futures::{Subscription, stream};
use secure_string::SecureString;
use tokio::process::Command;
use zbus::zvariant::{self, ObjectPath, Value};
use self::{
available_wifi::{AccessPoint, handle_wireless_device},
current_networks::{ActiveConnectionInfo, active_connections},
};
pub type SSID = Arc<str>;
pub type UUID = Arc<str>;
#[derive(thiserror::Error, Debug)]
pub enum Error {
#[error("access point not found")]
AccessPointNotFound,
#[error("failed to list bluetooth devices with rfkill")]
BluetoothRfkillList(std::io::Error),
#[error("failed to activate connection")]
ConnectionActivate,
#[error("no wifi devices found")]
NoWiFiDevices,
#[error("zbus error")]
Zbus(#[from] zbus::Error),
}
#[derive(Debug)]
pub enum State {
Ready(zbus::Connection),
Waiting(zbus::Connection, UnboundedReceiver<Request>),
Finished,
}
/// Reloads state on available connection changes.
pub async fn watch_connections_changed(
conn: zbus::Connection,
mut output: futures::channel::mpsc::Sender<Event>,
) {
let Ok(nm) = NetworkManager::new(&conn).await else {
return;
};
let mut device_stream = nm.receive_devices_changed().await;
loop {
// Emits updates when available connections changes.
let connections_changed = std::pin::pin!(async {
let devices = nm.devices().await.unwrap_or_default();
let mut connection_streams =
futures::stream::FuturesUnordered::from_iter(devices.into_iter().map(
|device| async move { device.receive_available_connections_changed().await },
))
.collect::<Vec<_>>()
.await;
let mut available_connections = futures::stream::FuturesUnordered::from_iter(
connection_streams
.iter_mut()
.map(|stream| async { stream.next().await }),
);
loop {
_ = futures::join!(
available_connections.next(),
tokio::time::sleep(Duration::from_secs(3))
);
// TODO: although it should consume the stream, the stream is never empty.
// while available_connections.next().now_or_never().is_some() {}
let state = NetworkManagerState::new(&conn).await.unwrap_or_default();
_ = output
.send(Event::RequestResponse {
req: Request::Reload,
state,
success: true,
})
.await;
}
});
// Reload the connection streams whenever devices change.
futures::future::select(connections_changed, device_stream.next()).await;
}
}
pub fn subscription<I: Copy + Debug + std::hash::Hash + 'static>(
id: I,
conn: zbus::Connection,
) -> iced_futures::Subscription<Event> {
Subscription::run_with_id(
id,
stream::channel(50, |output| async move {
watch(conn, output).await;
futures::future::pending().await
}),
)
}
pub async fn watch(conn: zbus::Connection, mut output: futures::channel::mpsc::Sender<Event>) {
let mut state = State::Ready(conn);
loop {
state = start_listening(state, &mut output).await;
}
}
async fn start_listening(
state: State,
output: &mut futures::channel::mpsc::Sender<Event>,
) -> State {
match state {
State::Ready(conn) => {
let (tx, rx) = unbounded();
if output
.send(Event::Init {
conn: conn.clone(),
sender: tx,
state: NetworkManagerState::new(&conn).await.unwrap_or_default(),
})
.await
.is_ok()
{
State::Waiting(conn, rx)
} else {
State::Finished
}
}
State::Waiting(conn, mut rx) => {
let network_manager = match NetworkManager::new(&conn).await {
Ok(n) => n,
Err(_) => return State::Finished,
};
match rx.next().await {
Some(Request::Deactivate(uuid)) => {
let mut success = false;
for c in network_manager
.active_connections()
.await
.unwrap_or_default()
{
if c.uuid().await.unwrap_or_default().as_str() == uuid.as_ref()
&& network_manager.deactivate_connection(&c).await.is_ok()
{
success = true;
if let Ok(ActiveConnectionState::Deactivated) = c.state().await {
break;
} else {
let mut changed = c.receive_state_changed().await;
_ = tokio::time::timeout(Duration::from_secs(5), async move {
loop {
if let Some(next) = changed.next().await {
if let Ok(ActiveConnectionState::Deactivated) =
next.get().await.map(ActiveConnectionState::from)
{
break;
}
}
}
})
.await;
}
break;
}
}
_ = request_response(&conn, Request::Deactivate(uuid.clone()), success)
.then(|event| output.send(event))
.await;
}
Some(Request::Disconnect(ssid)) => {
let mut success = false;
for c in network_manager
.active_connections()
.await
.unwrap_or_default()
{
if c.id().await.unwrap_or_default().as_str() == ssid.as_ref()
&& network_manager.deactivate_connection(&c).await.is_ok()
{
success = true;
if let Ok(ActiveConnectionState::Deactivated) = c.state().await {
break;
} else {
let mut changed = c.receive_state_changed().await;
_ = tokio::time::timeout(Duration::from_secs(5), async move {
loop {
if let Some(next) = changed.next().await {
if let Ok(ActiveConnectionState::Deactivated) =
next.get().await.map(ActiveConnectionState::from)
{
break;
}
}
}
})
.await;
}
break;
}
}
_ = request_response(&conn, Request::Disconnect(ssid.clone()), success)
.then(|event| output.send(event))
.await;
}
Some(Request::SetAirplaneMode(airplane_mode)) => {
// wifi
let mut success = network_manager
.set_wireless_enabled(!airplane_mode)
.await
.is_ok();
// bluetooth
success = success
&& Command::new("rfkill")
.arg(if airplane_mode { "block" } else { "unblock" })
.arg("bluetooth")
.output()
.await
.is_ok();
let mut state = NetworkManagerState::new(&conn).await.unwrap_or_default();
state.airplane_mode = if success {
airplane_mode
} else {
!airplane_mode
};
if state.airplane_mode {
state.wifi_enabled = false;
}
_ = output
.send(Event::RequestResponse {
req: Request::SetAirplaneMode(airplane_mode),
success,
state,
})
.await;
}
Some(Request::SetWiFi(enabled)) => {
let success = network_manager.set_wireless_enabled(enabled).await.is_ok();
let mut state = NetworkManagerState::new(&conn).await.unwrap_or_default();
state.wifi_enabled = if success { enabled } else { !enabled };
if state.wifi_enabled {
tokio::time::sleep(Duration::from_secs(3)).await;
}
_ = request_response(&conn, Request::SetWiFi(enabled), success)
.then(|event| output.send(event))
.await;
}
Some(Request::Authenticate {
ssid,
identity,
password,
hw_address,
}) => {
let nm_state = NetworkManagerState::new(&conn).await.unwrap_or_default();
let success = nm_state
.connect_wifi(
&conn,
&ssid,
identity.as_deref(),
Some(password.unsecure()),
hw_address,
)
.await
.is_ok();
_ = output
.send(Event::RequestResponse {
req: Request::Authenticate {
ssid: ssid.clone(),
identity: identity.clone(),
password: password.clone(),
hw_address,
},
success,
state: NetworkManagerState::new(&conn).await.unwrap_or_default(),
})
.await;
}
Some(Request::SelectAccessPoint(ssid, hw_address, network_type)) => {
if matches!(network_type, NetworkType::Open) {
attempt_wifi_connection(&conn, ssid, hw_address, network_type, output)
.await;
} else {
// For secured networks, check if we have saved credentials
if !has_saved_wifi_credentials(&conn, &ssid).await {
return State::Waiting(conn, rx);
}
// We have saved credentials, attempt connection
attempt_wifi_connection(&conn, ssid, hw_address, network_type, output)
.await;
}
}
Some(Request::Activate(device_path, connection_path)) => {
let mut success = true;
if let Err(why) = network_manager
.activate_connection_by_paths(&connection_path, &device_path)
.await
{
tracing::error!(
?why,
"failed to activate connection on {device_path:?} to {connection_path}"
);
success = false;
};
_ = request_response(
&conn,
Request::Activate(device_path, connection_path),
success,
)
.then(|event| output.send(event))
.await;
}
Some(Request::Reload) => {
_ = output
.send(request_response(&conn, Request::Reload, true).await)
.await;
}
Some(Request::Remove(uuid)) => {
let s = match NetworkManagerSettings::new(&conn).await {
Ok(s) => s,
Err(why) => {
tracing::error!(?why, "error getting network manager settings");
_ = output
.send(Event::RequestResponse {
req: Request::Forget(uuid.clone()),
success: false,
state: NetworkManagerState::new(&conn)
.await
.unwrap_or_default(),
})
.await;
return State::Waiting(conn, rx);
}
};
let known_conns = s.list_connections().await.unwrap_or_default();
let mut success = false;
for c in known_conns {
let settings = c.get_settings().await.ok().unwrap_or_default();
let c_uuid = settings
.get("connection")
.and_then(|conn| conn.get("uuid"))
.and_then(|uuid| uuid.downcast_ref::<String>().ok())
.unwrap_or_default();
if uuid.as_ref() == c_uuid.as_str() {
_ = c.delete().await;
success = true;
}
}
_ = request_response(&conn, Request::Remove(uuid.clone()), success)
.then(|event| output.send(event))
.await;
}
Some(Request::Forget(ssid)) => {
let s = match NetworkManagerSettings::new(&conn).await {
Ok(s) => s,
Err(why) => {
tracing::error!(?why, "error getting network manager settings");
_ = output
.send(Event::RequestResponse {
req: Request::Forget(ssid.clone()),
success: false,
state: NetworkManagerState::new(&conn)
.await
.unwrap_or_default(),
})
.await;
return State::Waiting(conn, rx);
}
};
let known_conns = s.list_connections().await.unwrap_or_default();
let mut success = false;
for c in known_conns {
let settings = c.get_settings().await.ok().unwrap_or_default();
let s = Settings::new(settings);
if s.wifi
.clone()
.and_then(|w| w.ssid)
.and_then(|ssid| String::from_utf8(ssid).ok())
.is_some_and(|s| s == ssid.as_ref())
{
_ = c.delete().await;
success = true;
break;
}
}
_ = request_response(&conn, Request::Forget(ssid.clone()), success)
.then(|event| output.send(event))
.await;
}
None => {
return State::Finished;
}
};
State::Waiting(conn, rx)
}
State::Finished => futures::future::pending().await,
}
}
async fn request_response(conn: &zbus::Connection, req: Request, success: bool) -> Event {
Event::RequestResponse {
req,
success,
state: NetworkManagerState::new(conn).await.unwrap_or_default(),
}
}
async fn has_saved_wifi_credentials(conn: &zbus::Connection, ssid: &str) -> bool {
let Ok(nm_settings) = NetworkManagerSettings::new(conn).await else {
return false;
};
let known_conns = nm_settings.list_connections().await.unwrap_or_default();
for connection in known_conns {
if let Ok(settings) = connection.get_settings().await {
let settings = Settings::new(settings);
if let Some(saved_ssid) = settings
.wifi
.and_then(|w| w.ssid)
.and_then(|ssid| String::from_utf8(ssid).ok())
{
if saved_ssid == ssid {
return true;
}
}
}
}
false
}
async fn attempt_wifi_connection(
conn: &zbus::Connection,
ssid: SSID,
hw_address: HwAddress,
network_type: NetworkType,
output: &mut futures::channel::mpsc::Sender<Event>,
) {
let state = NetworkManagerState::new(conn).await.unwrap_or_default();
let success = if let Err(err) = state
.connect_wifi(conn, ssid.as_ref(), None, None, hw_address)
.await
{
tracing::error!("Failed to connect to access point: {:?}", err);
false
} else {
true
};
_ = request_response(
conn,
Request::SelectAccessPoint(ssid, hw_address, network_type),
success,
)
.then(|event| output.send(event))
.await;
}
#[derive(Debug, Clone)]
pub enum Request {
/// Activate a device's connection profile
Activate(ObjectPath<'static>, ObjectPath<'static>),
/// Deactivate a connection
Deactivate(UUID),
/// Disconnect from an access point.
Disconnect(SSID),
/// Forget a known access point.
Forget(SSID),
/// Create a connection to a new access point.
Authenticate {
ssid: String,
identity: Option<String>,
password: SecureString,
hw_address: HwAddress,
},
/// Signal to reload the service.
Reload,
/// Remove a connection profile.
Remove(UUID),
/// Connect to a known access point.
SelectAccessPoint(SSID, HwAddress, NetworkType),
/// Toggle airplaine mode.
SetAirplaneMode(bool),
/// Toggle WiFi enablement.
SetWiFi(bool),
}
#[derive(Debug, Clone)]
pub enum Event {
RequestResponse {
req: Request,
state: NetworkManagerState,
success: bool,
},
Init {
conn: zbus::Connection,
sender: UnboundedSender<Request>,
state: NetworkManagerState,
},
Devices,
WiFiEnabled(bool),
WirelessAccessPoints,
ActiveConns,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NetworkManagerState {
pub wireless_access_points: Vec<AccessPoint>,
pub active_conns: Vec<ActiveConnectionInfo>,
pub known_access_points: Vec<AccessPoint>,
pub wifi_enabled: bool,
pub airplane_mode: bool,
pub connectivity: NmConnectivityState,
}
impl Default for NetworkManagerState {
fn default() -> Self {
Self {
wireless_access_points: Vec::new(),
active_conns: Vec::new(),
known_access_points: Vec::new(),
wifi_enabled: false,
airplane_mode: false,
connectivity: NmConnectivityState::Unknown,
}
}
}
impl NetworkManagerState {
pub async fn new(conn: &zbus::Connection) -> Result<Self, Error> {
let network_manager = NetworkManager::new(conn).await?;
let mut this = Self::default();
this.refresh_wifi_state(conn, &network_manager).await?;
Ok(this)
}
pub async fn refresh_wifi_state(
&mut self,
conn: &zbus::Connection,
network_manager: &NetworkManager<'_>,
) -> Result<(), Error> {
let (airplane_mode, wireless_enabled, settings_res) = futures::join!(
Command::new("rfkill")
.arg("list")
.arg("bluetooth")
.output()
.then(|res| async move {
let Ok(output) = res else {
return false;
};
std::str::from_utf8(&output.stdout)
.ok()
.map_or(false, |stdout| stdout.contains("Soft blocked: yes"))
}),
network_manager
.wireless_enabled()
.then(|res| async move { res.unwrap_or_default() }),
NetworkManagerSettings::new(conn)
);
self.wifi_enabled = wireless_enabled;
self.airplane_mode = airplane_mode && !self.wifi_enabled;
let settings = settings_res?;
_ = settings.load_connections(&[]).await;
let (known_conns, active_conns, devices, connectivity) = futures::join!(
settings.list_connections(),
network_manager.active_connections(),
network_manager.devices(),
network_manager.connectivity(),
);
let devices = devices.unwrap_or_default();
let known_conns = known_conns.unwrap_or_default();
let (active_conns, wireless_access_points) = futures::join!(
// Retrieve active connections.
async move {
let mut active_conns = active_connections(active_conns.unwrap_or_default())
.await
.unwrap_or_default();
active_conns.sort_by(|a, b| {
let helper = |conn: &ActiveConnectionInfo| match conn {
ActiveConnectionInfo::Vpn { name, .. } => format!("0{name}"),
ActiveConnectionInfo::Wired { name, .. } => format!("1{name}"),
ActiveConnectionInfo::WiFi { name, .. } => format!("2{name}"),
};
helper(a).cmp(&helper(b))
});
active_conns
},
// Retrieve all access points, and sort by strength.
async move {
let mut wireless_access_points = futures::stream::FuturesUnordered::from_iter(
devices.iter().map(|device| async move {
if let Ok(Some(SpecificDevice::Wireless(wireless_device))) =
device.downcast_to_device().await
{
handle_wireless_device(wireless_device, device.hw_address().await.ok())
.await
.unwrap_or_default()
} else {
Vec::new()
}
}),
)
.fold(
Vec::with_capacity(devices.len()),
|mut access_points, mut f| async move {
access_points.append(&mut f);
access_points
},
)
.await;
wireless_access_points.sort_by(|a, b| b.strength.cmp(&a.strength));
wireless_access_points
}
);
// Concurrently get
let known_ssid: Vec<Arc<str>> = futures::stream::FuturesOrdered::from_iter(
known_conns.into_iter().map(|c| async move {
let s = c.get_settings().await.ok()?;
let s = Settings::new(s);
let curr_ssid = s
.wifi
.clone()
.and_then(|w| w.ssid)
.and_then(|ssid| String::from_utf8(ssid).ok())?;
Some(Arc::from(curr_ssid))
}),
)
.filter_map(|c| async move { c })
.collect()
.await;
self.known_access_points = wireless_access_points
.iter()
.filter(|a| {
known_ssid.contains(&a.ssid)
&& !active_conns.iter().any(|ac| &ac.name() == a.ssid.as_ref())
})
.cloned()
.collect();
self.wireless_access_points = wireless_access_points;
self.active_conns = active_conns;
self.connectivity = connectivity?;
Ok(())
}
#[allow(dead_code)]
pub fn clear(&mut self) {
self.active_conns = Vec::new();
self.known_access_points = Vec::new();
self.wireless_access_points = Vec::new();
}
async fn connect_wifi<'a>(
&self,
conn: &zbus::Connection,
ssid: &str,
identity: Option<&str>,
password: Option<&str>,
hw_address: HwAddress,
) -> Result<(), Error> {
let nm = NetworkManager::new(conn).await?;
for c in nm.active_connections().await.unwrap_or_default() {
if self
.wireless_access_points
.iter()
.any(|w| Ok(Some(w.ssid.as_ref())) == c.cached_id().as_ref().map(|v| v.as_deref()))
{
_ = nm.deactivate_connection(&c).await;
break;
}
}
let Some(ap) = self
.wireless_access_points
.iter()
.find(|ap| ap.ssid.as_ref() == ssid && ap.hw_address == hw_address)
else {
return Err(Error::AccessPointNotFound);
};
let mut conn_settings: HashMap<&str, HashMap<&str, zvariant::Value>> = HashMap::from([
(
"802-11-wireless",
HashMap::from([("ssid", Value::Array(ssid.as_bytes().into()))]),
),
(
"connection",
HashMap::from([
("id", Value::Str(ssid.into())),
("type", Value::Str("802-11-wireless".into())),
]),
),
]);
if let Some(identity) = identity {
conn_settings.insert(
"802-1x",
HashMap::from([
("identity", Value::Str(identity.into())),
// most common default
("eap", Value::Array(vec!["peap"].into())),
// most common default
("phase2-auth", Value::Str("mschapv2".into())),
("password", Value::Str(password.unwrap_or("").into())),
]),
);
let wireless = conn_settings.get_mut("802-11-wireless").unwrap();
wireless.insert("security", Value::Str("802-11-wireless-security".into()));
wireless.insert("mode", Value::Str("infrastructure".into()));
conn_settings.insert(
"802-11-wireless-security",
HashMap::from([("key-mgmt", Value::Str("wpa-eap".into()))]),
);
} else if let Some(pass) = password {
conn_settings.insert(
"802-11-wireless-security",
HashMap::from([
("psk", Value::Str(pass.into())),
("key-mgmt", Value::Str("wpa-psk".into())),
]),
);
}
let devices = nm.devices().await?;
for device in devices {
if !matches!(
device.device_type().await.unwrap_or(DeviceType::Other),
DeviceType::Wifi
) {
continue;
}
let s = NetworkManagerSettings::new(conn).await?;
let known_conns = s.list_connections().await.unwrap_or_default();
let mut known_conn = None;
for c in known_conns {
let settings = c.get_settings().await.ok().unwrap_or_default();
let s = Settings::new(settings);
if let Some(cur_ssid) = s
.wifi
.clone()
.and_then(|w| w.ssid)
.and_then(|ssid| String::from_utf8(ssid).ok())
{
if cur_ssid == ssid {
known_conn = Some(c);
break;
}
}
}
let active_conn = if let Some(known_conn) = known_conn.as_ref() {
// update settings if needed
if password.is_some() {
known_conn.update(conn_settings).await?;
}
nm.activate_connection(known_conn, &device).await?
} else {
let (_, active_conn) = nm
.add_and_activate_connection(conn_settings, device.inner().path(), &ap.path)
.await?;
let dummy = ActiveConnectionProxy::new(&conn, active_conn).await?;
let active = ActiveConnectionProxy::builder(&conn)
.destination(dummy.inner().destination().to_owned())
.unwrap()
.interface(dummy.inner().interface().to_owned())
.unwrap()
.path(dummy.inner().path().to_owned())
.unwrap()
.build()
.await
.unwrap();
ActiveConnection::from(active)
};
let mut changes = active_conn.receive_state_changed().await;
_ = tokio::time::sleep(tokio::time::Duration::from_millis(500)).await;
let mut count = 5;
loop {
let state = active_conn.state().await;
if let Ok(enums::ActiveConnectionState::Activated) = state {
return Ok(());
} else if let Ok(enums::ActiveConnectionState::Deactivated) = state {
return Err(Error::ConnectionActivate);
}
match tokio::time::timeout(Duration::from_secs(20), changes.next()).await {
Ok(Some(s)) => {
let state = s.get().await.unwrap_or_default().into();
if matches!(state, enums::ActiveConnectionState::Activated) {
return Ok(());
}
}
_ => {}
};
count -= 1;
if count <= 0 {
return Err(Error::ConnectionActivate);
}
}
}
Err(Error::NoWiFiDevices)
}
}

View file

@ -0,0 +1,63 @@
// Copyright 2024 System76 <info@system76.com>
// SPDX-License-Identifier: MPL-2.0
use super::Event;
use cosmic_dbus_networkmanager::nm::NetworkManager;
use futures::{SinkExt, StreamExt};
use iced_futures::{Subscription, stream};
use std::{fmt::Debug, hash::Hash};
use zbus::Connection;
#[derive(Debug, Clone)]
pub enum State {
Continue(Connection),
Error,
}
pub fn wireless_enabled_subscription<I: 'static + Hash + Copy + Send + Sync + Debug>(
id: I,
conn: Connection,
) -> iced_futures::Subscription<Event> {
Subscription::run_with_id(
id,
stream::channel(50, move |output| async move {
watch(conn, output).await;
futures::future::pending().await
}),
)
}
pub async fn watch(conn: zbus::Connection, mut output: futures::channel::mpsc::Sender<Event>) {
let mut state = State::Continue(conn);
loop {
state = start_listening(state, &mut output).await;
}
}
async fn start_listening(
state: State,
output: &mut futures::channel::mpsc::Sender<Event>,
) -> State {
let conn = match state {
State::Continue(conn) => conn,
State::Error => futures::future::pending().await,
};
let network_manager = match NetworkManager::new(&conn).await {
Ok(n) => n,
Err(why) => {
tracing::error!(why = why.to_string(), "Failed to connect to NetworkManager");
return State::Error;
}
};
let mut wireless_enabled_changed = network_manager.receive_wireless_enabled_changed().await;
while let Some(change) = wireless_enabled_changed.next().await {
if let Ok(enable) = change.get().await {
_ = output.send(Event::WiFiEnabled(enable)).await;
}
}
State::Continue(conn)
}