chore: clippy

This commit is contained in:
Vukašin Vojinović 2026-02-19 18:33:47 +01:00 committed by Michael Murphy
parent 6e022755f1
commit 787c5ed49f
14 changed files with 218 additions and 243 deletions

View file

@ -41,14 +41,14 @@ pub fn import_theme(path: &Path) -> color_eyre::Result<()> {
let mut manager = Manager::default(); let mut manager = Manager::default();
if manager.mode().is_dark != is_dark { if manager.mode().is_dark != is_dark
if let Err(err) = manager.dark_mode(is_dark) { && let Err(err) = manager.dark_mode(is_dark)
return Err(color_eyre::eyre::eyre!( {
"Failed to set {} mode: {:?}", return Err(color_eyre::eyre::eyre!(
mode_str, "Failed to set {} mode: {:?}",
err mode_str,
)); err
} ));
} }
manager manager

View file

@ -536,7 +536,7 @@ impl Page {
Message::Daytime(day_time) => { Message::Daytime(day_time) => {
self.day_time = day_time; self.day_time = day_time;
return Task::none(); return Task::none();
}, }
Message::ThemeModeUpdate(mode) => { Message::ThemeModeUpdate(mode) => {
let was_dark = self.theme_manager.mode().is_dark; let was_dark = self.theme_manager.mode().is_dark;

View file

@ -189,7 +189,7 @@ impl Page {
} }
Message::ReplaceApply => { Message::ReplaceApply => {
if let Some((mut binding, ..)) = self.replace_dialog.pop() { if let Some((binding, ..)) = self.replace_dialog.pop() {
self.add_shortcut(binding, true); self.add_shortcut(binding, true);
if self.replace_dialog.is_empty() { if self.replace_dialog.is_empty() {

View file

@ -846,7 +846,7 @@ impl Page {
) )
.collect() .collect()
.then(|id| { .then(|id| {
if id.get(0).is_some_and(|id| *id == SECURE_INPUT_VPN.clone()) { if id.first().is_some_and(|id| *id == SECURE_INPUT_VPN.clone()) {
Task::none() Task::none()
} else { } else {
focus(SECURE_INPUT_VPN.clone()) focus(SECURE_INPUT_VPN.clone())

View file

@ -371,7 +371,7 @@ impl Page {
ssid, ssid,
network_type, network_type,
_tx, _tx,
interface, _interface,
) => { ) => {
if success || matches!(network_type, NetworkType::Open) { if success || matches!(network_type, NetworkType::Open) {
self.connecting.remove(ssid.as_ref()); self.connecting.remove(ssid.as_ref());
@ -747,7 +747,10 @@ impl Page {
) )
.collect() .collect()
.then(|id| { .then(|id| {
if id.get(0).is_some_and(|id| *id == SECURE_INPUT_WIFI.clone()) { if id
.first()
.is_some_and(|id| *id == SECURE_INPUT_WIFI.clone())
{
Task::none() Task::none()
} else { } else {
focus(SECURE_INPUT_WIFI.clone()) focus(SECURE_INPUT_WIFI.clone())

View file

@ -34,7 +34,7 @@ use pipewire::{
proxy::{ProxyListener, ProxyT}, proxy::{ProxyListener, ProxyT},
types::ObjectType, types::ObjectType,
}; };
use std::{cell::RefCell, rc::Rc, u32}; use std::{cell::RefCell, rc::Rc};
pub type NodeId = u32; pub type NodeId = u32;
pub type RouteId = u32; pub type RouteId = u32;
@ -181,10 +181,10 @@ fn run_service(
return; return;
} }
if let Some(device) = Device::from_device(info) { if let Some(device) = Device::from_device(info)
if let Some(state) = state.upgrade() { && let Some(state) = state.upgrade()
state.borrow_mut().add_device(pw_id, device); {
} state.borrow_mut().add_device(pw_id, device);
} }
} }
}) })
@ -281,10 +281,10 @@ fn run_service(
.info({ .info({
let state = Rc::downgrade(&state); let state = Rc::downgrade(&state);
move |info| { move |info| {
if let Some(node) = Node::from_node(info) { if let Some(node) = Node::from_node(info)
if let Some(state) = state.upgrade() { && let Some(state) = state.upgrade()
state.borrow_mut().add_node(id, node); {
} state.borrow_mut().add_node(id, node);
} }
} }
}) })
@ -357,24 +357,18 @@ fn run_service(
"default.audio.sink" => { "default.audio.sink" => {
if let Ok(value) = if let Ok(value) =
serde_json::de::from_str::<DefaultAudio>(value) serde_json::de::from_str::<DefaultAudio>(value)
&& let Some(state) = state.upgrade()
{ {
if let Some(state) = state.upgrade() { state.borrow_mut().default_sink(value.name.to_owned())
state
.borrow_mut()
.default_sink(value.name.to_owned())
}
} }
} }
"default.audio.source" => { "default.audio.source" => {
if let Ok(value) = if let Ok(value) =
serde_json::de::from_str::<DefaultAudio>(value) serde_json::de::from_str::<DefaultAudio>(value)
&& let Some(state) = state.upgrade()
{ {
if let Some(state) = state.upgrade() { state.borrow_mut().default_source(value.name.to_owned())
state
.borrow_mut()
.default_source(value.name.to_owned())
}
} }
} }
@ -530,7 +524,7 @@ impl State {
if routes.len() < index as usize + 1 { if routes.len() < index as usize + 1 {
let additional = (index as usize + 1) - routes.capacity(); let additional = (index as usize + 1) - routes.capacity();
routes.reserve_exact(additional); routes.reserve_exact(additional);
routes.extend(std::iter::repeat(Route::default()).take(additional)); routes.extend(std::iter::repeat_n(Route::default(), additional));
} }
routes[index as usize] = route.clone(); routes[index as usize] = route.clone();
@ -586,7 +580,7 @@ impl State {
if routes.len() < index as usize + 1 { if routes.len() < index as usize + 1 {
let additional = (index as usize + 1) - routes.capacity(); let additional = (index as usize + 1) - routes.capacity();
routes.reserve_exact(additional); routes.reserve_exact(additional);
routes.extend(std::iter::repeat(Route::default()).take(additional)); routes.extend(std::iter::repeat_n(Route::default(), additional));
} }
routes[index as usize] = route.clone(); routes[index as usize] = route.clone();
@ -769,7 +763,6 @@ impl State {
if let Some(param) = Pod::from_bytes(&serialized) { if let Some(param) = Pod::from_bytes(&serialized) {
device.set_param(ParamType::Route, 0, param); device.set_param(ParamType::Route, 0, param);
} }
return;
} }
fn set_node_props(&mut self, id: NodeId, props: NodeProps) { fn set_node_props(&mut self, id: NodeId, props: NodeProps) {
@ -817,7 +810,7 @@ impl State {
FormatProperties(libspa_sys::SPA_PROP_channelVolumes), FormatProperties(libspa_sys::SPA_PROP_channelVolumes),
ValueArray, ValueArray,
pod::ValueArray::Float(volume::to_channel_volumes( pod::ValueArray::Float(volume::to_channel_volumes(
&props.channel_map.as_deref().unwrap_or_default(), props.channel_map.as_deref().unwrap_or_default(),
volume, volume,
balance, balance,
)) ))
@ -887,7 +880,7 @@ impl State {
ValueArray, ValueArray,
pod::ValueArray::Float(if matches!(route.direction, Direction::Output) { pod::ValueArray::Float(if matches!(route.direction, Direction::Output) {
volume::to_channel_volumes( volume::to_channel_volumes(
&props.channel_map.as_deref().unwrap_or_default(), props.channel_map.as_deref().unwrap_or_default(),
volume, volume,
balance, balance,
) )

View file

@ -14,10 +14,8 @@ pub fn string_from_pod(pod: &Pod) -> Option<String> {
unsafe { unsafe {
// SAFETY: Pod is checked to be a string beforehand // SAFETY: Pod is checked to be a string beforehand
if libspa_sys::spa_pod_get_string(pod.as_raw_ptr(), &mut cstr) == 0 { if libspa_sys::spa_pod_get_string(pod.as_raw_ptr(), &mut cstr) == 0 && !cstr.is_null() {
if !cstr.is_null() { return Some(String::from_utf8_lossy(CStr::from_ptr(cstr).to_bytes()).into_owned());
return Some(String::from_utf8_lossy(CStr::from_ptr(cstr).to_bytes()).into_owned());
}
} }
} }

View file

@ -210,29 +210,29 @@ fn load_thumbnail(
cache_dir: Option<&Path>, cache_dir: Option<&Path>,
path: &Path, path: &Path,
) -> Option<ImageOperation> { ) -> Option<ImageOperation> {
if let Some(cache_dir) = cache_dir { if let Some(cache_dir) = cache_dir
if let Ok(ctime) = path.metadata().and_then(|meta| meta.created()) { && let Ok(ctime) = path.metadata().and_then(|meta| meta.created())
// Search for thumbnail by a unique hash string. {
let mut hasher = DefaultHasher::new(); // Search for thumbnail by a unique hash string.
path.hash(&mut hasher); let mut hasher = DefaultHasher::new();
ctime.hash(&mut hasher); path.hash(&mut hasher);
let hash = hasher.finish(); ctime.hash(&mut hasher);
let hash = hasher.finish();
let thumbnail_path = cache_dir.join(format!("{hash:x}.png")); let thumbnail_path = cache_dir.join(format!("{hash:x}.png"));
if thumbnail_path.exists() { if thumbnail_path.exists() {
if let Some(image) = open_image(input_buffer, &thumbnail_path) { if let Some(image) = open_image(input_buffer, &thumbnail_path) {
return Some(ImageOperation::Cached(image)); return Some(ImageOperation::Cached(image));
}
let _res = std::fs::remove_file(&thumbnail_path);
} }
return Some(ImageOperation::GenerateThumbnail { let _res = std::fs::remove_file(&thumbnail_path);
path: Some(thumbnail_path),
image: open_image(input_buffer, path)?,
});
} }
return Some(ImageOperation::GenerateThumbnail {
path: Some(thumbnail_path),
image: open_image(input_buffer, path)?,
});
} }
if let Some(image) = open_image(input_buffer, path) { if let Some(image) = open_image(input_buffer, path) {
@ -396,7 +396,7 @@ fn border_radius(
p += (2 * x + 2) as i32; p += (2 * x + 2) as i32;
} else { } else {
// draw when moving to next pixel in y-direction // draw when moving to next pixel in y-direction
if y % 16 == 0 { if y.is_multiple_of(16) {
draw(img, alpha, x / 16, y / 16); draw(img, alpha, x / 16, y / 16);
draw(img, alpha, y / 16, x / 16); draw(img, alpha, y / 16, x / 16);
skip_draw = true; skip_draw = true;

View file

@ -57,10 +57,10 @@ impl State {
}; };
let (tx, rx) = tokio::sync::mpsc::unbounded_channel(); let (tx, rx) = tokio::sync::mpsc::unbounded_channel();
let mut enabled = false; let mut enabled = false;
if let Ok(proxy) = StatusProxy::new(&conn).await { if let Ok(proxy) = StatusProxy::new(&conn).await
if let Ok(status) = proxy.screen_reader_enabled().await { && let Ok(status) = proxy.screen_reader_enabled().await
enabled = status; {
} enabled = status;
} }
_ = output.send(Response::Init(enabled, tx)).await; _ = output.send(Response::Init(enabled, tx)).await;
Some(State { Some(State {

View file

@ -21,11 +21,11 @@ pub async fn handle_wireless_device(
let mut scan_changed = device.receive_last_scan_changed().await; let mut scan_changed = device.receive_last_scan_changed().await;
if let Some(t) = scan_changed.next().await { if let Some(t) = scan_changed.next().await
if let Ok(-1) = t.get().await { && let Ok(-1) = t.get().await
tracing::error!("wireless device scan errored"); {
return Ok(Default::default()); tracing::error!("wireless device scan errored");
} return Ok(Default::default());
} }
let access_points = device.get_access_points().await?; let access_points = device.get_access_points().await?;
@ -45,10 +45,10 @@ pub async fn handle_wireless_device(
if let Some((ssid, strength)) = ssid_res.ok().zip(strength_res.ok()) { if let Some((ssid, strength)) = ssid_res.ok().zip(strength_res.ok()) {
let ssid = String::from_utf8_lossy(&ssid.clone()).into_owned(); let ssid = String::from_utf8_lossy(&ssid.clone()).into_owned();
if let Some(access_point) = aps.get(&ssid) { if let Some(access_point) = aps.get(&ssid)
if access_point.strength > strength { && access_point.strength > strength
continue; {
} continue;
} }
let Ok(flags) = ap.rsn_flags().await else { let Ok(flags) = ap.rsn_flags().await else {
@ -56,7 +56,8 @@ pub async fn handle_wireless_device(
}; };
let network_type = if flags.intersects(ApSecurityFlags::KEY_MGMT_802_1X) { let network_type = if flags.intersects(ApSecurityFlags::KEY_MGMT_802_1X) {
NetworkType::EAP NetworkType::EAP
} else if flags.intersects(ApSecurityFlags::KEY_MGMTPSK | ApSecurityFlags::KEY_MGMT_SAE) { } else if flags.intersects(ApSecurityFlags::KEY_MGMTPSK | ApSecurityFlags::KEY_MGMT_SAE)
{
NetworkType::PskOrSae NetworkType::PskOrSae
} else if flags.intersects(ApSecurityFlags::KEY_MGMT_OWE) || flags.is_empty() { } else if flags.intersects(ApSecurityFlags::KEY_MGMT_OWE) || flags.is_empty() {
NetworkType::Open NetworkType::Open

View file

@ -18,8 +18,8 @@ impl HwAddress {
.ok() .ok()
.map(|address| HwAddress { address }) .map(|address| HwAddress { address })
} }
pub fn from_string(arg: &String) -> Option<Self> { pub fn from_string(arg: &str) -> Option<Self> {
HwAddress::from_str(arg.as_str()) HwAddress::from_str(arg)
} }
} }

View file

@ -16,7 +16,6 @@ pub use cosmic_dbus_networkmanager as dbus;
pub use dbus::settings::connection::Settings; pub use dbus::settings::connection::Settings;
use cosmic_dbus_networkmanager::{ use cosmic_dbus_networkmanager::{
active_connection::ActiveConnection,
device::SpecificDevice, device::SpecificDevice,
interface::{ interface::{
enums::{self, ActiveConnectionState, DeviceType, NmConnectivityState}, enums::{self, ActiveConnectionState, DeviceType, NmConnectivityState},
@ -185,12 +184,11 @@ async fn start_listening(
let mut changed = c.receive_state_changed().await; let mut changed = c.receive_state_changed().await;
_ = tokio::time::timeout(Duration::from_secs(5), async move { _ = tokio::time::timeout(Duration::from_secs(5), async move {
loop { loop {
if let Some(next) = changed.next().await { if let Some(next) = changed.next().await
if let Ok(ActiveConnectionState::Deactivated) = && let Ok(ActiveConnectionState::Deactivated) =
next.get().await.map(ActiveConnectionState::from) next.get().await.map(ActiveConnectionState::from)
{ {
break; break;
}
} }
} }
}) })
@ -222,12 +220,11 @@ async fn start_listening(
let mut changed = c.receive_state_changed().await; let mut changed = c.receive_state_changed().await;
_ = tokio::time::timeout(Duration::from_secs(5), async move { _ = tokio::time::timeout(Duration::from_secs(5), async move {
loop { loop {
if let Some(next) = changed.next().await { if let Some(next) = changed.next().await
if let Ok(ActiveConnectionState::Deactivated) = && let Ok(ActiveConnectionState::Deactivated) =
next.get().await.map(ActiveConnectionState::from) next.get().await.map(ActiveConnectionState::from)
{ {
break; break;
}
} }
} }
}) })
@ -528,7 +525,8 @@ async fn start_listening(
}) })
.await; .await;
} }
}); })
.await;
} else { } else {
let known_conns = s.list_connections().await.unwrap_or_default(); let known_conns = s.list_connections().await.unwrap_or_default();
for c in known_conns { for c in known_conns {
@ -540,42 +538,41 @@ async fn start_listening(
.clone() .clone()
.and_then(|w| w.ssid) .and_then(|w| w.ssid)
.and_then(|s| String::from_utf8(s).ok()) .and_then(|s| String::from_utf8(s).ok())
&& saved_ssid == ssid.as_ref()
{ {
if saved_ssid == ssid.as_ref() { let password = c
let password = .get_secrets("802-11-wireless-security")
c.get_secrets("802-11-wireless-security") .await
.await .ok()
.ok() .and_then(|secrets| {
.and_then(|secrets| { // Look for PSK password
// Look for PSK password
secrets
.get("802-11-wireless-security")
.and_then(|sec| sec.get("psk"))
.and_then(|v| {
v.downcast_ref::<zbus::zvariant::Str>().ok()
})
.map(|s| s.to_string())
.or_else(|| {
// Fallback to WEP key
secrets secrets
.get("802-11-wireless-security") .get("802-11-wireless-security")
.and_then(|sec| sec.get("psk"))
.and_then(|v| {
v.downcast_ref::<zbus::zvariant::Str>().ok()
})
.map(|s| s.to_string())
.or_else(|| {
// Fallback to WEP key
secrets
.get("802-11-wireless-security")
.and_then(|sec| sec.get("wep-key0")) .and_then(|sec| sec.get("wep-key0"))
.and_then(|v| { .and_then(|v| {
v.downcast_ref::<zbus::zvariant::Str>().ok() v.downcast_ref::<zbus::zvariant::Str>().ok()
}) })
.map(|s| s.to_string()) .map(|s| s.to_string())
}) })
}); });
_ = output _ = output
.send(Event::WiFiCredentials { .send(Event::WiFiCredentials {
ssid: ssid.clone(), ssid: ssid.clone(),
password: password.map(SecureString::from), password: password.map(SecureString::from),
security_type, security_type,
}) })
.await; .await;
break; break;
}
} }
} }
} }
@ -616,10 +613,9 @@ async fn has_saved_wifi_credentials(conn: &zbus::Connection, ssid: &str) -> bool
.wifi .wifi
.and_then(|w| w.ssid) .and_then(|w| w.ssid)
.and_then(|ssid| String::from_utf8(ssid).ok()) .and_then(|ssid| String::from_utf8(ssid).ok())
&& saved_ssid == ssid
{ {
if saved_ssid == ssid { return true;
return true;
}
} }
} }
} }
@ -983,11 +979,10 @@ impl NetworkManagerState {
.clone() .clone()
.and_then(|w| w.ssid) .and_then(|w| w.ssid)
.and_then(|ssid| String::from_utf8(ssid).ok()) .and_then(|ssid| String::from_utf8(ssid).ok())
&& cur_ssid == ssid
{ {
if cur_ssid == ssid { known_conn = Some(c);
known_conn = Some(c); break;
break;
}
} }
} }
@ -1014,9 +1009,9 @@ impl NetworkManagerState {
.ok_or_else(|| Error::MissingField("uuid"))? .ok_or_else(|| Error::MissingField("uuid"))?
.clone(), .clone(),
) )
.map_err(|err| zbus::Error::Variant(err))?; .map_err(zbus::Error::Variant)?;
if let Some((pass, secret_tx)) = password.clone().zip(secret_tx.as_ref()) { if let Some((pass, secret_tx)) = password.zip(secret_tx.as_ref()) {
let pass = SecureString::from(pass); let pass = SecureString::from(pass);
let (applied_tx, applied_rx) = tokio::sync::oneshot::channel(); let (applied_tx, applied_rx) = tokio::sync::oneshot::channel();
@ -1056,7 +1051,7 @@ impl NetworkManagerState {
.ok_or_else(|| Error::MissingField("uuid"))? .ok_or_else(|| Error::MissingField("uuid"))?
.clone(), .clone(),
) )
.map_err(|err| zbus::Error::Variant(err))?; .map_err(zbus::Error::Variant)?;
let (applied_tx, applied_rx) = tokio::sync::oneshot::channel(); let (applied_tx, applied_rx) = tokio::sync::oneshot::channel();
let setting_name: String = if identity.is_some() { let setting_name: String = if identity.is_some() {
"802-1x".into() "802-1x".into()
@ -1081,8 +1076,7 @@ impl NetworkManagerState {
} }
} }
let active_conn = let active_conn = nm.activate_connection(&known_conn, &device).await?;
ActiveConnection::from(nm.activate_connection(&known_conn, &device).await?);
let mut changes = active_conn.receive_state_changed().await; let mut changes = active_conn.receive_state_changed().await;
_ = tokio::time::sleep(tokio::time::Duration::from_millis(500)).await; _ = tokio::time::sleep(tokio::time::Duration::from_millis(500)).await;
let mut count = 5; let mut count = 5;
@ -1120,7 +1114,7 @@ impl NetworkManagerState {
.ok_or_else(|| Error::MissingField("uuid"))? .ok_or_else(|| Error::MissingField("uuid"))?
.clone(), .clone(),
) )
.map_err(|err| zbus::Error::Variant(err))?; .map_err(zbus::Error::Variant)?;
let (applied_tx, applied_rx) = tokio::sync::oneshot::channel(); let (applied_tx, applied_rx) = tokio::sync::oneshot::channel();
let setting_name: String = if identity.is_some() { let setting_name: String = if identity.is_some() {
"802-1x".into() "802-1x".into()

View file

@ -16,7 +16,7 @@ use zbus::{
pub type SecretSender = Arc<tokio::sync::Mutex<Option<tokio::sync::oneshot::Sender<SecureString>>>>; pub type SecretSender = Arc<tokio::sync::Mutex<Option<tokio::sync::oneshot::Sender<SecureString>>>>;
pub const SECRET_ID: &'static str = "com.system76.CosmicSettings.NetworkManager"; pub const SECRET_ID: &str = "com.system76.CosmicSettings.NetworkManager";
pub const DBUS_PATH: &str = "/org/freedesktop/NetworkManager/SecretAgent"; pub const DBUS_PATH: &str = "/org/freedesktop/NetworkManager/SecretAgent";
bitflags! { bitflags! {
@ -151,10 +151,10 @@ async fn secret_agent_stream_impl(
{ {
let ss = secret_service::SecretService::connect(secret_service::EncryptionType::Dh) let ss = secret_service::SecretService::connect(secret_service::EncryptionType::Dh)
.await .await
.map_err(|e| Arc::new(e))?; .map_err(Arc::new)?;
let collection = ss.get_default_collection().await.map_err(|e| Arc::new(e))?; let collection = ss.get_default_collection().await.map_err(Arc::new)?;
if collection.is_locked().await.map_err(|e| Arc::new(e))? { if collection.is_locked().await.map_err(Arc::new)? {
_ = collection.unlock().await.map_err(|e| Arc::new(e))?; collection.unlock().await.map_err(Arc::new)?;
} }
} }
// register the secret agent with NetworkManager // register the secret agent with NetworkManager
@ -183,8 +183,8 @@ async fn secret_agent_stream_impl(
} => { } => {
let ss = secret_service::SecretService::connect(secret_service::EncryptionType::Dh) let ss = secret_service::SecretService::connect(secret_service::EncryptionType::Dh)
.await .await
.map_err(|e| Arc::new(e))?; .map_err(Arc::new)?;
let collection = ss.get_default_collection().await.map_err(|e| Arc::new(e))?; let collection = ss.get_default_collection().await.map_err(Arc::new)?;
if secrets.is_empty() { if secrets.is_empty() {
let mut attributes = std::collections::HashMap::new(); let mut attributes = std::collections::HashMap::new();
@ -193,10 +193,10 @@ async fn secret_agent_stream_impl(
let search_items = collection let search_items = collection
.search_items(attributes) .search_items(attributes)
.await .await
.map_err(|e| Arc::new(e))?; .map_err(Arc::new)?;
for item in &search_items { for item in &search_items {
item.delete().await.map_err(|e| Arc::new(e))?; item.delete().await.map_err(Arc::new)?;
} }
let _ = applied_tx.send(()); let _ = applied_tx.send(());
@ -218,7 +218,7 @@ async fn secret_agent_stream_impl(
"text/plain", "text/plain",
) )
.await .await
.map_err(|e| Arc::new(e))?; .map_err(Arc::new)?;
} }
let _ = applied_tx.send(()); let _ = applied_tx.send(());
} }
@ -229,8 +229,8 @@ async fn secret_agent_stream_impl(
} => { } => {
let ss = secret_service::SecretService::connect(secret_service::EncryptionType::Dh) let ss = secret_service::SecretService::connect(secret_service::EncryptionType::Dh)
.await .await
.map_err(|e| Arc::new(e))?; .map_err(Arc::new)?;
let collection = ss.get_default_collection().await.map_err(|e| Arc::new(e))?; let collection = ss.get_default_collection().await.map_err(Arc::new)?;
let mut attributes = std::collections::HashMap::new(); let mut attributes = std::collections::HashMap::new();
attributes.insert("application", SECRET_ID); attributes.insert("application", SECRET_ID);
@ -240,19 +240,19 @@ async fn secret_agent_stream_impl(
let search_items = collection let search_items = collection
.search_items(attributes) .search_items(attributes)
.await .await
.map_err(|e| Arc::new(e))?; .map_err(Arc::new)?;
let mut secrets = HashMap::new(); let mut secrets = HashMap::new();
for item in &search_items { for item in &search_items {
let name = item let name = item
.get_attributes() .get_attributes()
.await .await
.map_err(|e| Arc::new(e))? .map_err(Arc::new)?
.get("name") .get("name")
.cloned() .cloned()
.unwrap_or_else(|| "unknown".to_string()); .unwrap_or_else(|| "unknown".to_string());
let secret = item.get_secret().await.map_err(|e| Arc::new(e))?; let secret = item.get_secret().await.map_err(Arc::new)?;
let secret: String = String::from_utf8(secret)?.into(); let secret: String = String::from_utf8(secret)?;
secrets.insert(name, SecureString::from(secret)); secrets.insert(name, SecureString::from(secret));
} }
let _ = resp_tx.send(secrets); let _ = resp_tx.send(secrets);
@ -382,7 +382,7 @@ impl SettingsSecretAgent {
let conn = ConnectionSettingsProxy::builder( let conn = ConnectionSettingsProxy::builder(
&zbus::Connection::system() &zbus::Connection::system()
.await .await
.or_else(|_| Err(fdo::Error::Failed("failed to get uuid".to_string())))?, .map_err(|_| fdo::Error::Failed("failed to get uuid".to_string()))?,
) )
.path(connection_path)? .path(connection_path)?
.build() .build()
@ -437,13 +437,9 @@ impl SettingsSecretAgent {
hints: Vec<String>, hints: Vec<String>,
flags: u32, flags: u32,
) -> HashMap<String, HashMap<String, zbus::zvariant::OwnedValue>> { ) -> HashMap<String, HashMap<String, zbus::zvariant::OwnedValue>> {
match self self.get_secrets_inner(connection, connection_path, setting_name, hints, flags)
.get_secrets_inner(connection, connection_path, setting_name, hints, flags)
.await .await
{ .unwrap_or_default()
Ok(result) => result,
Err(_) => HashMap::new(),
}
} }
/// SaveSecrets method /// SaveSecrets method
@ -472,9 +468,9 @@ impl SettingsSecretAgent {
let ss = secret_service::SecretService::connect(secret_service::EncryptionType::Dh) let ss = secret_service::SecretService::connect(secret_service::EncryptionType::Dh)
.await .await
.map_err(|e| Arc::new(e))?; .map_err(Arc::new)?;
let collection = ss.get_default_collection().await.map_err(|e| Arc::new(e))?; let collection = ss.get_default_collection().await.map_err(Arc::new)?;
let conn_uuid = connection let conn_uuid = connection
.get("connection") .get("connection")
@ -484,10 +480,8 @@ impl SettingsSecretAgent {
.to_string(); .to_string();
let conn = let conn =
ConnectionSettingsProxy::builder(&zbus::Connection::system().await.or_else(|_| { ConnectionSettingsProxy::builder(&zbus::Connection::system().await.map_err(|_| {
Err(Error::Zbus( Error::Zbus(fdo::Error::Failed("failed to get uuid".to_string()).into())
fdo::Error::Failed("failed to get uuid".to_string()).into(),
))
})?) })?)
.path(connection_path)? .path(connection_path)?
.build() .build()
@ -498,7 +492,7 @@ impl SettingsSecretAgent {
.get("connection") .get("connection")
.and_then(|m| m.get("type")) .and_then(|m| m.get("type"))
.and_then(|v| v.downcast_ref::<String>().ok()) .and_then(|v| v.downcast_ref::<String>().ok())
.map_or(false, |t| t == "vpn"); .is_some_and(|t| t == "vpn");
let is_always_ask = is_connection_always_ask(&settings); let is_always_ask = is_connection_always_ask(&settings);
let mut setting_attributes = std::collections::HashMap::new(); let mut setting_attributes = std::collections::HashMap::new();
@ -509,7 +503,7 @@ impl SettingsSecretAgent {
let search_items = collection let search_items = collection
.search_items(setting_attributes.clone()) .search_items(setting_attributes.clone())
.await .await
.map_err(|e| Arc::new(e))?; .map_err(Arc::new)?;
let mut result = HashMap::new(); let mut result = HashMap::new();
let mut setting = HashMap::new(); let mut setting = HashMap::new();
@ -518,16 +512,16 @@ impl SettingsSecretAgent {
let name = item let name = item
.get_attributes() .get_attributes()
.await .await
.map_err(|e| Arc::new(e))? .map_err(Arc::new)?
.get("name") .get("name")
.cloned() .cloned()
.unwrap_or_else(|| "unknown".to_string()); .unwrap_or_else(|| "unknown".to_string());
let secret = item.get_secret().await.map_err(|e| Arc::new(e))?; let secret = item.get_secret().await.map_err(Arc::new)?;
let secret: String = String::from_utf8(secret)?.into(); let secret: String = String::from_utf8(secret)?;
setting.insert(name, zbus::zvariant::OwnedValue::from(Str::from(secret))); setting.insert(name, zbus::zvariant::OwnedValue::from(Str::from(secret)));
} }
result.insert(setting_name, setting); result.insert(setting_name, setting);
return Ok(result); Ok(result)
} else { } else {
let hints = parse_hints(hints); let hints = parse_hints(hints);
let mut requested = HashSet::new(); let mut requested = HashSet::new();
@ -563,49 +557,47 @@ impl SettingsSecretAgent {
&& e.is_disconnected() && e.is_disconnected()
{ {
continue; continue;
} else { } else if let Ok(secret) = resp_rx.await {
if let Ok(secret) = resp_rx.await { let mut named_attribute = setting_attributes.clone();
let mut named_attribute = setting_attributes.clone(); named_attribute.insert("name", key);
named_attribute.insert("name", key); let _item = collection
let _item = collection .create_item(
.create_item( "NetworkManager Secret",
"NetworkManager Secret", named_attribute,
named_attribute, secret.unsecure().as_bytes(),
secret.unsecure().as_bytes(), true,
true, "text/plain",
"text/plain", )
) .await
.await .map_err(Arc::new)?;
.map_err(|e| Arc::new(e))?;
setting.insert( setting.insert(
key.clone(), key.clone(),
zbus::zvariant::OwnedValue::from(Str::from(secret.unsecure())), zbus::zvariant::OwnedValue::from(Str::from(secret.unsecure())),
); );
}
} }
} else if !is_always_ask { } else if !is_always_ask {
let mut pos = None; let mut pos = None;
let mut pos_with_message = None; let mut pos_with_message = None;
for item in &search_items { for item in &search_items {
let attributes = item.get_attributes().await.map_err(|e| Arc::new(e))?; let attributes = item.get_attributes().await.map_err(Arc::new)?;
if let Some(value) = attributes.get("name") { if let Some(value) = attributes.get("name")
if value == key { && value == key
if let Some(saved_message) = attributes.get("message") { {
if message.as_ref().is_some_and(|msg| msg == saved_message) { if let Some(saved_message) = attributes.get("message") {
pos_with_message = Some(item); if message.as_ref().is_some_and(|msg| msg == saved_message) {
} pos_with_message = Some(item);
break;
} else {
pos = Some(item);
} }
break;
} else {
pos = Some(item);
} }
} }
} }
if let Some(item) = pos_with_message.or(pos) { if let Some(item) = pos_with_message.or(pos) {
let secret = item.get_secret().await.map_err(|e| Arc::new(e))?; let secret = item.get_secret().await.map_err(Arc::new)?;
let secret: String = String::from_utf8(secret)?.into(); let secret: String = String::from_utf8(secret)?;
if is_vpn { if is_vpn {
// ask anyway, but offer the previous one as a hint // ask anyway, but offer the previous one as a hint
let (resp_tx, resp_rx) = oneshot::channel(); let (resp_tx, resp_rx) = oneshot::channel();
@ -628,28 +620,24 @@ impl SettingsSecretAgent {
&& e.is_disconnected() && e.is_disconnected()
{ {
continue; continue;
} else { } else if let Ok(secret) = resp_rx.await {
if let Ok(secret) = resp_rx.await { let mut named_attribute = setting_attributes.clone();
let mut named_attribute = setting_attributes.clone(); named_attribute.insert("name", key);
named_attribute.insert("name", key); let _item = collection
let _item = collection .create_item(
.create_item( "NetworkManager Secret",
"NetworkManager Secret", named_attribute,
named_attribute, secret.unsecure().as_bytes(),
secret.unsecure().as_bytes(), true,
true, "text/plain",
"text/plain", )
) .await
.await .map_err(Arc::new)?;
.map_err(|e| Arc::new(e))?;
setting.insert( setting.insert(
key.clone(), key.clone(),
zbus::zvariant::OwnedValue::from(Str::from( zbus::zvariant::OwnedValue::from(Str::from(secret.unsecure())),
secret.unsecure(), );
)),
);
}
} }
} else { } else {
setting.insert( setting.insert(
@ -664,7 +652,7 @@ impl SettingsSecretAgent {
} }
} }
result.insert(setting_name, setting); result.insert(setting_name, setting);
return Ok(result); Ok(result)
} }
} }
@ -675,8 +663,8 @@ impl SettingsSecretAgent {
) -> Result<(), Error> { ) -> Result<(), Error> {
let ss = secret_service::SecretService::connect(secret_service::EncryptionType::Dh) let ss = secret_service::SecretService::connect(secret_service::EncryptionType::Dh)
.await .await
.map_err(|e| Arc::new(e))?; .map_err(Arc::new)?;
let collection = ss.get_default_collection().await.map_err(|e| Arc::new(e))?; let collection = ss.get_default_collection().await.map_err(Arc::new)?;
let conn_uuid = connection let conn_uuid = connection
.get("connection") .get("connection")
@ -692,10 +680,10 @@ impl SettingsSecretAgent {
let search_items = collection let search_items = collection
.search_items(attributes) .search_items(attributes)
.await .await
.map_err(|e| Arc::new(e))?; .map_err(Arc::new)?;
for item in &search_items { for item in &search_items {
item.delete().await.map_err(|e| Arc::new(e))?; item.delete().await.map_err(Arc::new)?;
} }
Ok(()) Ok(())
} }
@ -706,8 +694,8 @@ impl SettingsSecretAgent {
) -> Result<(), Error> { ) -> Result<(), Error> {
let ss = secret_service::SecretService::connect(secret_service::EncryptionType::Dh) let ss = secret_service::SecretService::connect(secret_service::EncryptionType::Dh)
.await .await
.map_err(|e| Arc::new(e))?; .map_err(Arc::new)?;
let collection = ss.get_default_collection().await.map_err(|e| Arc::new(e))?; let collection = ss.get_default_collection().await.map_err(Arc::new)?;
let conn_uuid = connection let conn_uuid = connection
.get("connection") .get("connection")
.and_then(|m| m.get("uuid")) .and_then(|m| m.get("uuid"))
@ -741,7 +729,7 @@ impl SettingsSecretAgent {
"text/plain", "text/plain",
) )
.await .await
.map_err(|e| Arc::new(e))?; .map_err(Arc::new)?;
Ok(()) Ok(())
} else { } else {
Err(Error::NoPasswordForIdentifier("unknown".to_string())) Err(Error::NoPasswordForIdentifier("unknown".to_string()))

View file

@ -251,7 +251,7 @@ impl Model {
None None
} else { } else {
self.node_names.get(node_id).map(|name| name.clone()) self.node_names.get(node_id).cloned()
}; };
tokio::task::spawn(async move { tokio::task::spawn(async move {
@ -327,10 +327,8 @@ impl Model {
} }
None None
} else if let Some(name) = self.node_names.get(node_id) {
Some(name.clone())
} else { } else {
None self.node_names.get(node_id).cloned()
}; };
tokio::task::spawn(async move { tokio::task::spawn(async move {
@ -527,10 +525,10 @@ impl Model {
} }
pipewire::Event::AddProfile(id, index, profile) => { pipewire::Event::AddProfile(id, index, profile) => {
if let Some(p) = self.active_profiles.get_mut(id) { if let Some(p) = self.active_profiles.get_mut(id)
if p.index == profile.index { && p.index == profile.index
*p = profile.clone(); {
} *p = profile.clone();
} }
let profiles = self.device_profiles.entry(id).or_default(); let profiles = self.device_profiles.entry(id).or_default();
@ -716,12 +714,12 @@ impl Model {
if let Some(pos) = self.sink_node_ids.iter().position(|&node_id| node_id == id) { if let Some(pos) = self.sink_node_ids.iter().position(|&node_id| node_id == id) {
self.sink_node_ids.remove(pos); self.sink_node_ids.remove(pos);
self.sinks.remove(pos); self.sinks.remove(pos);
if let Some(node_id) = self.active_sink_node { if let Some(node_id) = self.active_sink_node
if id == node_id { && id == node_id
self.active_sink = None; {
self.active_sink_node = None; self.active_sink = None;
self.active_sink_node_name.clear(); self.active_sink_node = None;
} self.active_sink_node_name.clear();
} }
} else if let Some(pos) = self } else if let Some(pos) = self
.source_node_ids .source_node_ids
@ -730,12 +728,12 @@ impl Model {
{ {
self.source_node_ids.remove(pos); self.source_node_ids.remove(pos);
self.sources.remove(pos); self.sources.remove(pos);
if let Some(node_id) = self.active_source_node { if let Some(node_id) = self.active_source_node
if id == node_id { && id == node_id
self.active_source = None; {
self.active_source_node = None; self.active_source = None;
self.active_source_node_name.clear(); self.active_source_node = None;
} self.active_source_node_name.clear();
} }
} }