Explain runtime invariants and avoid redundant unwraps

This commit is contained in:
Samuel Onoja committed 2026-10-22 01:28:03 +01:00
1 parent 34f2f07301
commit 1b51ba83b4
116 files changed
+1643 -515

No files matched your search

+67 -14
View File
@@ -68,7 +68,10 @@ enum Error {
impl Pairing {
fn begin(&self, target: &str) -> Result<u64, String> {
let mut state = self.0.lock().unwrap();
let mut state = self
.0
.lock()
.expect("pairing agent state must remain consistent across callbacks");
if state.target.is_some() {
return Err("Another device is already pairing.".into());
}
@@ -78,7 +81,10 @@ impl Pairing {
}
fn finish(&self, generation: u64) {
let mut state = self.0.lock().unwrap();
let mut state = self
.0
.lock()
.expect("pairing agent state must remain consistent across callbacks");
if state.generation == generation {
state.target = None;
state.prompt = None;
@@ -87,7 +93,10 @@ impl Pairing {
}
pub fn cancel_local(&self) -> Option<String> {
let mut state = self.0.lock().unwrap();
let mut state = self
.0
.lock()
.expect("pairing agent state must remain consistent across callbacks");
state.generation = state.generation.wrapping_add(1);
state.prompt = None;
state.reply = None;
@@ -95,11 +104,18 @@ impl Pairing {
}
pub fn prompt(&self) -> Option<Prompt> {
self.0.lock().unwrap().prompt.clone()
self.0
.lock()
.expect("pairing agent state must remain consistent across callbacks")
.prompt
.clone()
}
pub fn reply(&self, id: u64, value: Option<Zeroizing<String>>) {
let mut state = self.0.lock().unwrap();
let mut state = self
.0
.lock()
.expect("pairing agent state must remain consistent across callbacks");
if state.prompt.as_ref().is_some_and(|p| p.id == id) {
if let Some(reply) = state.reply.take() {
let _ = reply.send(value);
@@ -126,7 +142,10 @@ impl Pairing {
sender: Option<&str>,
) -> Result<Zeroizing<String>, Error> {
let (id, rx) = {
let mut state = self.0.lock().unwrap();
let mut state = self
.0
.lock()
.expect("pairing agent state must remain consistent across callbacks");
Self::check(&state, device.as_str(), sender)?;
if state.reply.is_some() {
return Err(Error::Rejected(
@@ -159,7 +178,10 @@ impl Pairing {
text: String,
sender: Option<&str>,
) -> Result<(), Error> {
let mut state = self.0.lock().unwrap();
let mut state = self
.0
.lock()
.expect("pairing agent state must remain consistent across callbacks");
Self::check(&state, device.as_str(), sender)?;
state.serial = state.serial.wrapping_add(1);
state.prompt = Some(Prompt {
@@ -171,7 +193,10 @@ impl Pairing {
}
fn dismiss(&self, sender: Option<&str>) -> Result<(), Error> {
let mut state = self.0.lock().unwrap();
let mut state = self
.0
.lock()
.expect("pairing agent state must remain consistent across callbacks");
if sender.is_none() || state.owner.as_deref() != sender {
return Err(Error::Rejected("Unknown sender".into()));
}
@@ -289,7 +314,10 @@ impl Pairing {
fn release(&self, #[zbus(header)] header: Header<'_>) -> Result<(), Error> {
self.dismiss(header.sender().map(|s| s.as_str()))?;
self.cancel_local();
self.0.lock().unwrap().owner = None;
self.0
.lock()
.expect("pairing agent state must remain consistent across callbacks")
.owner = None;
Ok(())
}
}
@@ -308,17 +336,29 @@ impl Client {
.map_err(|e| e.to_string())?;
let mut registered = self.registered.lock().await;
if registered.as_ref() == Some(&owner)
&& self.agent.0.lock().unwrap().owner.as_ref() == Some(&owner)
&& self
.agent
.0
.lock()
.expect("pairing agent state must remain consistent across callbacks")
.owner
.as_ref()
== Some(&owner)
{
return Ok(());
}
self.agent.0.lock().unwrap().owner = Some(owner.clone());
self.agent
.0
.lock()
.expect("pairing agent state must remain consistent across callbacks")
.owner = Some(owner.clone());
self.connection
.object_server()
.at(PATH, self.agent.clone())
.await
.map_err(|e| e.to_string())?;
let path = OwnedObjectPath::try_from(PATH).unwrap();
let path = OwnedObjectPath::try_from(PATH)
.expect("the pairing agent has a valid static object path");
proxy(
&self.connection,
"org.bluez",
@@ -341,13 +381,26 @@ impl Client {
}
let result = async {
self.register_agent().await?;
if self.agent.0.lock().unwrap().generation != generation {
if self
.agent
.0
.lock()
.expect("pairing agent state must remain consistent across callbacks")
.generation
!= generation
{
return Err("Pairing canceled.".into());
}
bluetooth::device_call(&self.connection, path, "Pair").await
}
.await;
let still_active = self.agent.0.lock().unwrap().generation == generation;
let still_active = self
.agent
.0
.lock()
.expect("pairing agent state must remain consistent across callbacks")
.generation
== generation;
self.agent.finish(generation);
if !still_active {
return Err("Pairing canceled.".into());
@@ -170,7 +170,12 @@ impl Client {
pub(crate) async fn discover(&self, path: String, epoch: u64) -> Result<(), String> {
// BlueZ discovery is reference counted per D-Bus caller. Never stop
// discovery owned by another app, and never acquire a lease twice.
if self.discovery.lock().unwrap().contains_key(&path) {
if self
.discovery
.lock()
.expect("Bluetooth discovery ownership must remain consistent across callbacks")
.contains_key(&path)
{
return Ok(());
}
adapter_call(&self.connection, &path, "StartDiscovery").await?;
@@ -179,13 +184,18 @@ impl Client {
return Err("Discovery canceled.".into());
}
let lease = std::time::Instant::now();
self.discovery.lock().unwrap().insert(path.clone(), lease);
self.discovery
.lock()
.expect("Bluetooth discovery ownership must remain consistent across callbacks")
.insert(path.clone(), lease);
let leases = self.discovery.clone();
let connection = self.connection.clone();
tokio::spawn(async move {
tokio::time::sleep(Duration::from_secs(30)).await;
let owned = {
let mut leases = leases.lock().unwrap();
let mut leases = leases.lock().expect(
"Bluetooth discovery ownership must remain consistent across callbacks",
);
if leases.get(&path) == Some(&lease) {
leases.remove(&path);
true
@@ -201,7 +211,12 @@ impl Client {
}
pub(crate) async fn stop_discovery(&self) -> Result<(), String> {
let paths = std::mem::take(&mut *self.discovery.lock().unwrap());
let paths = std::mem::take(
&mut *self
.discovery
.lock()
.expect("Bluetooth discovery ownership must remain consistent across callbacks"),
);
let mut result = Ok(());
for (path, _) in paths {
if let Err(error) = adapter_call(&self.connection, &path, "StopDiscovery").await {
@@ -212,7 +227,10 @@ impl Client {
}
pub(crate) fn discovering(&self, path: &str) -> bool {
self.discovery.lock().unwrap().contains_key(path)
self.discovery
.lock()
.expect("Bluetooth discovery ownership must remain consistent across callbacks")
.contains_key(path)
}
}
@@ -19,7 +19,9 @@ impl App {
column([])
.spacing(8)
.push(self.label("Bluetooth unavailable", 14.))
.push(self.connection_note(result.as_ref().unwrap_err())),
.push(self.connection_note(result.as_ref().expect_err(
"the unavailable-services branch contains a connection error",
))),
);
};
let mut body = column([]).spacing(6);
@@ -163,7 +163,12 @@ impl App {
}
if accepted
&& !super::agent::valid_answer(
&self.connections.prompt.as_ref().unwrap().kind,
&self
.connections
.prompt
.as_ref()
.expect("the pairing reply branch requires an active prompt")
.kind,
&self.connections.pairing_input,
)
{
+6 -1
View File
@@ -229,7 +229,12 @@ impl Client {
fn cleanup(&self) {
let target = self.agent.cancel_local();
let paths = std::mem::take(&mut *self.discovery.lock().unwrap());
let paths = std::mem::take(
&mut *self
.discovery
.lock()
.expect("Bluetooth discovery ownership must remain consistent across callbacks"),
);
let connection = self.connection.clone();
self.runtime.spawn(async move {
if let Some(path) = target {
@@ -20,7 +20,9 @@ impl App {
column([])
.spacing(8)
.push(self.label("Wi-Fi unavailable", 14.))
.push(self.connection_note(result.as_ref().unwrap_err())),
.push(self.connection_note(result.as_ref().expect_err(
"the unavailable-services branch contains a connection error",
))),
);
};
let mut body = column([]).spacing(6);
+10 -3
View File
@@ -258,7 +258,9 @@ impl cosmic::Application for App {
}
.into();
let error = initial.as_ref().err().cloned();
let current = initial.unwrap_or_else(|_| Snapshot::parse(String::new()).unwrap());
let current = initial.unwrap_or_else(|_| {
Snapshot::parse(String::new()).expect("an empty Settings document uses valid defaults")
});
let resolved = ferese_theme_client::service::current();
let font = fonts::interface_font(&resolved.presented.tokens.typography.font_family);
let native_palette = visuals::Palette::from_resolved(&resolved.presented);
@@ -540,7 +542,10 @@ impl cosmic::Application for App {
if let Some((id, appearance)) = &self.gallery_focus
&& self.gallery_position(id, *appearance) == Some((list, index))
{
let (id, appearance) = self.gallery_focus.take().unwrap();
let (id, appearance) = self
.gallery_focus
.take()
.expect("gallery focus was requested before this focus operation");
return cosmic::iced::advanced::widget::operate(
cosmic::iced::advanced::widget::operation::focusable::focus(
gallery_id(&id, appearance),
@@ -1100,7 +1105,9 @@ impl App {
{
return self.apply_wallpaper_edits(wallpaper_controls::edits(
wallpaper_controls::Target::Both,
path.rsplit('.').next().unwrap(),
path.rsplit('.')
.next()
.expect("splitting a field path always yields its final component"),
value.clone(),
));
}
+6 -3
View File
@@ -321,10 +321,13 @@ impl App {
.map(|panel| panel.resolved_geometry())
.unwrap_or_default(),
)
.unwrap();
*default = geometry[field.path.rsplit('.').next().unwrap()]
.expect("typed configuration and IPC values must serialize to JSON");
*default =
geometry[field.path.rsplit('.').next().expect(
"splitting a field path always yields its final component",
)]
.as_f64()
.unwrap();
.expect("splitting a field path always yields its final component");
}
let pinned = self.draft.item(&field.path).is_some();
let reset = pinned.then_some(Message::PanelEdit(Action::ClearGeometry(
+7 -3
View File
@@ -258,7 +258,7 @@ impl Widget<Message, Theme, Renderer> for Editor<'_> {
.find_map(|(region, bounds)| {
matches!(region, Region::Item(id, _) if id == item).then_some(*bounds)
})
.unwrap();
.expect("the active drag branch retains the pressed item and its measured bounds");
state.drag = Some(Drag {
item: item.clone(),
origin: cursor,
@@ -272,7 +272,9 @@ impl Widget<Message, Theme, Renderer> for Editor<'_> {
}
}
Event::Mouse(mouse::Event::CursorMoved { .. }) if state.drag.is_some() => {
let drag = state.drag.as_mut().unwrap();
let drag = state.drag.as_mut().expect(
"the active drag branch retains the pressed item and its measured bounds",
);
if let Some(cursor) = cursor.position() {
drag.cursor = cursor;
drag.moved |= (cursor.x - drag.origin.x).hypot(cursor.y - drag.origin.y) >= 6.;
@@ -291,7 +293,9 @@ impl Widget<Message, Theme, Renderer> for Editor<'_> {
Event::Mouse(mouse::Event::ButtonReleased(mouse::Button::Left))
if state.drag.is_some() =>
{
let drag = state.drag.take().unwrap();
let drag = state.drag.take().expect(
"the active drag branch retains the pressed item and its measured bounds",
);
if drag.moved {
if let Some(target) = cursor
.position()
+18 -8
View File
@@ -147,7 +147,7 @@ fn locate(panel: &Panel, id: &ItemId) -> Result<(String, usize), String> {
.groups
.iter()
.find(|group| group.id == destination.group)
.unwrap();
.expect("the selected destination group belongs to its resolved zone");
if let Some(index) = group.items.iter().position(|item| &item.id == id) {
return Ok((path, index));
}
@@ -309,7 +309,7 @@ pub(super) fn plan(snapshot: &Snapshot, action: Action) -> Result<Vec<Edit>, Str
}
let group = records(&candidate, &format!("panels.0.{}.groups", zone.key()))[0]["id"]
.as_str()
.unwrap()
.expect("validated panel groups and item kinds have string identifiers")
.to_owned();
edits.extend(plan(
&candidate,
@@ -337,7 +337,13 @@ pub(super) fn plan(snapshot: &Snapshot, action: Action) -> Result<Vec<Edit>, Str
}
let (path, index) = locate(panel, &id)?;
if field == "style"
&& !matches!(panel.item(&id).unwrap().kind, ItemKind::Workspaces { .. })
&& !matches!(
panel
.item(&id)
.expect("the item edit resolved its stable ID before checking its kind")
.kind,
ItemKind::Workspaces { .. }
)
{
return Err("Workspace style belongs to Workspaces items.".into());
}
@@ -349,11 +355,14 @@ pub(super) fn plan(snapshot: &Snapshot, action: Action) -> Result<Vec<Edit>, Str
}
let path = group_path(panel, &destination)?;
let name = serde_json::to_value(kind).map_err(|error| error.to_string())?;
let name = name["kind"].as_str().unwrap();
let name = name["kind"]
.as_str()
.expect("validated panel groups and item kinds have string identifiers");
let count = destinations(panel)
.iter()
.map(|destination| {
let path = group_path(panel, destination).unwrap();
let path = group_path(panel, destination)
.expect("catalog destinations refer to existing panel groups");
records(snapshot, &path).len()
})
.sum::<usize>();
@@ -366,7 +375,7 @@ pub(super) fn plan(snapshot: &Snapshot, action: Action) -> Result<Vec<Edit>, Str
}
})
.find(|id| panel.item(&ItemId(id.clone())).is_none())
.unwrap();
.expect("one more candidate ID than existing items guarantees an unused ID");
let mut items = records(snapshot, &path);
items.push(
serde_json::to_value(Item::new(&id, kind)).map_err(|error| error.to_string())?,
@@ -381,7 +390,7 @@ pub(super) fn plan(snapshot: &Snapshot, action: Action) -> Result<Vec<Edit>, Str
let id = (1..=count + 1)
.map(|number| format!("{}-{number}", zone.key()))
.find(|id| locate_group(panel, &GroupId(id.clone())).is_err())
.unwrap();
.expect("one more candidate ID than existing items guarantees an unused ID");
let path = format!("panels.0.{}.groups", zone.key());
let mut groups = records(snapshot, &path);
groups.push(serde_json::json!({
@@ -432,7 +441,8 @@ pub(super) fn plan(snapshot: &Snapshot, action: Action) -> Result<Vec<Edit>, Str
"padding_vertical" | "padding_horizontal" => {
let (zone, index) = locate_group(panel, &id)?;
let mut padding =
serde_json::to_value(zone.definition(panel).groups[index].padding).unwrap();
serde_json::to_value(zone.definition(panel).groups[index].padding)
.expect("typed configuration and IPC values must serialize to JSON");
padding[usize::from(field == "padding_horizontal")] = value;
("padding".to_owned(), padding)
}
+9 -4
View File
@@ -140,12 +140,12 @@ impl App {
.into_iter()
.flat_map(|zone| &zone.definition(panel).groups)
.find(|group| group.id == destination.group)
.unwrap();
.expect("the inspector selection refers to an item or group in the current panel");
let index = group
.items
.iter()
.position(|candidate| candidate.id == item.id)
.unwrap();
.expect("the inspector selection refers to an item or group in the current panel");
rows.push(self.panel_divider())
.push(
self.inspector_actions(
@@ -293,7 +293,7 @@ impl App {
.groups
.iter()
.position(|candidate| candidate.id == group.id)
.unwrap();
.expect("the inspector selection refers to an item or group in the current panel");
rows = rows.push(
self.inspector_actions(
(index > 0).then(|| Message::PanelEdit(Action::EarlierGroup(group.id.clone()))),
@@ -335,7 +335,12 @@ impl App {
fn panel_field(&self, item: &Item, field: Field) -> Element<'static, Message> {
let p = crate::visuals::Palette::from_resolved(&self.resolved.presented);
let id = item.id.clone();
let name = field.path.rsplit('.').next().unwrap().to_owned();
let name = field
.path
.rsplit('.')
.next()
.expect("splitting a field path always yields its final component")
.to_owned();
let values = serde_json::to_value(item).expect("serializable panel item");
match field.kind {
Kind::Choice { default, choices } => {
@@ -328,7 +328,9 @@ impl App {
return setting(
&self.draft,
self.wallpaper.target,
path.rsplit('.').next().unwrap(),
path.rsplit('.')
.next()
.expect("splitting a field path always yields its final component"),
fallback,
);
}