From dfd741872063150474f53bcbfd8527aef505ee0f Mon Sep 17 00:00:00 2001 From: lava Date: Mon, 30 Nov 2026 18:52:49 +0530 Subject: [PATCH 1/7] Improve UEFI GOP mode selection --- uefi/src/main.rs | 55 ++++++++++++++++++++++++++++++------------------ 1 file changed, 34 insertions(+), 21 deletions(-) diff --git a/uefi/src/main.rs b/uefi/src/main.rs index 928a290d..e7588439 100644 --- a/uefi/src/main.rs +++ b/uefi/src/main.rs @@ -351,28 +351,41 @@ fn init_logger(config: &BootConfig) -> Option { let gop_handle = boot::get_handle_for_protocol::().ok()?; let mut gop = boot::open_protocol_exclusive::(gop_handle).ok()?; + let minimum_height = config + .frame_buffer + .minimum_framebuffer_height + .and_then(|height| usize::try_from(height).ok()); + let minimum_width = config + .frame_buffer + .minimum_framebuffer_width + .and_then(|width| usize::try_from(width).ok()); + + // Prefer the smallest mode that satisfies the configured minimums. This + // avoids selecting an unnecessarily large mode just because firmware + // enumerates it last. let mode = { - let modes = gop.modes(); - match ( - config - .frame_buffer - .minimum_framebuffer_height - .map(|v| usize::try_from(v).unwrap()), - config - .frame_buffer - .minimum_framebuffer_width - .map(|v| usize::try_from(v).unwrap()), - ) { - (Some(height), Some(width)) => modes - .filter(|m| { - let res = m.info().resolution(); - res.1 >= height && res.0 >= width - }) - .last(), - (Some(height), None) => modes.filter(|m| m.info().resolution().1 >= height).last(), - (None, Some(width)) => modes.filter(|m| m.info().resolution().0 >= width).last(), - _ => None, - } + let mut modes = gop.modes(); + let best_fit = modes + .by_ref() + .filter(|mode| { + let (width, height) = mode.info().resolution(); + minimum_width.is_none_or(|minimum| width >= minimum) + && minimum_height.is_none_or(|minimum| height >= minimum) + }) + .min_by_key(|mode| { + let (width, height) = mode.info().resolution(); + (width * height, width, height) + }); + + // The documented fallback when no mode satisfies the minimums is to + // use the largest available mode. With no minimums, this also avoids + // inheriting an arbitrary low-resolution firmware default. + best_fit.or_else(|| { + modes.max_by_key(|mode| { + let (width, height) = mode.info().resolution(); + (width * height, width, height) + }) + }) }; if let Some(mode) = mode { gop.set_mode(&mode) From 7e71dfbf700f228212d78b868b1af26f8a13983c Mon Sep 17 00:00:00 2001 From: lava Date: Mon, 30 Nov 2026 18:56:25 +0530 Subject: [PATCH 2/7] Use best-fit GOP resolution selection --- uefi/src/main.rs | 70 +++++++++++++++++++++++------------------------- 1 file changed, 34 insertions(+), 36 deletions(-) diff --git a/uefi/src/main.rs b/uefi/src/main.rs index e7588439..3c96d9c4 100644 --- a/uefi/src/main.rs +++ b/uefi/src/main.rs @@ -34,6 +34,9 @@ use x86_64::{ }; mod memory_descriptor; +mod mode_selection; + +use mode_selection::select_framebuffer_resolution; struct BootFile { disk: &'static CStr16, @@ -351,42 +354,37 @@ fn init_logger(config: &BootConfig) -> Option { let gop_handle = boot::get_handle_for_protocol::().ok()?; let mut gop = boot::open_protocol_exclusive::(gop_handle).ok()?; - let minimum_height = config - .frame_buffer - .minimum_framebuffer_height - .and_then(|height| usize::try_from(height).ok()); - let minimum_width = config - .frame_buffer - .minimum_framebuffer_width - .and_then(|width| usize::try_from(width).ok()); - - // Prefer the smallest mode that satisfies the configured minimums. This - // avoids selecting an unnecessarily large mode just because firmware - // enumerates it last. - let mode = { - let mut modes = gop.modes(); - let best_fit = modes - .by_ref() - .filter(|mode| { - let (width, height) = mode.info().resolution(); - minimum_width.is_none_or(|minimum| width >= minimum) - && minimum_height.is_none_or(|minimum| height >= minimum) - }) - .min_by_key(|mode| { - let (width, height) = mode.info().resolution(); - (width * height, width, height) - }); - - // The documented fallback when no mode satisfies the minimums is to - // use the largest available mode. With no minimums, this also avoids - // inheriting an arbitrary low-resolution firmware default. - best_fit.or_else(|| { - modes.max_by_key(|mode| { - let (width, height) = mode.info().resolution(); - (width * height, width, height) - }) - }) - }; + let selected_resolution = select_framebuffer_resolution( + gop.modes().map(|mode| mode.info().resolution()), + config + .frame_buffer + .minimum_framebuffer_width + .map(|width| usize::try_from(width).unwrap()), + config + .frame_buffer + .minimum_framebuffer_height + .map(|height| usize::try_from(height).unwrap()), + config + .frame_buffer + .maximum_framebuffer_width + .map(|width| usize::try_from(width).unwrap()), + config + .frame_buffer + .maximum_framebuffer_height + .map(|height| usize::try_from(height).unwrap()), + config + .frame_buffer + .preferred_framebuffer_width + .map(|width| usize::try_from(width).unwrap()), + config + .frame_buffer + .preferred_framebuffer_height + .map(|height| usize::try_from(height).unwrap()), + ); + let mode = selected_resolution.and_then(|resolution| { + gop.modes() + .find(|mode| mode.info().resolution() == resolution) + }); if let Some(mode) = mode { gop.set_mode(&mode) .expect("Failed to apply the desired display mode"); From 5c3a7638fae2a9350f52df83fef3f85952eb7b0c Mon Sep 17 00:00:00 2001 From: lava Date: Mon, 30 Nov 2026 18:56:27 +0530 Subject: [PATCH 3/7] Add preferred and maximum framebuffer dimensions --- common/config/src/lib.rs | 23 +++++++++++++++++++---- 1 file changed, 19 insertions(+), 4 deletions(-) diff --git a/common/config/src/lib.rs b/common/config/src/lib.rs index 2f0da026..41a1b19b 100644 --- a/common/config/src/lib.rs +++ b/common/config/src/lib.rs @@ -43,16 +43,31 @@ impl Default for BootConfig { /// Configuration for the frame buffer used for graphical output. #[derive(Serialize, Deserialize, Debug, Default, PartialEq, Eq, Clone, Copy)] +#[serde(default)] #[non_exhaustive] pub struct FrameBuffer { - /// Instructs the bootloader to set up a framebuffer format that has at least the given height. + /// Instructs the UEFI bootloader to prefer a framebuffer at least this high. /// - /// If this is not possible, the bootloader will fall back to a smaller format. + /// If no available mode meets the minimum, the best available mode within the + /// configured maximum dimensions is used instead. pub minimum_framebuffer_height: Option, - /// Instructs the bootloader to set up a framebuffer format that has at least the given width. + /// Instructs the UEFI bootloader to prefer a framebuffer at least this wide. /// - /// If this is not possible, the bootloader will fall back to a smaller format. + /// If no available mode meets the minimum, the best available mode within the + /// configured maximum dimensions is used instead. pub minimum_framebuffer_width: Option, + /// Preferred framebuffer height. Defaults to 800 pixels when unset. + /// + /// Minimum and maximum constraints take precedence over this preference. + pub preferred_framebuffer_height: Option, + /// Preferred framebuffer width. Defaults to 1280 pixels when unset. + /// + /// Minimum and maximum constraints take precedence over this preference. + pub preferred_framebuffer_width: Option, + /// Maximum framebuffer height. Modes larger than this are not selected. + pub maximum_framebuffer_height: Option, + /// Maximum framebuffer width. Modes larger than this are not selected. + pub maximum_framebuffer_width: Option, } /// An enum representing the available verbosity level filters of the logger. From ac31322938c7cb1c55bf353c701d67c08ce0bca4 Mon Sep 17 00:00:00 2001 From: lava Date: Mon, 30 Nov 2026 18:56:29 +0530 Subject: [PATCH 4/7] Add tests for UEFI framebuffer mode selection --- uefi/src/mode_selection.rs | 172 +++++++++++++++++++++++++++++++++++++ 1 file changed, 172 insertions(+) create mode 100644 uefi/src/mode_selection.rs diff --git a/uefi/src/mode_selection.rs b/uefi/src/mode_selection.rs new file mode 100644 index 00000000..1e88679f --- /dev/null +++ b/uefi/src/mode_selection.rs @@ -0,0 +1,172 @@ +//! Resolution selection for the UEFI Graphics Output Protocol. + +const DEFAULT_PREFERRED_WIDTH: usize = 1280; +const DEFAULT_PREFERRED_HEIGHT: usize = 800; + +/// Selects the available resolution that best matches the configured constraints. +/// +/// Minimum dimensions are hard lower bounds when a matching mode exists. Maximum +/// dimensions are hard upper bounds. If no mode satisfies the minimums, the +/// highest-resolution mode within the maximum dimensions is used as a fallback. +pub(crate) fn select_framebuffer_resolution( + resolutions: impl IntoIterator, + minimum_width: Option, + minimum_height: Option, + maximum_width: Option, + maximum_height: Option, + preferred_width: Option, + preferred_height: Option, +) -> Option<(usize, usize)> { + let target_width = preferred_width + .or(minimum_width) + .unwrap_or(DEFAULT_PREFERRED_WIDTH); + let target_height = preferred_height + .or(minimum_height) + .unwrap_or(DEFAULT_PREFERRED_HEIGHT); + + let mut best_fit: Option<((u128, u128, usize, usize), (usize, usize))> = None; + let mut fallback: Option<((u128, usize, usize), (usize, usize))> = None; + + for (width, height) in resolutions { + if maximum_width.is_some_and(|maximum| width > maximum) + || maximum_height.is_some_and(|maximum| height > maximum) + { + continue; + } + + let area = (width as u128) * (height as u128); + let fallback_key = (area, width, height); + if fallback + .as_ref() + .map_or(true, |(best_key, _)| fallback_key > *best_key) + { + fallback = Some((fallback_key, (width, height))); + } + + let meets_minimums = minimum_width.map_or(true, |minimum| width >= minimum) + && minimum_height.map_or(true, |minimum| height >= minimum); + if !meets_minimums { + continue; + } + + let width_delta = width.abs_diff(target_width) as u128; + let height_delta = height.abs_diff(target_height) as u128; + let distance = width_delta * width_delta + height_delta * height_delta; + let score = (distance, area, width, height); + if best_fit + .as_ref() + .map_or(true, |(best_score, _)| score < *best_score) + { + best_fit = Some((score, (width, height))); + } + } + + best_fit + .map(|(_, resolution)| resolution) + .or_else(|| fallback.map(|(_, resolution)| resolution)) +} + +#[cfg(test)] +mod tests { + use super::select_framebuffer_resolution; + + #[test] + fn defaults_to_a_reasonable_resolution_instead_of_firmware_order() { + let modes = [(800, 600), (3840, 2160), (1280, 800), (1920, 1080)]; + + assert_eq!( + select_framebuffer_resolution(modes, None, None, None, None, None, None), + Some((1280, 800)) + ); + } + + #[test] + fn prefers_the_closest_mode_that_meets_minimum_dimensions() { + let modes = [(2560, 1600), (1920, 1200), (1920, 1080), (3840, 2160)]; + + assert_eq!( + select_framebuffer_resolution( + modes, + Some(1920), + Some(1080), + None, + None, + None, + None + ), + Some((1920, 1080)) + ); + } + + #[test] + fn preferred_dimensions_are_used_as_the_target() { + let modes = [(1280, 800), (1920, 1080), (2560, 1440)]; + + assert_eq!( + select_framebuffer_resolution( + modes, + None, + None, + None, + None, + Some(1920), + Some(1080) + ), + Some((1920, 1080)) + ); + } + + #[test] + fn maximum_dimensions_are_never_exceeded() { + let modes = [(1280, 800), (1920, 1080), (2560, 1600)]; + + assert_eq!( + select_framebuffer_resolution( + modes, + None, + None, + Some(1920), + Some(1080), + Some(1920), + Some(1080) + ), + Some((1920, 1080)) + ); + } + + #[test] + fn falls_back_to_the_largest_mode_within_maximum_dimensions() { + let modes = [(800, 600), (1280, 800), (1920, 1080), (2560, 1440)]; + + assert_eq!( + select_framebuffer_resolution( + modes, + Some(3840), + Some(2160), + Some(1920), + Some(1080), + None, + None + ), + Some((1920, 1080)) + ); + } + + #[test] + fn returns_none_when_no_mode_satisfies_maximum_dimensions() { + let modes = [(1920, 1080), (2560, 1440)]; + + assert_eq!( + select_framebuffer_resolution( + modes, + None, + None, + Some(1280), + Some(800), + None, + None + ), + None + ); + } +} From 242876e9bf461e8c18010da0457f196a7e451976 Mon Sep 17 00:00:00 2001 From: lava Date: Mon, 30 Nov 2026 18:57:22 +0530 Subject: [PATCH 5/7] Allow unit testing GOP mode selection --- uefi/src/main.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/uefi/src/main.rs b/uefi/src/main.rs index 3c96d9c4..db53a389 100644 --- a/uefi/src/main.rs +++ b/uefi/src/main.rs @@ -1,5 +1,5 @@ -#![no_std] -#![no_main] +#![cfg_attr(not(test), no_std)] +#![cfg_attr(not(test), no_main)] #![deny(unsafe_op_in_unsafe_fn)] use crate::memory_descriptor::UefiMemoryDescriptor; @@ -56,6 +56,7 @@ const RAMDISK_FILE: BootFile = BootFile { tftp: cstr8!("ramdisk"), }; +#[cfg(not(test))] #[entry] fn main() -> Status { let mut boot_mode = BootMode::Disk; From c06e62340ddefa963b01d4aba033b8631f36f04b Mon Sep 17 00:00:00 2001 From: lavanya Date: Mon, 30 Nov 2026 19:10:28 +0530 Subject: [PATCH 6/7] Format GOP mode selection tests --- uefi/src/mode_selection.rs | 30 +++--------------------------- 1 file changed, 3 insertions(+), 27 deletions(-) diff --git a/uefi/src/mode_selection.rs b/uefi/src/mode_selection.rs index 1e88679f..03f5b490 100644 --- a/uefi/src/mode_selection.rs +++ b/uefi/src/mode_selection.rs @@ -85,15 +85,7 @@ mod tests { let modes = [(2560, 1600), (1920, 1200), (1920, 1080), (3840, 2160)]; assert_eq!( - select_framebuffer_resolution( - modes, - Some(1920), - Some(1080), - None, - None, - None, - None - ), + select_framebuffer_resolution(modes, Some(1920), Some(1080), None, None, None, None), Some((1920, 1080)) ); } @@ -103,15 +95,7 @@ mod tests { let modes = [(1280, 800), (1920, 1080), (2560, 1440)]; assert_eq!( - select_framebuffer_resolution( - modes, - None, - None, - None, - None, - Some(1920), - Some(1080) - ), + select_framebuffer_resolution(modes, None, None, None, None, Some(1920), Some(1080)), Some((1920, 1080)) ); } @@ -157,15 +141,7 @@ mod tests { let modes = [(1920, 1080), (2560, 1440)]; assert_eq!( - select_framebuffer_resolution( - modes, - None, - None, - Some(1280), - Some(800), - None, - None - ), + select_framebuffer_resolution(modes, None, None, Some(1280), Some(800), None, None), None ); } From 39787ac9631f619e0229b8a1c554c02f12da2019 Mon Sep 17 00:00:00 2001 From: lavanya Date: Thu, 3 Dec 2026 15:29:11 +0530 Subject: [PATCH 7/7] Add ordered framebuffer resolution preferences --- common/config/src/lib.rs | 147 +++++++++++++++++++++++++++---- uefi/src/main.rs | 37 ++++---- uefi/src/mode_selection.rs | 173 ++++++++++++++++++++----------------- 3 files changed, 244 insertions(+), 113 deletions(-) diff --git a/common/config/src/lib.rs b/common/config/src/lib.rs index 41a1b19b..ec36f17c 100644 --- a/common/config/src/lib.rs +++ b/common/config/src/lib.rs @@ -1,6 +1,116 @@ #![no_std] -use serde::{Deserialize, Serialize}; +use core::fmt; +use serde::{ + Deserialize, Deserializer, Serialize, Serializer, + de::{Error as DeError, SeqAccess, Visitor}, + ser::SerializeSeq, +}; + +/// Maximum number of preferred framebuffer resolutions. +pub const MAX_PREFERRED_RESOLUTIONS: usize = 16; + +/// A fixed-capacity list of preferred framebuffer resolutions. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct PreferredResolutions { + entries: [(u64, u64); MAX_PREFERRED_RESOLUTIONS], + len: usize, +} + +impl PreferredResolutions { + pub fn new() -> Self { + Self::default() + } + + pub fn push(&mut self, resolution: (u64, u64)) -> Result<(), (u64, u64)> { + if self.len == MAX_PREFERRED_RESOLUTIONS { + return Err(resolution); + } + + self.entries[self.len] = resolution; + self.len += 1; + Ok(()) + } + + pub fn iter(&self) -> core::slice::Iter<'_, (u64, u64)> { + self.entries[..self.len].iter() + } + + pub fn len(&self) -> usize { + self.len + } + + pub fn is_empty(&self) -> bool { + self.len == 0 + } +} + +impl Default for PreferredResolutions { + fn default() -> Self { + Self { + entries: [(0, 0); MAX_PREFERRED_RESOLUTIONS], + len: 0, + } + } +} + +impl Serialize for PreferredResolutions { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + let mut seq = serializer.serialize_seq(Some(self.len))?; + + for resolution in self.iter() { + seq.serialize_element(resolution)?; + } + + seq.end() + } +} + +impl<'de> Deserialize<'de> for PreferredResolutions { + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + struct PreferredResolutionsVisitor; + + impl<'de> Visitor<'de> for PreferredResolutionsVisitor { + type Value = PreferredResolutions; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + write!( + formatter, + "a list of at most {} framebuffer resolutions", + MAX_PREFERRED_RESOLUTIONS + ) + } + + fn visit_seq(self, mut seq: A) -> Result + where + A: SeqAccess<'de>, + { + let mut resolutions = PreferredResolutions::new(); + + while let Some(resolution) = seq.next_element()? { + if resolutions.len == MAX_PREFERRED_RESOLUTIONS { + return Err(A::Error::invalid_length( + MAX_PREFERRED_RESOLUTIONS + 1, + &self, + )); + } + + resolutions.push(resolution).unwrap(); + } + + Ok(resolutions) + } + } + + deserializer.deserialize_seq(PreferredResolutionsVisitor) + } +} /// Configures the boot behavior of the bootloader. #[derive(Serialize, Deserialize)] @@ -46,28 +156,33 @@ impl Default for BootConfig { #[serde(default)] #[non_exhaustive] pub struct FrameBuffer { - /// Instructs the UEFI bootloader to prefer a framebuffer at least this high. + /// Minimum framebuffer height required. /// - /// If no available mode meets the minimum, the best available mode within the - /// configured maximum dimensions is used instead. + /// Modes below this height will not be selected. pub minimum_framebuffer_height: Option, - /// Instructs the UEFI bootloader to prefer a framebuffer at least this wide. + + /// Minimum framebuffer width required. /// - /// If no available mode meets the minimum, the best available mode within the - /// configured maximum dimensions is used instead. + /// Modes below this width will not be selected. pub minimum_framebuffer_width: Option, - /// Preferred framebuffer height. Defaults to 800 pixels when unset. - /// - /// Minimum and maximum constraints take precedence over this preference. - pub preferred_framebuffer_height: Option, - /// Preferred framebuffer width. Defaults to 1280 pixels when unset. + + /// Maximum framebuffer height allowed. /// - /// Minimum and maximum constraints take precedence over this preference. - pub preferred_framebuffer_width: Option, - /// Maximum framebuffer height. Modes larger than this are not selected. + /// Modes above this height will not be selected. pub maximum_framebuffer_height: Option, - /// Maximum framebuffer width. Modes larger than this are not selected. + + /// Maximum framebuffer width allowed. + /// + /// Modes above this width will not be selected. pub maximum_framebuffer_width: Option, + + /// Preferred framebuffer resolutions, ordered from most to least preferred. + /// + /// The bootloader selects the first supported resolution satisfying + /// the configured minimum and maximum dimensions. If none match, it + /// selects the largest supported resolution satisfying those constraints. + /// At most [`MAX_PREFERRED_RESOLUTIONS`] entries are supported. + pub preferred_framebuffer_resolutions: PreferredResolutions, } /// An enum representing the available verbosity level filters of the logger. diff --git a/uefi/src/main.rs b/uefi/src/main.rs index db53a389..c51c829f 100644 --- a/uefi/src/main.rs +++ b/uefi/src/main.rs @@ -242,7 +242,7 @@ fn load_file_from_tftp_boot_server(name: &CStr8) -> Option<&'static mut [u8]> { } fn allocate_loader_data(size: usize) -> &'static mut [u8] { - let mut ptr = boot::allocate_pages( + let ptr = boot::allocate_pages( AllocateType::AnyPages, MemoryType::LOADER_DATA, ((size - 1) / 4096) + 1, @@ -356,7 +356,7 @@ fn init_logger(config: &BootConfig) -> Option { let mut gop = boot::open_protocol_exclusive::(gop_handle).ok()?; let selected_resolution = select_framebuffer_resolution( - gop.modes().map(|mode| mode.info().resolution()), + || gop.modes().map(|mode| mode.info().resolution()), config .frame_buffer .minimum_framebuffer_width @@ -375,21 +375,26 @@ fn init_logger(config: &BootConfig) -> Option { .map(|height| usize::try_from(height).unwrap()), config .frame_buffer - .preferred_framebuffer_width - .map(|width| usize::try_from(width).unwrap()), - config - .frame_buffer - .preferred_framebuffer_height - .map(|height| usize::try_from(height).unwrap()), + .preferred_framebuffer_resolutions + .iter() + .map(|(width, height)| { + ( + usize::try_from(*width).unwrap(), + usize::try_from(*height).unwrap(), + ) + }), ); - let mode = selected_resolution.and_then(|resolution| { - gop.modes() - .find(|mode| mode.info().resolution() == resolution) - }); - if let Some(mode) = mode { - gop.set_mode(&mode) - .expect("Failed to apply the desired display mode"); - } + let Some(selected_resolution) = selected_resolution else { + log::warn!("No framebuffer resolution satisfies the configured constraints"); + return None; + }; + + let mode = gop + .modes() + .find(|mode| mode.info().resolution() == selected_resolution)?; + + gop.set_mode(&mode) + .expect("Failed to apply the desired display mode"); let mode_info = gop.current_mode_info(); let mut framebuffer = gop.frame_buffer(); diff --git a/uefi/src/mode_selection.rs b/uefi/src/mode_selection.rs index 03f5b490..7f418eeb 100644 --- a/uefi/src/mode_selection.rs +++ b/uefi/src/mode_selection.rs @@ -1,69 +1,44 @@ //! Resolution selection for the UEFI Graphics Output Protocol. -const DEFAULT_PREFERRED_WIDTH: usize = 1280; -const DEFAULT_PREFERRED_HEIGHT: usize = 800; - -/// Selects the available resolution that best matches the configured constraints. +/// Selects a framebuffer resolution based on the configured constraints. /// -/// Minimum dimensions are hard lower bounds when a matching mode exists. Maximum -/// dimensions are hard upper bounds. If no mode satisfies the minimums, the -/// highest-resolution mode within the maximum dimensions is used as a fallback. -pub(crate) fn select_framebuffer_resolution( - resolutions: impl IntoIterator, +/// Minimum and maximum dimensions are hard requirements. +/// Preferred resolutions are checked in the order provided. +/// If none of the preferred resolutions are available, the largest +/// available resolution satisfying the constraints is selected. +pub(crate) fn select_framebuffer_resolution( + mut resolutions: F, minimum_width: Option, minimum_height: Option, maximum_width: Option, maximum_height: Option, - preferred_width: Option, - preferred_height: Option, -) -> Option<(usize, usize)> { - let target_width = preferred_width - .or(minimum_width) - .unwrap_or(DEFAULT_PREFERRED_WIDTH); - let target_height = preferred_height - .or(minimum_height) - .unwrap_or(DEFAULT_PREFERRED_HEIGHT); - - let mut best_fit: Option<((u128, u128, usize, usize), (usize, usize))> = None; - let mut fallback: Option<((u128, usize, usize), (usize, usize))> = None; - - for (width, height) in resolutions { - if maximum_width.is_some_and(|maximum| width > maximum) - || maximum_height.is_some_and(|maximum| height > maximum) - { - continue; - } - - let area = (width as u128) * (height as u128); - let fallback_key = (area, width, height); - if fallback - .as_ref() - .map_or(true, |(best_key, _)| fallback_key > *best_key) - { - fallback = Some((fallback_key, (width, height))); - } - - let meets_minimums = minimum_width.map_or(true, |minimum| width >= minimum) - && minimum_height.map_or(true, |minimum| height >= minimum); - if !meets_minimums { - continue; - } - - let width_delta = width.abs_diff(target_width) as u128; - let height_delta = height.abs_diff(target_height) as u128; - let distance = width_delta * width_delta + height_delta * height_delta; - let score = (distance, area, width, height); - if best_fit - .as_ref() - .map_or(true, |(best_score, _)| score < *best_score) + preferred_resolutions: P, +) -> Option<(usize, usize)> +where + I: IntoIterator, + F: FnMut() -> I, + P: IntoIterator, +{ + let is_valid = |(width, height): &(usize, usize)| { + minimum_width.map_or(true, |minimum| *width >= minimum) + && minimum_height.map_or(true, |minimum| *height >= minimum) + && maximum_width.map_or(true, |maximum| *width <= maximum) + && maximum_height.map_or(true, |maximum| *height <= maximum) + }; + + for preferred in preferred_resolutions { + if resolutions() + .into_iter() + .any(|mode| mode == preferred && is_valid(&mode)) { - best_fit = Some((score, (width, height))); + return Some(preferred); } } - best_fit - .map(|(_, resolution)| resolution) - .or_else(|| fallback.map(|(_, resolution)| resolution)) + resolutions() + .into_iter() + .filter(is_valid) + .max_by_key(|(width, height)| ((*width as u128) * (*height as u128), *width, *height)) } #[cfg(test)] @@ -71,78 +46,114 @@ mod tests { use super::select_framebuffer_resolution; #[test] - fn defaults_to_a_reasonable_resolution_instead_of_firmware_order() { - let modes = [(800, 600), (3840, 2160), (1280, 800), (1920, 1080)]; + fn selects_first_available_preferred_resolution() { + let modes = [(1280, 800), (1920, 1080), (2560, 1440)]; + let preferred = [(1920, 1080), (1280, 800)]; assert_eq!( - select_framebuffer_resolution(modes, None, None, None, None, None, None), - Some((1280, 800)) + select_framebuffer_resolution( + || modes, + None, + None, + None, + None, + preferred.iter().copied() + ), + Some((1920, 1080)) ); } #[test] - fn prefers_the_closest_mode_that_meets_minimum_dimensions() { - let modes = [(2560, 1600), (1920, 1200), (1920, 1080), (3840, 2160)]; + fn skips_unavailable_preferred_resolutions() { + let modes = [(1280, 800), (1920, 1080)]; + let preferred = [(2560, 1440), (1920, 1080)]; assert_eq!( - select_framebuffer_resolution(modes, Some(1920), Some(1080), None, None, None, None), + select_framebuffer_resolution( + || modes, + None, + None, + None, + None, + preferred.iter().copied() + ), Some((1920, 1080)) ); } #[test] - fn preferred_dimensions_are_used_as_the_target() { + fn enforces_minimum_dimensions() { let modes = [(1280, 800), (1920, 1080), (2560, 1440)]; assert_eq!( - select_framebuffer_resolution(modes, None, None, None, None, Some(1920), Some(1080)), + select_framebuffer_resolution(|| modes, Some(1920), Some(1080), None, None, []), + Some((2560, 1440)) + ); + } + + #[test] + fn enforces_maximum_dimensions() { + let modes = [(1280, 800), (1920, 1080), (2560, 1440)]; + + assert_eq!( + select_framebuffer_resolution(|| modes, None, None, Some(1920), Some(1080), []), Some((1920, 1080)) ); } #[test] - fn maximum_dimensions_are_never_exceeded() { - let modes = [(1280, 800), (1920, 1080), (2560, 1600)]; + fn falls_back_to_largest_valid_resolution() { + let modes = [(800, 600), (1280, 800), (1920, 1080)]; + let preferred = [(2560, 1440)]; assert_eq!( select_framebuffer_resolution( - modes, + || modes, None, None, - Some(1920), - Some(1080), - Some(1920), - Some(1080) + None, + None, + preferred.iter().copied() ), Some((1920, 1080)) ); } #[test] - fn falls_back_to_the_largest_mode_within_maximum_dimensions() { - let modes = [(800, 600), (1280, 800), (1920, 1080), (2560, 1440)]; + fn returns_none_when_no_resolution_satisfies_constraints() { + let modes = [(1280, 800), (1920, 1080)]; + + assert_eq!( + select_framebuffer_resolution(|| modes, Some(2560), None, None, None, []), + None + ); + } + + #[test] + fn skips_preferred_resolution_that_violates_constraints() { + let modes = [(1280, 800), (1920, 1080), (2560, 1440)]; + let preferred = [(1280, 800), (1920, 1080)]; assert_eq!( select_framebuffer_resolution( - modes, - Some(3840), - Some(2160), + || modes, Some(1920), Some(1080), None, - None + None, + preferred.iter().copied(), ), Some((1920, 1080)) ); } #[test] - fn returns_none_when_no_mode_satisfies_maximum_dimensions() { - let modes = [(1920, 1080), (2560, 1440)]; + fn uses_deterministic_tiebreaker_for_equal_area_resolutions() { + let modes = [(1600, 900), (1200, 1200)]; assert_eq!( - select_framebuffer_resolution(modes, None, None, Some(1280), Some(800), None, None), - None + select_framebuffer_resolution(|| modes, None, None, None, None, []), + Some((1600, 900)) ); } }