diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml index 486faf3..1a61caf 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.yml +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -37,7 +37,7 @@ body: id: version attributes: label: drmcru version or commit - placeholder: "0.1.3 or commit hash" + placeholder: "0.1.4 or commit hash" validations: required: true - type: textarea diff --git a/Cargo.lock b/Cargo.lock index 10e1b9d..0e4474b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -117,7 +117,7 @@ dependencies = [ [[package]] name = "drmcru" -version = "0.1.3" +version = "0.1.4" dependencies = [ "anyhow", "crossterm", diff --git a/Cargo.toml b/Cargo.toml index 0a72ff8..27bc3e8 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "drmcru" -version = "0.1.3" +version = "0.1.4" edition = "2024" rust-version = "1.87" description = "Linux DRM/KMS custom resolution and EDID override utility" diff --git a/README.md b/README.md index f6e302b..ae1a0b4 100644 --- a/README.md +++ b/README.md @@ -34,15 +34,15 @@ yay -S drmcru-bin ``` Download the portable x86-64 binary from the -[latest release](https://github.com/ssupt/drmcru/releases/tag/v0.1.3): +[latest release](https://github.com/ssupt/drmcru/releases/tag/v0.1.4): ```sh -curl -LO https://github.com/ssupt/drmcru/releases/download/v0.1.3/drmcru-0.1.3-x86_64-unknown-linux-musl -curl -LO https://github.com/ssupt/drmcru/releases/download/v0.1.3/SHA256SUMS +curl -LO https://github.com/ssupt/drmcru/releases/download/v0.1.4/drmcru-0.1.4-x86_64-unknown-linux-musl +curl -LO https://github.com/ssupt/drmcru/releases/download/v0.1.4/SHA256SUMS sha256sum -c --ignore-missing SHA256SUMS -chmod +x drmcru-0.1.3-x86_64-unknown-linux-musl -./drmcru-0.1.3-x86_64-unknown-linux-musl doctor -./drmcru-0.1.3-x86_64-unknown-linux-musl +chmod +x drmcru-0.1.4-x86_64-unknown-linux-musl +./drmcru-0.1.4-x86_64-unknown-linux-musl doctor +./drmcru-0.1.4-x86_64-unknown-linux-musl ``` The TUI and manual Export work on Linux systems that expose connectors through @@ -100,6 +100,21 @@ new EDID mode appear. - Base-block detailed timing descriptors - Base-block standard timings - CTA-861 extension detailed timing descriptors +- EDID 1.4 range-limits-only VRR descriptors (minimum and maximum refresh) + +Choose **VRR range** or press `Shift+R` to edit an existing advertised range. +For example, change `24–120 Hz` to `40–120 Hz` when the monitor cannot operate +reliably below 40 Hz. Export or Install/Update the override and reboot to apply. +The editor preserves horizontal limits and other descriptor data and supports +whole Hz from 1 to 510. It requires a continuous-frequency EDID with an existing +range-limits-only descriptor, as used by Linux DRM for DisplayPort VRR. HDMI +FreeSync/Forum and DisplayID VRR blocks are currently read-only; the editor +does not add VRR support to a monitor that does not advertise it. + +Export and Install/Update clear stereo flags from all base and CTA detailed +resolutions and repair the affected checksums. This also works when clearing +stereo flags is the only pending change. Sync polarity, interlace, physical +dimensions, and unrelated descriptors and extension data are preserved. DisplayID Type I detailed timings are decoded and can be copied into an editable EDID DTD. DisplayID blocks themselves are currently read-only. diff --git a/packaging/aur/drmcru-bin/.SRCINFO b/packaging/aur/drmcru-bin/.SRCINFO index 3b4a146..f4cf3e9 100644 --- a/packaging/aur/drmcru-bin/.SRCINFO +++ b/packaging/aur/drmcru-bin/.SRCINFO @@ -1,6 +1,6 @@ pkgbase = drmcru-bin pkgdesc = Linux DRM/KMS custom resolution and EDID override utility - pkgver = 0.1.3 + pkgver = 0.1.4 pkgrel = 1 url = https://github.com/ssupt/drmcru arch = x86_64 @@ -10,11 +10,11 @@ pkgbase = drmcru-bin optdepends = mkinitcpio: initramfs integration for automatic Apply/Uninstall optdepends = limine: supported bootloader for automatic Apply/Uninstall optdepends = limine-mkinitcpio: Limine entry regeneration on Omarchy-style systems - provides = drmcru=0.1.3 + provides = drmcru=0.1.4 conflicts = drmcru options = !strip options = !debug - source_x86_64 = drmcru-0.1.3::https://github.com/ssupt/drmcru/releases/download/v0.1.3/drmcru-0.1.3-x86_64-unknown-linux-musl - sha256sums_x86_64 = 8507a68e93ab9846e31a7d90644b4307e3bf7198737f999db337163cc44fa29b + source_x86_64 = drmcru-0.1.4::https://github.com/ssupt/drmcru/releases/download/v0.1.4/drmcru-0.1.4-x86_64-unknown-linux-musl + sha256sums_x86_64 = 601fe35c1bc57a5d27828e782183fd244b777709e9b2412a55c09a67607a953b pkgname = drmcru-bin diff --git a/packaging/aur/drmcru-bin/PKGBUILD b/packaging/aur/drmcru-bin/PKGBUILD index 3dedd96..3bd937c 100644 --- a/packaging/aur/drmcru-bin/PKGBUILD +++ b/packaging/aur/drmcru-bin/PKGBUILD @@ -2,7 +2,7 @@ pkgname=drmcru-bin _pkgname=drmcru -pkgver=0.1.3 +pkgver=0.1.4 pkgrel=1 pkgdesc="Linux DRM/KMS custom resolution and EDID override utility" arch=('x86_64') @@ -19,7 +19,7 @@ optdepends=( ) options=('!strip' '!debug') source_x86_64=("${_pkgname}-${pkgver}::${url}/releases/download/v${pkgver}/${_pkgname}-${pkgver}-x86_64-unknown-linux-musl") -sha256sums_x86_64=('8507a68e93ab9846e31a7d90644b4307e3bf7198737f999db337163cc44fa29b') +sha256sums_x86_64=('601fe35c1bc57a5d27828e782183fd244b777709e9b2412a55c09a67607a953b') package() { install -Dm755 "${srcdir}/${_pkgname}-${pkgver}" "${pkgdir}/usr/bin/${_pkgname}" diff --git a/src/demo.rs b/src/demo.rs index ae72a48..7194755 100644 --- a/src/demo.rs +++ b/src/demo.rs @@ -52,7 +52,7 @@ fn sample_edid() -> Result> { base[21] = 60; base[22] = 34; base[23] = 120; - base[24] = 0x0a; + base[24] = 0x0b; base[35] = 1 << 5; base[36] = 1 << 3; base[38..54].fill(0x01); @@ -78,17 +78,16 @@ fn sample_edid() -> Result> { base[offset..offset + 2].copy_from_slice(&encoded); } - for (slot, timing) in [ - timing_1440p(144.0), - timing_1440p(120.0), - timing_1080p(120.0), - ] - .iter() - .enumerate() + for (slot, timing) in [timing_1440p(144.0), timing_1440p(120.0)] + .iter() + .enumerate() { let offset = 54 + slot * DTD_LEN; base[offset..offset + DTD_LEN].copy_from_slice(&encode_detailed_timing(timing)?); } + base[90..108].copy_from_slice(&[ + 0, 0, 0, 0xfd, 0, 48, 144, 30, 220, 60, 1, 10, 0, 0, 0, 0, 0, 0, + ]); write_name_descriptor(&mut base[108..126], "Example Display"); base[126] = 1; repair_checksum(base); @@ -100,6 +99,8 @@ fn sample_edid() -> Result> { cta[4] = (2 << 5) | 4; cta[5..9].copy_from_slice(&[0x80 | 16, 4, 64, 97]); cta[9..9 + DTD_LEN].copy_from_slice(&encode_detailed_timing(&timing_1080p(60.0))?); + cta[9 + DTD_LEN..9 + 2 * DTD_LEN] + .copy_from_slice(&encode_detailed_timing(&timing_1080p(120.0))?); repair_checksum(cta); Ok(raw) @@ -188,6 +189,13 @@ mod tests { assert!(monitor.hyprland.as_ref().unwrap().serial.is_none()); assert!(edid.checksum_valid); assert!(edid.cta_blocks[0].checksum_valid); + assert_eq!( + crate::edid::vrr_range(&edid.raw).unwrap(), + crate::edid::VrrRange { + min_hz: 48, + max_hz: 144 + } + ); assert_eq!(edid.monitor_name.as_deref(), Some("Example Displ")); } } diff --git a/src/edid.rs b/src/edid.rs index 2222e5e..7528c86 100644 --- a/src/edid.rs +++ b/src/edid.rs @@ -27,6 +27,68 @@ pub enum EdidError { NoAvailableDetailedTimingSlot, #[error("no empty standard timing slot is available")] NoAvailableStandardTimingSlot, + #[error( + "no EDID 1.4 range-limits-only VRR descriptor is available; HDMI and DisplayID VRR blocks are not editable" + )] + NoVrrRange, + #[error("VRR limits must be whole Hz between 1 and 510, with minimum <= maximum")] + InvalidVrrRange, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct VrrRange { + pub min_hz: u16, + pub max_hz: u16, +} + +fn vrr_descriptor_offsets(raw: &[u8]) -> Result, EdidError> { + if raw.len() < BASE_BLOCK_LEN { + return Err(EdidError::TooShort(raw.len())); + } + if raw[..8] != HEADER { + return Err(EdidError::InvalidHeader); + } + // Match DRM's monitor-range requirements without inventing VRR support. + if raw[18] != 1 || raw[19] < 4 || raw[24] & 1 == 0 { + return Err(EdidError::NoVrrRange); + } + let offsets: Vec<_> = (0..DTD_SLOTS) + .map(|slot| DTD_START + slot * DTD_LEN) + .filter(|&offset| { + let descriptor = &raw[offset..offset + DTD_LEN]; + descriptor[..4] == [0, 0, 0, 0xfd] && descriptor[10] == 1 + }) + .collect(); + if offsets.is_empty() { + return Err(EdidError::NoVrrRange); + } + Ok(offsets) +} + +pub fn vrr_range(raw: &[u8]) -> Result { + let offset = vrr_descriptor_offsets(raw)?[0]; + let descriptor = &raw[offset..offset + DTD_LEN]; + Ok(VrrRange { + min_hz: u16::from(descriptor[5]) + if descriptor[4] & 1 != 0 { 255 } else { 0 }, + max_hz: u16::from(descriptor[6]) + if descriptor[4] & 2 != 0 { 255 } else { 0 }, + }) +} + +pub fn patch_vrr_range(raw: &[u8], range: VrrRange) -> Result, EdidError> { + if range.min_hz == 0 || range.min_hz > range.max_hz || range.max_hz > 510 { + return Err(EdidError::InvalidVrrRange); + } + let offsets = vrr_descriptor_offsets(raw)?; + let mut patched = raw.to_vec(); + for offset in offsets { + patched[offset + 4] = (patched[offset + 4] & !0x03) + | u8::from(range.min_hz > 255) + | (u8::from(range.max_hz > 255) << 1); + patched[offset + 5] = (range.min_hz - if range.min_hz > 255 { 255 } else { 0 }) as u8; + patched[offset + 6] = (range.max_hz - if range.max_hz > 255 { 255 } else { 0 }) as u8; + } + repair_block_checksum(&mut patched[..BASE_BLOCK_LEN]); + Ok(patched) } const HEADER: [u8; 8] = [0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00]; @@ -409,6 +471,22 @@ pub fn delete_detailed_timing(raw: &[u8], location: DtdLocation) -> Result Result, EdidError> { + let (first_offset, first_block) = dtd_offset(raw, first)?; + let (second_offset, second_block) = dtd_offset(raw, second)?; + let mut patched = raw.to_vec(); + for index in 0..DTD_LEN { + patched.swap(first_offset + index, second_offset + index); + } + repair_block_checksum(&mut patched[first_block..first_block + EDID_BLOCK_LEN]); + repair_block_checksum(&mut patched[second_block..second_block + EDID_BLOCK_LEN]); + Ok(patched) +} + #[cfg(test)] pub fn patch_base_detailed_timing( raw: &[u8], @@ -610,6 +688,11 @@ pub fn encode_standard_timing( StandardTimingAspect::SixteenNine => 0b11, }; let refresh_bits = (timing.refresh_hz - 60) as u8; + if width_byte == 0x01 && aspect_bits == 0 && refresh_bits == 0x01 { + return Err(EdidError::InvalidStandardTiming( + "256x160 at 61 Hz encodes the unused-slot marker", + )); + } Ok([width_byte, aspect_bits << 6 | refresh_bits]) } @@ -626,6 +709,43 @@ fn repair_block_checksum(block: &mut [u8]) { block[last] = 0u8.wrapping_sub(sum_without_checksum); } +/// Remove stereoscopic DTD flags from a desktop EDID override. Preserve sync, +/// interlace, monitor descriptors, data blocks, and unsupported extensions. +pub fn clear_detailed_timing_stereo(raw: &mut [u8]) -> usize { + if raw.len() < BASE_BLOCK_LEN || raw[..8] != HEADER { + return 0; + } + let extension_blocks = raw[126]; + let mut cleared = 0; + for (index, block) in raw.chunks_exact_mut(EDID_BLOCK_LEN).enumerate() { + if index > usize::from(extension_blocks) { + break; + } + let range = if index == 0 { + DTD_START..126 + } else if block[0] == CTA_TAG { + let Some(range) = cta_dtd_range(block) else { + continue; + }; + range + } else { + continue; + }; + let mut changed = false; + for descriptor in block[range].chunks_exact_mut(DTD_LEN) { + if (descriptor[0] != 0 || descriptor[1] != 0) && descriptor[17] & 0x61 != 0 { + descriptor[17] &= !0x61; + cleared += 1; + changed = true; + } + } + if changed { + repair_block_checksum(block); + } + } + cleared +} + fn validate_12_bit(field: &'static str, value: u16) -> Result<(), EdidError> { validate_max(field, value, 0x0fff) } @@ -716,7 +836,10 @@ fn parse_displayid_block(extension_index: u8, block: &[u8]) -> Option Vec { payload .iter() .map(|descriptor| { - let native = descriptor & 0x80 != 0; - let vic = u16::from(descriptor & 0x7f); + let native = (129..=192).contains(descriptor); + let vic = u16::from(if native { + descriptor & 0x7f + } else { + *descriptor + }); cta_vic_mode(vic, native) .map(CtaVideoDescriptor::Known) .unwrap_or(CtaVideoDescriptor::Unknown { vic, native }) @@ -1246,6 +1373,170 @@ mod tests { )); } + fn sample_vrr_edid() -> Vec { + let mut raw = minimal_base_edid(0); + raw[18] = 1; + raw[19] = 4; + raw[24] |= 1; + raw[54..72].copy_from_slice(&[ + 0, 0, 0, 0xfd, 0x0c, 24, 120, 30, 200, 60, 1, 10, 0, 0, 0, 0, 0, 0, + ]); + repair_block_checksum(&mut raw); + raw + } + + #[test] + fn edits_vrr_range_and_preserves_other_limits() { + let raw = sample_vrr_edid(); + assert_eq!( + vrr_range(&raw).unwrap(), + VrrRange { + min_hz: 24, + max_hz: 120 + } + ); + for range in [ + VrrRange { + min_hz: 40, + max_hz: 120, + }, + VrrRange { + min_hz: 255, + max_hz: 256, + }, + VrrRange { + min_hz: 300, + max_hz: 510, + }, + ] { + let patched = patch_vrr_range(&raw, range).unwrap(); + assert_eq!(vrr_range(&patched).unwrap(), range); + assert_eq!(patched[58] & 0x0c, 0x0c); + assert!(block_checksum_valid(&patched)); + for index in 0..raw.len() { + if ![58, 59, 60, 127].contains(&index) { + assert_eq!(patched[index], raw[index]); + } + } + let lowered = patch_vrr_range( + &patched, + VrrRange { + min_hz: 40, + max_hz: 120, + }, + ) + .unwrap(); + assert_eq!(lowered[58], 0x0c); + } + } + + #[test] + fn vrr_edits_reject_invalid_ranges_and_unadvertised_capabilities() { + let raw = sample_vrr_edid(); + for range in [ + VrrRange { + min_hz: 0, + max_hz: 120, + }, + VrrRange { + min_hz: 121, + max_hz: 120, + }, + VrrRange { + min_hz: 40, + max_hz: 511, + }, + ] { + assert!(matches!( + patch_vrr_range(&raw, range), + Err(EdidError::InvalidVrrRange) + )); + } + for (index, value) in [(18, 2), (19, 3), (24, 0), (57, 0xfc), (64, 0)] { + let mut unsupported = raw.clone(); + unsupported[index] = value; + assert!(matches!( + vrr_range(&unsupported), + Err(EdidError::NoVrrRange) + )); + } + assert!(matches!( + vrr_range(&raw[..127]), + Err(EdidError::TooShort(127)) + )); + } + + #[test] + fn clears_all_stereo_encodings_without_changing_other_dtd_fields() { + for stereo in [0x01, 0x20, 0x21, 0x40, 0x41, 0x60, 0x61] { + let mut raw = minimal_base_edid(1); + let mut descriptor = encode_detailed_timing(&sample_timing()).unwrap(); + descriptor[17] = 0x9e | stereo; + raw[54..72].copy_from_slice(&descriptor); + // A monitor descriptor's last byte is text, not timing flags. + raw[75] = 0xfc; + raw[89] = 0x61; + repair_block_checksum(&mut raw); + let mut cta = vec![0; 128]; + cta[0] = CTA_TAG; + cta[1] = 3; + cta[2] = 8; + cta[4..8].copy_from_slice(&[0x63, 0x61, 0x61, 0x61]); + cta[8..26].copy_from_slice(&descriptor); + repair_block_checksum(&mut cta); + raw.extend_from_slice(&cta); + let before = raw.clone(); + assert_eq!(clear_detailed_timing_stereo(&mut raw), 2); + assert_eq!(raw[71], 0x9e); + assert_eq!(raw[153], 0x9e); + for index in 0..raw.len() { + if ![71, 127, 153, 255].contains(&index) { + assert_eq!(raw[index], before[index]); + } + } + assert!(raw.chunks_exact(128).all(block_checksum_valid)); + assert_eq!(clear_detailed_timing_stereo(&mut raw), 0); + } + } + + #[test] + fn displayid_product_id_does_not_hide_following_timings() { + let mut edid = minimal_base_edid(1); + let mut block = [0u8; 128]; + block[0] = DISPLAYID_TAG; + block[1] = 0x13; + block[2] = 30; + block[5..12].copy_from_slice(&[0, 0, 4, 1, 2, 3, 4]); + block[12..15].copy_from_slice(&[3, 1, 20]); + block[15..35].copy_from_slice(&[ + 0x19, 0x13, 0x01, 0x84, 0xff, 0x09, 0xaf, 0x00, 0x2f, 0x00, 0x1f, 0x00, 0x9f, 0x05, + 0x77, 0x00, 0x02, 0x00, 0x05, 0x00, + ]); + repair_block_checksum(&mut block); + edid.extend_from_slice(&block); + let parsed = parse_edid(edid).unwrap(); + let displayid = &parsed.displayid_blocks[0]; + assert_eq!(displayid.data_blocks.len(), 2); + assert_eq!(displayid.data_blocks[0].label(), "Product ID"); + assert_eq!(displayid.detailed_timings.len(), 1); + } + + #[test] + fn cta_extended_video_codes_do_not_alias_legacy_native_modes() { + assert_eq!( + parse_cta_video_modes(&[193]), + vec![CtaVideoDescriptor::Unknown { + vic: 193, + native: false + }] + ); + let CtaVideoDescriptor::Known(mode) = &parse_cta_video_modes(&[144])[0] else { + panic!("native VIC 16 should be mapped"); + }; + assert_eq!(mode.vic, 16); + assert!(mode.native); + } + #[test] fn parses_and_deletes_standard_timing() { let mut edid = minimal_base_edid(0); @@ -1322,6 +1613,18 @@ mod tests { )); } + #[test] + fn standard_timing_cannot_encode_the_unused_slot_marker() { + let timing = StandardTiming { + slot: 0, + width: 256, + height: 160, + refresh_hz: 61, + aspect: StandardTimingAspect::SixteenTen, + }; + assert!(encode_standard_timing(&timing).is_err()); + } + #[test] fn reports_available_base_standard_and_cta_slots() { let timing = sample_timing(); diff --git a/src/export.rs b/src/export.rs index c5a5ceb..eee9a52 100644 --- a/src/export.rs +++ b/src/export.rs @@ -48,7 +48,8 @@ pub fn export_patched_edid( output_dir: &Path, ) -> Result { let edid = monitor.edid.as_ref().ok_or(ExportError::MissingEdid)?; - let (patched, insert_location) = insert_detailed_timing(&edid.raw, timing)?; + let (mut patched, insert_location) = insert_detailed_timing(&edid.raw, timing)?; + crate::edid::clear_detailed_timing_stereo(&mut patched); let file_name = custom_edid_file_name(&monitor.connector); let path = output_dir.join(&file_name); let instructions_path = output_dir.join(instructions_file_name(&monitor.connector)); @@ -270,6 +271,51 @@ mod tests { assert!(instructions.contains(",auto,1")); } + #[test] + fn both_export_paths_clear_existing_stereo_flags() { + let monitor = crate::demo::monitors().unwrap().remove(0); + let mut monitor = monitor; + let mut raw = monitor.edid.as_ref().unwrap().raw.clone(); + raw[71] |= 0x61; + raw[154] |= 0x61; + // Repair fixture checksums before exercising validation and export. + for block in raw.chunks_exact_mut(128) { + block[127] = 0u8.wrapping_sub( + block[..127] + .iter() + .fold(0u8, |sum, byte| sum.wrapping_add(*byte)), + ); + } + monitor.edid = Some(crate::edid::parse_edid(raw.clone()).unwrap()); + let directory = std::env::temp_dir().join(format!( + "drmcru-export-{}-{}", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + fs::create_dir(&directory).unwrap(); + let workspace = EdidWorkspace::new(raw).unwrap(); + for workspace_export in [true, false] { + let result = if workspace_export { + export_workspace_edid(&monitor, &workspace, "2560x1440@144", &directory) + } else { + export_patched_edid(&monitor, &sample_timing(), &directory) + }; + let result = result.unwrap(); + let bytes = fs::read(result.path).unwrap(); + assert_eq!(bytes[71] & 0x61, 0); + assert_eq!(bytes[154] & 0x61, 0); + assert!( + bytes + .chunks_exact(128) + .all(crate::edid::block_checksum_valid) + ); + } + fs::remove_dir_all(directory).unwrap(); + } + #[test] fn instructions_shell_quote_generated_path() { let plan = build_export_plan_with_file("DP-1", "custom.bin", sample_timing()); diff --git a/src/hyprland_config.rs b/src/hyprland_config.rs index 9474b40..f1dc66e 100644 --- a/src/hyprland_config.rs +++ b/src/hyprland_config.rs @@ -175,7 +175,9 @@ fn lua_string(value: &str) -> String { #[derive(Default)] struct ConfigParser { + // Only active includes are guarded; source/dofile can load a file again. seen: BTreeSet, + required: BTreeSet, files_read: usize, monitor_rules: Vec, read_warnings: Vec, @@ -185,7 +187,7 @@ impl ConfigParser { fn read_file(&mut self, path: &Path) { let display_path = path.to_path_buf(); let seen_path = fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf()); - if !self.seen.insert(seen_path) { + if !self.seen.insert(seen_path.clone()) { return; } @@ -194,6 +196,7 @@ impl ConfigParser { Err(error) => { self.read_warnings .push(format!("Could not read {}: {error}", human_path(path))); + self.seen.remove(&seen_path); return; } }; @@ -228,11 +231,16 @@ impl ConfigParser { continue; }; if let Some(source) = resolve_lua_require(&module, &display_path) { - self.read_file(&source); + let module_path = + fs::canonicalize(&source).unwrap_or_else(|_| source.clone()); + if self.required.insert(module_path) { + self.read_file(&source); + } } } } } + self.seen.remove(&seen_path); return; } @@ -265,6 +273,7 @@ impl ConfigParser { _ => {} } } + self.seen.remove(&seen_path); } } @@ -549,10 +558,15 @@ fn strip_lua_comments(contents: &str) -> String { } fn parse_literal_lua_call_argument(raw: &str) -> Option { + let cleaned = strip_lua_comments(raw); + let raw = cleaned.as_str(); let open = raw.find('(')?; let value = raw.get(open + 1..raw.len().checked_sub(1)?)?.trim(); let quote = *value.as_bytes().first()?; - if !matches!(quote, b'\'' | b'"') || value.as_bytes().last() != Some("e) { + if !matches!(quote, b'\'' | b'"') + || value.as_bytes().last() != Some("e) + || skip_quoted_lua_string(value.as_bytes(), 0) != value.len() + { return None; } @@ -845,6 +859,55 @@ mod tests { )) } + #[test] + fn repeated_source_and_dofile_preserve_load_order_but_require_is_cached() { + for extension in ["conf", "lua"] { + let dir = unique_test_dir(); + fs::create_dir_all(&dir).unwrap(); + let root = dir.join(format!("hyprland.{extension}")); + let source = dir.join(format!("monitors.{extension}")); + let rule = "monitor=DP-1,1920x1080@60,auto,1"; + if extension == "conf" { + fs::write(&source, format!("{rule}\nsource=hyprland.conf\n")).unwrap(); + fs::write(&root, "source=monitors.conf\nmonitor=DP-1,1920x1080@144,auto,1\nsource=monitors.conf\n").unwrap(); + } else { + fs::write(&source, "hl.monitor({output='DP-1', mode='1920x1080@60', position='auto', scale=1})\ndofile('hyprland.lua')\n").unwrap(); + fs::write(&root, "dofile('monitors.lua')\nhl.monitor({output='DP-1', mode='1920x1080@144', position='auto', scale=1})\ndofile('monitors.lua')\n").unwrap(); + } + let report = inspect_monitor_rule_from(root.clone(), "DP-1", rule); + assert_eq!(report.connector_rules.len(), 3); + assert!(report.exact_match_is_effective()); + if extension == "lua" { + fs::write( + &source, + "hl.monitor({output='DP-1', mode='1920x1080@60', position='auto', scale=1})\n", + ) + .unwrap(); + fs::write(&root, "require('monitors')\nhl.monitor({output='DP-1', mode='1920x1080@144', position='auto', scale=1})\nrequire('monitors')\n").unwrap(); + let report = inspect_monitor_rule_from(root, "DP-1", rule); + assert_eq!(report.connector_rules.len(), 2); + assert!(!report.exact_match_is_effective()); + } + let _ = fs::remove_dir_all(dir); + } + } + + #[test] + fn literal_lua_arguments_reject_concatenation_and_accept_comments() { + assert_eq!( + parse_literal_lua_call_argument("dofile('monitors.lua' -- comment\n)"), + Some("monitors.lua".to_string()) + ); + assert_eq!( + parse_literal_lua_call_argument("dofile('monitors' .. '.lua')"), + None + ); + assert_eq!( + parse_literal_lua_call_argument("require('hypr.' .. module .. '.lua')"), + None + ); + } + #[test] fn parses_literal_monitor_rule() { let rule = parse_monitor_rule( diff --git a/src/install.rs b/src/install.rs index 1116833..3442e28 100644 --- a/src/install.rs +++ b/src/install.rs @@ -651,6 +651,7 @@ fn yes_no(value: bool) -> &'static str { /// Build the idempotent bash install script. pub fn build_install_script(plan: &InstallPlan) -> String { + let files_awk = include_str!("mkinitcpio_files.awk"); let edid_source = shell_quote(&plan.edid_source.display().to_string()); let firmware_target = shell_quote(&plan.firmware_target().display().to_string()); let kernel_param = shell_quote(&plan.kernel_parameter); @@ -659,7 +660,7 @@ pub fn build_install_script(plan: &InstallPlan) -> String { // The script is idempotent and validates the supported stack before mutating files. format!( r##"#!/bin/bash -set -euo pipefail +set -Eeuo pipefail echo "=== drmcru: installing custom EDID ===" @@ -760,29 +761,12 @@ echo "[OK] Installed EDID to $FIRMWARE_TARGET" # 2. Patch /etc/mkinitcpio.conf — add EDID to FILES if not already present if [ -f "$MKINIT" ]; then - if grep -qF -- "$FIRMWARE_TARGET" "$MKINIT" 2>/dev/null; then - echo "[OK] EDID already in mkinitcpio FILES (skipped)" - else - backup_file "$MKINIT" - TMP="$(mktemp /tmp/drmcru-mkinitcpio.XXXXXX)" - awk -v path="$FIRMWARE_TARGET" ' - BEGIN {{ inserted = 0 }} - /^[[:space:]]*FILES=\(/ && !inserted {{ - sub(/\(/, "(" path " ") - inserted = 1 - }} - {{ print }} - END {{ - if (!inserted) {{ - print "" - print "FILES=(" path ")" - }} - }} - ' "$MKINIT" > "$TMP" - cat "$TMP" > "$MKINIT" - rm -f "$TMP" - echo "[OK] Added EDID to mkinitcpio FILES" - fi + backup_file "$MKINIT" + TMP="$(mktemp /tmp/drmcru-mkinitcpio.XXXXXX)" + awk -v path="$FIRMWARE_TARGET" -v operation=add '{files_awk}' "$MKINIT" > "$TMP" + cat "$TMP" > "$MKINIT" + rm -f "$TMP" + echo "[OK] Ensured EDID is in mkinitcpio FILES" else echo "[ERR] /etc/mkinitcpio.conf not found — automatic Apply supports mkinitcpio only" >&2 exit 1 @@ -803,20 +787,25 @@ if command -v limine-mkinitcpio >/dev/null 2>&1; then mappings[++mapping_count] = mapping }} /^[[:space:]]*KERNEL_CMDLINE\[default\]\+=/ && index($0, "drm.edid_firmware=") > 0 {{ - value = substr($0, index($0, "drm.edid_firmware=") + length("drm.edid_firmware=")) - sub(/[\"[:space:]].*$/, "", value) - count = split(value, values, ",") - for (i = 1; i <= count; i++) - add_mapping(values[i]) + line = $0 + while (match(line, /drm.edid_firmware=[^\"\047[:space:]]*/)) {{ + value = substr(line, RSTART + length("drm.edid_firmware="), RLENGTH - length("drm.edid_firmware=")) + line = substr(line, 1, RSTART - 1) substr(line, RSTART + RLENGTH) + count = split(value, values, ",") + for (i = 1; i <= count; i++) + add_mapping(values[i]) + }} + if (line !~ /^[[:space:]]*KERNEL_CMDLINE\[default\]\+=[\"\047][[:space:]]*[\"\047][[:space:]]*$/) + print line next }} {{ print }} END {{ desired = substr(param, length("drm.edid_firmware=") + 1) - add_mapping(desired) combined = "" for (i = 1; i <= mapping_count; i++) combined = combined (combined == "" ? "" : ",") mappings[i] + combined = combined (combined == "" ? "" : ",") desired print "KERNEL_CMDLINE[default]+=\" drm.edid_firmware=" combined "\"" }} ' "$LIMINE_DROPIN" > "$TMP" @@ -853,21 +842,24 @@ if [ -f "$LIMINE" ]; then mapping_count = 0 prefix = substr($0, 1, index($0, ":")) other = "" - for (i = 2; i <= NF; i++) {{ - if (index($i, "drm.edid_firmware=") == 1) {{ - value = substr($i, length("drm.edid_firmware=") + 1) + token_count = split(substr($0, index($0, ":") + 1), tokens, /[[:space:]]+/) + for (i = 1; i <= token_count; i++) {{ + if (tokens[i] == "") + continue + if (index(tokens[i], "drm.edid_firmware=") == 1) {{ + value = substr(tokens[i], length("drm.edid_firmware=") + 1) count = split(value, values, ",") for (j = 1; j <= count; j++) add_mapping(values[j]) }} else {{ - other = other (other == "" ? "" : " ") $i + other = other (other == "" ? "" : " ") tokens[i] }} }} desired = substr(param, length("drm.edid_firmware=") + 1) - add_mapping(desired) combined = "" for (i = 1; i <= mapping_count; i++) combined = combined (combined == "" ? "" : ",") mappings[i] + combined = combined (combined == "" ? "" : ",") desired print prefix (other == "" ? "" : " " other) " drm.edid_firmware=" combined next }} @@ -913,13 +905,14 @@ fn shell_quote(value: &str) -> String { /// Build the idempotent bash uninstall script. pub fn build_uninstall_script(plan: &UninstallPlan) -> String { + let files_awk = include_str!("mkinitcpio_files.awk"); let firmware_target = shell_quote(&plan.firmware_target().display().to_string()); let kernel_param = shell_quote(&plan.kernel_parameter); let connector = shell_quote(&plan.connector); format!( r##"#!/bin/bash -set -euo pipefail +set -Eeuo pipefail echo "=== drmcru: uninstalling custom EDID ===" @@ -1004,17 +997,7 @@ if [ -f "$MKINIT" ]; then if grep -qF -- "$FIRMWARE_TARGET" "$MKINIT" 2>/dev/null; then backup_file "$MKINIT" TMP="$(mktemp /tmp/drmcru-mkinitcpio.XXXXXX)" - awk -v path="$FIRMWARE_TARGET" ' - /^[[:space:]]*FILES=\(/ {{ - while ((pos = index($0, path)) > 0) {{ - before = substr($0, 1, pos - 1) - after = substr($0, pos + length(path)) - sub(/^[[:space:]]+/, "", after) - $0 = before after - }} - }} - {{ print }} - ' "$MKINIT" > "$TMP" + awk -v path="$FIRMWARE_TARGET" -v operation=remove '{files_awk}' "$MKINIT" > "$TMP" cat "$TMP" > "$MKINIT" rm -f "$TMP" echo "[OK] Removed EDID from mkinitcpio FILES" @@ -1039,11 +1022,16 @@ if [ -f "$LIMINE_DROPIN" ]; then mappings[++mapping_count] = mapping }} /^[[:space:]]*KERNEL_CMDLINE\[default\]\+=/ && index($0, "drm.edid_firmware=") > 0 {{ - value = substr($0, index($0, "drm.edid_firmware=") + length("drm.edid_firmware=")) - sub(/[\"[:space:]].*$/, "", value) - count = split(value, values, ",") - for (i = 1; i <= count; i++) - add_mapping(values[i]) + line = $0 + while (match(line, /drm.edid_firmware=[^\"\047[:space:]]*/)) {{ + value = substr(line, RSTART + length("drm.edid_firmware="), RLENGTH - length("drm.edid_firmware=")) + line = substr(line, 1, RSTART - 1) substr(line, RSTART + RLENGTH) + count = split(value, values, ",") + for (i = 1; i <= count; i++) + add_mapping(values[i]) + }} + if (line !~ /^[[:space:]]*KERNEL_CMDLINE\[default\]\+=[\"\047][[:space:]]*[\"\047][[:space:]]*$/) + print line next }} {{ print }} @@ -1090,14 +1078,17 @@ if [ -f "$LIMINE" ]; then mapping_count = 0 prefix = substr($0, 1, index($0, ":")) other = "" - for (i = 2; i <= NF; i++) {{ - if (index($i, "drm.edid_firmware=") == 1) {{ - value = substr($i, length("drm.edid_firmware=") + 1) + token_count = split(substr($0, index($0, ":") + 1), tokens, /[[:space:]]+/) + for (i = 1; i <= token_count; i++) {{ + if (tokens[i] == "") + continue + if (index(tokens[i], "drm.edid_firmware=") == 1) {{ + value = substr(tokens[i], length("drm.edid_firmware=") + 1) count = split(value, values, ",") for (j = 1; j <= count; j++) add_mapping(values[j]) }} else {{ - other = other (other == "" ? "" : " ") $i + other = other (other == "" ? "" : " ") tokens[i] }} }} combined = "" @@ -1288,6 +1279,265 @@ mod tests { std::env::temp_dir().join(format!("drmcru-install-test-{}-{now}", std::process::id())) } + struct ScriptFixture { + dir: PathBuf, + } + + impl ScriptFixture { + fn new() -> Self { + let dir = unique_test_dir(); + fs::create_dir_all(dir.join("bin")).unwrap(); + fs::create_dir_all(dir.join("firmware")).unwrap(); + fs::create_dir_all(dir.join("entry-tool")).unwrap(); + fs::write(dir.join("source.bin"), b"new-edid").unwrap(); + fs::write(dir.join("mkinitcpio.conf"), "FILES=()\n").unwrap(); + fs::write(dir.join("limine.conf"), "cmdline: quiet\n").unwrap(); + let fixture = Self { dir }; + fixture.command("id", "printf '0\\n'"); + fixture.command("mkinitcpio", "exit 0"); + fixture.command("limine-mkinitcpio", "exit 0"); + fixture + } + + fn command(&self, name: &str, body: &str) { + let path = self.dir.join("bin").join(name); + fs::write(&path, format!("#!/bin/bash\n{body}\n")).unwrap(); + fs::set_permissions(path, fs::Permissions::from_mode(0o755)).unwrap(); + } + + fn run(&self, uninstall: bool) -> std::process::Output { + let script = if uninstall { + build_uninstall_script(&sample_uninstall_plan()) + } else { + let mut plan = sample_plan(); + plan.edid_source = self.dir.join("source.bin"); + build_install_script(&plan) + }; + let script = script + .replace( + "/lib/firmware/edid", + &self.dir.join("firmware").display().to_string(), + ) + .replace( + "/etc/mkinitcpio.conf", + &self.dir.join("mkinitcpio.conf").display().to_string(), + ) + .replace( + "/boot/limine.conf", + &self.dir.join("limine.conf").display().to_string(), + ) + .replace( + "/etc/limine-entry-tool.d", + &self.dir.join("entry-tool").display().to_string(), + ) + .replace( + "/etc/mkinitcpio.d", + &self.dir.join("presets").display().to_string(), + ); + Command::new("bash") + .args(["-c", &script]) + .env( + "PATH", + format!( + "{}:{}", + self.dir.join("bin").display(), + std::env::var("PATH").unwrap() + ), + ) + .output() + .unwrap() + } + + fn firmware(&self) -> PathBuf { + self.dir.join("firmware/drmcru_custom_DP-1.bin") + } + } + + impl Drop for ScriptFixture { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.dir); + } + } + + #[test] + fn install_updates_mapping_and_preserves_other_connectors_on_repeated_runs() { + let fixture = ScriptFixture::new(); + let other = "HDMI-A-1:edid/other.bin"; + fs::write( + fixture.dir.join("limine.conf"), + format!("cmdline: quiet drm.edid_firmware=DP-1:edid/old.bin,{other}\ncmdline: debug\n"), + ) + .unwrap(); + fs::write( + fixture.dir.join("entry-tool/drmcru-edid.conf"), + format!("KERNEL_CMDLINE[default]+=\" drm.edid_firmware=DP-1:edid/old.bin,{other}\"\n"), + ) + .unwrap(); + for _ in 0..2 { + let output = fixture.run(false); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + let limine = fs::read_to_string(fixture.dir.join("limine.conf")).unwrap(); + for line in limine.lines() { + assert!( + text_contains_kernel_mapping(line, &sample_plan().kernel_parameter), + "{line}" + ); + assert_eq!(line.matches("drm.edid_firmware=").count(), 1); + assert!(!line.contains("old.bin")); + } + assert!(limine.lines().next().unwrap().contains(other)); + let dropin = + fs::read_to_string(fixture.dir.join("entry-tool/drmcru-edid.conf")).unwrap(); + assert!( + text_contains_kernel_mapping(&dropin, &sample_plan().kernel_parameter), + "{dropin}" + ); + assert!(dropin.contains(other)); + } + } + + #[test] + fn install_rolls_back_when_a_backup_helper_fails() { + let fixture = ScriptFixture::new(); + fs::write(fixture.firmware(), b"old-edid").unwrap(); + let mkinit = fixture.dir.join("mkinitcpio.conf"); + fixture.command( + "cp", + &format!( + "if [ \"$3\" = {} ]; then exit 42; fi\nexec /usr/bin/cp \"$@\"", + shell_quote(&mkinit.display().to_string()) + ), + ); + let output = fixture.run(false); + assert!(!output.status.success()); + assert_eq!(fs::read(fixture.firmware()).unwrap(), b"old-edid"); + assert_eq!(fs::read_to_string(mkinit).unwrap(), "FILES=()\n"); + } + + #[test] + fn rebuild_failure_restores_install_and_uninstall_files() { + for uninstall in [false, true] { + let fixture = ScriptFixture::new(); + fs::write(fixture.firmware(), b"old-edid").unwrap(); + let mkinit = format!("FILES=(\"{}\")\n", fixture.firmware().display()); + let limine = format!("cmdline: quiet {}\n", sample_plan().kernel_parameter); + let dropin = format!( + "KERNEL_CMDLINE[default]+=\" {}\"\n", + sample_plan().kernel_parameter + ); + fs::write(fixture.dir.join("mkinitcpio.conf"), &mkinit).unwrap(); + fs::write(fixture.dir.join("limine.conf"), &limine).unwrap(); + fs::write(fixture.dir.join("entry-tool/drmcru-edid.conf"), &dropin).unwrap(); + fixture.command("limine-mkinitcpio", "exit 42"); + assert!(!fixture.run(uninstall).status.success()); + assert_eq!(fs::read(fixture.firmware()).unwrap(), b"old-edid"); + assert_eq!( + fs::read_to_string(fixture.dir.join("mkinitcpio.conf")).unwrap(), + mkinit + ); + assert_eq!( + fs::read_to_string(fixture.dir.join("limine.conf")).unwrap(), + limine + ); + assert_eq!( + fs::read_to_string(fixture.dir.join("entry-tool/drmcru-edid.conf")).unwrap(), + dropin + ); + } + } + + #[test] + fn install_and_uninstall_preserve_compact_cmdlines_and_dropin_options() { + let fixture = ScriptFixture::new(); + let other = "HDMI-A-1:edid/other.bin"; + fs::write( + fixture.dir.join("limine.conf"), + format!("cmdline:quiet drm.edid_firmware=DP-1:edid/old.bin,{other} root=/dev/test\n"), + ) + .unwrap(); + fs::write(fixture.dir.join("entry-tool/drmcru-edid.conf"), format!("KERNEL_CMDLINE[default]+=\" quiet drm.edid_firmware=DP-1:edid/old.bin,{other} loglevel=3\"\n")).unwrap(); + for uninstall in [false, true] { + let output = fixture.run(uninstall); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + let limine = fs::read_to_string(fixture.dir.join("limine.conf")).unwrap(); + assert!(limine.contains("quiet"), "{limine}"); + assert!(limine.contains("root=/dev/test")); + assert!(limine.contains(other)); + let dropin = + fs::read_to_string(fixture.dir.join("entry-tool/drmcru-edid.conf")).unwrap(); + assert!(dropin.contains("quiet"), "{dropin}"); + assert!(dropin.contains("loglevel=3"), "{dropin}"); + assert!(dropin.contains(other)); + } + } + + #[test] + fn install_does_not_mistake_comments_for_files_entries() { + let fixture = ScriptFixture::new(); + let path = fixture.firmware().display().to_string(); + fs::write( + fixture.dir.join("mkinitcpio.conf"), + format!("# FILES=({path})\nFILES=(\n /keep.bin # ) is a comment\n)\n"), + ) + .unwrap(); + for _ in 0..2 { + let output = fixture.run(false); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + } + let config = fs::read_to_string(fixture.dir.join("mkinitcpio.conf")).unwrap(); + assert_eq!(config.matches(&format!("\"{path}\"")).count(), 1); + assert!(config.contains("/keep.bin # ) is a comment")); + } + + #[test] + fn unsupported_files_syntax_fails_with_rollback_and_an_explanation() { + let fixture = ScriptFixture::new(); + let original = "FILES=($(printf /keep.bin))\n"; + fs::write(fixture.dir.join("mkinitcpio.conf"), original).unwrap(); + let output = fixture.run(false); + assert!(!output.status.success()); + assert!( + String::from_utf8_lossy(&output.stderr) + .contains("command substitutions are unsupported") + ); + assert_eq!( + fs::read_to_string(fixture.dir.join("mkinitcpio.conf")).unwrap(), + original + ); + assert!(!fixture.firmware().exists()); + } + + #[test] + fn uninstall_removes_only_exact_firmware_entries_from_multiline_files() { + let fixture = ScriptFixture::new(); + let path = fixture.firmware().display().to_string(); + fs::write(fixture.firmware(), b"old-edid").unwrap(); + fs::write(fixture.dir.join("mkinitcpio.conf"), format!("# Keep this comment: {path}\nFILES=(\n \"{path}\"\n '{path}.other'\n /keep.bin\n)\nOTHER='{path}'\n")).unwrap(); + let output = fixture.run(true); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + let config = fs::read_to_string(fixture.dir.join("mkinitcpio.conf")).unwrap(); + assert!(!config.contains(&format!("\"{path}\"")), "{config}"); + assert!(config.contains(&format!("'{path}.other'")), "{config}"); + assert!(config.contains(&format!("OTHER='{path}'"))); + assert!(config.contains(&format!("# Keep this comment: {path}"))); + } + #[test] fn system_support_accepts_limine_mkinitcpio_stack() { let dir = unique_test_dir(); @@ -1370,8 +1620,8 @@ mod tests { #[test] fn script_is_idempotent() { let script = build_install_script(&sample_plan()); - // The script checks mkinitcpio and de-duplicates connector mappings. - assert!(script.contains("grep -qF")); + // Repeated installs retain one FILES entry and de-duplicate mappings. + assert!(script.contains("operation=add")); assert!(script.contains("if (!seen[mapping]++)")); assert!(script.contains("index(mapping, connector \":\") == 1")); } diff --git a/src/mkinitcpio_files.awk b/src/mkinitcpio_files.awk new file mode 100644 index 0000000..f512084 --- /dev/null +++ b/src/mkinitcpio_files.awk @@ -0,0 +1,90 @@ +# Edit literal FILES arrays without evaluating the shell config. Preserve other +# assignments, comments, quoted paths, and entries that merely share a prefix. +function fail(message) { + print "[ERR] Cannot edit mkinitcpio FILES: " message > "/dev/stderr" + failed = 1 + exit 1 +} + +function finish_token( keep) { + keep = !(operation == "remove" && !dynamic && value == path) + if (!dynamic && value == path) + found = 1 + if (keep) + result = result token + token = value = "" + dynamic = 0 +} + +{ + result = "" + start = 1 + if (!in_files && match($0, /^[[:space:]]*FILES(\+)?=\(/)) { + in_files = 1 + saw_array = 1 + found = 0 + result = substr($0, 1, RLENGTH) + start = RLENGTH + 1 + } + for (i = start; i <= length($0); i++) { + character = substr($0, i, 1) + if (!in_files) { + result = result substr($0, i) + break + } + if (!escaped && quote != "\047" && + (character == "`" || (character == "$" && substr($0, i + 1, 1) == "("))) + fail("command substitutions are unsupported; use literal array entries") + if (escaped) { + token = token character + value = value character + escaped = 0 + } else if (character == "\\" && quote != "\047") { + token = token character + escaped = 1 + } else if (quote != "") { + token = token character + if (character == quote) + quote = "" + else { + value = value character + if (quote == "\"" && (character == "$" || character == "`")) + dynamic = 1 + } + } else if (character == "\"" || character == "\047") { + token = token character + quote = character + } else if (character == "#" && token == "") { + result = result substr($0, i) + break + } else if (character ~ /[[:space:]]/ || character == ")") { + finish_token() + if (character == ")") { + if (operation == "add" && !found) + result = result " \"" path "\"" + in_files = 0 + } + result = result character + } else { + token = token character + value = value character + if (character == "$" || character == "`") + dynamic = 1 + } + } + # Multiline quoted words and substitutions need a shell parser. Fail before + # the caller replaces the config instead of rewriting them incorrectly. + if (quote != "" || escaped) + fail("multiline quoted entries and continuations are unsupported") + finish_token() + print result +} + +END { + if (failed) + exit 1 + if (in_files) + fail("unterminated FILES array") + if (operation == "add" && !saw_array) + print "FILES=(\"" path "\")" +} diff --git a/src/models.rs b/src/models.rs index 9307024..6f5b9e5 100644 --- a/src/models.rs +++ b/src/models.rs @@ -105,13 +105,14 @@ pub struct DisplayIdDataBlock { impl DisplayIdDataBlock { pub fn label(&self) -> String { match self.tag { + 0x00 | 0x20 => "Product ID".to_string(), + 0x01 | 0x21 => "Display parameters".to_string(), + 0x02 => "Color characteristics".to_string(), 0x03 => "Type I timings".to_string(), 0x04 => "Type II timings".to_string(), 0x05 => "Type III timings".to_string(), 0x12 => "Tiled display".to_string(), - 0x20 => "Product ID".to_string(), - 0x21 => "Display parameters".to_string(), - 0x22 => "Color characteristics".to_string(), + 0x22 => "Type VII timings".to_string(), tag => format!("DisplayID tag 0x{tag:02x}"), } } diff --git a/src/timings.rs b/src/timings.rs index d7dbd8f..02b4872 100644 --- a/src/timings.rs +++ b/src/timings.rs @@ -106,11 +106,12 @@ pub fn cvt_reduced_blanking(request: CvtRequest) -> TimingDescriptor { let estimated_h_period_us = ((1_000_000.0 / refresh_hz) - RB_MIN_VBLANK_US) / f64::from(v_active); let min_vbi_lines = V_FRONT_PORCH + v_sync_width + MIN_V_BACK_PORCH; - let rb_vbi_lines = (RB_MIN_VBLANK_US / estimated_h_period_us).floor() as u16 + 1; + let rb_vbi_lines = + ((RB_MIN_VBLANK_US / estimated_h_period_us).floor() as u16).saturating_add(1); let v_blanking = rb_vbi_lines.max(min_vbi_lines); let v_total = u32::from(v_active) + u32::from(v_blanking); let pixel_clock_khz = round_down_to_step( - f64::from(h_total * v_total) * refresh_hz / 1000.0, + f64::from(h_total) * f64::from(v_total) * refresh_hz / 1000.0, CLOCK_STEP_KHZ, ); @@ -195,8 +196,14 @@ fn exact_timing(request: CvtRequest, current: Option<&TimingDescriptor>) -> Timi v_active: request.height, ..base }; - timing.h_blanking = timing.h_front_porch + timing.h_sync_width + timing.h_back_porch; - timing.v_blanking = timing.v_front_porch + timing.v_sync_width + timing.v_back_porch; + timing.h_blanking = timing + .h_front_porch + .saturating_add(timing.h_sync_width) + .saturating_add(timing.h_back_porch); + timing.v_blanking = timing + .v_front_porch + .saturating_add(timing.v_sync_width) + .saturating_add(timing.v_back_porch); timing.pixel_clock_khz = exact_pixel_clock_khz( u32::from(timing.h_total()), u32::from(timing.v_total()), @@ -223,8 +230,8 @@ fn detailed_from_parts( let h_blanking = h_front_porch + h_sync_width + h_back_porch; let v_blanking = v_front_porch + v_sync_width + v_back_porch; let pixel_clock_khz = exact_pixel_clock_khz( - u32::from(h_active + h_blanking), - u32::from(v_active + v_blanking), + u32::from(h_active) + u32::from(h_blanking), + u32::from(v_active) + u32::from(v_blanking), refresh_hz, ); @@ -247,7 +254,7 @@ fn detailed_from_parts( } fn exact_pixel_clock_khz(h_total: u32, v_total: u32, refresh_hz: f64) -> u32 { - (f64::from(h_total * v_total) * refresh_hz / 1000.0).round() as u32 + (f64::from(h_total) * f64::from(v_total) * refresh_hz / 1000.0).round() as u32 } fn round_down_to(value: u16, granularity: u16) -> u16 { @@ -255,7 +262,7 @@ fn round_down_to(value: u16, granularity: u16) -> u16 { } fn round_down_to_step(value: f64, step: u32) -> u32 { - ((value / f64::from(step)).floor() as u32) * step + ((value / f64::from(step)).floor() * f64::from(step)) as u32 } fn vertical_sync_width(width: u16, height: u16) -> u16 { @@ -295,6 +302,24 @@ mod tests { assert_eq!(timing.pixel_clock_khz, 138_500); } + #[test] + fn extreme_requests_do_not_overflow_before_validation() { + for preset in TimingPreset::ALL { + for refresh_hz in [60.0, 2173.9, 1e100] { + let timing = timing_for_preset( + preset, + CvtRequest { + width: u16::MAX, + height: u16::MAX, + refresh_hz, + }, + None, + ); + assert!(!crate::validation::validate_timing(&timing).is_empty()); + } + } + } + #[test] fn exact_preset_preserves_current_blanking_and_updates_clock() { let current = cvt_reduced_blanking(CvtRequest { diff --git a/src/tui/actions.rs b/src/tui/actions.rs index ff687c4..d2fb808 100644 --- a/src/tui/actions.rs +++ b/src/tui/actions.rs @@ -24,6 +24,61 @@ struct SwitchModeCandidate { } impl App { + pub(super) fn open_vrr_editor(&mut self) { + if self.modal_open() { + self.status = "Close the current dialog before editing the VRR range.".to_string(); + return; + } + let result = self + .selected_edid() + .ok_or_else(|| "Selected monitor has no editable EDID.".to_string()) + .and_then(|edid| crate::edid::vrr_range(&edid.raw).map_err(|error| error.to_string())); + match result { + Ok(range) => { + self.vrr_editor = Some(super::state::VrrRangeEditor::new(range)); + self.status = + "Edit the advertised VRR range, then Export or Install/Update and reboot." + .to_string(); + } + Err(error) => self.status = format!("Cannot edit VRR range: {error}"), + } + } + + pub(super) fn apply_vrr_editor(&mut self) { + let Some(editor) = self.vrr_editor.as_ref() else { + return; + }; + let range = editor.inputs[0] + .buffer + .parse::() + .ok() + .zip(editor.inputs[1].buffer.parse::().ok()) + .map(|(min_hz, max_hz)| crate::edid::VrrRange { min_hz, max_hz }); + let result = match range { + Some(range) => self + .selected_workspace_mut() + .ok_or_else(|| "Selected monitor has no editable EDID.".to_string()) + .and_then(|workspace| { + workspace + .set_vrr_range(range) + .map_err(|error| error.to_string()) + }), + None => Err("Enter whole Hz between 1 and 510, with minimum <= maximum.".to_string()), + }; + match result { + Ok(()) => { + let range = range.unwrap(); + self.vrr_editor = None; + self.status = format!( + "VRR range set to {}–{} Hz. Export or Install/Update and reboot to apply.", + range.min_hz, range.max_hz + ); + } + Err(error) => { + self.vrr_editor.as_mut().unwrap().error = error; + } + } + } pub(super) fn open_detailed_editor(&mut self, mode: EditorMode) { self.import_dialog = None; self.details_dialog = None; @@ -525,7 +580,7 @@ impl App { { Some(()) => { let remaining = self.working_dtds().len(); - self.selected_detailed = (remaining > 0).then_some(index.min(remaining - 1)); + self.selected_detailed = remaining.checked_sub(1).map(|last| index.min(last)); self.status = format!("Deleted DTD at {}.", format_location(location)); } None => { @@ -558,8 +613,8 @@ impl App { .and_then(|workspace| workspace.delete_dtd(location).ok()) { Some(()) => { - let remaining = self.working_cta_dtd_slots().len(); - self.selected_extension = (remaining > 0).then_some(index.min(remaining - 1)); + let remaining = self.working_extension_rows().len(); + self.selected_extension = remaining.checked_sub(1).map(|last| index.min(last)); self.status = format!("Deleted DTD at {}.", format_location(location)); } None => { @@ -632,7 +687,7 @@ impl App { { Some(()) => { let remaining = self.working_standard_timings().len(); - self.selected_standard = (remaining > 0).then_some(index.min(remaining - 1)); + self.selected_standard = remaining.checked_sub(1).map(|last| index.min(last)); self.status = format!("Deleted standard timing slot {slot}."); } None => { @@ -1021,28 +1076,12 @@ impl App { return issues; }; - if !edid.checksum_valid { - issues.push("Error: Base EDID checksum is invalid.".to_string()); - } - for cta in &edid.cta_blocks { - if !cta.checksum_valid { - issues.push(format!( - "Error: CTA-861 extension {} checksum is invalid.", - cta.extension_index - )); + if let Ok(mut workspace) = EdidWorkspace::from_edid(edid) { + issues.extend(self.workspace_validation_issues(&workspace)); + if let Err(error) = workspace.add_dtd(self.draft_timing.clone()) { + issues.push(format!("Error: Cannot insert draft timing: {error}")); } } - let free_dtd_slots = self - .selected_workspace() - .and_then(|workspace| workspace.slot_summary().ok()) - .map(|summary| summary.base_dtd_free + summary.cta_dtd_free) - .unwrap_or(0); - if free_dtd_slots == 0 { - issues.push( - "Error: No free base or CTA detailed timing slot is visible for draft insertion." - .to_string(), - ); - } issues.push( "Warning: No workspace EDID changes are pending; export will insert the current draft detailed timing." .to_string(), @@ -1890,6 +1929,7 @@ fn help_lines() -> Vec { "? / h / F1 Open this help", "i Details for the focused monitor or row", "e Export patched EDID", + "Shift+R Edit the advertised VRR range", "Shift+E Edit the selected detailed, standard, or CTA DTD row", "A Install/Update EDID override", "u Uninstall drmcru EDID override", diff --git a/src/tui/input.rs b/src/tui/input.rs index 3e30e6b..e21795b 100644 --- a/src/tui/input.rs +++ b/src/tui/input.rs @@ -23,6 +23,7 @@ impl App { } }, KeyCode::Char('e') => self.export_selected_monitor(), + KeyCode::Char('R') => self.open_vrr_editor(), KeyCode::Char('E') => match self.focus { FocusArea::Detailed => self.edit_selected_detailed(), FocusArea::Standard => self.edit_selected_standard(), @@ -65,6 +66,19 @@ impl App { } pub(super) fn handle_mouse(&mut self, mouse: MouseEvent) { + if self.vrr_editor.is_some() { + if let MouseEventKind::Down(MouseButton::Left) = mouse.kind { + if let Some(hitbox) = self.hit_test(mouse.column, mouse.row) { + if matches!( + hitbox.target, + HitTarget::VrrField(_) | HitTarget::ModalButton(_) + ) { + self.activate_hit(hitbox, mouse.column); + } + } + } + return; + } if self.details_dialog.is_some() { match mouse.kind { MouseEventKind::ScrollDown => { @@ -104,6 +118,18 @@ impl App { } } } + MouseEventKind::ScrollDown | MouseEventKind::ScrollUp if self.modal_open() => { + let delta = if mouse.kind == MouseEventKind::ScrollDown { + 3 + } else { + -3 + }; + if let Some(dialog) = self.apply_confirm_dialog.as_mut() { + dialog.scroll_by(delta); + } else if let Some(dialog) = self.apply_result_dialog.as_mut() { + dialog.scroll_by(delta); + } + } MouseEventKind::ScrollDown => self.move_selection(1), MouseEventKind::ScrollUp => self.move_selection(-1), _ => {} @@ -152,6 +178,12 @@ impl App { .set_cursor_from_column(mouse_column, hitbox.rect, 7); } } + HitTarget::VrrField(index) => { + if let Some(editor) = self.vrr_editor.as_mut() { + editor.active = index; + editor.inputs[index].set_cursor_from_column(mouse_column, hitbox.rect, 13); + } + } HitTarget::ModalButton(button) => self.activate_modal_button(button), } } @@ -226,6 +258,7 @@ impl App { fn activate_global_action(&mut self, action: GlobalAction) { match action { + GlobalAction::VrrRange => self.open_vrr_editor(), GlobalAction::Import => self.open_import_dialog(), GlobalAction::Export => self.export_selected_monitor(), GlobalAction::SwitchMode => self.switch_selected_monitor_mode(), @@ -510,6 +543,13 @@ impl App { } fn activate_modal_button(&mut self, button: ModalButton) { + if self.vrr_editor.is_some() { + match button { + ModalButton::Ok => self.apply_vrr_editor(), + ModalButton::Cancel => self.vrr_editor = None, + } + return; + } if self.import_dialog.is_some() { match button { ModalButton::Ok => self.apply_import_dialog(), @@ -583,3 +623,34 @@ impl App { } } } + +impl App { + pub(super) fn handle_vrr_editor_key(&mut self, key: KeyEvent) { + match key.code { + KeyCode::Esc => { + self.vrr_editor = None; + } + KeyCode::Enter => self.apply_vrr_editor(), + _ => { + let Some(editor) = self.vrr_editor.as_mut() else { + return; + }; + match key.code { + KeyCode::Tab | KeyCode::BackTab | KeyCode::Up | KeyCode::Down => { + editor.active ^= 1 + } + KeyCode::Left => editor.inputs[editor.active].move_left(), + KeyCode::Right => editor.inputs[editor.active].move_right(), + KeyCode::Home => editor.inputs[editor.active].cursor = 0, + KeyCode::End => editor.inputs[editor.active].move_end(), + KeyCode::Backspace => editor.inputs[editor.active].backspace(), + KeyCode::Delete => editor.inputs[editor.active].delete(), + KeyCode::Char(value) if value.is_ascii_digit() => { + editor.inputs[editor.active].insert(value) + } + _ => {} + } + } + } + } +} diff --git a/src/tui/mod.rs b/src/tui/mod.rs index dd51e5b..8113004 100644 --- a/src/tui/mod.rs +++ b/src/tui/mod.rs @@ -46,6 +46,7 @@ pub struct App { detailed_clipboard: Option, detailed_editor: Option, standard_editor: Option, + vrr_editor: Option, import_dialog: Option, details_dialog: Option, export_confirm_dialog: Option, @@ -92,6 +93,7 @@ enum SectionAction { #[derive(Debug, Clone, Copy, PartialEq, Eq)] enum GlobalAction { + VrrRange, Import, Export, SwitchMode, @@ -153,6 +155,7 @@ enum HitTarget { GlobalButton(GlobalAction), ModalField(state::EditorField), ImportPathField, + VrrField(usize), ModalButton(state::ModalButton), } @@ -212,6 +215,7 @@ impl App { detailed_clipboard: None, detailed_editor: None, standard_editor: None, + vrr_editor: None, import_dialog: None, details_dialog: None, export_confirm_dialog: None, @@ -240,6 +244,8 @@ impl App { Event::Key(key) => { if self.applying_in_progress { // Swallow all keys while install is running + } else if self.vrr_editor.is_some() { + self.handle_vrr_editor_key(key); } else if self.detailed_editor.is_some() { self.handle_detailed_editor_key(key); } else if self.standard_editor.is_some() { @@ -275,6 +281,19 @@ impl App { self.monitors.get(self.selected_monitor) } + fn modal_open(&self) -> bool { + self.vrr_editor.is_some() + || self.detailed_editor.is_some() + || self.standard_editor.is_some() + || self.import_dialog.is_some() + || self.details_dialog.is_some() + || self.export_confirm_dialog.is_some() + || self.export_dialog.is_some() + || self.apply_confirm_dialog.is_some() + || self.apply_result_dialog.is_some() + || self.applying_in_progress + } + fn selected_override_status(&self) -> Option<&InstalledOverrideStatus> { self.override_statuses.get(self.selected_monitor) } @@ -718,6 +737,149 @@ mod tests { assert_eq!(app.mode_provenance(key).sources.len(), 1); } + #[test] + fn modal_mouse_events_cannot_change_background_selection() { + use crossterm::event::{KeyModifiers, MouseButton, MouseEvent, MouseEventKind}; + let mut app = App::new(vec![monitor_with_cta_dtd(), monitor_with_cta_dtd()]); + app.open_detailed_editor(state::EditorMode::Add); + app.push_hitbox(Rect::new(0, 0, 20, 3), HitTarget::MonitorSelector, 0); + app.handle_mouse(MouseEvent { + kind: MouseEventKind::Down(MouseButton::Left), + column: 1, + row: 1, + modifiers: KeyModifiers::NONE, + }); + assert_eq!(app.selected_monitor, 0); + app.handle_mouse(MouseEvent { + kind: MouseEventKind::ScrollDown, + column: 1, + row: 1, + modifiers: KeyModifiers::NONE, + }); + assert_eq!(app.selected_detailed, None); + } + + #[test] + fn compact_terminal_keeps_active_editor_and_extension_rows_visible() { + use ratatui::backend::TestBackend; + let mut app = App::new(vec![monitor_with_cta_dtd()]); + let mut terminal = Terminal::new(TestBackend::new(80, 24)).unwrap(); + app.open_detailed_editor(state::EditorMode::Add); + for _ in 0..19 { + let active = app.detailed_editor.as_ref().unwrap().active_field; + terminal.draw(|frame| app.draw(frame)).unwrap(); + assert!( + app.hitboxes + .iter() + .any(|hitbox| hitbox.target == HitTarget::ModalField(active) + && hitbox.rect.height > 0) + ); + app.detailed_editor.as_mut().unwrap().next_field(); + } + assert!(app.hitboxes.iter().any(|hitbox| hitbox.target + == HitTarget::ModalButton(state::ModalButton::Ok) + && hitbox.rect.height > 0)); + + app.detailed_editor = None; + app.selected_extension = Some(3); + terminal.draw(|frame| app.draw(frame)).unwrap(); + assert!(app.hitboxes.iter().any(|hitbox| hitbox.target == HitTarget::ExtensionRow(3) && hitbox.rect.height > 0)); + } + + #[test] + fn deleting_last_detailed_and_standard_rows_clears_selection() { + let mut app = App::new(vec![monitor_with_cta_dtd()]); + app.selected_detailed = Some(0); + app.delete_selected_detailed(); + assert!(app.working_dtds().is_empty()); + assert_eq!(app.selected_detailed, None); + + let standard = crate::models::StandardTiming { + slot: 0, + width: 1920, + height: 1080, + refresh_hz: 60, + aspect: crate::models::StandardTimingAspect::SixteenNine, + }; + app.selected_workspace_mut() + .unwrap() + .add_standard_timing(standard) + .unwrap(); + app.selected_standard = Some(0); + app.delete_selected_standard(); + assert!(app.working_standard_timings().is_empty()); + assert_eq!(app.selected_standard, None); + } + + #[test] + fn cta_delete_keeps_selection_after_video_rows() { + let mut app = App::new(vec![monitor_with_cta_dtd()]); + let location = DtdLocation::Cta { + extension_index: 1, + slot: 5, + }; + app.selected_workspace_mut() + .unwrap() + .add_cta_dtd_at(location, timing()) + .unwrap(); + app.selected_extension = Some(6); + app.delete_selected_extension_dtd(); + assert_eq!(app.selected_extension, Some(6)); + assert!( + matches!(&app.working_extension_rows()[6], ExtensionRow::Dtd(row) if row.slot == 5 && row.timing.is_none()) + ); + } + + #[test] + fn draft_export_checks_unknown_extension_checksums_and_length() { + for truncate in [false, true] { + let mut monitor = monitor_with_cta_dtd(); + let mut raw = monitor.edid.take().unwrap().raw; + raw[128] = 0x40; + repair_checksum(&mut raw[128..]); + if truncate { + raw.pop(); + } else { + raw[129] ^= 1; + } + monitor.edid = Some(parse_edid(raw).unwrap()); + let mut app = App::new(vec![monitor]); + app.export_selected_monitor(); + assert!( + app.details_dialog + .as_ref() + .is_some_and(|dialog| dialog.title == "Export Blocked") + ); + assert!(app.export_confirm_dialog.is_none()); + } + } + + #[test] + fn draft_export_can_append_a_cta_when_existing_slots_are_full() { + let mut monitor = monitor_with_cta_dtd(); + let mut raw = monitor.edid.take().unwrap().raw; + for slot in 0..4 { + raw = crate::edid::patch_detailed_timing(&raw, DtdLocation::Base { slot }, &timing()) + .unwrap(); + } + for slot in 0..6 { + raw = crate::edid::patch_detailed_timing( + &raw, + DtdLocation::Cta { + extension_index: 1, + slot, + }, + &timing(), + ) + .unwrap(); + } + monitor.edid = Some(parse_edid(raw).unwrap()); + let mut app = App::new(vec![monitor]); + app.export_selected_monitor(); + assert!(app.export_confirm_dialog.is_some()); + assert!(app.details_dialog.is_none()); + } + #[test] fn apply_refuses_unchanged_workspace() { let mut app = App::new(vec![monitor_with_cta_dtd()]); @@ -729,6 +891,56 @@ mod tests { assert!(app.status.contains("No workspace changes")); } + #[test] + fn vrr_dialog_rejects_invalid_input_and_saves_a_valid_range() { + let mut monitor = monitor_with_cta_dtd(); + let mut raw = monitor.edid.as_ref().unwrap().raw.clone(); + raw[18] = 1; + raw[19] = 4; + raw[24] |= 1; + raw[108..126].copy_from_slice(&[ + 0, 0, 0, 0xfd, 0, 24, 120, 30, 200, 60, 1, 10, 0, 0, 0, 0, 0, 0, + ]); + repair_checksum(&mut raw[..128]); + monitor.edid = Some(parse_edid(raw).unwrap()); + let mut app = App::new(vec![monitor]); + app.open_help_dialog(); + app.open_vrr_editor(); + assert!(app.vrr_editor.is_none()); + assert!(app.details_dialog.is_some()); + app.details_dialog = None; + app.handle_main_key(crossterm::event::KeyEvent::from( + crossterm::event::KeyCode::Char('R'), + )); + app.vrr_editor.as_mut().unwrap().inputs[0].set("121".to_string()); + app.apply_vrr_editor(); + assert!(!app.vrr_editor.as_ref().unwrap().error.is_empty()); + assert!(!app.selected_workspace().unwrap().has_changes()); + app.vrr_editor.as_mut().unwrap().inputs[0].set("40".to_string()); + app.apply_vrr_editor(); + assert!(app.vrr_editor.is_none()); + assert!(app.selected_workspace().unwrap().has_changes()); + app.open_vrr_editor(); + assert_eq!(app.vrr_editor.as_ref().unwrap().inputs[0].buffer, "40"); + assert!(app.modal_open()); + let mut terminal = + ratatui::Terminal::new(ratatui::backend::TestBackend::new(80, 24)).unwrap(); + terminal.draw(|frame| app.draw(frame)).unwrap(); + let contents = terminal + .backend() + .buffer() + .content + .iter() + .map(|cell| cell.symbol()) + .collect::(); + assert!(contents.contains("VRR range limits")); + assert!(contents.contains("Minimum Hz: [40|]")); + app.handle_vrr_editor_key(crossterm::event::KeyEvent::from( + crossterm::event::KeyCode::Esc, + )); + assert!(app.vrr_editor.is_none()); + } + #[test] fn empty_discovery_has_actionable_first_run_status() { let app = App::new(Vec::new()); diff --git a/src/tui/render.rs b/src/tui/render.rs index c8d444c..f1af4e4 100644 --- a/src/tui/render.rs +++ b/src/tui/render.rs @@ -60,6 +60,10 @@ impl App { ); self.draw_global_buttons(frame, bottom_bar); + if let Some(editor) = self.vrr_editor.clone() { + self.draw_vrr_editor(frame, &editor); + } + if let Some(editor) = self.detailed_editor.clone() { self.draw_detailed_editor(frame, &editor); } @@ -245,8 +249,15 @@ impl App { ]) .areas(area); let inner = inner_rect(list_area); - self.sync_section_scroll(section, inner.height); - let title = self.section_title(section, inner.height); + let viewport_height = if section == ResolutionSection::Extension { + inner + .height + .saturating_sub(self.extension_header_count(inner.height) as u16) + } else { + inner.height + }; + self.sync_section_scroll(section, viewport_height); + let title = self.section_title(section, viewport_height); let focused = matches!( (self.focus, section), (FocusArea::Detailed, ResolutionSection::Detailed) @@ -355,8 +366,9 @@ impl App { fn draw_extension_rows(&mut self, frame: &mut Frame<'_>, area: Rect) { let mut y = area.y; + let header_count = self.extension_header_count(area.height); if let Some(edid) = self.selected_edid() { - for cta in edid.cta_blocks.clone().iter() { + for cta in edid.cta_blocks.clone().iter().take(header_count) { if y >= area.y.saturating_add(area.height) { return; } @@ -381,7 +393,12 @@ impl App { ); y = y.saturating_add(1); } - for displayid in edid.displayid_blocks.clone().iter() { + for displayid in edid + .displayid_blocks + .clone() + .iter() + .take(header_count.saturating_sub(edid.cta_blocks.len())) + { if y >= area.y.saturating_add(area.height) { return; } @@ -540,6 +557,13 @@ impl App { } } + fn extension_header_count(&self, viewport_height: u16) -> usize { + self.selected_edid() + .map(|edid| edid.cta_blocks.len() + edid.displayid_blocks.len()) + .unwrap_or(0) + .min(usize::from(viewport_height.saturating_sub(1))) + } + fn section_title(&self, section: ResolutionSection, viewport_height: u16) -> String { let Some(summary) = self .selected_workspace() @@ -685,6 +709,7 @@ impl App { "Install" }; let buttons = [ + ("VRR range", GlobalAction::VrrRange), ("Import", GlobalAction::Import), ("Export", GlobalAction::Export), ("Switch", GlobalAction::SwitchMode), @@ -708,6 +733,59 @@ impl App { ); } + fn draw_vrr_editor(&mut self, frame: &mut Frame<'_>, editor: &super::state::VrrRangeEditor) { + let area = centered_rect(frame.area(), 76, 14); + frame.render_widget(Clear, area); + frame.render_widget( + Block::default() + .title("VRR range limits") + .borders(Borders::ALL), + area, + ); + let [help, minimum, maximum, error, actions] = Layout::vertical([ + Constraint::Length(3), + Constraint::Length(2), + Constraint::Length(2), + Constraint::Length(2), + Constraint::Length(3), + ]) + .areas(area.inner(Margin { + horizontal: 2, + vertical: 1, + })); + frame.render_widget(Paragraph::new("Edit the existing EDID range in whole Hz (1–510).\nTab selects a field; Enter saves; Esc cancels.\nExport or Install/Update and reboot to apply.").wrap(Wrap { trim: true }), help); + for (index, (rect, label)) in [(minimum, "Minimum Hz"), (maximum, "Maximum Hz")] + .into_iter() + .enumerate() + { + frame.render_widget( + Paragraph::new(format!( + "{label}: [{}]", + editor.inputs[index].render(editor.active == index) + )) + .style(Style::default().fg(Color::Cyan)), + rect, + ); + self.push_hitbox(rect, HitTarget::VrrField(index), 2); + } + frame.render_widget( + Paragraph::new(editor.error.as_str()) + .style(Style::default().fg(Color::Red)) + .wrap(Wrap { trim: true }), + error, + ); + let [ok, cancel, _] = Layout::horizontal([ + Constraint::Length(10), + Constraint::Length(12), + Constraint::Min(0), + ]) + .areas(actions); + self.draw_button(frame, ok, "Save"); + self.draw_button(frame, cancel, "Cancel"); + self.push_hitbox(ok, HitTarget::ModalButton(ModalButton::Ok), 2); + self.push_hitbox(cancel, HitTarget::ModalButton(ModalButton::Cancel), 2); + } + fn draw_detailed_editor(&mut self, frame: &mut Frame<'_>, editor: &DetailedResolutionEditor) { let area = centered_rect(frame.area(), 88, 36); frame.render_widget(Clear, area); @@ -726,17 +804,15 @@ impl App { height: area.height.saturating_sub(2), }; let [intro, fields, derived, actions] = Layout::vertical([ - Constraint::Length(2), - Constraint::Length(20), - Constraint::Min(9), + Constraint::Length(1), + Constraint::Length(inner.height.saturating_sub(8).min(19)), + Constraint::Min(4), Constraint::Length(3), ]) .areas(inner); frame.render_widget( - Paragraph::new( - "Detailed Timing. Presets regenerate editable fields from active size and refresh.", - ), + Paragraph::new("Tab scrolls fields. Presets regenerate timings from size and refresh."), intro, ); @@ -748,7 +824,7 @@ impl App { } frame.render_widget( - Paragraph::new(editor.derived_text()).wrap(Wrap { trim: false }), + Paragraph::new(editor.summary_text(derived.height)).wrap(Wrap { trim: false }), derived, ); @@ -1209,6 +1285,7 @@ impl App { self.hitboxes .iter() .rev() + .filter(|hitbox| !self.modal_open() || hitbox.z > 0) .filter(|hitbox| super::support::rect_contains(hitbox.rect, x, y)) .max_by_key(|hitbox| hitbox.z) .copied() diff --git a/src/tui/state.rs b/src/tui/state.rs index ca0acd7..2fc14b2 100644 --- a/src/tui/state.rs +++ b/src/tui/state.rs @@ -48,6 +48,26 @@ pub(super) struct ImportDialog { pub(super) path: TextInput, } +#[derive(Debug, Clone)] +pub(super) struct VrrRangeEditor { + pub(super) inputs: [TextInput; 2], + pub(super) active: usize, + pub(super) error: String, +} + +impl VrrRangeEditor { + pub(super) fn new(range: crate::edid::VrrRange) -> Self { + Self { + inputs: [ + TextInput::new(range.min_hz.to_string()), + TextInput::new(range.max_hz.to_string()), + ], + active: 0, + error: String::new(), + } + } +} + #[derive(Debug, Clone)] pub(super) struct ExportDialog { pub(super) path: String, @@ -355,14 +375,53 @@ impl DetailedResolutionEditor { } pub(super) fn field_rows(&self, area: Rect) -> Vec<(EditorField, Rect, &'static str)> { - let rows = Layout::vertical([Constraint::Length(1); 19]).split(area); - detailed_field_order() + let order = detailed_field_order(); + let visible = usize::from(area.height).min(order.len()); + let active = order + .iter() + .position(|(field, _)| *field == self.active_field) + .unwrap_or(0); + let start = active + .saturating_add(1) + .saturating_sub(visible) + .min(order.len() - visible); + order .into_iter() - .zip(rows.iter().copied()) - .map(|((field, label), rect)| (field, rect, label)) + .skip(start) + .take(visible) + .enumerate() + .map(|(index, (field, label))| { + ( + field, + Rect::new(area.x, area.y + index as u16, area.width, 1), + label, + ) + }) .collect() } + pub(super) fn summary_text(&self, height: u16) -> String { + if height >= 9 { + return self.derived_text(); + } + match self.timing() { + Ok(timing) => { + let mut lines = vec![ + format!("Mode: {}", timing.hyprland_mode()), + format!("Pixel clock: {} kHz", timing.pixel_clock_khz), + ]; + lines.extend( + validate_timing(&timing) + .into_iter() + .take(usize::from(height.saturating_sub(2))) + .map(|warning| format!("{}: {}", warning.label(), warning.message)), + ); + lines.join("\n") + } + Err(reason) => format!("Invalid detailed timing: {reason}."), + } + } + pub(super) fn input(&self, field: EditorField) -> &TextInput { match field { EditorField::Width => &self.h_active, @@ -509,7 +568,8 @@ impl DetailedResolutionEditor { if value == ' ' { let _ = self.toggle_field(field); } else if field.allows(value, self.input(field)) { - self.active_input_mut().insert(value); + self.active_input_mut() + .insert(if value == ',' { '.' } else { value }); self.after_text_edit(field); } } @@ -674,7 +734,8 @@ impl DetailedResolutionEditor { return; } - let pixel_clock_khz = (f64::from(h_total * v_total) * refresh_hz / 1000.0).round() as u32; + let pixel_clock_khz = + (f64::from(h_total) * f64::from(v_total) * refresh_hz / 1000.0).round() as u32; self.pixel_clock.set(pixel_clock_khz.to_string()); self.h_rate.set(format!( "{:.3}", @@ -764,7 +825,7 @@ impl DetailedResolutionEditor { self.pixel_clock.set(pixel_clock_khz.to_string()); self.refresh_hint.set(format!( "{:.3}", - f64::from(pixel_clock_khz) * 1000.0 / f64::from(h_total * v_total) + f64::from(pixel_clock_khz) * 1000.0 / (f64::from(h_total) * f64::from(v_total)) )); } @@ -788,7 +849,7 @@ impl DetailedResolutionEditor { if edited_field != EditorField::Refresh { self.refresh_hint.set(format!( "{:.3}", - f64::from(pixel_clock_khz) * 1000.0 / f64::from(h_total * v_total) + f64::from(pixel_clock_khz) * 1000.0 / (f64::from(h_total) * f64::from(v_total)) )); } } @@ -1110,7 +1171,6 @@ impl TextInput { } pub(super) fn insert(&mut self, value: char) { - let value = if value == ',' { '.' } else { value }; self.buffer.insert(self.cursor, value); self.cursor += value.len_utf8(); } @@ -1173,6 +1233,46 @@ fn next_char_boundary(value: &str, cursor: usize) -> Option { mod tests { use super::*; + #[test] + fn text_paths_preserve_commas_while_refresh_accepts_decimal_commas() { + let mut input = TextInput::new("/tmp/display".to_string()); + input.insert(','); + assert_eq!(input.buffer, "/tmp/display,"); + let timing = crate::timings::cvt_reduced_blanking(CvtRequest { + width: 1920, + height: 1080, + refresh_hz: 60.0, + }); + let mut editor = DetailedResolutionEditor::from_timing(timing, EditorMode::Add); + editor.active_field = EditorField::Refresh; + editor.input_mut(EditorField::Refresh).set("60".to_string()); + editor.insert_char(','); + editor.insert_char('5'); + assert_eq!(editor.input(EditorField::Refresh).buffer, "60.5"); + } + + #[test] + fn large_editor_totals_do_not_overflow_clock_calculations() { + let timing = crate::timings::cvt_reduced_blanking(CvtRequest { + width: 1920, + height: 1080, + refresh_hz: 60.0, + }); + let mut editor = DetailedResolutionEditor::from_timing(timing, EditorMode::Add); + for field in [ + EditorField::Width, + EditorField::Height, + EditorField::HBack, + EditorField::VBack, + ] { + editor.input_mut(field).set(u16::MAX.to_string()); + } + editor.after_text_edit(EditorField::Width); + editor.set_pixel_clock_from_h_rate(); + editor.update_rate_fields_from_pixel_clock(EditorField::PixelClock); + assert!(editor.manual_timing().is_err()); + } + #[test] fn text_input_moves_and_deletes_on_unicode_boundaries() { let mut input = TextInput::new("éx".to_string()); diff --git a/src/validation.rs b/src/validation.rs index 5f9a09e..45edeb1 100644 --- a/src/validation.rs +++ b/src/validation.rs @@ -96,12 +96,16 @@ pub fn validate_timing(timing: &TimingDescriptor) -> Vec { timing.v_blanking ))); } - if timing.h_front_porch + timing.h_sync_width > timing.h_blanking { + if u32::from(timing.h_front_porch) + u32::from(timing.h_sync_width) + > u32::from(timing.h_blanking) + { warnings.push(TimingWarning::error( "horizontal front porch plus sync width exceeds horizontal blanking", )); } - if timing.v_front_porch + timing.v_sync_width > timing.v_blanking { + if u32::from(timing.v_front_porch) + u32::from(timing.v_sync_width) + > u32::from(timing.v_blanking) + { warnings.push(TimingWarning::error( "vertical front porch plus sync width exceeds vertical blanking", )); @@ -222,6 +226,20 @@ mod tests { assert!(validate_timing(&valid_timing()).is_empty()); } + #[test] + fn oversized_porches_report_errors_without_overflowing() { + let mut timing = valid_timing(); + timing.h_front_porch = u16::MAX; + timing.h_sync_width = u16::MAX; + timing.v_front_porch = u16::MAX; + timing.v_sync_width = u16::MAX; + assert!( + validate_timing(&timing) + .iter() + .any(|warning| warning.severity == TimingWarningSeverity::Error) + ); + } + #[test] fn warns_about_non_native_internal_panel_modes() { let native = valid_timing(); diff --git a/src/workspace.rs b/src/workspace.rs index 8da8906..4ae2739 100644 --- a/src/workspace.rs +++ b/src/workspace.rs @@ -1,9 +1,9 @@ use crate::edid::{ CtaDtdSlot, DtdLocation, EdidError, EdidSlotSummary, LocatedStandardTiming, - block_checksum_valid, cta_dtd_slots, delete_detailed_timing, delete_standard_timing, - detailed_timing_locations, insert_cta_detailed_timing, insert_detailed_timing, - insert_standard_timing, parse_edid, patch_detailed_timing, patch_standard_timing, slot_summary, - standard_timing_locations, + block_checksum_valid, clear_detailed_timing_stereo, cta_dtd_slots, delete_detailed_timing, + delete_standard_timing, detailed_timing_locations, insert_cta_detailed_timing, + insert_detailed_timing, insert_standard_timing, parse_edid, patch_detailed_timing, + patch_standard_timing, slot_summary, standard_timing_locations, swap_detailed_timings, }; use crate::models::{EdidData, StandardTiming, TimingDescriptor}; use std::path::Path; @@ -18,6 +18,9 @@ pub struct EdidWorkspace { #[derive(Debug, Clone, PartialEq)] pub enum WorkspaceOperation { + SetVrrRange { + range: crate::edid::VrrRange, + }, AddDtd { location: DtdLocation, timing: TimingDescriptor, @@ -90,8 +93,16 @@ impl EdidWorkspace { &self.working } + pub fn set_vrr_range(&mut self, range: crate::edid::VrrRange) -> Result<(), WorkspaceError> { + let raw = crate::edid::patch_vrr_range(&self.working.raw, range)?; + self.replace_working_raw(raw)?; + self.operations + .push(WorkspaceOperation::SetVrrRange { range }); + Ok(()) + } + pub fn has_changes(&self) -> bool { - self.original_raw != self.working.raw + self.original_raw != self.export_bytes() } pub fn add_dtd(&mut self, timing: TimingDescriptor) -> Result { @@ -221,8 +232,7 @@ impl EdidWorkspace { let current = &dtds[index]; let target = &dtds[target_index]; - let raw = patch_detailed_timing(&self.working.raw, current.location, &target.timing)?; - let raw = patch_detailed_timing(&raw, target.location, ¤t.timing)?; + let raw = swap_detailed_timings(&self.working.raw, current.location, target.location)?; let from = current.location; let to = target.location; @@ -295,21 +305,31 @@ impl EdidWorkspace { } pub fn diff_summary(&self) -> Vec { - if self.original_raw == self.working.raw { + let mut exported = self.working.raw.clone(); + let cleared = clear_detailed_timing_stereo(&mut exported); + if self.original_raw == exported { return vec!["No EDID byte changes.".to_string()]; } let changed_bytes = self .original_raw .iter() - .zip(self.working.raw.iter()) + .zip(exported.iter()) .filter(|(original, working)| original != working) .count() - + self.original_raw.len().abs_diff(self.working.raw.len()); + + self.original_raw.len().abs_diff(exported.len()); let mut summary = vec![format!("{changed_bytes} EDID bytes changed.")]; + if cleared > 0 { + summary.push(format!( + "Clear stereo flags from {cleared} detailed timings on export" + )); + } for operation in &self.operations { summary.push(match operation { + WorkspaceOperation::SetVrrRange { range } => { + format!("Set VRR range to {}–{} Hz", range.min_hz, range.max_hz) + } WorkspaceOperation::AddDtd { location, timing } => { format!( "Added {} at {}", @@ -359,8 +379,10 @@ impl EdidWorkspace { summary } - pub fn export_bytes(&self) -> &[u8] { - &self.working.raw + pub fn export_bytes(&self) -> Vec { + let mut raw = self.working.raw.clone(); + clear_detailed_timing_stereo(&mut raw); + raw } fn replace_working_raw(&mut self, raw: Vec) -> Result<(), WorkspaceError> { @@ -421,6 +443,22 @@ mod tests { } } + #[test] + fn reordering_moves_complete_descriptors_including_sync_and_size() { + let mut raw = minimal_base_edid(0); + raw = patch_base_detailed_timing(&raw, 0, &sample_timing()).unwrap(); + raw = patch_base_detailed_timing(&raw, 1, &alternate_timing()).unwrap(); + raw[54 + 12..54 + 18].copy_from_slice(&[1, 2, 3, 4, 5, 0x10]); + raw[72 + 12..72 + 18].copy_from_slice(&[6, 7, 8, 9, 10, 0x1e]); + let first = raw[54..72].to_vec(); + let second = raw[72..90].to_vec(); + let mut workspace = EdidWorkspace::new(raw).unwrap(); + workspace.move_dtd(0, MoveDirection::Down).unwrap(); + assert_eq!(&workspace.export_bytes()[54..72], second); + assert_eq!(&workspace.export_bytes()[72..90], first); + assert!(workspace.validate().is_empty()); + } + fn alternate_timing() -> TimingDescriptor { TimingDescriptor { pixel_clock_khz: 241_500, @@ -485,6 +523,56 @@ mod tests { assert!(workspace.validate().is_empty()); } + #[test] + fn stereo_only_override_is_pending_and_leaves_the_source_edid_untouched() { + let mut raw = + patch_base_detailed_timing(&minimal_base_edid(0), 0, &sample_timing()).unwrap(); + raw[71] |= 0x61; + repair_checksum(&mut raw); + let workspace = EdidWorkspace::new(raw.clone()).unwrap(); + assert!(workspace.has_changes()); + assert_eq!(workspace.parsed().raw, raw); + assert_eq!(workspace.export_bytes()[71] & 0x61, 0); + assert!(block_checksum_valid(&workspace.export_bytes())); + assert!( + workspace + .diff_summary() + .iter() + .any(|line| line.contains("stereo flags")) + ); + } + + #[test] + fn range_changes_export_with_a_valid_checksum_and_can_be_reset() { + let mut raw = minimal_base_edid(0); + raw[18] = 1; + raw[19] = 4; + raw[24] = 1; + raw[54..72].copy_from_slice(&[ + 0, 0, 0, 0xfd, 0, 24, 120, 30, 200, 60, 1, 10, 0, 0, 0, 0, 0, 0, + ]); + repair_checksum(&mut raw); + let mut workspace = EdidWorkspace::new(raw.clone()).unwrap(); + workspace + .set_vrr_range(crate::edid::VrrRange { + min_hz: 40, + max_hz: 120, + }) + .unwrap(); + assert!(workspace.has_changes()); + assert!( + workspace + .diff_summary() + .iter() + .any(|line| line.contains("40–120 Hz")) + ); + assert!(block_checksum_valid(&workspace.export_bytes())); + assert_eq!(workspace.export_bytes()[59], 40); + workspace.reset().unwrap(); + assert_eq!(workspace.export_bytes(), raw); + assert!(!workspace.has_changes()); + } + #[test] fn unchanged_valid_workspace_has_no_validation_issues() { let workspace = EdidWorkspace::new(minimal_base_edid(0)).expect("workspace");