Skip to content

Commit 10edcd9

Browse files
authored
Use better rounded divisions (#177)
* Use better rounded divisions * Rename div_round to div_round_u32
1 parent b14eba7 commit 10edcd9

File tree

3 files changed

+16
-12
lines changed

3 files changed

+16
-12
lines changed

src/brightness_backend/brightnessctl.rs

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
use crate::global_utils::div_round_u32;
2+
13
use super::{BrightnessBackend, BrightnessBackendConstructor};
24

35
const EXPECT_STR: &str = "VirtualDevice didn't test the command during initialization";
@@ -111,10 +113,16 @@ impl VirtualDevice {
111113

112114
fn set_percent(&mut self, mut val: u32) -> anyhow::Result<()> {
113115
val = val.clamp(0, 100);
114-
self.current = self.max.map(|max| val * max / 100);
116+
self.current = self.max.map(|max| div_round_u32(val * max, 100));
115117
let _: String = self.run(("set", &*format!("{val}%")))?;
116118
Ok(())
117119
}
120+
121+
pub fn get_percent(&mut self) -> u32 {
122+
let curr = self.get_current();
123+
let max = self.get_max();
124+
div_round_u32(curr * 100, max)
125+
}
118126
}
119127

120128
impl BrightnessBackendConstructor for BrightnessCtl {
@@ -135,20 +143,12 @@ impl BrightnessBackend for BrightnessCtl {
135143
}
136144

137145
fn lower(&mut self, by: u32) -> anyhow::Result<()> {
138-
let curr = self.get_current();
139-
let max = self.get_max();
140-
141-
let curr = curr * 100 / max;
142-
146+
let curr = self.device.get_percent();
143147
self.device.set_percent(curr.saturating_sub(by))
144148
}
145149

146150
fn raise(&mut self, by: u32) -> anyhow::Result<()> {
147-
let curr = self.get_current();
148-
let max = self.get_max();
149-
150-
let curr = curr * 100 / max;
151-
151+
let curr = self.device.get_percent();
152152
self.device.set_percent(curr + by)
153153
}
154154

src/global_utils.rs

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -262,3 +262,7 @@ fn volume_parser(is_sink: bool, value: &str) -> Result<(ArgTypes, Option<String>
262262
}
263263
Ok(v)
264264
}
265+
266+
pub fn div_round_u32(a: u32, b: u32) -> u32 {
267+
(a + b / 2) / b
268+
}

src/server/osd_window.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -153,7 +153,7 @@ impl SwayosdWindow {
153153
let max = brightness_backend.get_max() as f64;
154154
let progress = self.build_progress_widget(brightness / max);
155155
let label = self.build_text_widget(
156-
Some(&format!("{}%", (brightness / max * 100.) as i32)),
156+
Some(&format!("{}%", (brightness / max * 100.).round() as i32)),
157157
Some(4),
158158
);
159159

0 commit comments

Comments
 (0)