From cbecef086e023918a4c7089ca2eb66cc2eec2738 Mon Sep 17 00:00:00 2001 From: Sawyer McLane Date: Mon, 13 Jan 2025 06:48:36 -0700 Subject: [PATCH] Refactor variable names for clarity and improve code readability --- src/app.rs | 44 +++++++++++++++++++----------- src/color.rs | 62 ++++++++++++++++++++++++++----------------- src/device_info.rs | 7 +++-- src/device_manager.rs | 27 ++++++++++--------- src/screencap.rs | 44 +++++++++++++++--------------- src/settings.rs | 44 ++++++++++++++++-------------- src/shortcut.rs | 37 +++++++++++++++++--------- src/ui.rs | 54 ++++++++++++++++++------------------- src/utils.rs | 6 ++--- 9 files changed, 185 insertions(+), 140 deletions(-) diff --git a/src/app.rs b/src/app.rs index f6eb54a..6450754 100644 --- a/src/app.rs +++ b/src/app.rs @@ -12,7 +12,7 @@ use crate::{ display_color_circle, listener::input_listener::InputListener, scenes::Scene, - screencap::{FollowType, ScreenSubregion}, + screencap::{RegionCaptureTarget, ScreenSubregion}, settings::Settings, shortcut::ShortcutManager, toggle_button, @@ -39,7 +39,7 @@ pub const SUBREGION_ICON: &[u8; 218] = include_bytes!("../res/icons/square.png") pub struct RunningWaveform { pub active: bool, pub last_update: Instant, - pub follow_type: FollowType, + pub follow_type: RegionCaptureTarget, pub stop_tx: Option>, } pub struct ColorChannelEntry { @@ -53,7 +53,7 @@ pub type ColorChannel = HashMap; #[serde(default)] pub struct MantleApp { #[serde(skip)] - pub mgr: LifxManager, + pub lighting_manager: LifxManager, #[serde(skip)] pub screen_manager: ScreencapManager, #[serde(skip)] @@ -85,7 +85,7 @@ impl Default for MantleApp { let lifx_manager = LifxManager::new().expect("Failed to create manager"); let shortcut_handle = Some(shortcut_manager.start(lifx_manager.clone())); Self { - mgr: lifx_manager, + lighting_manager: lifx_manager, screen_manager: ScreencapManager::new().expect("Failed to create screen manager"), input_listener, shortcut_manager, @@ -145,13 +145,13 @@ impl MantleApp { } DeviceInfo::Group(group) => { if let Ok(s) = group.label.cstr().to_str() { - if *group == self.mgr.all { + if *group == self.lighting_manager.all_bulbs_group { ui.label(RichText::new(s).size(16.0).strong().underline()); } else { ui.label(RichText::new(s).size(16.0).strong()); } } - Some(self.mgr.get_avg_group_color(group, bulbs)) + Some(self.lighting_manager.get_avg_group_color(group, bulbs)) } }; @@ -168,7 +168,13 @@ impl MantleApp { ui.vertical(|ui| { ui.horizontal(|ui| { ui.label("Power"); - toggle_button(ui, &self.mgr, device, Vec2::new(1.0, 1.0), bulbs); + toggle_button( + ui, + &self.lighting_manager, + device, + Vec2::new(1.0, 1.0), + bulbs, + ); }); if let Some(before_color) = color { let mut after_color = @@ -180,7 +186,7 @@ impl MantleApp { if before_color != after_color.next { match device { DeviceInfo::Bulb(bulb) => { - if let Err(e) = self.mgr.set_color( + if let Err(e) = self.lighting_manager.set_color( &&**bulb, after_color.next, after_color.duration, @@ -189,7 +195,7 @@ impl MantleApp { } } DeviceInfo::Group(group) => { - if let Err(e) = self.mgr.set_group_color( + if let Err(e) = self.lighting_manager.set_group_color( group, after_color.next, bulbs, @@ -241,7 +247,7 @@ impl MantleApp { ui.ctx().send_viewport_cmd(egui::ViewportCommand::Close); } if ui.input_mut(|i| i.consume_shortcut(&refresh_shortcut)) { - if let Err(e) = self.mgr.refresh() { + if let Err(e) = self.lighting_manager.refresh() { log::error!("Error refreshing manager: {}", e); } } @@ -255,7 +261,7 @@ impl MantleApp { ) .clicked() { - if let Err(e) = self.mgr.refresh() { + if let Err(e) = self.lighting_manager.refresh() { log::error!("Error refreshing manager: {}", e); } ui.close_menu(); @@ -296,12 +302,16 @@ impl MantleApp { }); egui::CentralPanel::default().show(ctx, |ui| { egui::ScrollArea::vertical().show(ui, |ui| { - let bulbs = self.mgr.bulbs.clone(); + let bulbs = self.lighting_manager.bulbs.clone(); let bulbs = bulbs.lock(); let mut seen_groups = HashSet::::new(); ui.vertical(|ui| { if let Ok(bulbs) = bulbs { - self.display_device(ui, &DeviceInfo::Group(self.mgr.all.clone()), &bulbs); + self.display_device( + ui, + &DeviceInfo::Group(self.lighting_manager.all_bulbs_group.clone()), + &bulbs, + ); let sorted_bulbs = self.sort_bulbs(bulbs.values().collect()); for bulb in sorted_bulbs { if let Some(group) = bulb.group.data.as_ref() { @@ -354,12 +364,14 @@ impl eframe::App for MantleApp { fn update(&mut self, _ctx: &egui::Context, _frame: &mut eframe::Frame) { #[cfg(debug_assertions)] puffin::GlobalProfiler::lock().new_frame(); - if Instant::now() - self.mgr.last_discovery + if Instant::now() - self.lighting_manager.last_discovery > Duration::from_millis(self.settings.refresh_rate_ms) { - self.mgr.discover().expect("Failed to discover bulbs"); + self.lighting_manager + .discover() + .expect("Failed to discover bulbs"); } - if let Err(e) = self.mgr.refresh() { + if let Err(e) = self.lighting_manager.refresh() { log::error!("Error refreshing manager: {}", e); } self.update_ui(_ctx); diff --git a/src/color.rs b/src/color.rs index 4ce284a..9a28902 100644 --- a/src/color.rs +++ b/src/color.rs @@ -76,12 +76,18 @@ impl From for RGB8 { }; let rgb_k = kelvin_to_rgb(kelvin); - let a = saturation as f64 / u16::MAX as f64; - let b = (1.0 - a) / 255.0; - - let red = (rgb_hsb.red as f64 * (a + rgb_k.red as f64 * b)).round() as u8; - let green = (rgb_hsb.green as f64 * (a + rgb_k.green as f64 * b)).round() as u8; - let blue = (rgb_hsb.blue as f64 * (a + rgb_k.blue as f64 * b)).round() as u8; + let normalized_saturation = saturation as f64 / u16::MAX as f64; + let normalized_brightness = (1.0 - normalized_saturation) / 255.0; + + let red = (rgb_hsb.red as f64 + * (normalized_saturation + rgb_k.red as f64 * normalized_brightness)) + .round() as u8; + let green = (rgb_hsb.green as f64 + * (normalized_saturation + rgb_k.green as f64 * normalized_brightness)) + .round() as u8; + let blue = (rgb_hsb.blue as f64 + * (normalized_saturation + rgb_k.blue as f64 * normalized_brightness)) + .round() as u8; RGB8 { red, @@ -94,28 +100,28 @@ impl From for RGB8 { impl From for HSBK { fn from(color: RGB8) -> HSBK { - let cmax = *[color.red, color.green, color.blue] + let max_color_component = *[color.red, color.green, color.blue] .iter() .max() .expect("Invalid color tuple") as f32; - let cmin = *[color.red, color.green, color.blue] + let min_color_component = *[color.red, color.green, color.blue] .iter() .min() .expect("Invalid color tuple") as f32; - let cdel = cmax - cmin; + let color_range = max_color_component - min_color_component; - let brightness = ((cmax / 255.0) * u16::MAX as f32) as u16; + let brightness = ((max_color_component / 255.0) * u16::MAX as f32) as u16; - let (saturation, hue) = if cdel != 0.0 { - let saturation = ((cdel / cmax) * u16::MAX as f32) as u16; + let (saturation, hue) = if color_range != 0.0 { + let saturation = ((color_range / max_color_component) * u16::MAX as f32) as u16; - let redc = (cmax - color.red as f32) / cdel; - let greenc = (cmax - color.green as f32) / cdel; - let bluec = (cmax - color.blue as f32) / cdel; + let redc = (max_color_component - color.red as f32) / color_range; + let greenc = (max_color_component - color.green as f32) / color_range; + let bluec = (max_color_component - color.blue as f32) / color_range; - let mut hue = if color.red as f32 == cmax { + let mut hue = if color.red as f32 == max_color_component { bluec - greenc - } else if color.green as f32 == cmax { + } else if color.green as f32 == max_color_component { 2.0 + redc - bluec } else { 4.0 + greenc - redc @@ -147,25 +153,31 @@ impl From for Color32 { } pub fn kelvin_to_rgb(temperature: u16) -> RGB8 { - let p_temp = temperature / 100; + let percentage_temperature = temperature / 100; let red; let green; - if p_temp <= 66 { + if percentage_temperature <= 66 { red = 255.; - green = (99.4708025861 * (p_temp as f64 + 0.0000000001).ln() - 161.1195681661) + green = (99.4708025861 * (percentage_temperature as f64 + 0.0000000001).ln() + - 161.1195681661) .clamp(0.0, 255.0); } else { - red = 329.698727466 * ((p_temp - 60) as f64).powf(-0.1332047592).clamp(0.0, 255.0); - green = (288.1221695283 * ((p_temp - 60) as f64).powf(-0.0755148492)).clamp(0.0, 255.0); + red = 329.698727466 + * ((percentage_temperature - 60) as f64) + .powf(-0.1332047592) + .clamp(0.0, 255.0); + green = (288.1221695283 * ((percentage_temperature - 60) as f64).powf(-0.0755148492)) + .clamp(0.0, 255.0); } - let blue = if p_temp >= 66 { + let blue = if percentage_temperature >= 66 { 255.0 - } else if p_temp <= 19 { + } else if percentage_temperature <= 19 { 0.0 } else { - (138.5177312231 * ((p_temp - 10) as f64).ln() - 305.0447927307).clamp(0.0, 255.0) + (138.5177312231 * ((percentage_temperature - 10) as f64).ln() - 305.0447927307) + .clamp(0.0, 255.0) }; RGB8 { diff --git a/src/device_info.rs b/src/device_info.rs index 3faace1..39de20f 100644 --- a/src/device_info.rs +++ b/src/device_info.rs @@ -40,6 +40,9 @@ pub struct BulbInfo { deserialize_with = "deserialize_instant" )] pub last_seen: Instant, + /// If the source is non-zero, then the LIFX device with send a unicast message to the IP + /// address/port of the client that sent the originating message. If zero, then the LIFX + /// device may send a broadcast message that can be received by all clients on the same sub-net. pub source: u32, pub target: u64, pub addr: SocketAddr, @@ -327,8 +330,8 @@ impl std::fmt::Debug for BulbInfo { if let Some((major, minor)) = self.wifi_firmware.as_ref() { write!(f, " WifiFW:{}.{}", major, minor)?; } - if let Some(level) = self.power_level.as_ref() { - if *level > 0 { + if let Some(power_level) = self.power_level.as_ref() { + if *power_level > 0 { write!(f, " Powered On(")?; match self.color { DeviceColor::Unknown => write!(f, "??")?, diff --git a/src/device_manager.rs b/src/device_manager.rs index 1bafd76..edbbf3e 100644 --- a/src/device_manager.rs +++ b/src/device_manager.rs @@ -12,9 +12,12 @@ use std::time::{Duration, Instant}; pub struct LifxManager { pub bulbs: Arc>>, - pub all: GroupInfo, + pub all_bulbs_group: GroupInfo, pub last_discovery: Instant, - pub sock: UdpSocket, + pub socket: UdpSocket, + /// If the source is non-zero, then the LIFX device with send a unicast message to the IP + /// address/port of the client that sent the originating message. If zero, then the LIFX + /// device may send a broadcast message that can be received by all clients on the same sub-net. pub source: u32, } @@ -22,9 +25,9 @@ impl Clone for LifxManager { fn clone(&self) -> Self { LifxManager { bulbs: self.bulbs.clone(), - all: self.all.clone(), + all_bulbs_group: self.all_bulbs_group.clone(), last_discovery: self.last_discovery, - sock: self.sock.try_clone().expect("Failed to clone socket"), + socket: self.socket.try_clone().expect("Failed to clone socket"), source: self.source, } } @@ -43,15 +46,15 @@ impl LifxManager { spawn(move || Self::worker(recv_sock, source, receiver_bulbs)); - let mut mgr = LifxManager { + let mut lifx_manager = LifxManager { bulbs, last_discovery: Instant::now(), - sock, + socket: sock, source, - all: GroupInfo::build_all_group(), + all_bulbs_group: GroupInfo::build_all_group(), }; - mgr.discover()?; - Ok(mgr) + lifx_manager.discover()?; + Ok(lifx_manager) } fn handle_message(raw: RawMessage, bulb: &mut BulbInfo) -> Result<(), lifx_core::Error> { @@ -234,7 +237,7 @@ impl LifxManager { } let addr = SocketAddr::new(IpAddr::V4(bcast), 56700); log::debug!("Discovering bulbs on LAN {:?}", addr); - self.sock.send_to(&bytes, addr)?; + self.socket.send_to(&bytes, addr)?; count += 1; } } @@ -249,7 +252,7 @@ impl LifxManager { if let Ok(mut bulbs) = self.bulbs.lock() { let bulbs = bulbs.values_mut(); for bulb in bulbs { - bulb.query_for_missing_info(&self.sock)?; + bulb.query_for_missing_info(&self.socket)?; count += 1; } } @@ -267,7 +270,7 @@ impl LifxManager { }; let raw = RawMessage::build(&opts, message).expect("Failed to build message"); let bytes = raw.pack().expect("Failed to pack message"); - self.sock.send_to(&bytes, target) + self.socket.send_to(&bytes, target) } pub fn set_power(&self, bulb: &&BulbInfo, level: u16) -> Result { diff --git a/src/screencap.rs b/src/screencap.rs index dff20b4..f4738b1 100644 --- a/src/screencap.rs +++ b/src/screencap.rs @@ -29,31 +29,41 @@ impl ScreenSubregion { } } +impl PartialEq for ScreenSubregion { + fn eq(&self, other: &Self) -> bool { + self.monitor.as_ref().map(|m| m.id()) == other.monitor.as_ref().map(|m| m.id()) + && self.x == other.x + && self.y == other.y + && self.width == other.width + && self.height == other.height + } +} + #[derive(Clone, Debug)] -pub enum FollowType { +pub enum RegionCaptureTarget { Monitor(Vec), Window(Vec), Subregion(Vec), All, } -impl PartialEq for FollowType { +impl PartialEq for RegionCaptureTarget { fn eq(&self, other: &Self) -> bool { match (self, other) { - (FollowType::Monitor(m1), FollowType::Monitor(m2)) => { + (RegionCaptureTarget::Monitor(m1), RegionCaptureTarget::Monitor(m2)) => { Self::compare_by_id(m1, m2, |m| m.id().into()) } - (FollowType::Window(w1), FollowType::Window(w2)) => { + (RegionCaptureTarget::Window(w1), RegionCaptureTarget::Window(w2)) => { Self::compare_by_id(w1, w2, |w| w.id().into()) } - (FollowType::Subregion(s1), FollowType::Subregion(s2)) => s1 == s2, - (FollowType::All, FollowType::All) => true, + (RegionCaptureTarget::Subregion(s1), RegionCaptureTarget::Subregion(s2)) => s1 == s2, + (RegionCaptureTarget::All, RegionCaptureTarget::All) => true, _ => false, } } } -impl FollowType { +impl RegionCaptureTarget { /// Helper function to compare vectors of monitors/windows based on their IDs fn compare_by_id(v1: &[T], v2: &[T], id_fn: F) -> bool where @@ -71,16 +81,6 @@ impl FollowType { } } -impl PartialEq for ScreenSubregion { - fn eq(&self, other: &Self) -> bool { - self.monitor.as_ref().map(|m| m.id()) == other.monitor.as_ref().map(|m| m.id()) - && self.x == other.x - && self.y == other.y - && self.width == other.width - && self.height == other.height - } -} - #[derive(Clone)] pub struct ScreencapManager { pub monitors: Vec, @@ -148,7 +148,7 @@ impl ScreencapManager { ) } - pub fn avg_color(&self, follow: FollowType) -> Result { + pub fn calculate_average_color(&self, follow: RegionCaptureTarget) -> Result { let mut red: u64 = 0; let mut green: u64 = 0; let mut blue: u64 = 0; @@ -164,19 +164,19 @@ impl ScreencapManager { }; match follow { - FollowType::Monitor(monitors) => { + RegionCaptureTarget::Monitor(monitors) => { for monitor in monitors { let image = monitor.capture_image()?; calculate_image_pixel_average(&image); } } - FollowType::Window(windows) => { + RegionCaptureTarget::Window(windows) => { for window in windows { let image = window.capture_image()?; calculate_image_pixel_average(&image); } } - FollowType::Subregion(subregions) => { + RegionCaptureTarget::Subregion(subregions) => { for subregion in subregions { if let Some(monitor) = &subregion.monitor { let image = monitor.capture_image()?; @@ -194,7 +194,7 @@ impl ScreencapManager { } } } - FollowType::All => { + RegionCaptureTarget::All => { for monitor in &self.monitors { let image = monitor.capture_image()?; calculate_image_pixel_average(&image); diff --git a/src/settings.rs b/src/settings.rs index 96eb4bc..f0d485f 100644 --- a/src/settings.rs +++ b/src/settings.rs @@ -88,7 +88,11 @@ impl MantleApp { ui.horizontal(|ui| { if ui.button("Clear").clicked() { self.shortcut_manager.new_shortcut.name.clear(); - self.shortcut_manager.new_shortcut.shortcut.keys.clear(); + self.shortcut_manager + .new_shortcut + .shortcut + .input_action_keys + .clear(); self.shortcut_manager .new_shortcut .shortcut @@ -107,7 +111,11 @@ impl MantleApp { ); // Clear the fields after adding self.shortcut_manager.new_shortcut.name.clear(); - self.shortcut_manager.new_shortcut.shortcut.keys.clear(); + self.shortcut_manager + .new_shortcut + .shortcut + .input_action_keys + .clear(); self.shortcut_manager .new_shortcut .shortcut @@ -150,18 +158,17 @@ impl MantleApp { .new_shortcut .device .clone() - .unwrap_or(DeviceInfo::Group(self.mgr.all.clone())) + .unwrap_or(DeviceInfo::Group( + self.lighting_manager.all_bulbs_group.clone(), + )) .to_string(), ) .show_ui(ui, |ui| { - for device in self.mgr.bulbs.lock().unwrap().values() { + for device in self.lighting_manager.bulbs.lock().unwrap().values() { ui.selectable_label( - self.shortcut_manager - .new_shortcut - .device - .clone() - .unwrap_or(DeviceInfo::Group(self.mgr.all.clone())) - == DeviceInfo::Bulb(Box::new(device.clone())), + self.shortcut_manager.new_shortcut.device.clone().unwrap_or( + DeviceInfo::Group(self.lighting_manager.all_bulbs_group.clone()), + ) == DeviceInfo::Bulb(Box::new(device.clone())), device.name.data.as_ref().unwrap().to_str().unwrap(), ) .clicked() @@ -170,14 +177,11 @@ impl MantleApp { Some(DeviceInfo::Bulb(Box::new(device.clone()))); }); } - for group in self.mgr.get_groups() { + for group in self.lighting_manager.get_groups() { ui.selectable_label( - self.shortcut_manager - .new_shortcut - .device - .clone() - .unwrap_or(DeviceInfo::Group(self.mgr.all.clone())) - == DeviceInfo::Group(group.clone()), + self.shortcut_manager.new_shortcut.device.clone().unwrap_or( + DeviceInfo::Group(self.lighting_manager.all_bulbs_group.clone()), + ) == DeviceInfo::Group(group.clone()), group.label.cstr().to_str().unwrap(), ) .clicked() @@ -212,7 +216,7 @@ impl MantleApp { ui.label(&shortcut.name); ui.label(shortcut.device.as_ref().unwrap().to_string()); ui.label(shortcut.action.to_string()); - ui.label(&shortcut.shortcut.display_name); + ui.label(&shortcut.shortcut.name); if ui .button("Remove") .on_hover_text("Remove this shortcut") @@ -280,7 +284,7 @@ impl MantleApp { ui.label(format!("{} devices", scene.device_color_pairs.len())); ui.horizontal(|ui| { if ui.button("Apply").clicked() { - scene.apply(&mut self.mgr); + scene.apply(&mut self.lighting_manager); } if ui.button("Remove").clicked() { to_remove.push(scene.name.clone()); @@ -306,7 +310,7 @@ impl MantleApp { egui::ScrollArea::vertical() .max_height(150.0) .show(ui, |ui| { - for device in self.mgr.bulbs.lock().unwrap().values() { + for device in self.lighting_manager.bulbs.lock().unwrap().values() { let mut selected = self .new_scene .devices_mut() diff --git a/src/shortcut.rs b/src/shortcut.rs index 3b82a94..7534791 100644 --- a/src/shortcut.rs +++ b/src/shortcut.rs @@ -15,18 +15,21 @@ pub type ShortcutCallback = Arc; #[derive(Clone, Eq, PartialEq, Hash, Ord, PartialOrd, Serialize, Deserialize)] pub struct KeyboardShortcut { - pub keys: InputAction, - pub display_name: String, + pub input_action_keys: InputAction, + pub name: String, } impl KeyboardShortcut { pub fn new(keys: InputAction, display_name: String) -> Self { - KeyboardShortcut { keys, display_name } + KeyboardShortcut { + input_action_keys: keys, + name: display_name, + } } pub fn update_display_string(&mut self) { - self.display_name = self - .keys + self.name = self + .input_action_keys .iter() .map(|key| format!("{}", key)) .collect::>() @@ -34,29 +37,37 @@ impl KeyboardShortcut { } fn is_matched(&self, keys_pressed: &InputAction) -> bool { - self.keys.is_subset(keys_pressed) + self.input_action_keys.is_subset(keys_pressed) } } impl Default for KeyboardShortcut { fn default() -> Self { KeyboardShortcut { - keys: InputAction::default(), - display_name: "".to_string(), + input_action_keys: InputAction::default(), + name: "".to_string(), } } } impl Debug for KeyboardShortcut { fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult { - let keys: Vec = self.keys.iter().map(|k| format!("{}", k)).collect(); + let keys: Vec = self + .input_action_keys + .iter() + .map(|k| format!("{}", k)) + .collect(); write!(f, "KeyboardShortcut({})", keys.join(" + ")) } } impl Display for KeyboardShortcut { fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult { - let keys: Vec = self.keys.iter().map(|k| format!("{}", k)).collect(); + let keys: Vec = self + .input_action_keys + .iter() + .map(|k| format!("{}", k)) + .collect(); write!(f, "{}", keys.join(" + ")) } } @@ -239,12 +250,12 @@ impl Widget for ShortcutEdit<'_> { let input_item = from_egui(*key, modifiers); keys_pressed.extend(input_item); } - shortcut.keys.extend(keys_pressed); + shortcut.input_action_keys.extend(keys_pressed); }); } shortcut.update_display_string(); - let text = shortcut.display_name.clone(); + let text = shortcut.name.clone(); let text_pos = rect.center(); ui.painter().text( text_pos, @@ -273,7 +284,7 @@ mod tests { let keys: BTreeSet<_> = vec![InputItem::Key(Key::KeyA)].into_iter().collect(); let shortcut = KeyboardShortcut::new(InputAction::from(keys.clone()), "TestAction".to_string()); - assert_eq!(shortcut.keys, InputAction::from(keys.clone())); + assert_eq!(shortcut.input_action_keys, InputAction::from(keys.clone())); } #[test] diff --git a/src/ui.rs b/src/ui.rs index fd65994..82eb947 100644 --- a/src/ui.rs +++ b/src/ui.rs @@ -15,7 +15,7 @@ use crate::{ contrast_color, device_info::DeviceInfo, products::{KELVIN_RANGE, LIFX_RANGE}, - screencap::{FollowType, ScreenSubregion, ScreencapManager}, + screencap::{RegionCaptureTarget, ScreenSubregion, ScreencapManager}, AngleIter, BulbInfo, LifxManager, HSBK32, RGB8, }; @@ -124,7 +124,7 @@ pub fn handle_screencap( .or_insert(RunningWaveform { active: false, last_update: Instant::now(), - follow_type: FollowType::All, + follow_type: RegionCaptureTarget::All, stop_tx: None, }); if follow_state.active @@ -155,7 +155,7 @@ pub fn handle_screencap( let running_waveform = RunningWaveform { active: true, last_update: Instant::now(), - follow_type: FollowType::All, + follow_type: RegionCaptureTarget::All, stop_tx: None, }; app.waveform_map @@ -171,7 +171,7 @@ pub fn handle_screencap( .tx .clone(); let follow_type = app.waveform_map[&device.id()].follow_type.clone(); - let mgr = app.mgr.clone(); // Assuming you have a 'manager' field in MantleApp to control the bulb/group + let lifx_manager = app.lighting_manager.clone(); // Assuming you have a 'manager' field in MantleApp to control the bulb/group let device_id = device.id(); let (stop_tx, stop_rx) = mpsc::channel::<()>(); @@ -180,9 +180,9 @@ pub fn handle_screencap( #[cfg(debug_assertions)] puffin::profile_function!(); - match screen_manager.avg_color(follow_type.clone()) { + match screen_manager.calculate_average_color(follow_type.clone()) { Ok(avg_color) => { - if let Err(err) = mgr.set_color_by_id(device_id, avg_color) { + if let Err(err) = lifx_manager.set_color_by_id(device_id, avg_color) { eprintln!("Failed to set color: {}", err); } @@ -235,17 +235,17 @@ pub fn handle_screencap( .expect("Failed to get subregion"); // Create options for ComboBox with consistent ordering - let mut options = vec![("All".to_string(), FollowType::All)]; + let mut options = vec![("All".to_string(), RegionCaptureTarget::All)]; // Collect monitor options - let mut monitor_options: Vec<(String, FollowType)> = app + let mut monitor_options: Vec<(String, RegionCaptureTarget)> = app .screen_manager .monitors .iter() .map(|monitor| { ( monitor.name().to_string(), - FollowType::Monitor(vec![monitor.clone()]), + RegionCaptureTarget::Monitor(vec![monitor.clone()]), ) }) .collect(); @@ -254,14 +254,14 @@ pub fn handle_screencap( options.extend(monitor_options); // Collect window options - let mut window_options: Vec<(String, FollowType)> = app + let mut window_options: Vec<(String, RegionCaptureTarget)> = app .screen_manager .windows .iter() .map(|window| { ( window.title().to_string(), - FollowType::Window(vec![window.clone()]), + RegionCaptureTarget::Window(vec![window.clone()]), ) }) .collect(); @@ -271,21 +271,21 @@ pub fn handle_screencap( options.push(( "Subregion".to_string(), - FollowType::Subregion(vec![subregion.clone()]), + RegionCaptureTarget::Subregion(vec![subregion.clone()]), )); // Determine the selected text let selected_text = match &waveform.follow_type { - FollowType::All => "All".to_string(), - FollowType::Monitor(monitors) => monitors + RegionCaptureTarget::All => "All".to_string(), + RegionCaptureTarget::Monitor(monitors) => monitors .first() .map(|m| m.name().to_string()) .unwrap_or("Monitor".to_string()), - FollowType::Window(windows) => windows + RegionCaptureTarget::Window(windows) => windows .first() .map(|w| w.title().to_string()) .unwrap_or("Window".to_string()), - FollowType::Subregion(_) => "Subregion".to_string(), + RegionCaptureTarget::Subregion(_) => "Subregion".to_string(), }; // Use ComboBox with consistent ID ui.push_id(device.id(), |ui| { @@ -299,7 +299,7 @@ pub fn handle_screencap( }); // If the selected FollowType is Subregion, display the numerical fields - if let FollowType::Subregion(_) = waveform.follow_type { + if let RegionCaptureTarget::Subregion(_) = waveform.follow_type { ui.horizontal(|ui| { ui.label("X:"); ui.add(egui::DragValue::new(&mut subregion.x)); @@ -416,30 +416,30 @@ pub fn display_color_circle( pub fn toggle_button( ui: &mut Ui, - mgr: &LifxManager, + lifx_manager: &LifxManager, device: &DeviceInfo, scale: Vec2, - bulbs: &MutexGuard>, + registered_bulbs: &MutexGuard>, ) -> egui::Response { let desired_size = ui.spacing().interact_size * scale; let (rect, mut response) = ui.allocate_exact_size(desired_size, Sense::click()); ui.horizontal(|ui| { let on = match device { DeviceInfo::Bulb(bulb) => bulb.power_level.data.unwrap_or(0) != 0, - DeviceInfo::Group(group) => group.any_on(bulbs), + DeviceInfo::Group(group) => group.any_on(registered_bulbs), }; if response.clicked() { let level = if on { 0 } else { u16::MAX }; match device { DeviceInfo::Bulb(bulb) => { - if let Err(e) = mgr.set_power(&&**bulb, level) { + if let Err(e) = lifx_manager.set_power(&&**bulb, level) { log::error!("Error toggling bulb: {}", e); } else { log::info!("Toggled bulb {:?}", bulb.name); } } DeviceInfo::Group(group) => { - if let Err(e) = mgr.set_group_power(group, bulbs, level) { + if let Err(e) = lifx_manager.set_group_power(group, registered_bulbs, level) { log::error!("Error toggling group: {}", e); } else { log::info!("Toggled group {:?}", group.label); @@ -472,7 +472,7 @@ pub fn color_slider( value: &mut u16, range: std::ops::RangeInclusive, label: &str, - color_at: impl Fn(u16) -> Color32, + get_color_at_value: impl Fn(u16) -> Color32, ) -> Response { let desired_size = vec2(ui.spacing().slider_width, ui.spacing().interact_size.y); let (rect, response) = ui.allocate_at_least(desired_size, Sense::click_and_drag()); @@ -503,7 +503,7 @@ pub fn color_slider( let mut mesh = Mesh::default(); for i in 0..=SLIDER_RESOLUTION { let t = i as f32 / (SLIDER_RESOLUTION as f32); - let color = color_at((t * u16::MAX as f32) as u16); + let color = get_color_at_value((t * u16::MAX as f32) as u16); let x = lerp(rect.left()..=rect.right(), t); // round edges: let y_offset = if i == 0 || i == SLIDER_RESOLUTION { @@ -533,11 +533,11 @@ pub fn color_slider( 0.0..=1.0, ), ); - let r = ui.spacing().slider_rail_height / 2.0 + 2.0; - let picked_color = color_at(*value); + let radius = ui.spacing().slider_rail_height / 2.0 + 2.0; + let picked_color = get_color_at_value(*value); ui.painter().circle( pos2(x, rect.center().y), - r, + radius, picked_color, Stroke::new(visuals.fg_stroke.width, contrast_color(picked_color)), ); diff --git a/src/utils.rs b/src/utils.rs index 76df9f1..d3adc55 100644 --- a/src/utils.rs +++ b/src/utils.rs @@ -81,9 +81,9 @@ impl Iterator for AngleIter { } pub fn capitalize_first_letter(s: &str) -> String { - let mut c = s.chars(); - match c.next() { + let mut character_iter = s.chars(); + match character_iter.next() { None => String::new(), - Some(f) => f.to_uppercase().collect::() + c.as_str(), + Some(f) => f.to_uppercase().collect::() + character_iter.as_str(), } }