repo stringlengths 6 65 | file_url stringlengths 81 311 | file_path stringlengths 6 227 | content stringlengths 0 32.8k | language stringclasses 1 value | license stringclasses 7 values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:31:58 2026-01-04 20:25:31 | truncated bool 2 classes |
|---|---|---|---|---|---|---|---|---|
dbalsom/fluxfox | https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/tests/f86.rs | tests/f86.rs | mod common;
use crate::common::run_sector_test;
use fluxfox::prelude::*;
use std::path::PathBuf;
fn init() {
let _ = env_logger::builder().is_test(true).try_init();
}
#[test]
fn test_86f_write() {
init();
use std::io::Cursor;
let disk_image_buf = std::fs::read(".\\tests\\images\\transylvania\\Transylvania.86f").unwrap();
let mut in_buffer = Cursor::new(disk_image_buf);
let mut f86_image = DiskImage::load(&mut in_buffer, None, None, None).unwrap();
println!("Loaded 86F image of geometry {}...", f86_image.image_format().geometry);
let mut out_buffer = Cursor::new(Vec::new());
let fmt = DiskImageFileFormat::F86Image;
match fmt.save_image(&mut f86_image, &ParserWriteOptions::default(), &mut out_buffer) {
Ok(_) => println!("Saved 86F image."),
Err(e) => panic!("Failed to save 86F image: {}", e),
}
let out_inner: Vec<u8> = out_buffer.into_inner();
std::fs::write(".\\tests\\images\\temp\\temp_out.86f", out_inner).unwrap();
// let readback_disk_image_buf = std::fs::read(".\\tests\\images\\temp\\temp_out.86f").unwrap();
// let mut readback_in_buffer = Cursor::new(readback_disk_image_buf);
//
// let mut f86_image = match DiskImage::load(&mut readback_in_buffer) {
// Ok(image) => image,
// Err(e) => panic!("Failed to re-load new 86F image: {}", e),
// };
}
#[test]
fn test_86f_sector_tests() {
init();
run_sector_test(
PathBuf::from(".\\tests\\images\\sector_test\\sector_test_360k.86f"),
DiskImageFileFormat::F86Image,
);
}
| rust | MIT | b4c04b51746e5fe7769f49a1b32b8caad426fc81 | 2026-01-04T20:24:04.021295Z | false |
dbalsom/fluxfox | https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/tests/write_bitstream.rs | tests/write_bitstream.rs | mod common;
use fluxfox::prelude::*;
#[test]
fn test_bitstream_write() {
use std::io::Cursor;
let disk_image_buf = std::fs::read(".\\tests\\images\\transylvania\\Transylvania.86f").unwrap();
let mut in_buffer = Cursor::new(disk_image_buf);
let mut f86_image = DiskImage::load(&mut in_buffer, None, None, None).unwrap();
println!("Loaded 86F image of geometry {}...", f86_image.image_format().geometry);
let rsr = match f86_image.read_sector(
DiskCh::new(0, 0),
DiskChsnQuery::new(0, 0, 1, None),
None,
None,
RwScope::DataOnly,
false,
) {
Ok(result) => result,
Err(DiskImageError::DataError) => {
panic!("Data error reading sector.");
}
Err(e) => panic!("Error reading sector: {:?}", e),
};
let sector_data = rsr.data();
println!(
"Read sector data: {:02X?} of length {}",
§or_data[0..8],
sector_data.len()
);
assert_eq!(sector_data.len(), 512);
let original_data = sector_data.to_vec();
// let encoded_bits = encode_mfm(§or_data, false, mfm::MfmEncodingType::Data);
//
// let encoded_bytes = encoded_bits.to_bytes();
//
// let idx_range: Vec<u8> = (0..16).collect();
// for pair in idx_range.chunks_exact(2) {
// println!(
// "Encoded byte: {:08b}{:08b}",
// encoded_bytes[pair[0] as usize], encoded_bytes[pair[1] as usize]
// );
// }
match f86_image.write_sector(
DiskCh::new(0, 0),
DiskChsnQuery::new(0, 0, 1, 2),
None,
sector_data,
RwScope::DataOnly,
false,
false,
) {
Ok(result) => result,
Err(DiskImageError::DataError) => {
panic!("Data error writing sector.");
}
Err(e) => panic!("Error writing sector: {:?}", e),
};
// Read the sector back. It should be the same data.
let rsr = match f86_image.read_sector(
DiskCh::new(0, 0),
DiskChsnQuery::new(0, 0, 1, 2),
None,
None,
RwScope::DataOnly,
false,
) {
Ok(result) => result,
Err(DiskImageError::DataError) => {
panic!("Data error reading sector.");
}
Err(e) => panic!("Error reading sector: {:?}", e),
};
if rsr.data() != original_data {
println!("Original data: {:02X?}", &original_data[0..8]);
println!("Post-write data: {:02X?}", §or_data[0..8]);
panic!("Data read back from disk does not match written data!");
}
}
| rust | MIT | b4c04b51746e5fe7769f49a1b32b8caad426fc81 | 2026-01-04T20:24:04.021295Z | false |
dbalsom/fluxfox | https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/tests/hfe.rs | tests/hfe.rs | mod common;
use crate::common::run_sector_test;
use fluxfox::DiskImageFileFormat;
use std::path::PathBuf;
fn init() {
let _ = env_logger::builder().is_test(true).try_init();
}
#[test]
fn test_hfe_sector_tests() {
init();
run_sector_test(
PathBuf::from(".\\tests\\images\\sector_test\\sector_test_360k.hfe"),
DiskImageFileFormat::HfeImage,
);
}
| rust | MIT | b4c04b51746e5fe7769f49a1b32b8caad426fc81 | 2026-01-04T20:24:04.021295Z | false |
dbalsom/fluxfox | https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/tests/kryoflux.rs | tests/kryoflux.rs | mod common;
use crate::common::run_sector_test;
use fluxfox::DiskImageFileFormat;
use std::path::PathBuf;
fn init() {
let _ = env_logger::builder().is_test(true).try_init();
}
#[test]
fn test_kryoflux_sector_test() {
init();
run_sector_test(
PathBuf::from(".\\tests\\images\\sector_test\\sector_test_kryoflux_360k.zip"),
DiskImageFileFormat::KryofluxStream,
);
}
| rust | MIT | b4c04b51746e5fe7769f49a1b32b8caad426fc81 | 2026-01-04T20:24:04.021295Z | false |
dbalsom/fluxfox | https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/tests/common/convert_exact.rs | tests/common/convert_exact.rs | /*
FluxFox
https://github.com/dbalsom/fluxfox
Copyright 2024-2025 Daniel Balsom
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the “Software”),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
--------------------------------------------------------------------------
*/
//! Demonstrate the ability for a file parser that supports writing to produce
//! output to be matched against a reference image. Normally we would test
//! invertibility, but for example we may wish to test reading a compressed
//! image, but comparing the write result to an equivalent uncompressed image.
use crate::common::compute_slice_hash;
use fluxfox::{prelude::ParserWriteOptions, DiskImage, DiskImageFileFormat, ImageFormatParser};
use std::path::PathBuf;
pub fn test_convert_exact(in_path: impl Into<PathBuf>, reference_image: impl Into<PathBuf>, fmt: DiskImageFileFormat) {
use std::io::Cursor;
let in_path = in_path.into();
let reference_image = reference_image.into();
let ext = in_path
.extension()
.map(|os| os.to_string_lossy().to_string())
.unwrap_or("".to_string());
let disk_image_buf = std::fs::read(in_path).unwrap();
let mut in_buffer = Cursor::new(disk_image_buf);
let mut disk = DiskImage::load(&mut in_buffer, None, None, None).unwrap();
let geometry = disk.image_format().geometry;
println!("Loaded \"{}\" file of geometry {}...", ext, geometry);
let format = disk.closest_format(false).unwrap();
println!("Closest format is {:?}", format);
let mut out_buffer = Cursor::new(Vec::new());
fmt.save_image(&mut disk, &ParserWriteOptions::default(), &mut out_buffer)
.unwrap();
let out_inner: Vec<u8> = out_buffer.into_inner();
let ref_image_buf = std::fs::read(reference_image).unwrap();
let ref_buffer = Cursor::new(ref_image_buf);
let ref_inner: Vec<u8> = ref_buffer.into_inner();
let ref_hash = compute_slice_hash(&ref_inner);
//println!("Input file is {} bytes.", in_inner.len());
//println!("First bytes of input file: {:02X?}", &in_inner[0..16]);
println!("Reference file SHA1: {}", ref_hash);
let out_hash = compute_slice_hash(&out_inner);
println!("Output file SHA1: {:}", out_hash);
assert_eq!(ref_hash, out_hash);
println!("Hashes match!");
}
| rust | MIT | b4c04b51746e5fe7769f49a1b32b8caad426fc81 | 2026-01-04T20:24:04.021295Z | false |
dbalsom/fluxfox | https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/tests/common/invertibility.rs | tests/common/invertibility.rs | /*
FluxFox
https://github.com/dbalsom/fluxfox
Copyright 2024-2025 Daniel Balsom
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the “Software”),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
--------------------------------------------------------------------------
*/
//! File formats that support reading and writing should be able to demonstrate
//! invertibility - that is, a file that is read from and written back to the
//! same format should be identical to the original file (assuming that the source
//! file does not contain missing or invalid metadata that fluxfox is able to
//! reconstruct).
use crate::common::compute_slice_hash;
use fluxfox::{prelude::ParserWriteOptions, DiskImage, DiskImageFileFormat, ImageFormatParser};
use std::path::PathBuf;
pub fn test_invertibility(in_path: impl Into<PathBuf>, fmt: DiskImageFileFormat) {
use std::io::Cursor;
let in_path = in_path.into();
let ext = in_path
.extension()
.map(|os| os.to_string_lossy().to_string())
.unwrap_or("".to_string());
let disk_image_buf = std::fs::read(in_path).unwrap();
let mut in_buffer = Cursor::new(disk_image_buf);
let mut disk = DiskImage::load(&mut in_buffer, None, None, None).unwrap();
let geometry = disk.image_format().geometry;
println!("Loaded \"{}\" file of geometry {}...", ext, geometry);
let format = disk.closest_format(false).unwrap();
println!("Closest format is {:?}", format);
//assert_eq!(format, StandardFormat::AmigaFloppy880);
let mut out_buffer = Cursor::new(Vec::new());
fmt.save_image(&mut disk, &ParserWriteOptions::default(), &mut out_buffer)
.unwrap();
let in_inner: Vec<u8> = in_buffer.into_inner();
let out_inner: Vec<u8> = out_buffer.into_inner();
let in_hash = compute_slice_hash(&in_inner);
//println!("Input file is {} bytes.", in_inner.len());
//println!("First bytes of input file: {:02X?}", &in_inner[0..16]);
println!("Input file SHA1: {}", in_hash);
let out_hash = compute_slice_hash(&out_inner);
println!("Output file SHA1: {:}", out_hash);
assert_eq!(in_hash, out_hash);
println!("Hashes match!");
}
| rust | MIT | b4c04b51746e5fe7769f49a1b32b8caad426fc81 | 2026-01-04T20:24:04.021295Z | false |
dbalsom/fluxfox | https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/tests/common/mod.rs | tests/common/mod.rs | /*
FluxFox
https://github.com/dbalsom/fluxfox
Copyright 2024-2025 Daniel Balsom
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the “Software”),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
--------------------------------------------------------------------------
tests/common/mod.rs
Common support routines for tests
*/
#![allow(dead_code)]
#![allow(unused_imports)]
pub mod convert_exact;
pub mod invertibility;
pub use convert_exact::test_convert_exact;
pub use invertibility::test_invertibility;
use fluxfox::{io::Read, prelude::*, DiskImage, DiskImageFileFormat, DEFAULT_SECTOR_SIZE};
use hex::encode;
use sha1::{Digest, Sha1};
use std::{
io::{Seek, SeekFrom},
path::{Path, PathBuf},
sync::{Arc, RwLock},
};
#[allow(dead_code)]
pub fn compute_file_hash<P: AsRef<Path>>(path: P) -> String {
let file_buf = std::fs::read(path).unwrap();
let mut hasher = Sha1::new();
hasher.update(file_buf);
let result = hasher.finalize();
encode(result)
}
#[allow(dead_code)]
pub fn compute_slice_hash(slice: &[u8]) -> String {
let mut hasher = Sha1::new();
hasher.update(slice);
let result = hasher.finalize();
encode(result)
}
#[allow(dead_code)]
pub fn get_raw_image_address(chs: DiskChs, geom: DiskChs) -> usize {
if chs.s() == 0 {
log::warn!("Invalid sector == 0");
return 0;
}
let hpc = geom.h() as usize;
let spt = geom.s() as usize;
let lba: usize = (chs.c() as usize * hpc + (chs.h() as usize)) * spt + (chs.s() as usize - 1);
lba * DEFAULT_SECTOR_SIZE
}
pub fn run_sector_test(file_path: impl Into<PathBuf>, fmt: DiskImageFileFormat) {
use std::io::Cursor;
let file_path = file_path.into();
let disk_image_buf = std::fs::read(file_path).unwrap();
let mut in_buffer = Cursor::new(disk_image_buf);
let disk = match DiskImage::load(&mut in_buffer, None, None, None) {
Ok(image) => image,
Err(e) => panic!("Failed to load {} image: {}", fmt, e),
};
println!("Loaded {} image of geometry {}...", fmt, disk.image_format().geometry);
println!("Verifying sectors...");
verify_sector_test_sectors(DiskImage::into_arc(disk));
println!("Success!");
}
pub fn verify_sector_test_sectors(disk_lock: Arc<RwLock<DiskImage>>) {
{
let mut disk = disk_lock.write().unwrap();
verify_sector_test_sectors_direct(&mut disk);
}
verify_sector_test_sectors_via_view(disk_lock);
}
/// The sector test image stores a u8 value in each sector that increments for each sector, wrapping.
/// This image was written to a floppy, then read back as a Kryoflux and SCP file via Greaseweazle,
/// then converted to other formats.
///
/// This function reads the sectors of a DiskImage and verifies that the u8 values are correct and
/// incrementing in the same way as the sector test image.
#[allow(dead_code)]
pub fn verify_sector_test_sectors_direct(disk: &mut DiskImage) {
let layout = disk.closest_format(false).unwrap().layout();
for (si, sector) in layout.chsn_iter().skip(1).enumerate() {
let sector_byte = si + 1;
let sector_data = disk
.read_sector_basic(sector.ch(), sector.into(), None)
.unwrap_or_else(|e| panic!("Failed to read sector {}: {}", sector.ch(), e));
for byte in §or_data {
if *byte != sector_byte as u8 {
eprintln!(
"Sector byte mismatch at sector {}: expected {}, got {}.",
sector, sector_byte, *byte,
);
assert_eq!(*byte, sector_byte as u8);
}
}
}
}
/// The sector test image stores a u8 value in each sector that increments for each sector, wrapping.
/// This image was written to a floppy, then read back as a Kryoflux and SCP file via Greaseweazle,
/// then converted to other formats.
///
/// This function reads the sectors of a DiskImage and verifies that the u8 values are correct and
/// incrementing in the same way as the sector test image, using a StandardSectorView.
#[allow(dead_code)]
pub fn verify_sector_test_sectors_via_view(disk_lock: Arc<RwLock<DiskImage>>) {
let format = {
let disk = disk_lock.read().unwrap();
match disk.closest_format(true) {
Some(f) => f,
None => panic!("Couldn't detect disk format."),
}
};
let mut view = match StandardSectorView::new(disk_lock.clone(), format) {
Ok(view) => view,
Err(e) => panic!("Failed to create StandardSectorView: {}", e),
};
let chs = DiskChs::from(format);
let sector_ct = chs.sector_count() as usize;
let mut sector_buf = vec![0u8; format.sector_size()];
// Skip the boot sector
view.seek(SeekFrom::Start(format.chsn().n_size() as u64)).unwrap();
// Start counting from 1 as we skipped boot sector
for sector_idx in 1..sector_ct {
//let offset = sector_idx * format.sector_size();
// Read the sector
view.read_exact(&mut sector_buf) // Read the sector
.unwrap_or_else(|e| panic!("Failed to read sector {}: {}", sector_idx, e));
for byte in §or_buf {
if *byte != sector_idx as u8 {
eprintln!(
"Sector byte mismatch at sector {}: expected {}, got {}.",
sector_idx, sector_idx, byte
);
assert_eq!(*byte, sector_idx as u8);
}
}
}
}
| rust | MIT | b4c04b51746e5fe7769f49a1b32b8caad426fc81 | 2026-01-04T20:24:04.021295Z | false |
dbalsom/fluxfox | https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/crates/fluxfox_tiny_skia/src/render_display_list.rs | crates/fluxfox_tiny_skia/src/render_display_list.rs | /*
FluxFox
https://github.com/dbalsom/fluxfox
Copyright 2024-2025 Daniel Balsom
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the “Software”),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
--------------------------------------------------------------------------
*/
use crate::{render_elements::*, styles::SkiaStyle};
use fluxfox::{track_schema::GenericTrackElement, visualization::prelude::*, FoxHashMap};
use tiny_skia::{Paint, Pixmap, Stroke};
pub fn render_display_list(
pixmap: &mut Pixmap,
paint: &mut Paint,
angle: f32,
display_list: &VizElementDisplayList,
track_style: &SkiaStyle,
styles: &FoxHashMap<GenericTrackElement, SkiaStyle>,
) -> Result<(), String> {
// Create a transform to rotate around the center of the pixmap
let transform = tiny_skia::Transform::from_rotate_at(
angle.to_degrees(),
pixmap.width() as f32 / 2.0,
pixmap.height() as f32 / 2.0,
);
for element in display_list.iter() {
skia_render_element(pixmap, paint, &transform, track_style, &styles, element);
}
Ok(())
}
pub fn render_data_display_list(
pixmap: &mut Pixmap,
paint: &mut Paint,
angle: f32,
display_list: &VizDataSliceDisplayList,
) -> Result<(), String> {
// Create a transform to rotate around the center of the pixmap
let transform = tiny_skia::Transform::from_rotate_at(
angle.to_degrees(),
pixmap.width() as f32 / 2.0,
pixmap.height() as f32 / 2.0,
);
// Disable antialiasing to reduce moiré. We do a similar thing with SVG rendering
paint.anti_alias = false;
let mut stroke = Stroke::default();
if display_list.track_width == 0.0 {
log::error!("Track width is 0, nothing will be rendered!");
}
stroke.width = display_list.track_width;
for slice in display_list.iter() {
skia_render_data_slice(pixmap, paint, &mut stroke, &transform, slice);
}
Ok(())
}
| rust | MIT | b4c04b51746e5fe7769f49a1b32b8caad426fc81 | 2026-01-04T20:24:04.021295Z | false |
dbalsom/fluxfox | https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/crates/fluxfox_tiny_skia/src/prelude.rs | crates/fluxfox_tiny_skia/src/prelude.rs | /*
FluxFox
https://github.com/dbalsom/fluxfox
Copyright 2024-2025 Daniel Balsom
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the “Software”),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
--------------------------------------------------------------------------
*/
pub use crate::styles::{default_skia_styles, SkiaStyle};
| rust | MIT | b4c04b51746e5fe7769f49a1b32b8caad426fc81 | 2026-01-04T20:24:04.021295Z | false |
dbalsom/fluxfox | https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/crates/fluxfox_tiny_skia/src/lib.rs | crates/fluxfox_tiny_skia/src/lib.rs | /*
FluxFox
https://github.com/dbalsom/fluxfox
Copyright 2024-2025 Daniel Balsom
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the “Software”),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
--------------------------------------------------------------------------
*/
pub mod prelude;
pub mod render_display_list;
pub mod render_elements;
pub mod renderer;
pub mod styles;
// Re-export tiny_skia
pub use tiny_skia;
pub const DEFAULT_DATA_SLICES: usize = 1440;
pub const DEFAULT_VIEW_BOX: f32 = 512.0;
| rust | MIT | b4c04b51746e5fe7769f49a1b32b8caad426fc81 | 2026-01-04T20:24:04.021295Z | false |
dbalsom/fluxfox | https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/crates/fluxfox_tiny_skia/src/render_elements.rs | crates/fluxfox_tiny_skia/src/render_elements.rs | /*
FluxFox
https://github.com/dbalsom/fluxfox
Copyright 2024-2025 Daniel Balsom
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the “Software”),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
--------------------------------------------------------------------------
*/
use tiny_skia::{Color, FillRule, Paint, PathBuilder, Pixmap, Stroke, Transform};
use crate::styles::SkiaStyle;
use fluxfox::{
track_schema::GenericTrackElement,
visualization::{
prelude::{VizArc, VizDataSlice, VizElement, VizElementDisplayList, VizQuadraticArc, VizSector},
types::shapes::{VizElementFlags, VizShape},
},
FoxHashMap,
};
#[inline]
pub fn skia_render_arc(path: &mut PathBuilder, arc: &VizArc, line_to: bool) {
if line_to {
path.line_to(arc.start.x, arc.start.y);
}
else {
path.move_to(arc.start.x, arc.start.y);
}
path.cubic_to(arc.cp1.x, arc.cp1.y, arc.cp2.x, arc.cp2.y, arc.end.x, arc.end.y);
}
#[inline]
pub fn skia_render_quadratic_arc(path: &mut PathBuilder, arc: &VizQuadraticArc, line_to: bool) {
if line_to {
path.line_to(arc.start.x, arc.start.y);
}
else {
path.move_to(arc.start.x, arc.start.y);
}
path.quad_to(arc.cp.x, arc.cp.y, arc.end.x, arc.end.y);
}
#[inline]
pub fn skia_render_sector(path: &mut PathBuilder, sector: &VizSector) {
// Draw the inner curve from start to end
skia_render_arc(path, §or.inner, false);
// Draw the outer curve from end to start
skia_render_arc(path, §or.outer, true);
// Draw a line back to the inner curve start
path.line_to(sector.inner.start.x, sector.inner.start.y);
}
pub fn skia_render_shape(path: &mut PathBuilder, shape: &VizShape) {
match shape {
VizShape::CubicArc(arc, _thickness) => {
skia_render_arc(path, arc, false);
}
VizShape::QuadraticArc(arc, _thickness) => {
skia_render_quadratic_arc(path, arc, false);
}
VizShape::Sector(sector) => {
skia_render_sector(path, sector);
}
VizShape::Circle(_circle, _thickness) => {
//skia_render_circle(data, circle, line_to);
}
VizShape::Line(_line, _thickness) => {
//skia_render_line(data, line, line_to);
}
}
}
pub fn skia_render_display_list(
pixmap: &mut Pixmap,
paint: &mut Paint,
transform: &Transform,
display_list: &VizElementDisplayList,
track_style: &SkiaStyle,
palette: &FoxHashMap<GenericTrackElement, SkiaStyle>,
) {
for element in display_list.iter() {
skia_render_element(pixmap, paint, transform, track_style, palette, element);
}
}
pub fn skia_render_element(
pixmap: &mut Pixmap,
paint: &mut Paint,
transform: &Transform,
track_style: &SkiaStyle,
palette: &FoxHashMap<GenericTrackElement, SkiaStyle>,
element: &VizElement,
) {
let mut path = PathBuilder::new();
//log::debug!("Rendering sector: {:#?}", &element.sector);
//log::debug!("Rendering element: {:#?}", &element);
skia_render_shape(&mut path, &element.shape);
path.close();
let default_style = SkiaStyle::default();
let style = if element.flags.contains(VizElementFlags::TRACK) {
track_style
}
else if let Some(style) = palette.get(&element.info.element_type) {
style
}
else {
&default_style
};
paint.set_color(Color::from(style.fill));
if let Some(path) = path.finish() {
if !path.is_empty() {
pixmap.fill_path(&path, &paint, FillRule::Winding, transform.clone(), None);
}
}
}
/// Render a single data slice as a tiny_skia path. Unlike a sector element, a data slice is a single
/// arc with a stroke rendered at the track width.
pub fn skia_render_data_slice(
pixmap: &mut Pixmap,
paint: &mut Paint,
stroke: &mut Stroke,
transform: &Transform,
slice: &VizDataSlice,
) {
let mut path = PathBuilder::new();
skia_render_quadratic_arc(&mut path, &slice.arc, false);
//let v = ((slice.density * 1.5).clamp(0.0, 1.0) * 255.0) as u8;
let v = slice.mapped_density;
paint.set_color(Color::from_rgba8(v, v, v, 255));
if let Some(path) = path.finish() {
if !path.is_empty() {
pixmap.stroke_path(&path, &paint, stroke, transform.clone(), None);
}
}
}
| rust | MIT | b4c04b51746e5fe7769f49a1b32b8caad426fc81 | 2026-01-04T20:24:04.021295Z | false |
dbalsom/fluxfox | https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/crates/fluxfox_tiny_skia/src/renderer.rs | crates/fluxfox_tiny_skia/src/renderer.rs | /*
FluxFox
https://github.com/dbalsom/fluxfox
Copyright 2024-2025 Daniel Balsom
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the “Software”),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
--------------------------------------------------------------------------
*/
use fluxfox::{prelude::*, track_schema::GenericTrackElement, visualization::prelude::*, FoxHashMap};
use crate::{
styles::{default_skia_styles, BlendMode, ElementStyle, SkiaStyle},
DEFAULT_VIEW_BOX,
};
#[derive(Clone, Default)]
pub struct TinySkiaRenderer {
// The view box for a single head. This should be square.
side_view_box: VizRect<f32>,
// The view box for the entire visualization. This can be rectangular.
global_view_box: VizRect<f32>,
// Margins as top, right, bottom, left.
global_margins: (f32, f32, f32, f32),
// Whether to render the data layer.
render_data: bool,
// Maximum outer radius (should not exceed side_view_box.width / 2).
// Will be overridden if outer_radius_ratio is set.
outer_radius: f32,
// The direct inner radius (should not exceed max_outer_radius). Will be overridden if
// inner_radius_ratio is set.
inner_radius: f32,
// Whether to decode the data layer.
decode_data: bool,
// Whether to disable antialiasing for data groups (recommended: true, avoids moiré patterns).
data_crisp: bool,
// The number of segments to render the data layer with. Default is 1440.
data_slices: Option<usize>,
// Whether to render the metadata layer.
render_metadata: bool,
// Whether to render data and metadata layers to separate files,
// or to render them together in a single file.
render_layered: bool,
// Whether to render the sides side-by-side. If false, the sides will be rendered
// in separate documents.
render_side_by_side: bool,
// The spacing between sides when rendering side-by-side. Default is 0.
side_spacing: f32,
// The CSS blend mode to apply to the metadata layer if `render_layered` is enabled.
layer_blend_mode: BlendMode,
// The total number of sides to render. Default is 1. Will be overridden if `side_to_render`
// is set.
total_sides_to_render: u8,
// The side to render. Default is 0. If set, this will override `total_sides_to_render`
// to 1.
side_to_render: Option<u8>,
// Specify a single track to render. If isolate_track is set, the track will be rendered with
// width between outer and inner radii.
track_to_render: Option<u16>,
// Specify a single sector to render. If isolate_track is set, the sector will be rendered in
// position on its enclosing track, with the track width between the specified inner and outer
// radii. Otherwise, it will be rendered at its normal position on the disk.
// The second parameter in the tuple is an optional bitcell address, to allow selection of
// sectors when duplicate sector IDs are present. If None, the first matching sector will be
// rendered.
sector_to_render: (Option<DiskChsn>, Option<usize>),
// Flag to control whether turning direction is reversed for the second side.
reverse_turning: bool,
// Style mappings for generic elements. If not set, a default set of styles will be used.
skia_styles: FoxHashMap<GenericTrackElement, SkiaStyle>,
// Default style for track elements - a solid ring that is the background of each track.
// Default is transparent fill and 0 stroke.
track_style: ElementStyle,
// Internal state
common_params: CommonVizParams,
overlay_style: ElementStyle,
export_path: Option<String>,
build_error: bool,
error_message: Option<String>,
}
impl TinySkiaRenderer {
pub fn new() -> Self {
Self {
side_view_box: VizRect::from_tuple((0.0, 0.0), (DEFAULT_VIEW_BOX, DEFAULT_VIEW_BOX)),
global_view_box: VizRect::from_tuple((0.0, 0.0), (DEFAULT_VIEW_BOX, DEFAULT_VIEW_BOX)),
skia_styles: default_skia_styles(),
data_crisp: true,
reverse_turning: true,
// Start at 2 and take the minimum of image heads and 2.
// This can also get set to 1 if a specific side is set.
total_sides_to_render: 2,
..Default::default()
}
}
/// Set the view box for a single side. This effectively controls the default "resolution"
/// of the rendered image. The view box should be square, unless you really want a distorted
/// image. If radius is not set, radius will be set to half the height of the view box.
pub fn with_side_view_box(mut self, view_box: VizRect<f32>) -> Self {
if self.common_params.radius.is_none() {
self.common_params.radius = Some(view_box.height() / 2.0);
}
self.side_view_box = view_box;
self
}
/// Set the value of the track gap - ie, the inverse factor if the track width to render.
/// 0.5 will render tracks half as wide as the calculated track width.
/// 0.0 will render tracks at the calculated track width.
/// Value is clamped to the range [0.0, 0.9].
pub fn with_track_gap(mut self, gap: f32) -> Self {
// clamp the value
self.common_params.track_gap = gap.clamp(0.0, 0.9);
self
}
/// Set the global view box. You could use this to control margins, but it's probably better
/// to use the `with_margins` method instead.
pub fn with_global_view_box(mut self, view_box: VizRect<f32>) -> Self {
self.global_view_box = view_box;
self
}
/// Set a flag to render the data layer representation. In vector format, this will render
/// the data layer as a series of segments, stroked with a color representing the average flux
/// density for that segment.
/// # Arguments
/// * `state` - A boolean flag to enable or disable rendering of the data layer.
/// * `segments` - An optional parameter to specify the number of segments to render. If None,
/// the default number of segments will be used. If a value is provided, it will be clamped
/// to the range [360, 2880].
pub fn with_data_layer(mut self, state: bool, segments: Option<usize>) -> Self {
self.render_data = state;
self.data_slices = segments;
self
}
/// The angle in radians at which the index position will be rendered, from the perspective of
/// the specified turning direction. The default is 0.0, which will render the index position
/// at the 3 o'clock position. The angle is specified in radians.
///
/// Note that this value is ignored when generating metadata display lists - in general,
/// rotation should be handled by the renderer. For SVG output we emit a transformation to
/// rotate the entire group.
pub fn with_index_angle(mut self, angle: f32) -> Self {
self.common_params.index_angle = angle;
self
}
/// Specify a specific side to be rendered instead of the entire disk. The value must be
/// 0 or 1. If the value is 0, the bottom side will be rendered. If the value is 1, the top
/// side will be rendered.
pub fn with_side(mut self, side: u8) -> Self {
if side > 1 {
self.build_error = true;
self.error_message = Some("Invalid side to render.".to_string());
}
self.side_to_render = Some(side);
self.total_sides_to_render = 1;
self
}
/// Set the initial data turning direction. The default is Clockwise. This value represents
/// how the data wraps on the visualization from the viewer's perspective. It is the reverse
/// of the physical rotation direction of the disk.
pub fn with_initial_turning(mut self, turning: TurningDirection) -> Self {
self.common_params.direction = turning;
self
}
/// Specify whether the turning direction should be reversed for the second side. The default
/// is true. This will apply to the second side even if only the second side is rendered, for
/// consistency.
pub fn with_turning_side_flip(mut self, state: bool) -> Self {
self.reverse_turning = state;
self
}
/// Specify a single track to be rendered instead of the entire disk.
/// This will render the same track number on both sides unless a specific side is specified.
pub fn with_rendered_track(mut self, track: u16) -> Self {
self.track_to_render = Some(track);
self
}
/// Set the total number of sides to render. This value can be either 1 or 2, but this method
/// is typically used to set the rendering to 2 sides as 1 side is assumed when the side is
/// specified with `render_side`.
fn render_side(mut self, sides: u8) -> Self {
if sides < 1 || sides > 2 {
self.build_error = true;
self.error_message = Some("Invalid number of sides to render.".to_string());
}
else {
self.total_sides_to_render = sides;
if sides == 2 {
// If we're rendering both sides, clear the side to render.
// We shouldn't have really set this in the first place, but whatever.
self.side_to_render = None;
}
}
self
}
/// Flag to decode the data layer when rendering. Currently only supported for MFM tracks.
/// It will be ignored for GCR tracks.
pub fn decode_data(mut self, state: bool) -> Self {
self.decode_data = state;
self
}
/// Render the metadata layer.
pub fn with_metadata_layer(mut self, state: bool) -> Self {
self.render_metadata = state;
self
}
/// Render metadata on top of data layers, using the specified blend mode.
/// The default is true. If false, separate documents will be created for data and metadata
/// layers.
pub fn with_layer_stack(mut self, state: bool) -> Self {
self.render_layered = state;
self
}
/// Set a flag to render both sides of the disk in a single document, with the sides rendered
/// side-by-side, using the specified value of `spacing` between the two sides.
/// The default is true. If false, separate documents will be created for each side, and
/// potentially up to four documents may be created if `render_layered` is false and metadata
/// layer rendering is enabled.
pub fn side_by_side(mut self, state: bool, spacing: f32) -> Self {
self.render_side_by_side = state;
self.side_spacing = spacing;
self
}
/// Expand the global view box by the specified margins.
pub fn with_margins(mut self, top: f32, right: f32, bottom: f32, left: f32) -> Self {
self.global_margins = (top, right, bottom, left);
self
}
/// Specify the blend mode to use when rendering both data and metadata layers as a stack.
/// The default is `BlendMode::Normal`, which will hide the data layer when metadata is
/// present - be sure to set it to your desired mode if you want to see both layers.
pub fn with_blend_mode(mut self, mode: BlendMode) -> Self {
log::trace!("Setting blend mode to {:?}", mode);
self.layer_blend_mode = mode;
self
}
/// Specify the inner and outer radius ratios, as a fraction of the side view box width.
pub fn with_radius_ratios(mut self, inner: f32, outer: f32) -> Self {
self.common_params.min_radius_ratio = inner;
self.common_params.max_radius_ratio = outer;
self
}
/// Override the default styles with a custom set of styles. This must be a hash map of
/// `GenericTrackElement` to `ElementStyle`.
pub fn with_styles(mut self, _styles: FoxHashMap<GenericTrackElement, ElementStyle>) -> Self {
self
}
/// Override the default track style. Useful if you want to render metadata on its own,
/// with some sort of background.
pub fn with_track_style(mut self, style: ElementStyle) -> Self {
self.track_style = style;
self
}
pub fn render(mut self, disk: &DiskImage) -> Result<Self, String> {
if self.build_error {
return Err(self.error_message.unwrap_or("Unknown error.".to_string()));
}
self.total_sides_to_render = std::cmp::min(self.total_sides_to_render, disk.heads());
// Render each side
let starting_side = self.side_to_render.unwrap_or(0);
log::trace!(
"render(): starting side: {} sides to render: {}",
starting_side,
self.total_sides_to_render
);
Ok(self)
}
}
| rust | MIT | b4c04b51746e5fe7769f49a1b32b8caad426fc81 | 2026-01-04T20:24:04.021295Z | false |
dbalsom/fluxfox | https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/crates/fluxfox_tiny_skia/src/styles.rs | crates/fluxfox_tiny_skia/src/styles.rs | /*
FluxFox
https://github.com/dbalsom/fluxfox
Copyright 2024-2025 Daniel Balsom
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the “Software”),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
--------------------------------------------------------------------------
*/
use fluxfox::{track_schema::GenericTrackElement, visualization::prelude::VizColor, FoxHashMap};
use std::fmt::{self, Display, Formatter};
#[derive(Copy, Clone, Debug, Default)]
pub struct SkiaStyle {
pub fill: VizColor,
pub stroke: VizColor,
pub stroke_width: f32,
}
impl SkiaStyle {
pub fn fill_only(fill: VizColor) -> SkiaStyle {
SkiaStyle {
fill,
stroke: VizColor::from_rgba8(0, 0, 0, 0),
stroke_width: 0.0,
}
}
}
/// All supported SVG `style` tag blending modes.
/// https://developer.mozilla.org/en-US/docs/Web/CSS/mix-blend-mode
///
/// If the `serde` feature is enabled these will be available for deserialization,
/// such as from a config file (see the `imgviz` example for an example of this).
///
/// The blending mode is applied to the metadata layer when metadata visualization
/// is enabled in addition to data visualization.
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "lowercase"))]
#[derive(Copy, Clone, Debug, Default)]
pub enum BlendMode {
#[default]
Normal,
Multiply,
Screen,
Overlay,
Darken,
Lighten,
ColorDodge,
ColorBurn,
HardLight,
SoftLight,
Difference,
Exclusion,
Hue,
Saturation,
Color,
Luminosity,
}
impl Display for BlendMode {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match self {
BlendMode::Normal => write!(f, "normal"),
BlendMode::Multiply => write!(f, "multiply"),
BlendMode::Screen => write!(f, "screen"),
BlendMode::Overlay => write!(f, "overlay"),
BlendMode::Darken => write!(f, "darken"),
BlendMode::Lighten => write!(f, "lighten"),
BlendMode::ColorDodge => write!(f, "color-dodge"),
BlendMode::ColorBurn => write!(f, "color-burn"),
BlendMode::HardLight => write!(f, "hard-light"),
BlendMode::SoftLight => write!(f, "soft-light"),
BlendMode::Difference => write!(f, "difference"),
BlendMode::Exclusion => write!(f, "exclusion"),
BlendMode::Hue => write!(f, "hue"),
BlendMode::Saturation => write!(f, "saturation"),
BlendMode::Color => write!(f, "color"),
BlendMode::Luminosity => write!(f, "luminosity"),
}
}
}
/// Define style attributes for SVG elements.
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Copy, Clone, Debug, Default)]
pub struct ElementStyle {
/// The color to fill the element with. If no fill is desired, use `VizColor::TRANSPARENT`.
pub fill: VizColor,
/// The color to use to stroke the element path. If no stroke is desired, use `VizColor::TRANSPARENT`.
/// or set stroke_width to 0.0 (probably do both).
pub stroke: VizColor,
/// The width of the stroke. If no stroke is desired, set to 0.0.
pub stroke_width: f32,
}
/// Return a default mapping between [GenericTrackElement]s and [VizColor]s.
fn default_element_palette() -> FoxHashMap<GenericTrackElement, VizColor> {
// Defined colors
let viz_light_red: VizColor = VizColor::from_rgba8(180, 0, 0, 255);
let vis_purple: VizColor = VizColor::from_rgba8(180, 0, 180, 255);
let pal_medium_green = VizColor::from_rgba8(0x38, 0xb7, 0x64, 0xff);
let pal_dark_green = VizColor::from_rgba8(0x25, 0x71, 0x79, 0xff);
let pal_medium_blue = VizColor::from_rgba8(0x3b, 0x5d, 0xc9, 0xff);
let pal_light_blue = VizColor::from_rgba8(0x41, 0xa6, 0xf6, 0xff);
let pal_orange = VizColor::from_rgba8(0xef, 0x7d, 0x57, 0xff);
#[rustfmt::skip]
let palette = FoxHashMap::from([
(GenericTrackElement::SectorData, pal_medium_green),
(GenericTrackElement::SectorBadData, pal_orange),
(GenericTrackElement::SectorDeletedData, pal_dark_green),
(GenericTrackElement::SectorBadDeletedData, viz_light_red),
(GenericTrackElement::SectorHeader, pal_light_blue),
(GenericTrackElement::SectorBadHeader, pal_medium_blue),
(GenericTrackElement::Marker, vis_purple),
]);
palette
}
/// Return a default mapping between [GenericTrackElement]s and [SkiaStyle]s.
pub fn default_skia_styles() -> FoxHashMap<GenericTrackElement, SkiaStyle> {
let palette = default_element_palette();
let mut styles = FoxHashMap::new();
for (element, color) in palette.iter() {
styles.insert(
*element,
SkiaStyle {
fill: *color,
stroke: VizColor::TRANSPARENT,
stroke_width: 0.0,
},
);
}
styles
}
| rust | MIT | b4c04b51746e5fe7769f49a1b32b8caad426fc81 | 2026-01-04T20:24:04.021295Z | false |
dbalsom/fluxfox | https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/crates/ff_egui_app/src/app.rs | crates/ff_egui_app/src/app.rs | /*
FluxFox
https://github.com/dbalsom/fluxfox
Copyright 2024-2025 Daniel Balsom
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the “Software”),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
--------------------------------------------------------------------------
*/
use egui::Layout;
use fluxfox::{
file_system::{fat::fat_fs::FatFileSystem, FileSystemArchive},
DiskImage,
DiskImageError,
LoadingStatus,
};
use fluxfox_egui::{
controls::{
boot_sector::BootSectorWidget,
disk_info::DiskInfoWidget,
error_banner::ErrorBanner,
filesystem::FileSystemWidget,
header_group::{HeaderFn, HeaderGroup},
},
SectorSelection,
TrackListSelection,
TrackSelection,
TrackSelectionScope,
UiEvent,
UiLockContext,
};
use std::{
collections::VecDeque,
default::Default,
fmt,
fmt::{Display, Formatter},
path::PathBuf,
sync::{mpsc, Arc},
};
#[cfg(not(target_arch = "wasm32"))]
pub const APP_NAME: &str = "fluxfox-egui";
#[cfg(not(target_arch = "wasm32"))]
use crate::native::worker;
#[cfg(target_arch = "wasm32")]
use crate::wasm::worker;
#[cfg(target_arch = "wasm32")]
pub const APP_NAME: &str = "fluxfox-web";
use crate::{
widgets::{filename::FilenameWidget, hello::HelloWidget},
windows::{
disk_visualization::VisualizationViewer,
element_map::ElementMapViewer,
file_viewer::FileViewer,
new_viz::NewVizViewer,
sector_viewer::SectorViewer,
source_map::SourceMapViewer,
track_timing_viewer::TrackTimingViewer,
track_viewer::TrackViewer,
},
};
use fluxfox_egui::{controls::track_list::TrackListWidget, tracking_lock::TrackingLock};
pub const DEMO_IMAGE: &[u8] = include_bytes!("../../../resources/demo.imz");
/// The number of selection slots available for disk images.
/// These slots will be enumerating in the UI as `A:`, `B:`, and so on. The UI design does not
/// anticipate more than 2 slots, but could be adapted for more if you wish.
pub const DISK_SLOTS: usize = 2;
/// fluxfox-egui comprises several conceptual Tools.
///
/// Each tool has a unique identifier that can be used to track disk image locks for debugging.
/// Each tool may correspond to one or more widgets or windows, but provides a shared pool of
/// resources and communication channels.
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
pub enum Tool {
/// App is not a tool per se, but represents locks made in the main application logic.
/// Some Tools do not need to keep a persistent disk image lock as they display static
/// data that cannot change for the life of the loaded image (for example, the SourceMap)
/// The main application logic locks the disk image for the duration of the tool's update
/// cycle.
App,
/// The visualization tool renders a graphical depiction of the disk and allows track element
/// selection. It must own a DiskLock to support hit-testing user selections and rendering
/// vector display lists of the current selection.
Visualization,
NewViz,
SectorViewer,
TrackViewer,
TrackListViewer,
/// The filesystem viewer is currently the only tool that requires a write lock, due to
/// the use of a StandardSectorView, which requires a mutable reference to the disk image.
/// StandardSectorView is used as an interface for reading and writing sectors in a standard
/// raw-sector based order, such as what is expected by rust-fatfs.
FileSystemViewer,
/// A file system operation not necessarily tied to the filesystem viewer.
FileSystemOperation,
SourceMap,
TrackElementMap,
TrackTimingViewer,
}
impl Display for Tool {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
write!(f, "{:?}", self)
}
}
#[derive(Default)]
pub enum ThreadLoadStatus {
#[default]
Inactive,
Loading(f64),
Success(DiskImage, usize),
Error(DiskImageError),
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum RunMode {
Reactive,
Continuous,
}
#[derive(serde::Deserialize, serde::Serialize)]
#[serde(default)]
pub struct AppUserOptions {
auto_show_viz: bool,
logo_panel: bool,
archive_format: FileSystemArchive,
}
impl Default for AppUserOptions {
fn default() -> Self {
Self {
auto_show_viz: true,
logo_panel: true,
archive_format: FileSystemArchive::Zip,
}
}
}
#[derive(serde::Deserialize, serde::Serialize)]
#[serde(default)]
#[derive(Default)]
pub struct PersistentState {
user_opts: AppUserOptions,
}
pub struct AppWidgets {
hello: HelloWidget,
disk_info: DiskInfoWidget,
boot_sector: BootSectorWidget,
track_list: TrackListWidget,
file_system: FileSystemWidget,
filename: FilenameWidget,
}
impl AppWidgets {
pub fn new(_ui_sender: mpsc::SyncSender<UiEvent>) -> Self {
Self {
hello: HelloWidget::default(),
disk_info: DiskInfoWidget::default(),
boot_sector: BootSectorWidget::default(),
track_list: TrackListWidget::default(),
file_system: FileSystemWidget::default(),
filename: FilenameWidget::default(),
}
}
pub fn update_disk(&mut self, disk_lock: TrackingLock<DiskImage>, name: Option<String>) {
let disk = match disk_lock.read(UiLockContext::App) {
Ok(disk) => disk,
Err(_) => {
log::error!("Failed to lock disk image for reading. Cannot update widgets.");
return;
}
};
self.filename.set(name);
self.disk_info.update(&disk, None);
self.boot_sector.update(&disk);
self.track_list.update(&disk);
}
pub fn update_mut(&mut self, disk_lock: TrackingLock<DiskImage>) {
let mut fs = match FatFileSystem::mount(disk_lock, UiLockContext::FileSystemViewer, None) {
Ok(fs) => {
log::debug!("FAT filesystem mounted successfully!");
Some(fs)
}
Err(e) => {
log::error!("Error mounting FAT filesystem: {:?}", e);
None
}
};
if let Some(fs) = &mut fs {
self.file_system.update(fs);
}
drop(fs);
}
pub fn reset(&mut self) {
self.filename = FilenameWidget::default();
self.disk_info = DiskInfoWidget::default();
self.boot_sector = BootSectorWidget::default();
self.track_list = TrackListWidget::default();
self.file_system = FileSystemWidget::default();
}
}
pub struct AppWindows {
viz_viewer: VisualizationViewer,
new_viz_viewer: NewVizViewer,
sector_viewer: SectorViewer,
track_viewer: TrackViewer,
file_viewer: FileViewer,
source_map: SourceMapViewer,
element_map: ElementMapViewer,
track_timing_viewer: TrackTimingViewer,
}
impl AppWindows {
pub fn new(_ui_sender: mpsc::SyncSender<UiEvent>) -> Self {
Self {
viz_viewer: VisualizationViewer::new(),
new_viz_viewer: NewVizViewer::default(),
sector_viewer: SectorViewer::default(),
track_viewer: TrackViewer::default(),
file_viewer: FileViewer::default(),
source_map: SourceMapViewer::default(),
element_map: ElementMapViewer::default(),
track_timing_viewer: TrackTimingViewer::default(),
}
}
pub fn reset(&mut self) {
self.viz_viewer.reset();
self.new_viz_viewer.reset();
self.sector_viewer = SectorViewer::default();
self.track_viewer = TrackViewer::default();
self.file_viewer = FileViewer::default();
self.source_map = SourceMapViewer::default();
self.element_map = ElementMapViewer::default();
self.track_timing_viewer = TrackTimingViewer::default();
}
/// Update windows that hold a disk image lock with a new lock.
pub fn update_disk(&mut self, disk_lock: TrackingLock<DiskImage>, _name: Option<String>) {
// The visualization viewer can hold a read lock in the background for rendering, so it
// should be updated last.
match disk_lock.read(UiLockContext::App) {
Ok(disk) => self.source_map.update(&disk),
Err(_) => {
log::error!("Failed to lock disk image for reading. Cannot update windows.");
return;
}
};
log::debug!("Updating track data viewer...");
self.track_viewer.update_disk(disk_lock.clone());
log::debug!("Updating sector viewer...");
self.sector_viewer.update(disk_lock.clone(), SectorSelection::default());
log::debug!("Updating visualization...");
self.viz_viewer.update_disk(disk_lock.clone());
}
}
/// App events are sent from Tools to the main application state to request changes in the UI.
pub enum AppEvent {
#[allow(dead_code)]
Reset,
ResetDisk,
/// A DiskImage has been successfully loaded into the specified slot index.
ImageLoaded(usize),
SectorSelected(SectorSelection),
TrackSelected(TrackSelection),
TrackElementsSelected(TrackSelection),
TrackTimingsSelected(TrackSelection),
}
/// A [DiskSlot] represents data about a specific disk image slot.
#[derive(Default)]
pub struct DiskSlot {
pub image: Option<TrackingLock<DiskImage>>,
pub image_name: Option<String>,
pub source_path: Option<PathBuf>,
}
impl DiskSlot {
/// Create a new [DiskSlot] with the given [DiskImage], name, and source path.
/// Note: Do not use `into_arc` with [DiskImage], as the [TrackingLock] will do this for you.
pub fn new(image: DiskImage, name: Option<String>, path: Option<PathBuf>) -> Self {
Self {
image: Some(TrackingLock::new(image)),
image_name: name,
source_path: path,
}
}
pub fn attach_image(&mut self, image: DiskImage) {
self.image = Some(TrackingLock::new(image));
}
pub fn set_name(&mut self, name: Option<String>) {
self.image_name = name;
}
pub fn set_source_path(&mut self, path: Option<PathBuf>) {
self.source_path = path;
}
}
/// The main fluxfox-gui application state.
pub struct App {
/// State that should be serialized and deserialized on restart should be stored here.
/// Everything else will start as default.
p_state: PersistentState,
run_mode: RunMode,
ctx_init: bool,
pub(crate) dropped_files: Vec<egui::DroppedFile>,
load_status: ThreadLoadStatus,
load_sender: Option<mpsc::SyncSender<ThreadLoadStatus>>,
load_receiver: Option<mpsc::Receiver<ThreadLoadStatus>>,
tool_sender: mpsc::SyncSender<UiEvent>,
tool_receiver: mpsc::Receiver<UiEvent>,
/// The selected disk slot. This is used to track which disk image is currently selected for
/// viewing and manipulation.
pub(crate) selected_slot: usize,
pub(crate) disk_slots: [DiskSlot; DISK_SLOTS],
old_locks: Vec<TrackingLock<DiskImage>>,
supported_extensions: Vec<String>,
widgets: AppWidgets,
windows: AppWindows,
events: VecDeque<AppEvent>,
deferred_file_ui_event: Option<UiEvent>,
sector_selection: Option<SectorSelection>,
track_selection: Option<TrackSelection>,
error_msg: Option<String>,
}
impl Default for App {
fn default() -> Self {
let (load_sender, load_receiver) = mpsc::sync_channel(128);
let (tool_sender, tool_receiver) = mpsc::sync_channel(16);
Self {
// Example stuff:
p_state: PersistentState {
user_opts: AppUserOptions::default(),
},
run_mode: RunMode::Reactive,
ctx_init: false,
dropped_files: Vec::new(),
load_status: ThreadLoadStatus::Inactive,
load_sender: Some(load_sender),
load_receiver: Some(load_receiver),
widgets: AppWidgets::new(tool_sender.clone()),
windows: AppWindows::new(tool_sender.clone()),
tool_sender,
tool_receiver,
selected_slot: 0,
disk_slots: Default::default(),
old_locks: Vec::new(),
supported_extensions: Vec::new(),
events: VecDeque::new(),
deferred_file_ui_event: None,
sector_selection: None,
track_selection: None,
error_msg: None,
}
}
}
impl App {
pub fn selected_disk(&self) -> Option<TrackingLock<DiskImage>> {
self.disk_slots[self.selected_slot].image.clone()
}
pub fn have_disk_in_slot(&self, slot: usize) -> bool {
if slot >= DISK_SLOTS {
return false;
}
self.disk_slots[slot].image.is_some()
}
pub fn have_disk_in_selected_slot(&self) -> bool {
self.have_disk_in_slot(self.selected_slot)
}
pub fn slot(&self, slot: usize) -> &DiskSlot {
&self.disk_slots[slot % DISK_SLOTS]
}
pub fn slot_mut(&mut self, slot: usize) -> &mut DiskSlot {
&mut self.disk_slots[slot % DISK_SLOTS]
}
pub fn selected_slot(&self) -> &DiskSlot {
&self.disk_slots[self.selected_slot]
}
pub fn selected_slot_mut(&mut self) -> &mut DiskSlot {
&mut self.disk_slots[self.selected_slot]
}
pub fn set_slot(&mut self, slot: usize, new_slot: DiskSlot) {
if slot >= DISK_SLOTS {
return;
}
if self.disk_slots[slot].image.is_some() {
log::debug!(
"load_slot(): Ejecting disk {:?} from slot {}",
self.disk_slots[slot].image_name,
slot
);
self.eject_slot(slot);
}
log::debug!("load_slot(): Loading disk into slot {}", slot);
self.disk_slots[slot] = new_slot;
}
/// Eject the DiskSlot from the given slot index.
/// The corresponding DiskLock is moved to the old_locks list so that memory leaks can be
/// detected and reported.
pub fn eject_slot(&mut self, slot: usize) {
if slot >= DISK_SLOTS {
return;
}
if let Some(disk_slot) = self.disk_slots.get_mut(slot) {
if let Some(disk) = disk_slot.image.take() {
log::debug!("eject_slot(): Ejecting disk from slot {}", slot);
self.old_locks.push(disk);
}
else {
log::trace!("eject_slot(): No disk in slot {}", slot);
}
}
else {
log::error!("eject_slot(): Invalid slot index {}", slot);
}
}
}
impl App {
/// Called once before the first frame.
pub fn new(cc: &eframe::CreationContext<'_>) -> Self {
// This is also where you can customize the look and feel of egui using
// `cc.egui_ctx.set_visuals` and `cc.egui_ctx.set_fonts`.
let mut app_state = App::default();
// Load previous app state (if any).
// Note that you must enable the `persistence` feature for this to work.
if let Some(storage) = cc.storage {
app_state.p_state = eframe::get_value(storage, eframe::APP_KEY).unwrap_or_default();
}
// Initialize the visualization viewer
app_state
.windows
.viz_viewer
.init(cc.egui_ctx.clone(), 512, app_state.tool_sender.clone());
egui_extras::install_image_loaders(&cc.egui_ctx);
// Set dark mode. This doesn't seem to work for some reason.
// So we'll use a flag in state and do it on the first update().
//cc.egui_ctx.set_visuals(egui::Visuals::dark());
// Get and store the list of supported extensions
fluxfox::supported_extensions()
.iter()
.filter(|ext| **ext != "raw")
.for_each(|ext| {
app_state.supported_extensions.push(ext.to_string().to_uppercase());
});
app_state.supported_extensions.sort();
app_state
}
pub fn collect_garbage(&mut self) {
let lock_ct = self.old_locks.len();
self.old_locks.retain(|lock| lock.strong_count() > 0);
if lock_ct != self.old_locks.len() {
log::debug!(
"collect_garbage(): Collected {} locks, {} remaining",
lock_ct - self.old_locks.len(),
self.old_locks.len()
);
}
}
}
impl eframe::App for App {
/// Called each time the UI needs repainting, which may be many times per second.
fn update(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
// Put your widgets into a `SidePanel`, `TopBottomPanel`, `CentralPanel`, `Window` or `Area`.
// For inspiration and more examples, go to https://emilk.github.io/egui
self.collect_garbage();
if !self.ctx_init {
self.ctx_init(ctx);
}
if matches!(self.run_mode, RunMode::Continuous) {
ctx.request_repaint();
}
// Show windows
if self.have_disk_in_selected_slot() {
self.windows.source_map.show(ctx);
}
#[cfg(feature = "devmode")]
{
self.windows.new_viz_viewer.show(ctx);
}
self.windows.viz_viewer.show(ctx);
self.windows.sector_viewer.show(ctx);
self.windows.track_viewer.show(ctx);
self.windows.file_viewer.show(ctx);
self.windows.element_map.show(ctx);
self.windows.track_timing_viewer.show(ctx);
egui::TopBottomPanel::top("top_panel").show(ctx, |ui| {
// The top panel is often a good place for a menu bar:
self.handle_menu(ctx, ui);
// Done with menu bar.
if self.p_state.user_opts.logo_panel {
self.widgets.hello.show(ui, APP_NAME, &self.supported_extensions);
ui.add_space(8.0);
}
// Show filename widget
self.widgets.filename.show(ui);
});
egui::SidePanel::left("disk_info_gallery")
.exact_width(250.0)
.show(ctx, |ui| {
ui.with_layout(Layout::top_down(egui::Align::Center), |ui| {
ui.add_space(6.0);
self.handle_image_info(ui);
ui.add_space(6.0);
self.handle_bootsector_info(ui);
});
});
egui::CentralPanel::default().show(ctx, |ui| {
// The central panel the region left after adding TopPanels and SidePanels
self.show_error(ui);
// Show dropped files (if any):
self.handle_dropped_files(ctx, None);
self.handle_loading_progress(ui);
ui.with_layout(Layout::top_down_justified(egui::Align::Center), |ui| {
ui.allocate_ui_with_layout(ui.available_size(), Layout::left_to_right(egui::Align::Min), |ui| {
self.handle_track_info(ui);
self.handle_fs_info(ui);
});
});
self.handle_load_messages(ctx);
ui.with_layout(Layout::bottom_up(egui::Align::LEFT), |ui| {
egui::warn_if_debug_build(ui);
});
});
self.handle_ui_events();
self.handle_app_events();
}
/// Called by the framework to save persistent state before shutdown.
fn save(&mut self, storage: &mut dyn eframe::Storage) {
eframe::set_value(storage, eframe::APP_KEY, &self.p_state);
}
}
impl App {
/// Initialize the egui context, for visuals, etc.
/// Tried doing this in new() but it didn't take effect.
pub fn ctx_init(&mut self, ctx: &egui::Context) {
ctx.set_visuals(egui::Visuals::dark());
self.ctx_init = true;
}
pub fn new_disk(&mut self) {
log::debug!("Resetting application state for new disk...");
//self.disk_image_name = None;
self.error_msg = None;
self.widgets.reset();
self.windows.reset();
}
pub fn reset(&mut self) {
log::debug!("Resetting application state...");
for i in 0..DISK_SLOTS {
self.eject_slot(i);
}
self.error_msg = None;
self.load_status = ThreadLoadStatus::Inactive;
self.run_mode = RunMode::Reactive;
self.widgets.reset();
self.windows.reset();
}
// Optional: clear dropped files when done
fn clear_dropped_files(&mut self) {
self.dropped_files.clear();
}
fn show_error(&mut self, ui: &mut egui::Ui) {
if let Some(msg) = &self.error_msg {
ErrorBanner::new(msg).large().show(ui);
// egui::Frame::none()
// .fill(egui::Color32::DARK_RED)
// .rounding(8.0)
// .inner_margin(8.0)
// .stroke(egui::Stroke::new(1.0, egui::Color32::GRAY))
// .show(ui, |ui| {
// ui.horizontal(|ui| {
// ui.label(egui::RichText::new("🗙").color(egui::Color32::WHITE).size(32.0));
// ui.add(egui::Label::new(
// egui::RichText::new(msg).color(egui::Color32::WHITE).size(24.0),
// ));
// });
// });
}
}
fn handle_menu(&mut self, ctx: &egui::Context, ui: &mut egui::Ui) {
egui::menu::bar(ui, |ui| {
// NOTE: no File->Quit on web pages!
let is_web = cfg!(target_arch = "wasm32");
if !is_web {
ui.menu_button("File", |ui| {
if ui.button("Quit").clicked() {
ctx.send_viewport_cmd(egui::ViewportCommand::Close);
}
});
ui.add_space(16.0);
}
else {
//log::debug!("Running on web platform, showing Image menu");
ui.menu_button("Image", |ui| {
if ui.button("Load demo image...").clicked() {
let mut cursor = std::io::Cursor::new(DEMO_IMAGE);
DiskImage::load(&mut cursor, None, None, None)
.map(|disk| {
log::debug!("Disk image loaded successfully!");
let disk = DiskSlot {
image: Some(TrackingLock::new(disk)),
image_name: Some("demo.imz".to_string()),
source_path: None,
};
self.set_slot(0, disk);
self.new_disk();
ctx.request_repaint();
self.events.push_back(AppEvent::ImageLoaded(self.selected_slot));
})
.unwrap_or_else(|e| {
log::error!("Error loading disk image: {:?}", e);
self.error_msg = Some(e.to_string());
});
ui.close_menu();
}
});
}
ui.menu_button("Windows", |ui| {
ui.checkbox(self.windows.viz_viewer.open_mut(), "Visualization");
#[cfg(feature = "devmode")]
{
ui.checkbox(self.windows.new_viz_viewer.open_mut(), "Visualization (New)");
}
ui.checkbox(self.windows.source_map.open_mut(), "Image Source Map");
});
ui.menu_button("Options", |ui| {
ui.checkbox(&mut self.p_state.user_opts.auto_show_viz, "Auto-show Visualization");
ui.checkbox(&mut self.p_state.user_opts.logo_panel, "Show fluxfox logo panel");
ui.menu_button("Archive format", |ui| {
ui.radio_value(
&mut self.p_state.user_opts.archive_format,
FileSystemArchive::Zip,
"ZIP",
);
ui.radio_value(
&mut self.p_state.user_opts.archive_format,
FileSystemArchive::Tar,
"TAR",
);
});
});
});
}
fn handle_app_events(&mut self) {
while let Some(event) = self.events.pop_front() {
match event {
AppEvent::Reset => {
log::debug!("Got AppEvent::Reset");
self.reset();
}
AppEvent::ResetDisk => {
log::debug!("Got AppEvent::ResetDisk");
self.new_disk();
}
AppEvent::ImageLoaded(slot_idx) => {
log::debug!("Got AppEvent::ImageLoaded");
// Return to reactive mode
self.run_mode = RunMode::Reactive;
self.error_msg = None;
if self.p_state.user_opts.auto_show_viz {
self.windows.viz_viewer.set_open(true);
#[cfg(feature = "devmode")]
{
self.windows.new_viz_viewer.set_open(true);
}
}
if let (Some(disk_image), image_name) = (
self.slot(slot_idx).image.clone(),
self.slot(slot_idx).image_name.clone(),
) {
// Update widgets. Update widgets that use a mutable reference first.
log::debug!("Updating widgets with new disk image...");
self.widgets.update_mut(disk_image.clone());
self.widgets.update_disk(disk_image.clone(), image_name.clone());
self.windows.update_disk(disk_image.clone(), image_name.clone());
self.sector_selection = Some(SectorSelection::default());
self.widgets.hello.set_small(true);
}
}
AppEvent::SectorSelected(selection) => {
if let Some(disk) = self.selected_disk() {
self.windows.sector_viewer.update(disk.clone(), selection.clone());
self.sector_selection = Some(selection);
self.windows.sector_viewer.set_open(true);
}
}
AppEvent::TrackSelected(selection) => {
if let Some(_disk) = self.selected_disk() {
self.windows.track_viewer.update_selection(selection.clone());
self.track_selection = Some(selection);
self.windows.track_viewer.set_open(true);
}
}
AppEvent::TrackElementsSelected(selection) => {
if let Some(disk) = self.selected_disk() {
self.windows.element_map.update(disk.clone(), selection.clone());
self.windows.element_map.set_open(true);
}
}
AppEvent::TrackTimingsSelected(selection) => {
if let Some(disk) = self.selected_disk() {
match disk.read(UiLockContext::App) {
Ok(disk) => {
if let Some(track) = disk.track(selection.phys_ch) {
if let Some(track) = track.as_fluxstream_track() {
self.windows.track_timing_viewer.update(
selection.phys_ch,
track.flux_deltas(),
Some(track.pll_markers()),
);
self.windows.track_timing_viewer.set_open(true);
}
}
}
Err(e) => {
log::error!("Failed to lock disk image for reading. Locked by {:?}", e);
}
}
}
}
}
}
}
fn handle_image_info(&mut self, ui: &mut egui::Ui) {
if self.have_disk_in_selected_slot() {
HeaderGroup::new("Disk Info").strong().expand().show(
ui,
|ui| {
self.widgets.disk_info.show(ui);
},
None::<HeaderFn>,
);
}
}
fn handle_bootsector_info(&mut self, ui: &mut egui::Ui) {
if self.have_disk_in_selected_slot() {
HeaderGroup::new("Boot Sector").strong().expand().show(
ui,
|ui| {
self.widgets.boot_sector.show(ui);
},
None::<HeaderFn>,
);
}
}
/// Handle UI events - events sent from tools to the application.
fn handle_ui_events(&mut self) {
let mut keep_polling = true;
while keep_polling {
match self.tool_receiver.try_recv() {
Ok(event) => match event {
UiEvent::SelectionChange(selection) => match selection {
TrackListSelection::Track(track) => {
self.events.push_back(AppEvent::TrackSelected(track));
}
TrackListSelection::Sector(sector) => {
log::warn!("handle_ui_events(): Sector selected: {:?}", sector);
self.events.push_back(AppEvent::SectorSelected(sector));
}
},
_ => {
log::warn!("Unhandled UiEvent: {:?}", event);
}
},
Err(_) => {
keep_polling = false;
}
}
}
}
fn handle_track_info(&mut self, ui: &mut egui::Ui) {
if self.have_disk_in_selected_slot() {
ui.group(|ui| {
if let Some(selection) = self.widgets.track_list.show(ui) {
log::debug!("TrackList selection: {:?}", selection);
match selection {
TrackListSelection::Track(track) => match track.sel_scope {
TrackSelectionScope::DecodedDataStream => {
self.events.push_back(AppEvent::TrackSelected(track));
}
TrackSelectionScope::Elements => {
self.events.push_back(AppEvent::TrackElementsSelected(track));
}
TrackSelectionScope::Timings => {
self.events.push_back(AppEvent::TrackTimingsSelected(track));
}
_ => log::warn!("Unsupported TrackSelectionScope: {:?}", track.sel_scope),
},
TrackListSelection::Sector(sector) => {
self.events.push_back(AppEvent::SectorSelected(sector));
}
}
}
});
}
}
fn handle_fs_info(&mut self, ui: &mut egui::Ui) {
let mut new_event = None;
if let Some(disk) = &mut self.selected_disk() {
| rust | MIT | b4c04b51746e5fe7769f49a1b32b8caad426fc81 | 2026-01-04T20:24:04.021295Z | true |
dbalsom/fluxfox | https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/crates/ff_egui_app/src/lib.rs | crates/ff_egui_app/src/lib.rs | /*
FluxFox
https://github.com/dbalsom/fluxfox
Copyright 2024-2025 Daniel Balsom
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the “Software”),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
--------------------------------------------------------------------------
*/
#![warn(clippy::all, rust_2018_idioms)]
pub(crate) mod app;
pub(crate) mod time;
pub(crate) mod widgets;
#[cfg(not(target_arch = "wasm32"))]
pub(crate) mod native;
pub(crate) mod ui;
#[cfg(target_arch = "wasm32")]
pub(crate) mod wasm;
pub(crate) mod windows;
pub use app::{App, APP_NAME};
| rust | MIT | b4c04b51746e5fe7769f49a1b32b8caad426fc81 | 2026-01-04T20:24:04.021295Z | false |
dbalsom/fluxfox | https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/crates/ff_egui_app/src/time.rs | crates/ff_egui_app/src/time.rs | /*
FluxFox
https://github.com/dbalsom/fluxfox
Copyright 2024-2025 Daniel Balsom
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the “Software”),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
--------------------------------------------------------------------------
*/
#![allow(unused_imports)]
//! Module providing time utilities for the application, resolving to either
//! `std::time` or `web_time` depending on the target platform.
#[cfg(target_arch = "wasm32")]
pub use web_time::{Duration, Instant};
#[cfg(not(target_arch = "wasm32"))]
pub use std::time::{Duration, Instant};
| rust | MIT | b4c04b51746e5fe7769f49a1b32b8caad426fc81 | 2026-01-04T20:24:04.021295Z | false |
dbalsom/fluxfox | https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/crates/ff_egui_app/src/ui.rs | crates/ff_egui_app/src/ui.rs | /*
FluxFox
https://github.com/dbalsom/fluxfox
Copyright 2024-2025 Daniel Balsom
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the “Software”),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
--------------------------------------------------------------------------
*/
use std::fmt::{Display, Formatter, Result};
#[allow(dead_code)]
pub enum UiTerm {
SaveFile,
OpenFile,
}
impl Display for UiTerm {
#[cfg(not(target_arch = "wasm32"))]
fn fmt(&self, f: &mut Formatter<'_>) -> Result {
match self {
UiTerm::SaveFile => write!(f, "Save File"),
UiTerm::OpenFile => write!(f, "Open File"),
}
}
#[cfg(target_arch = "wasm32")]
fn fmt(&self, f: &mut Formatter<'_>) -> Result {
match self {
UiTerm::SaveFile => write!(f, "Download File"),
UiTerm::OpenFile => write!(f, "Upload File"),
}
}
}
| rust | MIT | b4c04b51746e5fe7769f49a1b32b8caad426fc81 | 2026-01-04T20:24:04.021295Z | false |
dbalsom/fluxfox | https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/crates/ff_egui_app/src/main.rs | crates/ff_egui_app/src/main.rs | /*
FluxFox
https://github.com/dbalsom/fluxfox
Copyright 2024-2025 Daniel Balsom
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the “Software”),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
--------------------------------------------------------------------------
*/
#![warn(clippy::all, rust_2018_idioms)]
// hide console window on Windows in release, unless devmode feature is enabled
#![cfg_attr(all(not(debug_assertions), not(feature = "devmode")), windows_subsystem = "windows")]
// When compiling natively:
#[cfg(not(target_arch = "wasm32"))]
fn main() -> eframe::Result {
use ff_egui_app::APP_NAME;
env_logger::init(); // Log to stderr (if you run with `RUST_LOG=debug`).
let native_options = eframe::NativeOptions {
viewport: egui::ViewportBuilder::default()
.with_inner_size([640.0, 480.0])
.with_min_inner_size([640.0, 480.0])
.with_icon(
// NOTE: Adding an icon is optional
eframe::icon_data::from_png_bytes(&include_bytes!("../assets/icon-256.png")[..])
.expect("Failed to load icon"),
)
.with_drag_and_drop(true),
..Default::default()
};
eframe::run_native(
APP_NAME,
native_options,
Box::new(|cc| Ok(Box::new(ff_egui_app::App::new(cc)))),
)
}
// When compiling to web using trunk:
#[cfg(target_arch = "wasm32")]
fn main() {
use eframe::wasm_bindgen::JsCast as _;
// Redirect `log` message to `console.log` and friends:
eframe::WebLogger::init(log::LevelFilter::Debug).ok();
log::debug!("Hello, web!");
let web_options = eframe::WebOptions::default();
wasm_bindgen_futures::spawn_local(async {
let document = web_sys::window().expect("No window").document().expect("No document");
let canvas = document
.get_element_by_id("the_canvas_id")
.expect("Failed to find the_canvas_id")
.dyn_into::<web_sys::HtmlCanvasElement>()
.expect("the_canvas_id was not a HtmlCanvasElement");
let start_result = eframe::WebRunner::new()
.start(
canvas,
web_options,
Box::new(|cc| Ok(Box::new(ff_egui_app::App::new(cc)))),
)
.await;
// Remove the loading text and spinner:
if let Some(loading_text) = document.get_element_by_id("loading_text") {
match start_result {
Ok(_) => {
loading_text.remove();
}
Err(e) => {
loading_text.set_inner_html("<p> The app has crashed. See the developer console for details. </p>");
panic!("Failed to start eframe: {e:?}");
}
}
}
});
}
| rust | MIT | b4c04b51746e5fe7769f49a1b32b8caad426fc81 | 2026-01-04T20:24:04.021295Z | false |
dbalsom/fluxfox | https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/crates/ff_egui_app/src/native/app.rs | crates/ff_egui_app/src/native/app.rs | /*
FluxFox
https://github.com/dbalsom/fluxfox
Copyright 2024-2025 Daniel Balsom
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the “Software”),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
--------------------------------------------------------------------------
*/
use std::sync::Arc;
use crate::App;
use anyhow::Result;
impl App {
pub(crate) fn load_dropped_files(&mut self) {
for file in &mut self.dropped_files {
// Check if the file needs to be loaded
if file.bytes.is_none() && file.path.is_some() && file.path.as_ref().unwrap().is_file() {
let path = file.path.as_ref().unwrap();
// Load the file
file.bytes = match std::fs::read(path) {
Ok(bytes) => Some(Arc::from(bytes.into_boxed_slice())),
Err(e) => {
log::error!("Failed to read file {}: {:?}", path.display(), e);
None
}
};
}
}
}
pub(crate) fn save_file_as(_path: &str, _bytes: &[u8]) -> Result<()> {
Ok(())
}
}
| rust | MIT | b4c04b51746e5fe7769f49a1b32b8caad426fc81 | 2026-01-04T20:24:04.021295Z | false |
dbalsom/fluxfox | https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/crates/ff_egui_app/src/native/util.rs | crates/ff_egui_app/src/native/util.rs | /*
FluxFox
https://github.com/dbalsom/fluxfox
Copyright 2024-2025 Daniel Balsom
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the “Software”),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
--------------------------------------------------------------------------
*/
pub(crate) fn get_logo_image<'a>() -> egui::Image<'a> {
egui::Image::new(egui::include_image!("../../assets/fluxfox_logo.png")).fit_to_original_size(1.0)
}
| rust | MIT | b4c04b51746e5fe7769f49a1b32b8caad426fc81 | 2026-01-04T20:24:04.021295Z | false |
dbalsom/fluxfox | https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/crates/ff_egui_app/src/native/worker.rs | crates/ff_egui_app/src/native/worker.rs | /*
FluxFox
https://github.com/dbalsom/fluxfox
Copyright 2024-2025 Daniel Balsom
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the “Software”),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
--------------------------------------------------------------------------
*/
use anyhow::Error;
use std::thread::JoinHandle;
pub(crate) fn spawn_closure_worker<F, T>(f: F) -> Result<JoinHandle<T>, Error>
where
F: FnOnce() -> T + Send + 'static,
T: Send + 'static,
{
Ok(std::thread::spawn(f))
}
| rust | MIT | b4c04b51746e5fe7769f49a1b32b8caad426fc81 | 2026-01-04T20:24:04.021295Z | false |
dbalsom/fluxfox | https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/crates/ff_egui_app/src/native/mod.rs | crates/ff_egui_app/src/native/mod.rs | /*
FluxFox
https://github.com/dbalsom/fluxfox
Copyright 2024-2025 Daniel Balsom
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the “Software”),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
--------------------------------------------------------------------------
*/
pub(crate) mod app;
pub(crate) mod util;
pub(crate) mod worker;
| rust | MIT | b4c04b51746e5fe7769f49a1b32b8caad426fc81 | 2026-01-04T20:24:04.021295Z | false |
dbalsom/fluxfox | https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/crates/ff_egui_app/src/wasm/app.rs | crates/ff_egui_app/src/wasm/app.rs | /*
FluxFox
https://github.com/dbalsom/fluxfox
Copyright 2024-2025 Daniel Balsom
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the “Software”),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
--------------------------------------------------------------------------
*/
use crate::App;
use anyhow::{anyhow, Result};
use wasm_bindgen::prelude::*;
use web_sys::{js_sys, window, Blob, BlobPropertyBag, Url};
impl App {
pub(crate) fn load_dropped_files(&mut self) {
// The browser loads dropped files for us, so this is a stub.
}
pub(crate) fn save_file_as(path: &str, bytes: &[u8]) -> Result<()> {
let filename = path.rsplit('/').next().ok_or_else(|| anyhow!("Invalid path"))?;
// Convert the bytes to a `Uint8Array` for compatibility with JavaScript
log::debug!("Saving file as: {}, byte dump: {:0X?}", path, &bytes[0..16]);
// I don't really understand this sequence of operations, but attempting to use the uint8_array
// directly doesn't seem to work. Working code shamelessly taken from:
// https://stackoverflow.com/questions/69556755/web-sysurlcreate-object-url-with-blobblob-not-formatting-binary-data-co
let uint8_array = js_sys::Uint8Array::new(&unsafe { js_sys::Uint8Array::view(bytes) }.into());
let array = js_sys::Array::new();
array.push(&uint8_array.buffer());
// Create a new `Blob` from the `Uint8Array`
let bag = BlobPropertyBag::new();
bag.set_type("application/octet-stream");
let blob =
Blob::new_with_u8_array_sequence_and_options(&array, &bag).map_err(|_| anyhow!("Failed to create Blob"))?;
// Create an object URL for the Blob
let url =
Url::create_object_url_with_blob(&blob).map_err(|_| anyhow!("Failed to create object URL for Blob"))?;
log::debug!("url: {:?}", url);
// Use the window object to create an `a` element
let window = window().ok_or_else(|| anyhow!("Failed to get window object"))?;
let document = window
.document()
.ok_or_else(|| anyhow!("Failed to get document object"))?;
let a = document
.create_element("a")
.map_err(|_| anyhow!("Failed to create anchor element"))?
.dyn_into::<web_sys::HtmlAnchorElement>()
.map_err(|_| anyhow!("Failed to cast element to HtmlAnchorElement"))?;
// Set the href attribute to the Blob URL and the download attribute to the desired file name
a.set_href(&url);
a.set_download(filename);
// Programmatically click the `a` element to trigger the download
a.click();
// Revoke the Blob URL to free resources
//Url::revoke_object_url(&url).map_err(|_| anyhow!("Failed to revoke object URL"))?;
Ok(())
}
}
| rust | MIT | b4c04b51746e5fe7769f49a1b32b8caad426fc81 | 2026-01-04T20:24:04.021295Z | false |
dbalsom/fluxfox | https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/crates/ff_egui_app/src/wasm/util.rs | crates/ff_egui_app/src/wasm/util.rs | /*
FluxFox
https://github.com/dbalsom/fluxfox
Copyright 2024-2025 Daniel Balsom
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the “Software”),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
--------------------------------------------------------------------------
*/
use eframe::{egui::Image, wasm_bindgen::prelude::wasm_bindgen};
#[wasm_bindgen(module = "/assets/base_url.js")]
extern "C" {
fn getBaseURL() -> String;
}
fn construct_full_url(relative_path: &str) -> String {
let mut path_components = Vec::new();
let base_url = getBaseURL();
path_components.push(base_url.trim_end_matches('/'));
let base_path = option_env!("URL_PATH");
if let Some(base_path) = base_path {
path_components.push(base_path.trim_start_matches('/').trim_end_matches('/'));
}
path_components.push(relative_path);
let url = path_components.join("/");
url
}
pub(crate) fn get_logo_image<'a>() -> Image<'a> {
let url = construct_full_url("assets/fluxfox_logo.png");
egui::Image::new(url).fit_to_original_size(1.0)
}
| rust | MIT | b4c04b51746e5fe7769f49a1b32b8caad426fc81 | 2026-01-04T20:24:04.021295Z | false |
dbalsom/fluxfox | https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/crates/ff_egui_app/src/wasm/worker.rs | crates/ff_egui_app/src/wasm/worker.rs | /*
FluxFox
https://github.com/dbalsom/fluxfox
Copyright 2024-2025 Daniel Balsom
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the “Software”),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
--------------------------------------------------------------------------
*/
// Worker code adapted from
// https://www.tweag.io/blog/2022-11-24-wasm-threads-and-messages/
use eframe::{
wasm_bindgen,
wasm_bindgen::{closure::Closure, prelude::wasm_bindgen, JsCast, JsValue},
};
// Spawn a worker and communicate with it.
#[allow(dead_code)]
pub(crate) fn spawn_worker() {
let worker_opts = web_sys::WorkerOptions::new();
worker_opts.set_type(web_sys::WorkerType::Module);
let worker = match web_sys::Worker::new_with_options("./worker.js", &worker_opts) {
Ok(worker) => worker,
Err(e) => {
log::error!("failed to spawn worker: {:?}", e);
return;
}
};
// let callback = Closure<FnMut(web_sys::MessageEvent)>::new(|msg| {
// assert_eq!(msg.data.as_f64(), Some(2.0));
// });
let callback = Closure::<dyn FnMut(web_sys::MessageEvent)>::new(|msg: web_sys::MessageEvent| {
log::debug!("Received result from worker: {:?}", msg);
});
// Set up a callback to be invoked whenever we receive a message from the worker.
// .as_ref().unchecked_ref() turns a wasm_bindgen::Closure into a &js_sys::Function
worker.set_onmessage(Some(callback.as_ref().unchecked_ref()));
// Send a message to the worker.
worker.post_message(&JsValue::from(1.0)).expect("failed to post");
// Did you notice that `set_onmessage` took a borrow? We still own `callback`, and we'd
// better not free it too soon! See also
// https://rustwasm.github.io/wasm-bindgen/reference/weak-references.html
std::mem::forget(callback); // FIXME: memory management is hard
}
// Spawn a worker and communicate with it.
#[allow(dead_code)]
pub(crate) fn spawn_loading_worker(bytes: &[u8]) {
let worker_opts = web_sys::WorkerOptions::new();
worker_opts.set_type(web_sys::WorkerType::Module);
let worker = match web_sys::Worker::new_with_options("./load_worker.js", &worker_opts) {
Ok(worker) => worker,
Err(e) => {
log::error!("failed to spawn worker: {:?}", e);
return;
}
};
// let callback = Closure<FnMut(web_sys::MessageEvent)>::new(|msg| {
// assert_eq!(msg.data.as_f64(), Some(2.0));
// });
let callback = Closure::<dyn FnMut(web_sys::MessageEvent)>::new(|msg: web_sys::MessageEvent| {
log::debug!(
"Worker reports it received {} bytes.",
msg.data().as_f64().unwrap_or(0.0)
);
});
// Set up a callback to be invoked whenever we receive a message from the worker.
// .as_ref().unchecked_ref() turns a wasm_bindgen::Closure into a &js_sys::Function
worker.set_onmessage(Some(callback.as_ref().unchecked_ref()));
// Convert the `u8` slice to a `Uint8Array`.
//let data_array = unsafe { web_sys::js_sys::Uint8Array::view(bytes) };
log::debug!("Creating Uint8Array from {} bytes.", bytes.len());
let data_array = web_sys::js_sys::Uint8Array::from(bytes);
// Send the data to the worker.
worker.post_message(&data_array).expect("failed to post");
// Did you notice that `set_onmessage` took a borrow? We still own `callback`, and we'd
// better not free it too soon! See also
// https://rustwasm.github.io/wasm-bindgen/reference/weak-references.html
std::mem::forget(callback); // FIXME: memory management is hard
log::debug!("spawn_loading_worker(): finished");
}
// Spawn a worker and communicate with it.
pub(crate) fn spawn_closure_worker(f: impl FnOnce() + Send + 'static) -> Result<web_sys::Worker, JsValue> {
let worker_opts = web_sys::WorkerOptions::new();
worker_opts.set_type(web_sys::WorkerType::Module);
let worker = web_sys::Worker::new_with_options("./worker.js", &worker_opts)?;
// Double-boxing because `dyn FnOnce` is unsized and so `Box<dyn FnOnce()>` is a fat pointer.
// But `Box<Box<dyn FnOnce()>>` is just a plain pointer, and since wasm has 32-bit pointers,
// we can cast it to a `u32` and back.
let ptr = Box::into_raw(Box::new(Box::new(f) as Box<dyn FnOnce()>));
let msg = web_sys::js_sys::Array::new();
// Send the worker a reference to our memory chunk, so it can initialize a wasm module
// using the same memory.
msg.push(&wasm_bindgen::memory());
// Also send the worker the address of the closure we want to execute.
msg.push(&JsValue::from(ptr as u32));
// Send the data to the worker.
log::debug!("spawn_closure_worker(): posting message to worker");
worker.post_message(&msg)?;
Ok(worker)
}
#[wasm_bindgen]
pub fn closure_worker_entry_point(ptr: u32) {
// Interpret the address we were given as a pointer to a closure to call.
log::debug!("In closure worker!");
let closure = unsafe { Box::from_raw(ptr as *mut Box<dyn FnOnce()>) };
(*closure)();
}
// An entry point for the JavaScript worker to call back into WASM.
#[wasm_bindgen]
pub fn load_worker_entry_point(data: web_sys::js_sys::Uint8Array) {
log::debug!("In worker: received {} bytes.", data.length());
let rust_data: Vec<u8> = data.to_vec();
web_sys::js_sys::global()
.dyn_into::<web_sys::DedicatedWorkerGlobalScope>()
.unwrap()
.post_message(&JsValue::from(rust_data.len()))
.unwrap();
log::debug!("loading worker: completed");
}
| rust | MIT | b4c04b51746e5fe7769f49a1b32b8caad426fc81 | 2026-01-04T20:24:04.021295Z | false |
dbalsom/fluxfox | https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/crates/ff_egui_app/src/wasm/mod.rs | crates/ff_egui_app/src/wasm/mod.rs | /*
FluxFox
https://github.com/dbalsom/fluxfox
Copyright 2024-2025 Daniel Balsom
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the “Software”),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
--------------------------------------------------------------------------
*/
pub(crate) mod app;
pub(crate) mod util;
pub(crate) mod worker;
| rust | MIT | b4c04b51746e5fe7769f49a1b32b8caad426fc81 | 2026-01-04T20:24:04.021295Z | false |
dbalsom/fluxfox | https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/crates/ff_egui_app/src/widgets/filename.rs | crates/ff_egui_app/src/widgets/filename.rs | /*
FluxFox
https://github.com/dbalsom/fluxfox
Copyright 2024-2025 Daniel Balsom
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the “Software”),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
--------------------------------------------------------------------------
Implement the filename display widget
*/
#[derive(Default)]
pub struct FilenameWidget {
filename: Option<String>,
}
impl FilenameWidget {
pub fn set(&mut self, filename: Option<String>) {
self.filename = filename;
}
pub fn show(&self, ui: &mut egui::Ui) {
if self.filename.is_none() {
return;
}
ui.horizontal(|ui| {
ui.heading(egui::RichText::new("💾 Disk Image:").strong());
ui.heading(self.filename.as_ref().unwrap());
});
}
}
| rust | MIT | b4c04b51746e5fe7769f49a1b32b8caad426fc81 | 2026-01-04T20:24:04.021295Z | false |
dbalsom/fluxfox | https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/crates/ff_egui_app/src/widgets/hello.rs | crates/ff_egui_app/src/widgets/hello.rs | /*
FluxFox
https://github.com/dbalsom/fluxfox
Copyright 2024-2025 Daniel Balsom
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the “Software”),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
--------------------------------------------------------------------------
Implement the hello widget
*/
#[cfg(not(target_arch = "wasm32"))]
use crate::native::util;
use fluxfox::prelude::Platform;
use strum::IntoEnumIterator;
#[cfg(target_arch = "wasm32")]
use crate::wasm::util;
#[derive(Default)]
pub struct HelloWidget {
small: bool,
}
impl HelloWidget {
pub fn set_small(&mut self, state: bool) {
self.small = state;
}
pub fn show(&self, ui: &mut egui::Ui, app_name: &str, supported_extensions: &[String]) {
let scale = if self.small { 0.5 } else { 1.0 };
ui.add(util::get_logo_image().fit_to_original_size(scale));
if !self.small {
ui.horizontal(|ui| {
ui.heading(
egui::RichText::new(format!("Welcome to {}!", app_name)).color(ui.visuals().strong_text_color()),
);
ui.label(format!("v{}", env!("CARGO_PKG_VERSION")));
ui.hyperlink_to("GitHub", "https://github.com/dbalsom/fluxfox");
});
}
ui.vertical(|ui| {
ui.label(
"Drag disk image files to this window to load. Kryoflux sets should be in single-disk ZIP archives.",
);
ui.label(format!("Image types supported: {}", supported_extensions.join(", ")));
ui.label(format!(
"Platform features enabled: {}",
Platform::iter()
.map(|x| x.to_string())
.collect::<Vec<String>>()
.join(", ")
));
});
}
}
| rust | MIT | b4c04b51746e5fe7769f49a1b32b8caad426fc81 | 2026-01-04T20:24:04.021295Z | false |
dbalsom/fluxfox | https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/crates/ff_egui_app/src/widgets/mod.rs | crates/ff_egui_app/src/widgets/mod.rs | /*
FluxFox
https://github.com/dbalsom/fluxfox
Copyright 2024-2025 Daniel Balsom
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the “Software”),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
--------------------------------------------------------------------------
*/
pub mod filename;
pub mod hello;
| rust | MIT | b4c04b51746e5fe7769f49a1b32b8caad426fc81 | 2026-01-04T20:24:04.021295Z | false |
dbalsom/fluxfox | https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/crates/ff_egui_app/src/windows/source_map.rs | crates/ff_egui_app/src/windows/source_map.rs | /*
FluxFox
https://github.com/dbalsom/fluxfox
Copyright 2024-2025 Daniel Balsom
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the “Software”),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
--------------------------------------------------------------------------
*/
use fluxfox::DiskImage;
use fluxfox_egui::controls::source_map::SourceMapWidget;
#[derive(Default)]
pub struct SourceMapViewer {
pub open: bool,
pub widget: SourceMapWidget,
}
impl SourceMapViewer {
#[allow(dead_code)]
pub fn new() -> Self {
Self {
open: false,
widget: SourceMapWidget::new(),
}
}
pub fn update(&mut self, disk: &DiskImage) {
self.widget.update(disk);
}
#[allow(dead_code)]
pub fn set_open(&mut self, open: bool) {
self.open = open;
}
pub fn open_mut(&mut self) -> &mut bool {
&mut self.open
}
pub fn show(&mut self, ctx: &egui::Context) {
egui::Window::new("Source Map")
.open(&mut self.open)
.resizable(egui::Vec2b::new(true, true))
.show(ctx, |ui| self.widget.show(ui));
}
}
| rust | MIT | b4c04b51746e5fe7769f49a1b32b8caad426fc81 | 2026-01-04T20:24:04.021295Z | false |
dbalsom/fluxfox | https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/crates/ff_egui_app/src/windows/track_viewer.rs | crates/ff_egui_app/src/windows/track_viewer.rs | /*
FluxFox
https://github.com/dbalsom/fluxfox
Copyright 2024-2025 Daniel Balsom
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the “Software”),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
--------------------------------------------------------------------------
*/
use crate::app::Tool;
use fluxfox::{
prelude::*,
track::{DiskTrack, TrackInfo},
track_schema::{TrackElementInstance, TrackSchema},
};
use fluxfox_egui::{
controls::data_table::{DataRange, DataTableWidget},
tracking_lock::TrackingLock,
widgets::chs::ChsWidget,
TrackSelection,
UiLockContext,
};
use std::ops::Range;
#[derive(Default)]
pub struct TrackViewer {
disk: Option<TrackingLock<DiskImage>>,
phys_ch: DiskCh,
track: Option<DiskTrack>,
track_info: TrackInfo,
markers: Vec<TrackElementInstance>,
marker_sync: usize,
table: DataTableWidget,
open: bool,
valid: bool,
error_string: Option<String>,
}
impl TrackViewer {
#[allow(dead_code)]
pub fn new(phys_ch: DiskCh) -> Self {
Self {
disk: None,
phys_ch,
track: None,
track_info: TrackInfo::default(),
// Capacity of 37 markers (18 sectors * 2 (IDAM + DAM) + IAM)
markers: Vec::with_capacity(38),
marker_sync: 0,
table: DataTableWidget::default(),
open: false,
valid: false,
error_string: None,
}
}
pub fn update_disk(&mut self, disk: TrackingLock<DiskImage>) {
self.disk = Some(disk);
self.phys_ch = DiskCh::default();
self.track = None;
self.markers = Vec::new();
self.track_info = TrackInfo::default();
}
pub fn update_selection(&mut self, selection: TrackSelection) {
self.marker_sync = 0;
self.error_string = None;
if let Some(disk_lock) = &self.disk {
let disk = disk_lock.read(UiLockContext::TrackViewer).unwrap();
self.phys_ch = selection.phys_ch;
let track_ref = match disk.track(selection.phys_ch) {
Some(tr) => tr,
None => {
self.error_string = Some("Invalid track index".to_string());
self.valid = false;
return;
}
};
self.track_info = track_ref.info();
// Take a clone of the track reference so we can re-read the track at different offsets
// without having to re-acquire the lock.
self.track = Some(track_ref.clone());
}
self.scan_track();
self.read_track(0);
}
// Scan the track for markers.
fn scan_track(&mut self) {
if let Some(track) = &self.track {
if let Some(metadata) = track.metadata() {
self.markers = metadata.markers();
log::debug!("scan_track(): Found {} markers", self.markers.len());
}
}
}
fn read_track(&mut self, offset: isize) {
if let Some(track) = &self.track {
let rtr = match track.read(Some(offset), None) {
Ok(rtr) => rtr,
Err(e) => {
log::error!("Error reading sector: {:?}", e);
self.error_string = Some(e.to_string());
self.valid = false;
return;
}
};
if rtr.not_found {
self.error_string = Some("Unexpected error: Track not found(?)".to_string());
self.valid = false;
return;
}
self.table.set_data(&rtr.read_buf);
self.valid = true;
if let Some(metadata) = track.metadata() {
for item in metadata.header_ranges() {
//let offset_range = (item.start + offset as usize)..(item.end + offset as usize);
let range = DataRange {
name: "Sector Header".to_string(),
range: (item.start / 16)..(item.end / 16).saturating_sub(1),
fg_color: egui::Color32::from_rgb(0xff, 0x53, 0x53),
};
self.table.add_range(range);
}
for item in metadata.marker_ranges() {
//let offset_range = (item.start + offset as usize)..(item.end + offset as usize);
let range = DataRange {
name: "Marker".to_string(),
range: (item.start / 16)..(item.end / 16).saturating_sub(1),
fg_color: egui::Color32::from_rgb(0x53, 0xdd, 0xff),
};
self.table.add_range(range);
}
};
}
}
fn decompose_header_range(&self, range: Range<usize>) {}
fn sync_to(&mut self, marker_start: usize) {
// Marker offset is modulo 16 for FM and MFM.
match self.track_info.encoding {
TrackDataEncoding::Fm | TrackDataEncoding::Mfm => {
let offset = marker_start % 16;
self.read_track(offset as isize);
}
_ => {
self.error_string = Some("Unsupported encoding".to_string());
self.valid = false;
}
}
}
pub fn open_mut(&mut self) -> &mut bool {
&mut self.open
}
pub fn set_open(&mut self, open: bool) {
self.open = open;
}
// Show the window
pub fn show(&mut self, ctx: &egui::Context) {
// Separate open state to avoid borrowing self
let mut open = self.open;
// Show the window
egui::Window::new("Track Viewer").open(&mut open).show(ctx, |ui| {
self.ui(ui);
});
// Sync open state
self.set_open(open);
}
fn ui(&mut self, ui: &mut egui::Ui) {
ui.vertical(|ui| {
egui::Grid::new("track_viewer_grid").num_columns(4).show(ui, |ui| {
ui.label("Physical Track:");
ui.add(ChsWidget::from_ch(self.phys_ch));
ui.end_row();
ui.label("Sync to bitcell:");
egui::ComboBox::new("track_viewer_combo", "")
.selected_text(format!("{}", self.marker_sync))
.show_ui(ui, |ui| {
let mut sync_to_opt = None;
if ui.selectable_value(&mut self.marker_sync, 0, "Track Start").clicked() {
sync_to_opt = Some(0);
}
for marker in &self.markers {
if ui
.selectable_value(
&mut self.marker_sync,
marker.range().start,
format!("Marker @ {}", marker.range().start),
)
.clicked()
{
sync_to_opt = Some(marker.range().start);
}
}
if let Some(marker_start) = sync_to_opt {
self.sync_to(marker_start);
}
});
ui.label("Offset:");
ui.label(format!("{}", self.marker_sync % 16));
ui.end_row();
});
self.table.show(ui);
});
}
}
| rust | MIT | b4c04b51746e5fe7769f49a1b32b8caad426fc81 | 2026-01-04T20:24:04.021295Z | false |
dbalsom/fluxfox | https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/crates/ff_egui_app/src/windows/new_viz.rs | crates/ff_egui_app/src/windows/new_viz.rs | /*
FluxFox
https://github.com/dbalsom/fluxfox
Copyright 2024-2025 Daniel Balsom
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the “Software”),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
--------------------------------------------------------------------------
*/
#![allow(dead_code)]
use crate::app::Tool;
use anyhow::Result;
use fluxfox::{prelude::TrackDataResolution, visualization::prelude::*, DiskImage};
use fluxfox_egui::{
controls::{error_banner::ErrorBanner, vector_disk_visualizer::DiskVisualizerWidget},
tracking_lock::TrackingLock,
UiLockContext,
};
use std::f32::consts::TAU;
pub const VIZ_RESOLUTION: u32 = 768;
pub struct NewVizViewer {
disk: Option<TrackingLock<DiskImage>>,
compatible: bool,
viz: DiskVisualizerWidget,
resolution: u32,
show_data_layer: bool,
show_metadata_layer: bool,
show_error_layer: bool,
show_weak_layer: bool,
open: bool,
}
impl Default for NewVizViewer {
fn default() -> Self {
Self::new()
}
}
impl NewVizViewer {
pub fn new() -> Self {
Self {
disk: None,
compatible: false,
viz: DiskVisualizerWidget::new(VIZ_RESOLUTION, TurningDirection::Clockwise, 80),
resolution: VIZ_RESOLUTION,
open: false,
show_data_layer: true,
show_metadata_layer: true,
show_error_layer: false,
show_weak_layer: false,
}
}
/// Reset, but don't destroy the visualization state
pub fn reset(&mut self) {
self.open = false;
}
pub fn set_open(&mut self, state: bool) {
self.open = state;
}
pub fn open_mut(&mut self) -> &mut bool {
&mut self.open
}
pub fn set_disk(&mut self, disk: TrackingLock<DiskImage>) {
self.disk = Some(disk);
}
pub fn render(&mut self) -> Result<()> {
if self.disk.is_none() {
return Ok(());
}
let disk = self
.disk
.as_ref()
.unwrap()
.read(UiLockContext::DiskVisualization)
.unwrap();
self.compatible = !disk.resolution().contains(&TrackDataResolution::MetaSector);
let common_viz_params = CommonVizParams {
radius: Some(VIZ_RESOLUTION as f32 / 2.0),
max_radius_ratio: 1.0,
min_radius_ratio: 0.3,
pos_offset: None,
index_angle: 0.0,
track_limit: None,
pin_last_standard_track: true,
track_gap: 0.0,
direction: TurningDirection::Clockwise,
..CommonVizParams::default()
};
let metadata_params = RenderTrackMetadataParams {
quadrant: None,
geometry: RenderGeometry::Arc,
winding: Default::default(),
side: 0,
draw_empty_tracks: false,
draw_sector_lookup: false,
};
let display_list = vectorize_disk_elements_by_quadrants(&disk, &common_viz_params, &metadata_params)?;
log::debug!("Updating visualization with {} elements", display_list.len());
self.viz.update_metadata(display_list);
let data_params = RenderTrackDataParams {
side: 0,
decode: false,
sector_mask: false,
resolution: Default::default(),
slices: 360,
overlap: -0.10,
};
let vector_params = RenderVectorizationParams {
view_box: Default::default(),
image_bg_color: None,
disk_bg_color: None,
mask_color: None,
pos_offset: None,
};
let data_display_list = vectorize_disk_data(&disk, &common_viz_params, &data_params, &vector_params)?;
self.viz.update_data(data_display_list);
Ok(())
}
pub fn show(&mut self, ctx: &egui::Context) {
if self.open {
egui::Window::new("New Disk Visualization")
.open(&mut self.open)
.show(ctx, |ui| {
egui::menu::bar(ui, |ui| {
ui.menu_button("Layers", |ui| {
if ui.checkbox(self.viz.show_data_layer_mut(), "Data Layer").changed() {
//self.viz.enable_data_layer(self.show_data_layer);
}
if ui
.checkbox(self.viz.show_metadata_layer_mut(), "Metadata Layer")
.changed()
{
//self.viz.enable_metadata_layer(self.show_metadata_layer);
}
if ui.checkbox(&mut self.show_error_layer, "Error Layer").changed() {
//self.viz.set_error_layer(self.show_error_layer);
}
if ui.checkbox(&mut self.show_weak_layer, "Weak Layer").changed() {
//self.viz.set_weak_layer(self.show_weak_layer);
}
});
// ui.menu_button("Save", |ui| {
// for side in 0..self.viz.sides {
// if ui.button(format!("Save Side {} as PNG", side).as_str()).clicked() {
// self.viz.save_side_as(&format!("fluxfox_viz_side{}.png", side), side);
// }
// }
// });
});
ui.horizontal(|ui| {
ui.set_min_width(200.0);
ui.add(
egui::Slider::new(self.viz.angle_mut(), 0.0..=TAU)
.text("Angle")
.step_by((TAU / 360.0) as f64),
);
});
if self.compatible {
// if let Some(new_event) = self.viz.show(ui) {
// match new_event {
// VizEvent::NewSectorSelected { c, h, s_idx } => {
// log::debug!("New sector selected: c:{} h:{}, s:{}", c, h, s_idx);
//
// //self.viz.update_selection(disk_lock, c, h, s_idx);
// }
// _ => {}
// }
// }
self.viz.show(ui);
}
else {
ErrorBanner::new("Visualization not compatible with current disk image.")
.medium()
.show(ui);
}
});
}
}
}
| rust | MIT | b4c04b51746e5fe7769f49a1b32b8caad426fc81 | 2026-01-04T20:24:04.021295Z | false |
dbalsom/fluxfox | https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/crates/ff_egui_app/src/windows/file_viewer.rs | crates/ff_egui_app/src/windows/file_viewer.rs | /*
FluxFox
https://github.com/dbalsom/fluxfox
Copyright 2024-2025 Daniel Balsom
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the “Software”),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
--------------------------------------------------------------------------
*/
use egui::Grid;
use fluxfox::file_system::fat::fat_fs::FatFileSystem;
use fluxfox_egui::controls::data_table::DataTableWidget;
#[derive(Default)]
pub struct FileViewer {
path: String,
table: DataTableWidget,
open: bool,
error_string: Option<String>,
}
impl FileViewer {
#[allow(dead_code)]
pub fn new() -> Self {
Self {
path: String::new(),
table: DataTableWidget::default(),
open: false,
error_string: None,
}
}
pub fn update(&mut self, fs: &FatFileSystem, path: String) {
self.path = path;
let data = match fs.read_file(&self.path) {
Ok(data) => data,
Err(e) => {
self.error_string = Some(format!("Error reading file: {}", e));
return;
}
};
self.table.set_data(&data);
}
pub fn set_open(&mut self, open: bool) {
self.open = open;
}
pub fn show(&mut self, ctx: &egui::Context) {
egui::Window::new("File Viewer").open(&mut self.open).show(ctx, |ui| {
Grid::new("file_viewer_grid").striped(true).show(ui, |ui| {
ui.label("Path:");
ui.label(self.path.to_string());
ui.end_row();
ui.label("Size:");
ui.label(self.table.data_len().to_string());
ui.end_row();
});
ui.separator();
self.table.show(ui);
});
}
}
| rust | MIT | b4c04b51746e5fe7769f49a1b32b8caad426fc81 | 2026-01-04T20:24:04.021295Z | false |
dbalsom/fluxfox | https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/crates/ff_egui_app/src/windows/sector_viewer.rs | crates/ff_egui_app/src/windows/sector_viewer.rs | /*
FluxFox
https://github.com/dbalsom/fluxfox
Copyright 2024-2025 Daniel Balsom
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the “Software”),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
--------------------------------------------------------------------------
*/
use crate::app::Tool;
use fluxfox::{
prelude::*,
types::{IntegrityCheck, IntegrityField, ReadSectorResult},
};
use fluxfox_egui::{
controls::{data_table::DataTableWidget, error_banner::ErrorBanner},
tracking_lock::TrackingLock,
widgets::{chs::ChsWidget, pill::PillWidget},
SectorSelection,
UiLockContext,
};
#[derive(Default)]
pub struct SectorViewer {
phys_ch: DiskCh,
sector_id: SectorId,
table: DataTableWidget,
open: bool,
valid: bool,
error_string: Option<String>,
read_result: Option<ReadSectorResult>,
}
impl SectorViewer {
#[allow(dead_code)]
pub fn new(phys_ch: DiskCh, sector_id: SectorId) -> Self {
Self {
phys_ch,
sector_id,
table: DataTableWidget::default(),
open: false,
valid: false,
error_string: None,
read_result: None,
}
}
pub fn update(&mut self, disk_lock: TrackingLock<DiskImage>, selection: SectorSelection) {
match disk_lock.write(UiLockContext::SectorViewer) {
Ok(mut disk) => {
self.phys_ch = selection.phys_ch;
let query = SectorIdQuery::new(
selection.sector_id.c(),
selection.sector_id.h(),
selection.sector_id.s(),
selection.sector_id.n(),
);
log::debug!("Reading sector: {:?}", query);
let rsr = match disk.read_sector(self.phys_ch, query, None, None, RwScope::DataOnly, true) {
Ok(rsr) => rsr,
Err(e) => {
log::error!("Error reading sector: {:?}", e);
self.error_string = Some(e.to_string());
self.valid = false;
return;
}
};
self.read_result = Some(rsr.clone());
if rsr.not_found {
self.error_string = Some(format!("Sector {} not found", selection.sector_id));
self.table.set_data(&[0; 512]);
self.valid = false;
return;
}
// When is id_chsn None after a successful read?
if let Some(chsn) = rsr.id_chsn {
self.sector_id = chsn;
self.table.set_data(&rsr.read_buf[rsr.data_range]);
self.error_string = None;
self.valid = true;
}
else {
self.error_string = Some("Sector ID not returned".to_string());
self.table.set_data(&[0; 512]);
self.valid = false;
}
}
Err(e) => {
for tool in e {
log::warn!("Failed to acquire write lock, locked by tool: {:?}", tool);
}
self.error_string = Some("Failed to acquire disk write lock.".to_string());
self.valid = false;
}
}
}
pub fn set_open(&mut self, open: bool) {
self.open = open;
}
pub fn show(&mut self, ctx: &egui::Context) {
egui::Window::new("Sector Viewer").open(&mut self.open).show(ctx, |ui| {
ui.vertical(|ui| {
if let Some(error_string) = &self.error_string {
ErrorBanner::new(error_string).small().show(ui);
}
egui::Grid::new("sector_viewer_grid").show(ui, |ui| {
ui.label("Physical Track:");
ui.add(ChsWidget::from_ch(self.phys_ch));
ui.end_row();
ui.label("Sector ID:");
ui.add(ChsWidget::from_chsn(self.sector_id));
ui.end_row();
if let Some(rsr) = &self.read_result {
ui.label("Sector Size:");
ui.label(format!("{} bytes", rsr.data_range.len()));
ui.end_row();
if let Some(check) = rsr.data_crc {
let (valid, recorded, calculated) = match check {
IntegrityCheck::Crc16(IntegrityField {
valid,
recorded,
calculated,
}) => {
ui.label("CRC16:");
(valid, recorded, calculated)
}
IntegrityCheck::Checksum16(IntegrityField {
valid,
recorded,
calculated,
}) => {
ui.label("Checksum16:");
(valid, recorded, calculated)
}
};
if let Some(recorded_val) = recorded {
ui.label("Recorded:");
ui.add(PillWidget::new(&format!("{:04X}", recorded_val)).with_fill(if valid {
egui::Color32::DARK_GREEN
}
else {
egui::Color32::DARK_RED
}));
}
else {
ui.add(
PillWidget::new(if valid { "Valid" } else { "Invalid" }).with_fill(if valid {
egui::Color32::DARK_GREEN
}
else {
egui::Color32::DARK_RED
}),
);
}
ui.end_row();
ui.label("");
ui.label("Calculated:");
ui.label(format!("{:04X}", calculated));
ui.end_row();
}
}
});
ui.separator();
self.table.show(ui);
});
});
}
}
| rust | MIT | b4c04b51746e5fe7769f49a1b32b8caad426fc81 | 2026-01-04T20:24:04.021295Z | false |
dbalsom/fluxfox | https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/crates/ff_egui_app/src/windows/mod.rs | crates/ff_egui_app/src/windows/mod.rs | /*
FluxFox
https://github.com/dbalsom/fluxfox
Copyright 2024-2025 Daniel Balsom
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the “Software”),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
--------------------------------------------------------------------------
*/
pub mod disk_visualization;
pub mod element_map;
pub mod file_viewer;
pub mod new_viz;
pub mod sector_viewer;
pub mod source_map;
pub mod track_timing_viewer;
pub mod track_viewer;
| rust | MIT | b4c04b51746e5fe7769f49a1b32b8caad426fc81 | 2026-01-04T20:24:04.021295Z | false |
dbalsom/fluxfox | https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/crates/ff_egui_app/src/windows/track_timing_viewer.rs | crates/ff_egui_app/src/windows/track_timing_viewer.rs | /*
FluxFox
https://github.com/dbalsom/fluxfox
Copyright 2024-2025 Daniel Balsom
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the “Software”),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
--------------------------------------------------------------------------
*/
use egui::Grid;
use fluxfox::{flux::pll::PllMarkerEntry, prelude::DiskCh};
use fluxfox_egui::{controls::track_timing_chart::TrackTimingChart, widgets::chs::ChsWidget};
#[derive(Default)]
pub struct TrackTimingViewer {
chart: TrackTimingChart,
phys_ch: DiskCh,
open: bool,
}
impl TrackTimingViewer {
#[allow(dead_code)]
pub fn new(phys_ch: DiskCh, fts: &[f64], markers: Option<&[PllMarkerEntry]>) -> Self {
Self {
chart: TrackTimingChart::new(fts, markers),
phys_ch,
open: false,
}
}
pub fn set_open(&mut self, open: bool) {
self.open = open;
}
pub fn update(&mut self, phys_ch: DiskCh, fts: &[f64], markers: Option<&[PllMarkerEntry]>) {
self.phys_ch = phys_ch;
self.chart = TrackTimingChart::new(fts, markers);
}
pub fn show(&mut self, ctx: &egui::Context) {
egui::Window::new("Track Timings").open(&mut self.open).show(ctx, |ui| {
ui.vertical(|ui| {
Grid::new("track_timings_info_grid").show(ui, |ui| {
ui.label("Physical Track");
ui.add(ChsWidget::from_ch(self.phys_ch));
ui.end_row();
ui.checkbox(self.chart.marker_enable_mut(), "Show Markers");
ui.end_row();
});
ui.separator();
self.chart.show(ui);
});
});
}
}
| rust | MIT | b4c04b51746e5fe7769f49a1b32b8caad426fc81 | 2026-01-04T20:24:04.021295Z | false |
dbalsom/fluxfox | https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/crates/ff_egui_app/src/windows/element_map.rs | crates/ff_egui_app/src/windows/element_map.rs | /*
FluxFox
https://github.com/dbalsom/fluxfox
Copyright 2024-2025 Daniel Balsom
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the “Software”),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
--------------------------------------------------------------------------
*/
use crate::app::Tool;
use fluxfox::DiskImage;
use fluxfox_egui::{controls::source_map::SourceMapWidget, tracking_lock::TrackingLock, TrackSelection, UiLockContext};
#[derive(Default)]
pub struct ElementMapViewer {
pub open: bool,
pub widget: SourceMapWidget,
}
impl ElementMapViewer {
#[allow(dead_code)]
pub fn new() -> Self {
Self {
open: false,
widget: SourceMapWidget::new(),
}
}
pub fn update(&mut self, disk_lock: TrackingLock<DiskImage>, selection: TrackSelection) {
match disk_lock.read(UiLockContext::TrackElementMap) {
Ok(disk) => {
if let Some(map) = disk.track(selection.phys_ch).and_then(|track| track.element_map()) {
self.widget.update_direct(map, None);
}
}
Err(_) => {
log::error!("Failed to lock disk image");
}
}
}
#[allow(dead_code)]
pub fn set_open(&mut self, open: bool) {
self.open = open;
}
#[allow(dead_code)]
pub fn open_mut(&mut self) -> &mut bool {
&mut self.open
}
pub fn show(&mut self, ctx: &egui::Context) {
egui::Window::new("Track Element Map")
.open(&mut self.open)
.resizable(egui::Vec2b::new(true, true))
.show(ctx, |ui| self.widget.show(ui));
}
}
| rust | MIT | b4c04b51746e5fe7769f49a1b32b8caad426fc81 | 2026-01-04T20:24:04.021295Z | false |
dbalsom/fluxfox | https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/crates/ff_egui_app/src/windows/disk_visualization.rs | crates/ff_egui_app/src/windows/disk_visualization.rs | /*
FluxFox
https://github.com/dbalsom/fluxfox
Copyright 2024-2025 Daniel Balsom
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the “Software”),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
--------------------------------------------------------------------------
*/
use std::sync::{mpsc, Arc};
use fluxfox::DiskImage;
use fluxfox_egui::{
controls::{
disk_visualization::{DiskVisualization, VizEvent},
error_banner::ErrorBanner,
},
tracking_lock::TrackingLock,
UiEvent,
};
use crate::App;
use anyhow::Result;
#[derive(Default)]
pub struct VisualizationViewer {
viz: DiskVisualization,
show_data_layer: bool,
show_metadata_layer: bool,
show_error_layer: bool,
show_weak_layer: bool,
open: bool,
}
impl VisualizationViewer {
pub fn new() -> Self {
let mut viz = DiskVisualization::default();
viz.set_save_file_callback(Arc::new(|filename, data| {
_ = App::save_file_as(filename, data);
}));
Self {
viz,
open: false,
show_data_layer: true,
show_metadata_layer: true,
show_error_layer: false,
show_weak_layer: false,
}
}
/// Reset, but don't destroy the visualization state
pub fn reset(&mut self) {
//self.viz.clear();
self.open = false;
}
pub fn init(&mut self, ctx: egui::Context, resolution: u32, sender: mpsc::SyncSender<UiEvent>) {
self.viz = DiskVisualization::new(ctx, resolution);
self.viz.set_event_sender(sender);
}
pub fn set_open(&mut self, state: bool) {
self.open = state;
}
pub fn open_mut(&mut self) -> &mut bool {
&mut self.open
}
pub fn update_disk(&mut self, disk_lock: TrackingLock<DiskImage>) {
self.viz.update_disk(disk_lock);
_ = self.render()
}
pub fn render(&mut self) -> Result<()> {
self.viz.render_visualization(0)?;
self.viz.render_visualization(1)?;
Ok(())
}
pub fn show(&mut self, ctx: &egui::Context) {
if self.open {
egui::Window::new("Disk Visualization")
.open(&mut self.open)
.resizable([false, false])
.show(ctx, |ui| {
egui::menu::bar(ui, |ui| {
ui.menu_button("Layers", |ui| {
if ui.checkbox(&mut self.show_data_layer, "Data Layer").changed() {
self.viz.enable_data_layer(self.show_data_layer);
}
if ui.checkbox(&mut self.show_metadata_layer, "Metadata Layer").changed() {
self.viz.enable_metadata_layer(self.show_metadata_layer);
}
if ui.checkbox(&mut self.show_error_layer, "Error Layer").changed() {
//self.viz.set_error_layer(self.show_error_layer);
}
if ui.checkbox(&mut self.show_weak_layer, "Weak Layer").changed() {
//self.viz.set_weak_layer(self.show_weak_layer);
}
});
ui.menu_button("Save", |ui| {
for side in 0..self.viz.sides {
#[cfg(not(feature = "svg"))]
if ui.button(format!("Save Side {} as PNG", side).as_str()).clicked() {
self.viz
.save_side_as_png(&format!("fluxfox_viz_side{}.png", side), side);
}
#[cfg(feature = "svg")]
ui.menu_button(format!("Save Side {} as...", side).as_str(), |ui| {
if ui.button("PNG").clicked() {
self.viz
.save_side_as_png(&format!("fluxfox_viz_side{}.png", side), side);
ui.close_menu();
}
if ui.button("SVG").clicked() {
match self
.viz
.save_side_as_svg(&format!("fluxfox_viz_side{}.svg", side), side)
{
Ok(_) => {
log::info!("SVG saved successfully");
}
Err(e) => {
log::error!("Error saving SVG: {}", e);
}
}
ui.close_menu();
}
});
}
});
ui.menu_button("Zoom", |ui| {
for side in 0..self.viz.sides {
ui.label(format!("Side {} Zoom", side));
ui.group(|ui| {
egui::Grid::new(format!("side{}_zoom_grid", side)).show(ui, |ui| {
if ui.button("1").clicked() {
self.viz.set_quadrant(side, Some(1));
}
if ui.button("0").clicked() {
self.viz.set_quadrant(side, Some(0));
}
ui.end_row();
if ui.button("2").clicked() {
self.viz.set_quadrant(side, Some(2));
}
if ui.button("3").clicked() {
self.viz.set_quadrant(side, Some(3));
}
ui.end_row();
});
if ui.button("Reset").on_hover_text("Reset zoom").clicked() {
self.viz.set_quadrant(side, None);
}
});
}
});
});
if self.viz.compatible {
if let Some(new_event) = self.viz.show(ui) {
match new_event {
VizEvent::NewSectorSelected { c, h, s_idx } => {
log::debug!("New sector selected: c:{} h:{}, s:{}", c, h, s_idx);
self.viz.update_selection(c, h, s_idx);
}
_ => {}
}
}
}
else {
ErrorBanner::new("Visualization not compatible with current disk image.")
.medium()
.show(ui);
}
});
}
}
}
| rust | MIT | b4c04b51746e5fe7769f49a1b32b8caad426fc81 | 2026-01-04T20:24:04.021295Z | false |
dbalsom/fluxfox | https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/crates/ff_egui_lib/src/lib.rs | crates/ff_egui_lib/src/lib.rs | /*
FluxFox
https://github.com/dbalsom/fluxfox
Copyright 2024-2025 Daniel Balsom
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the “Software”),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
--------------------------------------------------------------------------
*/
pub mod character_encoding;
pub mod controls;
mod range_check;
pub mod tracking_lock;
pub mod visualization;
pub mod widgets;
use fluxfox::{file_system::FileEntry, prelude::*};
use std::{
fmt,
fmt::{Debug, Display, Formatter, Result},
sync::Arc,
};
use thiserror::Error;
#[derive(Debug, Copy, Clone, Default)]
pub enum WidgetSize {
Small,
#[default]
Normal,
Large,
}
impl WidgetSize {
pub fn rounding(&self) -> f32 {
match self {
WidgetSize::Small => 4.0,
WidgetSize::Normal => 6.0,
WidgetSize::Large => 8.0,
}
}
pub fn padding(&self) -> f32 {
match self {
WidgetSize::Small => 2.0,
WidgetSize::Normal => 4.0,
WidgetSize::Large => 6.0,
}
}
}
#[derive(Debug, Clone, Default)]
pub struct SectorSelection {
pub phys_ch: DiskCh,
pub sector_id: SectorId,
pub bit_offset: Option<usize>,
}
#[derive(Debug, Clone, Default)]
pub enum TrackSelectionScope {
RawDataStream,
#[default]
DecodedDataStream,
Elements,
Timings,
}
#[derive(Debug, Clone, Default)]
pub struct TrackSelection {
pub sel_scope: TrackSelectionScope,
pub phys_ch: DiskCh,
}
#[derive(Debug, Clone)]
pub enum TrackListSelection {
Track(TrackSelection),
Sector(SectorSelection),
}
#[derive(Clone)]
pub enum UiEvent {
SelectionChange(TrackListSelection),
ExportFile(String),
SelectPath(String),
SelectFile(FileEntry),
ExportDir(String),
ExportDirAsArchive(String),
}
impl Debug for UiEvent {
fn fmt(&self, f: &mut Formatter<'_>) -> Result {
// Match on the enum to display only the variant name
let variant_name = match self {
UiEvent::SelectionChange(_) => "SelectionChange",
UiEvent::ExportFile(_) => "ExportFile",
UiEvent::SelectPath(_) => "SelectPath",
UiEvent::SelectFile(_) => "SelectFile",
UiEvent::ExportDir(_) => "ExportDir",
UiEvent::ExportDirAsArchive(_) => "ExportDirAsArchive",
};
write!(f, "{}", variant_name)
}
}
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
pub enum UiLockContext {
/// App is not a tool per se, but represents locks made in the main application logic.
/// Some Tools do not need to keep a persistent disk image lock as they display static
/// data that cannot change for the life of the loaded image (for example, the SourceMap)
/// The main application logic locks the disk image for the duration of the tool's update
/// cycle.
App,
/// This context represents a lock held by an emulator consuming the fluxfox_egui library.
/// Ideally an emulator releases its lock before calling into the library, but in cases where
/// the core runs in a separate thread, this may be unavoidable.
Emulator,
/// The visualization tool renders a graphical depiction of the disk and allows track element
/// selection. It must own a DiskLock to support hit-testing user selections and rendering
/// vector display lists of the current selection.
DiskVisualization,
SectorViewer,
TrackViewer,
TrackListViewer,
/// The filesystem viewer is currently the only tool that requires a write lock, due to
/// the use of a StandardSectorView, which requires a mutable reference to the disk image.
/// StandardSectorView is used as an interface for reading and writing sectors in a standard
/// raw-sector based order, such as what is expected by rust-fatfs.
FileSystemViewer,
/// A file system operation not necessarily tied to the filesystem viewer.
FileSystemOperation,
SourceMap,
TrackElementMap,
TrackTimingViewer,
}
impl Display for UiLockContext {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
write!(f, "{:?}", self)
}
}
#[derive(Clone, Debug, Error)]
pub enum UiError {
#[error("An error occurred rendering the disk visualization: {0}")]
VisualizationError(String),
}
type SaveFileCallbackFn = Arc<dyn Fn(&str, &[u8]) + Send + Sync>;
| rust | MIT | b4c04b51746e5fe7769f49a1b32b8caad426fc81 | 2026-01-04T20:24:04.021295Z | false |
dbalsom/fluxfox | https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/crates/ff_egui_lib/src/tracking_lock.rs | crates/ff_egui_lib/src/tracking_lock.rs | /*
FluxFox
https://github.com/dbalsom/fluxfox
Copyright 2024-2025 Daniel Balsom
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the “Software”),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
--------------------------------------------------------------------------
*/
//! The tracking_lock module defines a [TrackingLock] that tracks lock usage by [Tool].
use crate::UiLockContext;
use egui::Ui;
use fluxfox::{
disk_lock::{DiskLock, LockContext, NonTrackingDiskLock},
DiskImage,
};
use std::{
collections::HashMap,
ops::{Deref, DerefMut},
sync::{Arc, Mutex, RwLock, RwLockReadGuard, RwLockWriteGuard},
};
impl LockContext for UiLockContext {}
/// The [TrackingLock] is a wrapper around `Arc<RwLock<T>>` that tracks lock usage by [Tool].
pub struct TrackingLock<T> {
inner: Arc<RwLock<T>>,
// Protects the tracking data
tracking: Arc<Mutex<TrackingData>>,
}
struct TrackingData {
read_locks: HashMap<UiLockContext, usize>, // Tool -> count of read locks
write_lock: Option<UiLockContext>, // Currently held write lock
}
impl<T> Clone for TrackingLock<T> {
fn clone(&self) -> Self {
TrackingLock {
inner: Arc::clone(&self.inner),
tracking: Arc::clone(&self.tracking),
}
}
}
impl DiskLock<DiskImage, UiLockContext> for TrackingLock<DiskImage> {
type T = DiskImage;
type C = UiLockContext;
type ReadGuard<'a> = TrackingReadGuard<'a, DiskImage>;
type WriteGuard<'a> = TrackingWriteGuard<'a, DiskImage>;
fn read(&self, context: UiLockContext) -> Result<TrackingReadGuard<'_, DiskImage>, UiLockContext> {
self.read(context)
}
fn write(&self, context: UiLockContext) -> Result<TrackingWriteGuard<'_, DiskImage>, Vec<UiLockContext>> {
self.write(context)
}
fn strong_count(&self) -> usize {
self.strong_count()
}
}
impl From<TrackingLock<DiskImage>> for NonTrackingDiskLock<DiskImage> {
fn from(lock: TrackingLock<DiskImage>) -> Self {
NonTrackingDiskLock::new(lock.inner)
}
}
impl<T> TrackingLock<T> {
/// Creates a new TrackingLock.
pub fn new(data: T) -> Self {
TrackingLock {
inner: Arc::new(RwLock::new(data)),
tracking: Arc::new(Mutex::new(TrackingData {
read_locks: HashMap::new(),
write_lock: None,
})),
}
}
pub fn strong_count(&self) -> usize {
Arc::strong_count(&self.inner)
}
/// Attempts to acquire a read lock for the given tool.
pub fn read(&self, context: UiLockContext) -> Result<TrackingReadGuard<'_, T>, UiLockContext> {
let mut tracking = self.tracking.lock().unwrap();
if tracking.write_lock.is_some() {
log::error!(
"Tool {:?} attempted to acquire a read lock while a write lock is held by {:?}",
context,
tracking.write_lock
);
return Err(tracking.write_lock.unwrap());
}
// Acquire the actual read lock
match self.inner.try_read() {
Ok(guard) => {
// Increment the read lock count for the tool
*tracking.read_locks.entry(context).or_insert(0) += 1;
Ok(TrackingReadGuard {
guard,
tracking: Arc::clone(&self.tracking),
context,
})
}
Err(_) => {
// Failed to acquire the read lock. We should have detected this above, so panic.
panic!("Failed to detect write lock while acquiring read lock");
}
}
}
/// Attempts to acquire a write lock for the given tool.
pub fn write(&self, context: UiLockContext) -> Result<TrackingWriteGuard<'_, T>, Vec<UiLockContext>> {
let mut tracking = self.tracking.lock().unwrap();
if !tracking.read_locks.is_empty() {
log::error!(
"Tool {:?} attempted to acquire a write lock while read locks are held by {:?}",
context,
tracking.read_locks.iter().map(|(t, _)| *t).collect::<Vec<_>>()
);
return Err(tracking.read_locks.keys().cloned().collect());
}
if tracking.write_lock.is_some() {
log::error!(
"Tool {:?} attempted to acquire a write lock while write lock is held by {:?}",
context,
tracking.write_lock
);
return Err(vec![tracking.write_lock.unwrap()]);
}
// Set the write lock
tracking.write_lock = Some(context);
// Acquire the actual write lock
match self.inner.try_write() {
Ok(guard) => Ok(TrackingWriteGuard {
guard,
tracking: Arc::clone(&self.tracking),
context,
}),
Err(_) => {
// Failed to acquire the write lock. We should have detected this above, so panic.
panic!("Failed to detect existing lock while acquiring write lock");
}
}
}
/// Clones the Arc to allow sharing the TrackingLock.
pub fn clone_arc(&self) -> Self {
TrackingLock {
inner: Arc::clone(&self.inner),
tracking: Arc::clone(&self.tracking),
}
}
}
/// Guard that removes the read lock tracking when dropped.
pub struct TrackingReadGuard<'a, T> {
guard: RwLockReadGuard<'a, T>,
tracking: Arc<Mutex<TrackingData>>,
context: UiLockContext,
}
impl<'a, T> Deref for TrackingReadGuard<'a, T> {
type Target = T;
fn deref(&self) -> &Self::Target {
&*self.guard
}
}
impl<'a, T> Drop for TrackingReadGuard<'a, T> {
fn drop(&mut self) {
let mut tracking = self.tracking.lock().unwrap();
if let Some(count) = tracking.read_locks.get_mut(&self.context) {
*count -= 1;
if *count == 0 {
tracking.read_locks.remove(&self.context);
}
}
else {
log::error!(
"Context {:?} is dropping a read lock but it was not registered",
self.context
);
}
}
}
/// Guard that removes the write lock tracking when dropped.
pub struct TrackingWriteGuard<'a, T> {
guard: RwLockWriteGuard<'a, T>,
tracking: Arc<Mutex<TrackingData>>,
context: UiLockContext,
}
impl<'a, T> Deref for TrackingWriteGuard<'a, T> {
type Target = T;
fn deref(&self) -> &Self::Target {
&*self.guard
}
}
impl<'a, T> DerefMut for TrackingWriteGuard<'a, T> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut *self.guard
}
}
impl<'a, T> Drop for TrackingWriteGuard<'a, T> {
fn drop(&mut self) {
let mut tracking = self.tracking.lock().unwrap();
if let Some(current_tool) = tracking.write_lock {
if current_tool != self.context {
log::error!(
"Tool {:?} is dropping a write lock but the current write lock is held by {:?}",
self.context,
current_tool
);
}
else {
tracking.write_lock = None;
log::debug!(
"Tool {:?} dropped write lock. Strong references left: {}",
self.context,
Arc::strong_count(&self.tracking)
);
}
}
else {
log::error!(
"Tool {:?} is dropping a write lock but no write lock was registered",
self.context
);
}
}
}
| rust | MIT | b4c04b51746e5fe7769f49a1b32b8caad426fc81 | 2026-01-04T20:24:04.021295Z | false |
dbalsom/fluxfox | https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/crates/ff_egui_lib/src/visualization/palette.rs | crates/ff_egui_lib/src/visualization/palette.rs | /*
FluxFox
https://github.com/dbalsom/fluxfox
Copyright 2024-2025 Daniel Balsom
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the “Software”),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
--------------------------------------------------------------------------
*/
use std::collections::HashMap;
use fluxfox::{track_schema::GenericTrackElement, FoxHashMap};
use egui::Color32;
pub fn default_palette() -> FoxHashMap<GenericTrackElement, Color32> {
let viz_light_red: Color32 = Color32::from_rgba_premultiplied(180, 0, 0, 255);
//let viz_orange: Color = Color::from_rgba8(255, 100, 0, 255);
let vis_purple: Color32 = Color32::from_rgba_premultiplied(180, 0, 180, 255);
//let viz_cyan: Color = Color::from_rgba8(70, 200, 200, 255);
//let vis_light_purple: Color = Color::from_rgba8(185, 0, 255, 255);
let pal_medium_green = Color32::from_rgba_premultiplied(0x38, 0xb7, 0x64, 0xff);
let pal_dark_green = Color32::from_rgba_premultiplied(0x25, 0x71, 0x79, 0xff);
//let pal_dark_blue = Color::from_rgba8(0x29, 0x36, 0x6f, 0xff);
let pal_medium_blue = Color32::from_rgba_premultiplied(0x3b, 0x5d, 0xc9, 0xff);
let pal_light_blue = Color32::from_rgba_premultiplied(0x41, 0xa6, 0xf6, 0xff);
//let pal_dark_purple = Color::from_rgba8(0x5d, 0x27, 0x5d, 0xff);
let pal_orange = Color32::from_rgba_premultiplied(0xef, 0x7d, 0x57, 0xff);
//let pal_dark_red = Color::from_rgba8(0xb1, 0x3e, 0x53, 0xff);
//let pal_weak_bits = Color32::from_rgba8(70, 200, 200, 255);
//let pal_error_bits = Color32::from_rgba8(255, 0, 0, 255);
#[rustfmt::skip]
let palette = HashMap::from([
(GenericTrackElement::SectorData, pal_medium_green),
(GenericTrackElement::SectorBadData, pal_orange),
(GenericTrackElement::SectorDeletedData, pal_dark_green),
(GenericTrackElement::SectorBadDeletedData, viz_light_red),
(GenericTrackElement::SectorHeader, pal_light_blue),
(GenericTrackElement::SectorBadHeader, pal_medium_blue),
(GenericTrackElement::Marker, vis_purple),
]);
palette
}
| rust | MIT | b4c04b51746e5fe7769f49a1b32b8caad426fc81 | 2026-01-04T20:24:04.021295Z | false |
dbalsom/fluxfox | https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/crates/ff_egui_lib/src/visualization/viz_elements.rs | crates/ff_egui_lib/src/visualization/viz_elements.rs | /*
FluxFox
https://github.com/dbalsom/fluxfox
Copyright 2024-2025 Daniel Balsom
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the “Software”),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
--------------------------------------------------------------------------
*/
use crate::visualization::VizPalette;
use egui::{
emath::RectTransform,
epaint::{CubicBezierShape, PathShape, PathStroke, QuadraticBezierShape},
Color32,
Painter,
Pos2,
Shape,
Stroke,
};
use fluxfox::visualization::{prelude::*, VizRotate};
#[inline]
fn to_pos2_transformed(pt: &VizPoint2d<f32>, transform: &RectTransform) -> Pos2 {
let new_pt = Pos2::new(pt.x, pt.y);
transform.transform_pos(new_pt)
}
// Creates a [CubicBezierShape] from a [VizArc].
pub fn make_arc(
transform: &RectTransform,
rotation: &VizRotation,
arc: &VizArc,
stroke: &PathStroke,
) -> CubicBezierShape {
let arc = arc.rotate(rotation);
CubicBezierShape {
points: [
to_pos2_transformed(&arc.start, transform),
to_pos2_transformed(&arc.cp1, transform),
to_pos2_transformed(&arc.cp2, transform),
to_pos2_transformed(&arc.end, transform),
],
closed: false,
fill: Color32::TRANSPARENT,
stroke: stroke.clone(),
}
}
// Creates a [QuadraticBezierShape] from a [VizQuadraticArc].
pub fn make_quadratic_arc(
transform: &RectTransform,
rotation: &VizRotation,
arc: &VizQuadraticArc,
stroke: &PathStroke,
) -> QuadraticBezierShape {
let arc = arc.rotate(rotation);
QuadraticBezierShape {
points: [
to_pos2_transformed(&arc.start, transform),
to_pos2_transformed(&arc.cp, transform),
to_pos2_transformed(&arc.end, transform),
],
closed: false,
fill: Color32::TRANSPARENT,
stroke: stroke.clone(),
}
}
pub fn arc_to_points(transform: &RectTransform, rotation: &VizRotation, arc: &VizArc) -> Vec<Pos2> {
let arc = arc.rotate(rotation);
let bezier = CubicBezierShape {
points: [
to_pos2_transformed(&arc.start, transform),
to_pos2_transformed(&arc.cp1, transform),
to_pos2_transformed(&arc.cp2, transform),
to_pos2_transformed(&arc.end, transform),
],
closed: false,
fill: Color32::TRANSPARENT,
stroke: PathStroke::NONE,
};
bezier.flatten(Some(0.1))
}
/// Paint a shape - dispatch to the appropriate function based on the shape type.
pub fn paint_shape(
painter: &Painter,
transform: &RectTransform,
rotation: &VizRotation,
shape: &VizShape,
fill_color: Color32,
stroke: &PathStroke,
) {
match shape {
VizShape::Sector(sector) => paint_sector(painter, transform, rotation, sector, fill_color, stroke),
VizShape::CubicArc(arc, thickness) => {
// For an arc, stroke becomes the "fill" and the fill color is the stroke color.
let stroke = PathStroke::from(Stroke::new(*thickness * transform.scale().x, fill_color));
paint_arc(painter, transform, rotation, arc, &stroke)
}
VizShape::QuadraticArc(arc, thickness) => {
// For an arc, stroke becomes the "fill" and the fill color is the stroke color.
let stroke = PathStroke::from(Stroke::new(*thickness * transform.scale().x, fill_color));
paint_quadratic_arc(painter, transform, rotation, arc, &stroke)
}
VizShape::Circle(circle, thickness) => {
// For a circle, stroke becomes the "fill" and the fill color is the stroke color.
let stroke = Stroke::new(*thickness * transform.scale().x, fill_color);
paint_circle(painter, transform, circle, &stroke);
}
_ => {}
}
}
/// Renders a sector by drawing its outer and inner arcs and connecting lines.
pub fn paint_sector(
painter: &Painter,
transform: &RectTransform,
rotation: &VizRotation,
sector: &VizSector,
_fill_color: Color32,
stroke: &PathStroke,
) {
// Draw outer arc.
//let bezier_shape = Shape::CubicBezier(make_bezier(transform, §or.outer, fill_color, stroke));
//painter.add(bezier_shape);
// Draw inside wedge
//log::warn!("paint_sector: outer start: {:?}", sector.outer.start);
// Draw inner arc from start to end
let mut points = Vec::new();
// We need clockwise winding - start with the outer arc, which should be drawn from start to end
// point in clockwise winding.
points.extend(arc_to_points(transform, rotation, §or.outer));
// Then draw the inner arc
points.extend(arc_to_points(transform, rotation, §or.inner));
let shape = PathShape {
points,
closed: true,
fill: Color32::TRANSPARENT, // egui cannot fill a concave path.
stroke: stroke.clone(),
};
painter.add(Shape::Path(shape));
// Carve out the inner arc
//painter.add(make_bezier(transform, §or.inner, Color32::BLACK, stroke));
}
/// Renders an arc by drawing a cubic Bézier curve.
pub fn paint_arc(
painter: &Painter,
transform: &RectTransform,
rotation: &VizRotation,
arc: &VizArc,
stroke: &PathStroke,
) {
let shape = make_arc(transform, rotation, arc, stroke);
painter.add(Shape::CubicBezier(shape));
}
/// Renders an arc by drawing a cubic Bézier curve.
pub fn paint_quadratic_arc(
painter: &Painter,
transform: &RectTransform,
rotation: &VizRotation,
arc: &VizQuadraticArc,
stroke: &PathStroke,
) {
//let shape = make_quadratic_arc(transform, rotation, arc, stroke);
//painter.add(Shape::QuadraticBezier(shape));
painter.line(
vec![
to_pos2_transformed(&arc.start.rotate(rotation), transform),
to_pos2_transformed(&arc.end.rotate(rotation), transform),
],
stroke.clone(),
);
}
/// Renders a circle. Note no rotation parameter as rotating a circle does nothing.
pub fn paint_circle(painter: &Painter, transform: &RectTransform, circle: &VizCircle, stroke: &Stroke) {
painter.circle(
to_pos2_transformed(&circle.center, transform),
circle.radius,
Color32::TRANSPARENT,
*stroke,
);
}
pub fn paint_elements(
painter: &Painter,
transform: &RectTransform,
rotation: &VizRotation,
palette: &VizPalette,
elements: &[VizElement],
multiply: bool,
) {
let stroke = PathStroke::NONE;
match multiply {
true => {
// Check track flag and draw as gray
for element in elements {
let fill_color = if element.flags.contains(VizElementFlags::TRACK) {
Color32::from_gray(128)
}
else if let Some(color) = palette.get(&element.info.element_type) {
*color
}
else {
// Use a warning color to indicate missing palette entry.
Color32::RED
};
paint_shape(painter, transform, rotation, &element.shape, fill_color, &stroke);
}
}
false => {
// Paint normally.
for element in elements {
let fill_color = if element.flags.contains(VizElementFlags::HIGHLIGHT) {
//log::warn!("Highlighting element: {:?}", element.info.element_type);
Color32::from_white_alpha(80)
}
else if let Some(color) = palette.get(&element.info.element_type) {
*color
}
else {
// Use a warning color to indicate missing palette entry.
Color32::RED
};
paint_shape(painter, transform, rotation, &element.shape, fill_color, &stroke);
}
}
}
}
pub fn paint_data(
painter: &Painter,
transform: &RectTransform,
rotation: &VizRotation,
slices: &[VizDataSlice],
width: f32,
multiply: bool,
) {
let stroke = PathStroke::NONE;
match multiply {
true => {
// Multiply mode: render as black, density as alpha.
for slice in slices {
let fill_color =
Color32::from_black_alpha((((1.0 - slice.density * 2.0).clamp(0.0, 1.0)) * 255.0) as u8);
paint_shape(
painter,
transform,
rotation,
&VizShape::QuadraticArc(slice.arc, width),
fill_color,
&stroke,
);
}
}
false => {
// Normal mode; full alpha, grayscale rendering.
for slice in slices {
let fill_color = Color32::from_gray(((slice.density * 1.5).clamp(0.0, 1.0) * 255.0) as u8);
paint_shape(
painter,
transform,
rotation,
&VizShape::QuadraticArc(slice.arc, width),
fill_color,
&stroke,
);
}
}
}
}
| rust | MIT | b4c04b51746e5fe7769f49a1b32b8caad426fc81 | 2026-01-04T20:24:04.021295Z | false |
dbalsom/fluxfox | https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/crates/ff_egui_lib/src/visualization/mod.rs | crates/ff_egui_lib/src/visualization/mod.rs | /*
FluxFox
https://github.com/dbalsom/fluxfox
Copyright 2024-2025 Daniel Balsom
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the “Software”),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
--------------------------------------------------------------------------
*/
pub mod palette;
pub mod viz_elements;
use egui::Color32;
use fluxfox::{track_schema::GenericTrackElement, FoxHashMap};
pub type VizPalette = FoxHashMap<GenericTrackElement, Color32>;
| rust | MIT | b4c04b51746e5fe7769f49a1b32b8caad426fc81 | 2026-01-04T20:24:04.021295Z | false |
dbalsom/fluxfox | https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/crates/ff_egui_lib/src/widgets/chs.rs | crates/ff_egui_lib/src/widgets/chs.rs | /*
FluxFox
https://github.com/dbalsom/fluxfox
Copyright 2024-2025 Daniel Balsom
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the “Software”),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
--------------------------------------------------------------------------
*/
//! A widget for displaying pills representing the Cylinder-Head-Sector (CHS) addressing mode.
use crate::{widgets::pill::PillWidget, WidgetSize};
use fluxfox::prelude::{DiskCh, DiskChs, DiskChsn};
use egui::{Response, Widget};
#[derive(Clone, Default)]
pub struct ChsWidget {
pub size: WidgetSize,
pub head: u8,
pub cylinder: u16,
pub size_n: Option<u8>,
pub size_bytes: Option<usize>,
pub sector: Option<u8>,
}
impl ChsWidget {
pub fn from_ch(ch: DiskCh) -> Self {
Self {
head: ch.h(),
cylinder: ch.c(),
..Self::default()
}
}
pub fn from_chs(chs: DiskChs) -> Self {
Self {
head: chs.h(),
cylinder: chs.c(),
sector: Some(chs.s()),
..Self::default()
}
}
pub fn from_chsn(chsn: DiskChsn) -> Self {
Self {
head: chsn.h(),
cylinder: chsn.c(),
sector: Some(chsn.s()),
size_n: Some(chsn.n()),
size_bytes: Some(chsn.n_size()),
..Self::default()
}
}
pub fn with_size(mut self, size: WidgetSize) -> Self {
self.size = size;
self
}
pub fn with_sector(mut self, sector: u8) -> Self {
self.sector = Some(sector);
self
}
pub fn with_n(mut self, n: u8) -> Self {
self.size_n = Some(n);
self.size_bytes = Some(DiskChsn::n_to_bytes(n));
self
}
fn show(&self, ui: &mut egui::Ui) -> Response {
// Get color from ui visuals
let fill_color = ui.visuals().widgets.inactive.bg_fill;
let text_color = ui.visuals().widgets.inactive.fg_stroke.color;
// Attempt to center the pills vertically in whatever containing ui they are in?
ui.horizontal(|ui| {
//ui.allocate_ui_with_layout(ui.available_size(), Layout::left_to_right(Align::TOP), |ui| {
// Cylinder pill
ui.add(
PillWidget::new(&format!("c: {}", self.cylinder))
.with_size(self.size)
.with_color(text_color)
.with_fill(fill_color),
);
// Head pill
ui.add(
PillWidget::new(&format!("h: {}", self.head))
.with_size(self.size)
.with_color(text_color)
.with_fill(fill_color),
);
// Sector pill (if present)
if let Some(sector) = self.sector {
ui.add(
PillWidget::new(&format!("s: {}", sector))
.with_size(self.size)
.with_color(text_color)
.with_fill(fill_color),
);
}
// Size pill (if present)
if let Some(sector) = self.size_n {
ui.add(
PillWidget::new(&format!("n: {}", sector))
.with_size(self.size)
.with_color(text_color)
.with_fill(fill_color),
);
}
})
.response
}
}
impl Widget for ChsWidget {
fn ui(self, ui: &mut egui::Ui) -> Response {
self.show(ui)
}
}
| rust | MIT | b4c04b51746e5fe7769f49a1b32b8caad426fc81 | 2026-01-04T20:24:04.021295Z | false |
dbalsom/fluxfox | https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/crates/ff_egui_lib/src/widgets/mod.rs | crates/ff_egui_lib/src/widgets/mod.rs | /*
FluxFox
https://github.com/dbalsom/fluxfox
Copyright 2024-2025 Daniel Balsom
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the “Software”),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
--------------------------------------------------------------------------
*/
//! Module defining custom widgets. A widget is a control that implements the `Widget` trait
//! and is designed to be added to a `ui` via `ui.add()`.
pub mod chs;
pub mod pill;
| rust | MIT | b4c04b51746e5fe7769f49a1b32b8caad426fc81 | 2026-01-04T20:24:04.021295Z | false |
dbalsom/fluxfox | https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/crates/ff_egui_lib/src/widgets/pill.rs | crates/ff_egui_lib/src/widgets/pill.rs | /*
FluxFox
https://github.com/dbalsom/fluxfox
Copyright 2024-2025 Daniel Balsom
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the “Software”),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
--------------------------------------------------------------------------
*/
//! A [Pill] widget for egui. This creates a label with a rounded background.
use crate::WidgetSize;
use egui::{Color32, Response, Ui, Widget};
pub struct PillWidget {
label: String,
size: WidgetSize,
color: Color32,
fill: Color32,
}
impl PillWidget {
pub fn new(label: &str) -> Self {
Self {
label: label.to_string(),
size: WidgetSize::default(),
color: Color32::WHITE,
fill: Color32::TRANSPARENT,
}
}
pub fn with_size(mut self, size: WidgetSize) -> Self {
self.size = size;
self
}
pub fn with_color(mut self, color: Color32) -> Self {
self.color = color;
self
}
pub fn with_fill(mut self, color: Color32) -> Self {
self.fill = color;
self
}
pub fn show(&self, ui: &mut Ui) -> Response {
let frame = egui::Frame::none()
.fill(self.fill)
.rounding(self.size.rounding())
.inner_margin(self.size.padding())
.outer_margin(egui::Margin::from(0.0));
frame
.show(ui, |ui| {
ui.label(egui::RichText::new(&self.label).color(self.color));
})
.response
}
}
impl Widget for PillWidget {
fn ui(self, ui: &mut Ui) -> Response {
self.show(ui)
}
}
| rust | MIT | b4c04b51746e5fe7769f49a1b32b8caad426fc81 | 2026-01-04T20:24:04.021295Z | false |
dbalsom/fluxfox | https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/crates/ff_egui_lib/src/controls/source_map.rs | crates/ff_egui_lib/src/controls/source_map.rs | /*
fluxfox
https://github.com/dbalsom/fluxfox
Copyright 2024-2025 Daniel Balsom
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the “Software”),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
--------------------------------------------------------------------------
Implements a custom control that displays the image source map
*/
use egui::{CollapsingHeader, Ui};
use fluxfox::{source_map::SourceMap, DiskImage, DiskImageFileFormat};
#[derive(Default)]
pub struct SourceMapWidget {
pub source_map: Option<SourceMap>,
pub source_format: Option<DiskImageFileFormat>,
}
impl SourceMapWidget {
pub fn new() -> Self {
Self {
source_map: None,
source_format: None,
}
}
pub fn update(&mut self, disk: &DiskImage) {
self.source_map = disk.source_map().as_some().cloned();
self.source_format = disk.source_format();
}
pub fn update_direct(&mut self, source_map: &SourceMap, source_format: Option<DiskImageFileFormat>) {
self.source_map = Some(source_map.clone());
self.source_format = source_format;
}
pub fn show(&mut self, ui: &mut Ui) {
if self.source_map.is_none() {
ui.label("No source map available");
}
else {
egui::ScrollArea::vertical().show(ui, |ui| {
ui.set_min_width(500.00);
self.render_source_map(ui);
});
}
}
/// Recursively renders a node and its children.
pub fn render_source_map(&mut self, ui: &mut Ui) {
let tree = self.source_map.as_ref().unwrap();
// Display the file format as the root note, if there is one
if let Some(format) = self.source_format {
CollapsingHeader::new(format!("{:?}", format)).show(ui, |ui| {
Self::render_source_map_recursive(ui, tree, 0);
});
}
else {
// No file format, so just start at the root's children
Self::render_source_map_recursive(ui, tree, 0);
}
}
pub fn render_source_map_recursive(ui: &mut Ui, map: &SourceMap, idx: usize) {
for &child_index in map.children(idx) {
let (name, value) = map.node(child_index);
if map.children(child_index).is_empty() {
//log::debug!("Rendering leaf node: {}", name);
// Node has no children, so just show a label
//ui.label(format! {"{}: {}", name, value});
ui.horizontal(|ui| {
ui.horizontal(|ui| {
// Set a minimum width for the key field
ui.set_min_width(120.0);
ui.label(name);
});
let value_text = egui::RichText::new(value.to_string());
// If value is bad, display it as error color
if value.is_bad() {
ui.label(value_text.color(ui.visuals().error_fg_color));
}
else {
ui.label(value_text);
}
// Display any comment in the third grid column, as weak fg and italics
if let Some(comment) = value.comment_ref() {
ui.label(
egui::RichText::new(comment)
.italics()
.color(ui.visuals().weak_text_color()),
);
}
});
}
else {
//log::debug!("Rendering new parent node: {}", name);
// Render children under collapsing header
CollapsingHeader::new(name)
.id_salt(format!("ch_node{}", child_index))
.show(ui, |ui| {
// Recursively render children
Self::render_source_map_recursive(ui, map, child_index);
});
}
}
}
}
| rust | MIT | b4c04b51746e5fe7769f49a1b32b8caad426fc81 | 2026-01-04T20:24:04.021295Z | false |
dbalsom/fluxfox | https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/crates/ff_egui_lib/src/controls/header_group.rs | crates/ff_egui_lib/src/controls/header_group.rs | /*
FluxFox
https://github.com/dbalsom/fluxfox
Copyright 2024-2025 Daniel Balsom
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the “Software”),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
--------------------------------------------------------------------------
*/
use egui::{Pos2, Rect, RichText, Rounding, Stroke, TextStyle, Vec2};
pub type HeaderFn = fn(&mut egui::Ui, default_text: RichText);
pub struct HeaderGroup {
heading: String,
strong: bool,
expand: bool,
}
impl HeaderGroup {
pub fn new(str: &str) -> Self {
Self {
heading: str.to_string(),
strong: false,
expand: false,
}
}
pub fn strong(mut self) -> Self {
self.strong = true;
self
}
pub fn expand(mut self) -> Self {
self.expand = true;
self
}
// pub fn show<F>(&self, ui: &mut egui::Ui, body_content: F, header_content: Option<F>)
// where
// F: FnOnce(&mut egui::Ui),
pub fn show(
&self,
ui: &mut egui::Ui,
body_content: impl FnOnce(&mut egui::Ui),
header_content: Option<impl FnOnce(&mut egui::Ui, RichText)>,
) {
// Add some margin space for the group
let margin = ui.style().spacing.window_margin;
// Begin the group
let response = ui.scope(|ui| {
if self.expand {
ui.set_width(ui.available_width()); // Use the full width
}
ui.horizontal(|ui| {
ui.add_space(margin.left); // Left margin
ui.vertical(|ui| {
// Paint the heading
ui.add_space(margin.top); // Top margin
let mut text = RichText::new(&self.heading);
if self.strong {
text = text.strong();
}
ui.horizontal(|ui| {
// Let the header callback fully control drawing the header content in its
// own scope.
if let Some(header_content) = header_content {
ui.scope(|ui| {
header_content(ui, text);
});
}
else {
ui.heading(text);
}
});
ui.add_space(margin.top); // Top margin
// Draw the custom content
ui.horizontal(|ui| {
body_content(ui);
//ui.add_space(ui.available_width());
});
ui.add_space(margin.bottom); // Bottom margin
});
});
});
// Get the rect for the entire group we just created
let group_rect = response.response.rect;
// Paint the header background
if ui.is_rect_visible(group_rect) {
let header_height = ui.fonts(|fonts| fonts.row_height(&TextStyle::Heading.resolve(ui.style())));
let header_rect = Rect::from_min_size(
group_rect.min,
Vec2::new(group_rect.width(), header_height + margin.top * 2.0), // Include padding for margins
);
let painter = ui.painter();
let visuals = ui.visuals();
let bg_color = visuals.faint_bg_color.gamma_multiply(1.2); // Slightly brighter than the default background
let rounding = Rounding {
nw: 4.0, // Top-left corner
ne: 4.0, // Top-right corner
sw: 0.0, // Bottom-left corner
se: 0.0, // Bottom-right corner
};
painter.rect_filled(header_rect, rounding, bg_color);
// Draw a light line at the bottom of the header
let line_color = visuals.widgets.inactive.bg_fill; // Use a lighter color for the line
let line_stroke = Stroke::new(1.0, line_color);
let bottom_line_start = Pos2::new(header_rect.min.x, header_rect.max.y);
let bottom_line_end = Pos2::new(header_rect.max.x, header_rect.max.y);
painter.line_segment([bottom_line_start, bottom_line_end], line_stroke);
}
// Draw the overall border for the group
if ui.is_rect_visible(group_rect) {
let painter = ui.painter();
let visuals = ui.visuals();
let border_color = visuals.widgets.noninteractive.bg_stroke.color;
let stroke = Stroke::new(1.0, border_color);
let rounding = Rounding::same(6.0); // Overall group rounding
painter.rect_stroke(group_rect, rounding, stroke);
}
}
}
| rust | MIT | b4c04b51746e5fe7769f49a1b32b8caad426fc81 | 2026-01-04T20:24:04.021295Z | false |
dbalsom/fluxfox | https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/crates/ff_egui_lib/src/controls/vector_disk_visualizer.rs | crates/ff_egui_lib/src/controls/vector_disk_visualizer.rs | /*
FluxFox
https://github.com/dbalsom/fluxfox
Copyright 2024-2025 Daniel Balsom
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the “Software”),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
--------------------------------------------------------------------------
*/
use crate::visualization::{
palette::default_palette,
viz_elements::{paint_data, paint_elements},
VizPalette,
};
use egui::{Pos2, Rect, Vec2};
use fluxfox::visualization::prelude::*;
pub struct DiskVisualizerWidget {
pub open: bool,
pub show_data_layer: bool,
pub show_metadata_layer: bool,
pub show_error_layer: bool,
pub show_weak_layer: bool,
pub resolution: Vec2,
pub angle: f32,
pub track_width: f32,
pub palette: VizPalette,
pub data_display_list: VizDataSliceDisplayList,
pub metadata_display_list: VizElementDisplayList,
}
impl DiskVisualizerWidget {
pub fn new(resolution: u32, turning_direction: TurningDirection, cylinders: usize) -> Self {
Self {
open: false,
show_data_layer: true,
show_metadata_layer: true,
show_error_layer: false,
show_weak_layer: false,
resolution: Vec2::new(resolution as f32, resolution as f32),
angle: 0.0,
track_width: 1.0,
palette: default_palette(),
data_display_list: VizDataSliceDisplayList::new(turning_direction, cylinders, 0.0),
metadata_display_list: VizElementDisplayList::new(turning_direction, 0, cylinders as u16),
}
}
pub fn update_data(&mut self, display_list: VizDataSliceDisplayList) {
self.data_display_list = display_list;
}
pub fn update_metadata(&mut self, display_list: VizElementDisplayList) {
self.metadata_display_list = display_list;
}
pub fn angle_mut(&mut self) -> &mut f32 {
&mut self.angle
}
pub fn show_metadata_layer_mut(&mut self) -> &mut bool {
&mut self.show_metadata_layer
}
pub fn show_data_layer_mut(&mut self) -> &mut bool {
&mut self.show_data_layer
}
pub fn show(&mut self, ui: &mut egui::Ui) {
let (rect, _response) = ui.allocate_exact_size(self.resolution, egui::Sense::hover());
let meta_painter = ui.painter().with_clip_rect(rect);
// log::debug!(
// "DiskVisualizerWidget::show: rect: {:?} res: {:?}",
// rect,
// self.resolution
// );
let zoom = 1.0;
// Create a transform to map from local (0,0) to rect.min
let viz_rect = Rect::from_min_size(Pos2::ZERO, self.resolution / zoom);
let to_screen = egui::emath::RectTransform::from_to(
viz_rect, // Local space
rect, // Screen space
);
let rotation = VizRotation::new(
self.angle,
VizPoint2d::new(self.resolution.x / 2.0, self.resolution.y / 2.0),
);
let data_painter = meta_painter.with_clip_rect(rect);
if self.show_metadata_layer {
for track in &self.metadata_display_list.tracks {
paint_elements(
&meta_painter,
&to_screen,
&rotation,
&self.palette,
track,
self.show_data_layer,
);
}
}
if self.show_data_layer {
for (_ti, track) in self.data_display_list.tracks.iter().enumerate() {
// log::debug!(
// "DiskVisualizerWidget::show: painting data on track: {}, elements: {}",
// ti,
// track.len()
// );
paint_data(
&data_painter,
&to_screen,
&rotation,
track,
self.data_display_list.track_width,
self.show_metadata_layer,
);
}
}
}
}
| rust | MIT | b4c04b51746e5fe7769f49a1b32b8caad426fc81 | 2026-01-04T20:24:04.021295Z | false |
dbalsom/fluxfox | https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/crates/ff_egui_lib/src/controls/disk_info.rs | crates/ff_egui_lib/src/controls/disk_info.rs | /*
FluxFox
https://github.com/dbalsom/fluxfox
Copyright 2024-2025 Daniel Balsom
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the “Software”),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
--------------------------------------------------------------------------
src/widgets/disk_info.rs
Disk Info widget for displaying basic disk information.
*/
use fluxfox::prelude::*;
#[derive(Default)]
pub struct DiskInfoWidget {
pub filename: Option<String>,
pub platforms: Option<Vec<Platform>>,
pub resolution: Vec<TrackDataResolution>,
pub geometry: DiskCh,
pub rate: TrackDataRate,
pub encoding: TrackDataEncoding,
pub density: TrackDensity,
}
impl DiskInfoWidget {
pub fn new() -> Self {
Self::default()
}
pub fn update(&mut self, disk: &DiskImage, filename: Option<String>) {
self.filename = filename;
self.platforms = disk.image_format().platforms.clone();
self.resolution = disk.resolution();
self.geometry = disk.geometry();
self.rate = disk.data_rate();
self.encoding = disk.data_encoding();
self.density = disk.image_format().density;
}
pub fn show(&self, ui: &mut egui::Ui) {
ui.vertical(|ui| {
egui::Grid::new("disk_info_grid").striped(true).show(ui, |ui| {
// Filename can be very long (think TDC title names) - maybe there is a better place to
// display the filename.
// ui.label("Filename:");
// ui.label(self.filename.as_ref().unwrap_or(&"None".to_string()));
// ui.end_row();
if let Some(platforms) = &self.platforms {
if platforms.len() > 1 {
ui.label("Multi-platform:");
ui.end_row();
for (i, platform) in platforms.iter().enumerate() {
ui.label(format!("[{}]", i));
ui.label(format!("{}", platform));
ui.end_row();
}
}
else if !platforms.is_empty() {
ui.label("Platform:");
ui.label(format!("{}", platforms[0]));
ui.end_row();
}
}
if self.resolution.len() > 1 {
ui.label("Multi-resolution:");
ui.end_row();
for (i, resolution) in self.resolution.iter().enumerate() {
ui.label(format!("[{}]", i));
ui.label(format!("{:?}", resolution));
ui.end_row();
}
}
else if !self.resolution.is_empty() {
ui.label("Resolution:");
ui.label(format!("{:?}", self.resolution[0]));
ui.end_row();
}
ui.label("Sides:");
ui.label(format!("{}", self.geometry.h()));
ui.end_row();
ui.label("Cylinders:");
ui.label(format!("{}", self.geometry.c()));
ui.end_row();
ui.label("Data Rate:");
ui.label(format!("{}", self.rate));
ui.end_row();
ui.label("Data Encoding:");
ui.label(format!("{:?}", self.encoding).to_uppercase());
ui.end_row();
ui.label("Density:");
ui.label(format!("{:?}", self.density));
ui.end_row();
});
});
}
}
| rust | MIT | b4c04b51746e5fe7769f49a1b32b8caad426fc81 | 2026-01-04T20:24:04.021295Z | false |
dbalsom/fluxfox | https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/crates/ff_egui_lib/src/controls/data_table.rs | crates/ff_egui_lib/src/controls/data_table.rs | /*
FluxFox
https://github.com/dbalsom/fluxfox
Copyright 2024-2025 Daniel Balsom
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the “Software”),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
--------------------------------------------------------------------------
src/widgets/disk_info.rs
Disk Info widget for displaying basic disk information.
*/
use std::ops::Range;
use crate::{
character_encoding::CharacterEncoding,
controls::{data_visualizer::DataVisualizerWidget, tab_group::TabGroup},
range_check::RangeChecker,
};
use egui_extras::{Column, TableBuilder};
use strum::IntoEnumIterator;
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub struct DataRange {
pub name: String,
pub fg_color: egui::Color32,
pub range: Range<usize>,
}
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub struct DataTableWidget {
encoding: CharacterEncoding,
num_columns: usize,
num_rows: usize,
scroll_to_row_slider: usize,
scroll_to_row: Option<usize>,
selection: std::collections::HashSet<usize>,
hover_address: Option<usize>,
checked: bool,
reversed: bool,
data: Vec<u8>,
row_string_width: usize,
tabs: TabGroup,
viz_widget: Option<DataVisualizerWidget>,
ranges: Vec<DataRange>,
}
impl Default for DataTableWidget {
fn default() -> Self {
Self {
encoding: CharacterEncoding::IsoIec8559_1,
num_columns: 16,
num_rows: 512 / 16,
scroll_to_row_slider: 0,
scroll_to_row: None,
selection: Default::default(),
hover_address: None,
checked: false,
reversed: false,
data: vec![0xFF; 512],
row_string_width: 3,
tabs: TabGroup::new().with_tab("hex").with_tab("text").with_tab("viz"),
viz_widget: None,
ranges: Vec::new(),
}
}
}
impl DataTableWidget {
pub fn add_range(&mut self, range: DataRange) {
self.ranges.push(range);
}
pub fn show(&mut self, ui: &mut egui::Ui) {
ui.horizontal(|ui| {
egui::ComboBox::from_id_salt("Encoding")
.selected_text(self.encoding.to_string())
.show_ui(ui, |ui| {
for encoding in CharacterEncoding::iter() {
ui.selectable_value(&mut self.encoding, encoding, encoding.to_string());
}
});
});
self.tabs.show(ui);
ui.separator();
match self.tabs.selected_tab() {
0 => {
self.table_ui(ui, false);
}
1 => {
egui::ScrollArea::horizontal().show(ui, |ui| {
self.text_ui(ui);
});
}
2 => {
if self.viz_widget.is_some() {
self.viz_ui(ui);
}
else {
let id = format!(
"data_table_{},{}",
ui.next_widget_position().x as u32,
ui.next_widget_position().y as u32
);
self.viz_widget = Some(DataVisualizerWidget::new(ui.ctx(), &id));
self.viz_ui(ui);
}
}
_ => {}
}
}
fn viz_ui(&mut self, ui: &mut egui::Ui) {
if let Some(viz_widget) = &mut self.viz_widget {
let (_, start) = viz_widget.get_address();
let start = start.min(self.data.len());
let end = start + viz_widget.get_required_data_size();
let end = end.min(self.data.len());
let slice = &self.data[start..end];
viz_widget.update_data(slice);
viz_widget.show(ui);
}
}
fn text_ui(&mut self, ui: &mut egui::Ui) {
ui.vertical(|ui| {
let strings = self.data_to_string();
let available_height = ui.available_height();
let text_height = egui::TextStyle::Body
.resolve(ui.style())
.size
.max(ui.spacing().interact_size.y);
let table = TableBuilder::new(ui)
.striped(false)
.resizable(false)
.cell_layout(egui::Layout::left_to_right(egui::Align::LEFT))
.column(Column::initial(40.0))
.column(Column::remainder())
.min_scrolled_height(0.0)
.max_scroll_height(available_height);
table
.header(20.0, |mut header| {
header.col(|ui| {
ui.strong("Line");
});
header.col(|ui| {
ui.strong("Text");
});
})
.body(|body| {
body.rows(text_height, strings.len(), |mut row| {
let row_index = row.index();
row.col(|ui| {
let formatted = format!("{}", row_index);
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
ui.add(
egui::Label::new(egui::RichText::new(formatted).monospace().strong())
.selectable(false),
);
});
});
row.col(|ui| {
ui.label(egui::RichText::new(&strings[row_index]).monospace());
});
});
});
});
}
fn table_ui(&mut self, ui: &mut egui::Ui, reset: bool) {
ui.vertical(|ui| {
use egui_extras::{Column, TableBuilder};
let text_height = egui::TextStyle::Body
.resolve(ui.style())
.size
.max(ui.spacing().interact_size.y);
let available_height = ui.available_height();
let mut table = TableBuilder::new(ui)
.striped(false)
.resizable(false)
.cell_layout(egui::Layout::left_to_right(egui::Align::LEFT))
.column(Column::auto())
.column(Column::auto())
.column(Column::auto())
.min_scrolled_height(0.0)
.max_scroll_height(available_height);
// if self.clickable {
// table = table.sense(egui::Sense::click());
// }
if let Some(row_index) = self.scroll_to_row.take() {
table = table.scroll_to_row(row_index, None);
}
if reset {
table.reset();
}
// Create range checker
let range_checker = RangeChecker::new(
&self
.ranges
.iter()
.map(|r| (r.range.start, r.range.end))
.collect::<Vec<_>>(),
);
let mut any_row_hovered_idx = None;
table
.header(20.0, |mut header| {
header.col(|ui| {
ui.strong("Addr");
});
header.col(|ui| {
ui.strong("Hex");
});
header.col(|ui| {
ui.strong("Char");
});
})
.body(|body| {
body.rows(text_height, self.num_rows, |mut row| {
let row_index = row.index();
let mut row_hovered_idx = None;
row.set_selected(self.selection.contains(&row_index));
row.col(|ui| {
let formatted = format!(
"{:0width$X}",
row_index * self.num_columns,
width = self.row_string_width
);
ui.label(egui::RichText::new(formatted).monospace());
});
row.col(|ui| {
for (ei, element) in self.row_elements_hex(row_index).into_iter().enumerate() {
let element_address = row_index * self.num_columns + ei;
let mut hit_range = false;
let mut range_text = String::new();
let mut fg_color = ui.visuals().text_color();
if let Some(idx) = range_checker.contains(element_address) {
if let Some(range) = self.ranges.get(idx) {
hit_range = true;
range_text = range.name.clone();
fg_color = range.fg_color;
}
}
ui.visuals_mut().override_text_color = Some(fg_color);
if ui.add(element).hovered() {
self.hover_address = Some(element_address);
if hit_range {
egui::popup::show_tooltip(
ui.ctx(),
ui.layer_id(),
egui::Id::new("data_table_range_popup"),
|ui| {
ui.horizontal(|ui| {
ui.label(range_text);
});
},
);
}
row_hovered_idx = Some(ei);
any_row_hovered_idx = Some(ei);
}
ui.visuals_mut().override_text_color = None;
}
//ui.label(self.row_string_hex(row_index));
});
row.col(|ui| {
for (ei, element) in self
.row_elements_ascii(row_index, row_hovered_idx)
.into_iter()
.enumerate()
{
let element_address = row_index * self.num_columns + ei;
ui.spacing_mut().item_spacing = egui::vec2(0.1, ui.spacing().item_spacing.y);
if ui.add(element).hovered() {
self.hover_address = Some(element_address);
}
}
//ui.label(self.row_string_ascii(row_index));
});
self.toggle_row_selection(row_index, &row.response());
});
});
if any_row_hovered_idx.is_none() {
self.hover_address = None;
}
});
}
pub fn set_data(&mut self, data: &[u8]) {
self.ranges = Vec::new();
self.data = data.to_vec();
self.calc_layout();
}
pub fn data_len(&self) -> usize {
self.data.len()
}
fn row_elements_hex(&mut self, row_index: usize) -> Vec<egui::Label> {
let data_index = row_index * self.num_columns;
if data_index >= self.data.len() {
return vec![];
}
let data_slice = &self.data[data_index..std::cmp::min(data_index + self.num_columns, self.data.len())];
let mut row_elements = Vec::new();
for byte in data_slice {
row_elements.push(egui::Label::new(
egui::RichText::new(format!("{:02X}", byte)).monospace(),
));
}
row_elements
}
fn row_elements_ascii(&mut self, row_index: usize, hovered: Option<usize>) -> Vec<egui::Label> {
let data_index = row_index * self.num_columns;
if data_index >= self.data.len() {
return vec![];
}
let data_slice = &self.data[data_index..std::cmp::min(data_index + self.num_columns, self.data.len())];
let mut row_elements = Vec::new();
for (bi, byte) in data_slice.iter().enumerate() {
let char = self.encoding.display_byte(*byte);
let mut label_text = egui::RichText::new(char).monospace();
if Some(bi) == hovered {
label_text = label_text.strong();
}
row_elements.push(egui::Label::new(label_text));
}
row_elements
}
fn calc_layout(&mut self) {
assert!(self.num_columns > 0, "num_columns must be greater than 0");
// Calculate the number of rows, including a partial row
let num_rows = self.data.len().div_ceil(self.num_columns);
// Determine the required number of hex digits for row numbers
let max_row_index = num_rows.saturating_sub(1);
let required_hex_digits = ((max_row_index * self.num_columns) as f64).log(16.0).ceil() as usize;
self.num_rows = num_rows;
self.row_string_width = required_hex_digits;
}
fn toggle_row_selection(&mut self, row_index: usize, row_response: &egui::Response) {
if row_response.clicked() {
if self.selection.contains(&row_index) {
self.selection.remove(&row_index);
}
else {
self.selection.insert(row_index);
}
}
}
fn data_to_string(&self) -> Vec<String> {
let converted_data = self
.data
.iter()
.map(|byte| match byte {
0x0A | 0x0D => *byte,
0x20..0x7E => *byte,
_ => 0x20,
})
.collect::<Vec<u8>>();
let converted_string = String::from_utf8_lossy(&converted_data);
// Split by Unix newlines (`\n`) and trim DOS carriage returns (`\r`)
let strings: Vec<String> = converted_string
.lines()
.map(|line| line.trim_end_matches('\r').to_string())
.collect();
strings
}
}
| rust | MIT | b4c04b51746e5fe7769f49a1b32b8caad426fc81 | 2026-01-04T20:24:04.021295Z | false |
dbalsom/fluxfox | https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/crates/ff_egui_lib/src/controls/file_list.rs | crates/ff_egui_lib/src/controls/file_list.rs | /*
FluxFox
https://github.com/dbalsom/fluxfox
Copyright 2024-2025 Daniel Balsom
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the “Software”),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
--------------------------------------------------------------------------
*/
use crate::UiEvent;
use egui::{Label, Sense};
use egui_extras::{Column, TableBuilder};
use fluxfox::file_system::FileEntry;
pub const GENERIC_FILE_ICON: &str = "🗋";
pub struct FileListWidget {
is_web: bool,
file_list: Vec<FileEntry>,
icon_map: fluxfox::FoxHashMap<&'static str, &'static str>,
}
impl Default for FileListWidget {
fn default() -> Self {
Self::new()
}
}
impl FileListWidget {
pub fn new() -> Self {
Self {
is_web: {
#[cfg(target_arch = "wasm32")]
{
true
}
#[cfg(not(target_arch = "wasm32"))]
{
false
}
},
file_list: Vec::new(),
icon_map: FileListWidget::icon_map(),
}
}
fn icon_map() -> fluxfox::FoxHashMap<&'static str, &'static str> {
let mut map = fluxfox::FoxHashMap::new();
let exe_icon = "🖥";
let doc_icon = "🖹";
let image_icon = "🖻";
let audio_icon = "🔉";
let archive_icon = "📚";
map.insert("exe", exe_icon);
map.insert("com", exe_icon);
map.insert("bat", exe_icon);
map.insert("sys", exe_icon);
map.insert("dll", exe_icon);
map.insert("doc", doc_icon);
map.insert("txt", doc_icon);
map.insert("pcx", image_icon);
map.insert("iff", image_icon);
map.insert("tga", image_icon);
map.insert("bmp", image_icon);
map.insert("jpg", image_icon);
map.insert("gif", image_icon);
map.insert("png", image_icon);
map.insert("wav", audio_icon);
map.insert("mp3", audio_icon);
map.insert("arj", archive_icon);
map.insert("zip", archive_icon);
map.insert("lha", archive_icon);
map.insert("lzh", archive_icon);
map.insert("arc", archive_icon);
map
}
pub fn reset(&mut self) {
self.file_list.clear();
}
pub fn update(&mut self, files: &[FileEntry]) {
self.file_list = files.to_vec();
}
pub fn show(&self, ui: &mut egui::Ui) -> Option<UiEvent> {
self.show_dir_table(ui)
}
fn show_dir_table(&self, ui: &mut egui::Ui) -> Option<UiEvent> {
// if self.dir_list.is_empty() {
// return None;
// }
let mut new_event = None;
let num_rows = self.file_list.len();
let text_height = egui::TextStyle::Body
.resolve(ui.style())
.size
.max(ui.spacing().interact_size.y);
ui.with_layout(egui::Layout::top_down(egui::Align::Min), |ui| {
let available_height = ui.available_height();
//ui.set_min_height(available_height);
let table = TableBuilder::new(ui)
.striped(true)
.resizable(true)
.cell_layout(egui::Layout::left_to_right(egui::Align::LEFT))
.column(Column::exact(120.0))
.column(Column::auto())
//.column(Column::auto())
.column(Column::auto())
.column(Column::auto())
.min_scrolled_height(0.0)
.max_scroll_height(available_height);
table
.header(20.0, |mut header| {
header.col(|ui| {
ui.strong("Filename");
});
header.col(|ui| {
ui.strong("Size");
});
// header.col(|ui| {
// ui.strong("Created Date");
// });
header.col(|ui| {
ui.strong("Modified Date");
});
header.col(|ui| {
ui.strong("Attributes");
});
})
.body(|body| {
body.rows(text_height, num_rows, |mut row| {
let row_index = row.index();
//row.set_selected(self.selection.contains(&row_index));
let icon = self.get_icon(&self.file_list[row_index]);
// First column - file icon and filename.
// Filename is clickable to select the file, right clickable to open context menu.
row.col(|ui| {
ui.with_layout(egui::Layout::left_to_right(egui::Align::Center), |ui| {
//ui.label(icon);
let file_name = format!("{} {}", icon, self.file_list[row_index].short_name());
let item_response = ui
.add(Label::new(egui::RichText::new(file_name).monospace()).sense(Sense::click()));
if item_response.clicked() {
log::debug!(
"show_dir_table(): Clicked on {:?}",
self.file_list[row_index].path().to_string()
);
new_event = Some(UiEvent::SelectFile(self.file_list[row_index].clone()));
}
item_response.context_menu(|ui| {
let save_label_text = match self.is_web {
true => "Download",
false => "Save As...",
};
if ui.button(save_label_text).clicked() {
new_event =
Some(UiEvent::ExportFile(self.file_list[row_index].path().to_string()));
ui.close_menu();
}
});
});
});
// Size column
row.col(|ui| {
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
ui.label(self.file_list[row_index].size().to_string());
});
});
// // Created date column - Not implemented in DOS FAT12 filesystems
// row.col(|ui| {
// if let Some(created) = self.file_list[row_index].created() {
// ui.label(created.to_string());
// }
// else {
// ui.label("");
// }
// });
// Modified date column
row.col(|ui| {
if let Some(modified) = self.file_list[row_index].modified() {
ui.label(modified.to_string());
}
});
// Attributes column
row.col(|ui| {
ui.label("");
});
});
});
});
new_event
}
fn get_icon(&self, entry: &FileEntry) -> String {
if entry.is_dir() {
"📁".to_string()
}
else {
self.icon_map
.get(entry.ext().unwrap_or("").to_ascii_lowercase().as_str())
.map_or_else(|| GENERIC_FILE_ICON.to_string(), ToString::to_string)
}
}
}
| rust | MIT | b4c04b51746e5fe7769f49a1b32b8caad426fc81 | 2026-01-04T20:24:04.021295Z | false |
dbalsom/fluxfox | https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/crates/ff_egui_lib/src/controls/filesystem.rs | crates/ff_egui_lib/src/controls/filesystem.rs | /*
FluxFox
https://github.com/dbalsom/fluxfox
Copyright 2024-2025 Daniel Balsom
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the “Software”),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
--------------------------------------------------------------------------
*/
use crate::{
controls::{dir_tree::DirTreeWidget, file_list::FileListWidget, path_selection::PathSelectionWidget},
UiEvent,
};
use fluxfox::file_system::{fat::fat_fs::FatFileSystem, FileTreeNode};
use std::cell::Cell;
pub struct FileSystemWidget {
tree_widget: DirTreeWidget,
list_widget: FileListWidget,
path_selection_widget: PathSelectionWidget,
path_selection: Option<String>,
file_selection: Option<String>,
new_file_selection: Cell<bool>,
tree: FileTreeNode,
}
impl Default for FileSystemWidget {
fn default() -> Self {
Self::new()
}
}
impl FileSystemWidget {
pub fn new() -> Self {
Self {
tree_widget: DirTreeWidget::new(),
list_widget: FileListWidget::new(),
path_selection_widget: PathSelectionWidget::default(),
path_selection: None,
file_selection: None,
new_file_selection: Cell::new(false),
tree: FileTreeNode::default(),
}
}
#[allow(dead_code)]
pub fn reset(&mut self) {
*self = FileSystemWidget { ..Default::default() }
}
/// Show the file system widget
/// This widget comprises a header, a path selection widget, then a horizontal ui with
/// a directory tree on the left and a file list on the right.
pub fn show(&mut self, ui: &mut egui::Ui) -> Option<UiEvent> {
let mut new_event = None;
ui.vertical(|ui| {
// Show the header. We may eventually want to make this a separate widget...
ui.horizontal(|ui| {
ui.heading(egui::RichText::new("File System").strong());
ui.button("🗐 Archive").clicked().then(|| {
new_event = Some(UiEvent::ExportDirAsArchive("/".to_string()));
});
});
ui.separator();
// Make sure the path selection widget is set to the current path.
self.path_selection_widget.set(self.path_selection.as_deref());
// Next, show the path selection widget and process any resulting event.
// Currently, it can only return a SelectPath event so we can unwrap it directly.
if let Some(UiEvent::SelectPath(selected_path)) = self.path_selection_widget.show(ui) {
self.update_selection(Some(selected_path));
}
ui.separator();
// Start a horizontal UI layout to place the tree and file list widgets side-by-side
ui.with_layout(egui::Layout::left_to_right(egui::Align::Min), |ui| {
// Show the directory tree widget and process any resulting event from it.
if let Some(event) = self.tree_widget.show(ui) {
log::debug!("Got event from tree widget: {:?}", event);
match event {
UiEvent::SelectPath(path) => {
log::debug!("Got selected path from tree widget: {:?}", path);
self.update_selection(Some(path));
}
_ => {
log::debug!("Got unhandled event from tree widget: {:?}", event);
new_event = Some(event);
}
}
}
// Draw vertical separator between tree and file list
ui.separator();
// Show the file list widget and process any resulting event from it.
if let Some(event) = self.list_widget.show(ui) {
//log::debug!("Selected file: {:?}", event);
match &event {
UiEvent::SelectFile(entry) => {
self.file_selection = Some(entry.path().to_string());
self.new_file_selection.set(true);
}
_ => {
// We shouldn't be able ot generate an event from the file list widget
// if the directory tree widget generated one, but just in case, show
// a warning.
if new_event.is_some() {
log::warn!("Multiple UI events in one frame! {:?}", new_event);
}
}
}
new_event = Some(event);
}
});
});
new_event
}
pub fn new_file_selection(&self) -> Option<String> {
if self.new_file_selection.get() {
self.new_file_selection.set(false);
self.file_selection.clone()
}
else {
None
}
}
fn update_selection(&mut self, new_selection: Option<String>) {
log::debug!("Updating selection: {:?}", new_selection);
self.list_widget.reset();
if let Some(path) = new_selection.clone() {
// Read the directory
let files = self.tree.dir(&path).unwrap_or_else(|| {
log::error!("Failed to read directory: {}", path);
Vec::new()
});
self.list_widget.update(&files);
self.tree_widget.set_selection(new_selection.clone());
}
self.path_selection = new_selection;
}
pub fn update(&mut self, fs: &FatFileSystem) {
self.tree = fs.build_file_tree_from_root().unwrap_or_else(|| {
log::error!("Failed to build filesystem tree!");
FileTreeNode::default()
});
self.tree_widget.update(self.tree.clone());
self.update_selection(Some("/".to_string()));
}
}
| rust | MIT | b4c04b51746e5fe7769f49a1b32b8caad426fc81 | 2026-01-04T20:24:04.021295Z | false |
dbalsom/fluxfox | https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/crates/ff_egui_lib/src/controls/path_selection.rs | crates/ff_egui_lib/src/controls/path_selection.rs | /*
FluxFox
https://github.com/dbalsom/fluxfox
Copyright 2024-2025 Daniel Balsom
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the “Software”),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
--------------------------------------------------------------------------
*/
use crate::UiEvent;
#[derive(Default)]
pub struct PathSelectionWidget {
path: String,
}
impl PathSelectionWidget {
pub fn set(&mut self, path: Option<&str>) {
if let Some(path) = path {
self.path = path.to_string();
}
else {
self.path = "/".to_string();
}
}
pub fn get(&self) -> String {
let path = self.path.clone().strip_prefix("root").unwrap_or(&self.path).to_string();
if path.is_empty() {
"/".to_string()
}
else {
path
}
}
pub fn show(&mut self, ui: &mut egui::Ui) -> Option<UiEvent> {
let path = self.path.clone();
let mut changed = false;
let parts = if path == "/" {
vec!["root"]
}
else {
let mut parts = path.split("/").collect::<Vec<&str>>();
if parts.len() > 1 {
parts[0] = "root"
}
parts
};
//log::debug!("split path: {} into parts: {:?}", path, parts);
ui.horizontal(|ui| {
ui.spacing_mut().item_spacing.x = 0.0;
let mut new_selection = Vec::new();
for (pi, part) in parts.iter().enumerate() {
new_selection.push(*part);
if pi > 0 {
ui.label("⏵");
}
if ui.button(*part).clicked() {
changed = true;
self.path = new_selection.join("/");
log::debug!("Clicked: {}", self.path);
}
}
});
if changed {
Some(UiEvent::SelectPath(self.get()))
}
else {
None
}
}
}
| rust | MIT | b4c04b51746e5fe7769f49a1b32b8caad426fc81 | 2026-01-04T20:24:04.021295Z | false |
dbalsom/fluxfox | https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/crates/ff_egui_lib/src/controls/dir_tree.rs | crates/ff_egui_lib/src/controls/dir_tree.rs | /*
FluxFox
https://github.com/dbalsom/fluxfox
Copyright 2024-2025 Daniel Balsom
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the “Software”),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
--------------------------------------------------------------------------
*/
use crate::UiEvent;
use egui::{CollapsingHeader, RichText, TextStyle};
use fluxfox::file_system::FileTreeNode;
pub const MIN_TREE_WIDTH: f32 = 120.0;
pub struct DirTreeWidget {
pub tree: FileTreeNode,
pub selected_path: Option<String>,
}
impl Default for DirTreeWidget {
fn default() -> Self {
Self::new()
}
}
impl DirTreeWidget {
pub fn new() -> Self {
Self {
tree: FileTreeNode::default(),
selected_path: Some("/".to_string()),
}
}
pub fn update(&mut self, tree: FileTreeNode) {
self.tree = tree;
self.selected_path = Some("/".to_string());
}
pub fn selection(&mut self) -> Option<String> {
self.selected_path.clone()
}
pub fn set_selection(&mut self, selection: Option<String>) {
self.selected_path = selection;
}
pub fn show(&mut self, ui: &mut egui::Ui) -> Option<UiEvent> {
let selected_path = self.selected_path.clone();
let mut new_selection = None;
let mut new_event = None;
ui.with_layout(egui::Layout::top_down(egui::Align::Min), |ui| {
ui.set_min_width(MIN_TREE_WIDTH);
new_event = self.tree_ui(ui, &self.tree, &selected_path, true);
//log::debug!("show(): got event from tree: {:?}", new_event);
if let Some(event) = &new_event {
match event {
UiEvent::SelectPath(path) => {
new_selection = Some(path.clone());
}
UiEvent::SelectFile(file) => {
new_selection = Some(file.path().to_string());
}
_ => {}
}
}
ui.set_min_height(ui.available_height());
});
new_event
}
pub fn tree_ui(
&self,
ui: &mut egui::Ui,
node: &FileTreeNode,
selected_path: &Option<String>,
root: bool,
) -> Option<UiEvent> {
let mut new_event = None;
fn dir_icon(ui: &mut egui::Ui, openness: f32, response: &egui::Response) {
let rect = response.rect;
// Calculate the position for the icon
let icon = if openness > 0.0 { "📂" } else { "📁" };
let icon_pos = rect.min + egui::vec2(0.0, rect.height() / 2.0);
let font = TextStyle::Button.resolve(ui.style());
// Draw the icon using the painter
ui.painter().text(
icon_pos,
egui::Align2::LEFT_CENTER,
icon,
font,
ui.visuals().text_color(),
);
}
match node {
FileTreeNode::File(_) => {}
FileTreeNode::Directory { dfe, children } => {
//log::debug!("Drawing directory: {} with {:?} children", fs.name, children);
let is_selected = Some(dfe.path().to_string()) == *selected_path;
//ui.visuals_mut().collapsing_header_frame = true;
let mut text = RichText::new((if root { "root" } else { dfe.short_name() }).to_string());
if is_selected {
text = text.color(ui.visuals().strong_text_color())
}
// Prevent empty directories from being opened
let open_control = children.is_empty().then_some(false);
let header_response = CollapsingHeader::new(text)
.default_open(root)
.icon(dir_icon)
.show_background(is_selected)
.open(open_control)
.show(ui, |ui| {
// Draw children recursively
children.iter().for_each(|child| {
if let Some(event) = self.tree_ui(ui, child, selected_path, false) {
// Cascade event down from children
new_event = Some(event)
}
});
})
.header_response;
let mut visuals = ui.style_mut().interact_selectable(&header_response, is_selected);
if is_selected {
visuals.weak_bg_fill = egui::Color32::from_rgb(200, 200, 255);
}
if header_response.clicked() {
//log::debug!("tree_ui(): Selected path: {}", fs.path);
new_event = Some(UiEvent::SelectPath(dfe.path().to_string()));
};
}
}
new_event
}
}
| rust | MIT | b4c04b51746e5fe7769f49a1b32b8caad426fc81 | 2026-01-04T20:24:04.021295Z | false |
dbalsom/fluxfox | https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/crates/ff_egui_lib/src/controls/canvas.rs | crates/ff_egui_lib/src/controls/canvas.rs | /*
FluxFox
https://github.com/dbalsom/fluxfox
Copyright 2024-2025 Daniel Balsom
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the “Software”),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
--------------------------------------------------------------------------
*/
//! The PixelCanvas is a bit of an experiment in creating a pixel-based canvas
//! that supports multiple bit depths and palettes. It's a bit of a work in
//! progress, and perhaps it should be split out into different widgets.
//!
//! Not everything requires multi-bit depth support, and the things that do
//! almost certainly don't need rotation support...
#![allow(dead_code)]
use egui::{
emath::RectTransform,
epaint::Vertex,
Color32,
ColorImage,
Context,
ImageData,
Mesh,
Pos2,
Rect,
Response,
ScrollArea,
Sense,
Shape,
TextureHandle,
TextureOptions,
Vec2,
};
use std::{io::Cursor, sync::Arc};
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
#[repr(u8)]
pub enum PixelCanvasZoom {
One,
Two,
Four,
Eight,
Sixteen,
}
pub type HoverCallback = fn(&Response, f32, f32);
pub const GRAYSCALE_RAMP: [Color32; 256] = {
let mut palette = [Color32::BLACK; 256];
let mut i = 0;
while i < 256 {
let shade = i as u8;
palette[i] = Color32::from_rgb(shade, shade, shade);
i += 1;
}
palette
};
pub const ZOOM_LUT: [f32; 5] = [1.0, 2.0, 4.0, 8.0, 16.0];
pub const DEFAULT_WIDTH: u32 = 128;
pub const DEFAULT_HEIGHT: u32 = 128;
pub const PALETTE_1BPP: [Color32; 2] = [Color32::from_rgb(0, 0, 0), Color32::from_rgb(255, 255, 255)];
pub const PALETTE_2BPP: [Color32; 4] = [
Color32::from_rgb(0x00u8, 0x00u8, 0x00u8),
Color32::from_rgb(0x55u8, 0xFFu8, 0xFFu8),
Color32::from_rgb(0xFFu8, 0x55u8, 0xFFu8),
Color32::from_rgb(0xFFu8, 0xFFu8, 0xFFu8),
];
pub const PALETTE_4BPP: [Color32; 16] = [
Color32::from_rgb(0x00u8, 0x00u8, 0x00u8),
Color32::from_rgb(0x00u8, 0x00u8, 0xAAu8),
Color32::from_rgb(0x00u8, 0xAAu8, 0x00u8),
Color32::from_rgb(0x00u8, 0xAAu8, 0xAAu8),
Color32::from_rgb(0xAAu8, 0x00u8, 0x00u8),
Color32::from_rgb(0xAAu8, 0x00u8, 0xAAu8),
Color32::from_rgb(0xAAu8, 0x55u8, 0x00u8),
Color32::from_rgb(0xAAu8, 0xAAu8, 0xAAu8),
Color32::from_rgb(0x55u8, 0x55u8, 0x55u8),
Color32::from_rgb(0x55u8, 0x55u8, 0xFFu8),
Color32::from_rgb(0x55u8, 0xFFu8, 0x55u8),
Color32::from_rgb(0x55u8, 0xFFu8, 0xFFu8),
Color32::from_rgb(0xFFu8, 0x55u8, 0x55u8),
Color32::from_rgb(0xFFu8, 0x55u8, 0xFFu8),
Color32::from_rgb(0xFFu8, 0xFFu8, 0x55u8),
Color32::from_rgb(0xFFu8, 0xFFu8, 0xFFu8),
];
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
#[derive(Copy, Clone, PartialEq, Default, Debug)]
pub enum PixelCanvasDepth {
#[default]
OneBpp,
TwoBpp,
FourBpp,
EightBpp,
Rgb,
Rgba,
}
impl PixelCanvasDepth {
pub fn bits(&self) -> usize {
match self {
PixelCanvasDepth::OneBpp => 1,
PixelCanvasDepth::TwoBpp => 2,
PixelCanvasDepth::FourBpp => 4,
PixelCanvasDepth::EightBpp => 8,
PixelCanvasDepth::Rgb => 24,
PixelCanvasDepth::Rgba => 32,
}
}
}
pub struct PixelCanvasPalette {
name: String,
depth: PixelCanvasDepth,
colors: Vec<Color32>,
}
pub struct PixelCanvas {
id: String,
data_buf: Vec<u8>,
backing_buf: Vec<Color32>,
view_dimensions: (u32, u32),
virtual_rect: Rect,
virtual_transform: RectTransform,
zoom: f32,
bpp: PixelCanvasDepth,
device_palette: PixelCanvasPalette,
use_device_palette: bool,
current_palette: PixelCanvasPalette,
palettes: Vec<Vec<PixelCanvasPalette>>,
texture: Option<TextureHandle>,
image_data: ImageData,
texture_opts: TextureOptions,
default_uv: Rect,
ctx: Context,
data_unpacked: bool,
rotation: f32,
}
impl Default for PixelCanvas {
fn default() -> Self {
Self {
id: String::from("pixel_canvas"),
data_buf: Vec::new(),
backing_buf: Vec::new(),
view_dimensions: (DEFAULT_WIDTH, DEFAULT_HEIGHT),
virtual_rect: Rect::from_min_size(
egui::pos2(0.0, 0.0),
egui::vec2(DEFAULT_WIDTH as f32, DEFAULT_HEIGHT as f32),
),
virtual_transform: RectTransform::identity(Rect::from_min_size(
egui::pos2(0.0, 0.0),
egui::vec2(DEFAULT_WIDTH as f32, DEFAULT_HEIGHT as f32),
)),
zoom: 1.0,
bpp: PixelCanvasDepth::OneBpp,
device_palette: PixelCanvasPalette {
name: "Default".to_string(),
depth: PixelCanvasDepth::OneBpp,
colors: vec![Color32::from_rgb(0, 0, 0), Color32::from_rgb(255, 255, 255)],
},
use_device_palette: true,
current_palette: PixelCanvasPalette {
name: "Default".to_string(),
depth: PixelCanvasDepth::OneBpp,
colors: vec![Color32::from_rgb(0, 0, 0), Color32::from_rgb(255, 255, 255)],
},
palettes: Vec::new(),
texture: None,
image_data: PixelCanvas::create_default_imagedata((DEFAULT_WIDTH, DEFAULT_HEIGHT)),
texture_opts: TextureOptions {
magnification: egui::TextureFilter::Nearest,
minification: egui::TextureFilter::Nearest,
wrap_mode: egui::TextureWrapMode::ClampToEdge,
mipmap_mode: Some(egui::TextureFilter::Nearest),
},
default_uv: Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)),
ctx: Context::default(),
data_unpacked: false,
rotation: 0.0,
}
}
}
#[allow(dead_code)]
impl PixelCanvas {
pub fn new(dims: (u32, u32), ctx: Context, id: &str) -> Self {
let mut pc = PixelCanvas::default();
pc.id = id.to_string();
pc.view_dimensions = dims;
pc.virtual_rect = Rect::from_min_size(egui::pos2(0.0, 0.0), egui::vec2(dims.0 as f32, dims.1 as f32));
pc.data_buf = vec![0; PixelCanvas::calc_slice_size(dims, pc.bpp)];
pc.backing_buf = vec![Color32::WHITE; (dims.0 * dims.1) as usize];
pc.ctx = ctx.clone();
pc.texture = Some(PixelCanvas::create_texture(&mut pc));
pc
}
pub fn clear(&mut self) {
self.backing_buf = vec![Color32::BLACK; (self.view_dimensions.0 * self.view_dimensions.1) as usize];
self.update_texture();
}
pub fn create_default_colorimage(dims: (u32, u32)) -> ColorImage {
ColorImage::new([dims.0 as usize, dims.1 as usize], Color32::BLACK)
}
pub fn create_default_imagedata(dims: (u32, u32)) -> ImageData {
ImageData::Color(Arc::new(PixelCanvas::create_default_colorimage(dims)))
}
pub fn update_imagedata(&mut self) {
if !self.data_unpacked {
log::warn!("PixelCanvas::update_imagedata(): Data was not unpacked before ColorImage update!");
}
let color_image = ColorImage {
size: [self.view_dimensions.0 as usize, self.view_dimensions.1 as usize],
pixels: self.backing_buf.clone(),
};
self.image_data = ImageData::Color(Arc::new(color_image));
}
pub fn use_device_palette(&mut self, state: bool) {
self.use_device_palette = state;
}
pub fn calc_slice_size(dims: (u32, u32), bpp: PixelCanvasDepth) -> usize {
let size = match bpp {
PixelCanvasDepth::OneBpp => (dims.0 * dims.1) as usize / 8 + 1,
PixelCanvasDepth::TwoBpp => (dims.0 * dims.1) as usize / 4 + 1,
PixelCanvasDepth::FourBpp => (dims.0 * dims.1) as usize / 1 + 1,
PixelCanvasDepth::EightBpp => (dims.0 * dims.1) as usize,
PixelCanvasDepth::Rgb => (dims.0 * dims.1) as usize * 3,
PixelCanvasDepth::Rgba => (dims.0 * dims.1) as usize * 4,
};
size
}
pub fn create_texture(&mut self) -> TextureHandle {
self.image_data = PixelCanvas::create_default_imagedata(self.view_dimensions);
self.ctx
.load_texture("pixel_canvas".to_string(), self.image_data.clone(), self.texture_opts)
}
pub fn width(&self) -> f32 {
self.view_dimensions.0 as f32 * self.zoom
}
pub fn rotation_mut(&mut self) -> &mut f32 {
&mut self.rotation
}
pub fn set_rotation(&mut self, angle: f32) {
self.rotation = angle;
}
pub fn set_virtual_rect(&mut self, rect: Rect) {
self.virtual_rect = rect;
self.virtual_transform = RectTransform::from_to(
Rect::from_min_size(
egui::pos2(0.0, 0.0),
egui::vec2(self.view_dimensions.0 as f32, self.view_dimensions.1 as f32),
),
rect,
);
}
pub fn virtual_rect(&self) -> &Rect {
&self.virtual_rect
}
pub fn virtual_transform(&self) -> &RectTransform {
&self.virtual_transform
}
pub fn show(&mut self, ui: &mut egui::Ui, on_hover: Option<impl FnOnce(&Response, f32, f32)>) -> Option<Response> {
let mut inner_response = None;
if let Some(texture) = &self.texture {
ui.vertical(|ui| {
// Draw background rect
//ui.painter().rect_filled(ui.max_rect(), egui::Rounding::default(), egui::Color32::BLACK);
let scroll_area = ScrollArea::vertical().id_salt(&self.id).auto_shrink([false; 2]);
let img_w = self.view_dimensions.0 as f32 * self.zoom;
let img_h = self.view_dimensions.1 as f32 * self.zoom;
ui.shrink_width_to_current();
ui.set_width(img_w);
//ui.set_height(ui.cursor().top() + img_h);
ui.set_height(img_h);
scroll_area.show_viewport(ui, |ui, viewport| {
let start_x = viewport.min.x + ui.min_rect().left();
let start_y = viewport.min.y + ui.min_rect().top();
let (rect, response) = ui.allocate_exact_size(Vec2::new(img_w, img_h), Sense::click_and_drag());
//log::debug!("Viewport is: {:?} StartX: {} StartY: {}", viewport, start_x, start_y);
if ui.is_rect_visible(rect) {
ui.painter().image(
texture.id(),
Rect::from_min_max(
egui::pos2(start_x, start_y),
egui::pos2(start_x + img_w, start_y + img_h),
),
self.default_uv,
Color32::WHITE,
);
}
if response.secondary_clicked() {
log::debug!("Secondary click detected!");
}
if let Some(mouse_pos) = response.hover_pos() {
let x = mouse_pos.x - start_x;
let y = mouse_pos.y - start_y;
if x >= 0.0 && x < img_w && y >= 0.0 && y < img_h {
if let Some(on_hover) = on_hover {
on_hover(&response, x, y);
}
}
}
inner_response = Some(response);
});
inner_response
})
.inner
}
else {
log::debug!("No texture to draw.");
None
}
}
pub fn show_as_mesh2(
&mut self,
ui: &mut egui::Ui,
on_hover: Option<impl FnOnce(&egui::Response, Pos2, Pos2)>,
) -> Option<egui::Response> {
let mut inner_response = None;
if let Some(texture) = &self.texture {
ui.vertical(|ui| {
// The final UI region to fill, e.g. 512×512
let view_w = self.view_dimensions.0 as f32;
let view_h = self.view_dimensions.1 as f32;
ui.set_width(view_w);
ui.set_height(view_h);
let (rect, response) =
ui.allocate_exact_size(egui::vec2(view_w, view_h), egui::Sense::click_and_drag());
let top_left = Pos2::new(ui.min_rect().left(), ui.min_rect().top());
if ui.is_rect_visible(rect) {
let painter = ui.painter().with_clip_rect(rect);
// Full image corners in "image space"
let image_corners = [
egui::pos2(0.0, 0.0),
egui::pos2(view_w, 0.0),
egui::pos2(view_w, view_h),
egui::pos2(0.0, view_h),
];
let pivot = egui::pos2(view_w / 2.0, view_h / 2.0);
let sub_rect = self.virtual_rect;
let sub_w = sub_rect.width();
let sub_h = sub_rect.height();
let scale_x = view_w / sub_w;
let scale_y = view_h / sub_h;
let sub_min_local_x = sub_rect.min.x - pivot.x; // e.g. 256-256=0 if quadrant
let sub_min_local_y = sub_rect.min.y - pivot.y; // e.g. 0-256=-256 if quadrant
// Scale that local corner (without rotation, i.e. rotation=0 path)
let scaled_sub_min_x = sub_min_local_x * scale_x;
let scaled_sub_min_y = sub_min_local_y * scale_y;
// So offset is:
let offset_x = rect.min.x - scaled_sub_min_x;
let offset_y = rect.min.y - scaled_sub_min_y;
let cos_a = self.rotation.cos();
let sin_a = self.rotation.sin();
// Create mesh
let mut mesh = Mesh::default();
for corner in image_corners {
// local coords: corner minus pivot
let lx = corner.x - pivot.x;
let ly = corner.y - pivot.y;
// rotate
let rx = lx * cos_a - ly * sin_a;
let ry = lx * sin_a + ly * cos_a;
// scale
let sx = rx * scale_x;
let sy = ry * scale_y;
// offset
let final_x = offset_x + sx;
let final_y = offset_y + sy;
mesh.vertices.push(Vertex {
pos: egui::pos2(final_x, final_y),
uv: egui::pos2(corner.x / 512.0, corner.y / 512.0),
color: Color32::WHITE,
});
}
mesh.indices.extend(&[0, 1, 2, 2, 3, 0]);
mesh.texture_id = texture.id();
painter.add(Shape::Mesh(mesh));
}
if let Some(mouse_pos) = response.hover_pos() {
let pos = mouse_pos - top_left;
if pos.x >= 0.0 && pos.x < view_w && pos.y >= 0.0 && pos.y < view_h {
if let Some(on_hover) = on_hover {
on_hover(
&response,
pos.to_pos2(),
self.virtual_transform.transform_pos(pos.to_pos2()),
);
}
}
}
inner_response = Some(response);
});
inner_response
}
else {
None
}
}
pub fn show_as_mesh(
&mut self,
ui: &mut egui::Ui,
on_hover: Option<impl FnOnce(&Response, f32, f32)>,
) -> Option<Response> {
let mut inner_response = None;
if let Some(texture) = &self.texture {
ui.vertical(|ui| {
let scroll_area = ScrollArea::vertical().id_salt(&self.id).auto_shrink([false; 2]);
let img_w = self.view_dimensions.0 as f32 * self.zoom;
let img_h = self.view_dimensions.1 as f32 * self.zoom;
ui.shrink_width_to_current();
ui.set_width(img_w);
ui.set_height(img_h);
// Debug resolution and view dimensions
log::debug!(
"Virtual: {} x {}, View Dimensions: {} x {}",
self.virtual_rect.width(),
self.virtual_rect.height(),
self.view_dimensions.0,
self.view_dimensions.1
);
scroll_area.show_viewport(ui, |ui, _viewport| {
let (rect, response) = ui.allocate_exact_size(Vec2::new(img_w, img_h), Sense::click_and_drag());
if ui.is_rect_visible(rect) {
let painter = ui.painter();
// Map the full texture to the mesh (full UV range)
let uv = [
Pos2::new(0.0, 0.0),
Pos2::new(1.0, 0.0),
Pos2::new(1.0, 1.0),
Pos2::new(0.0, 1.0),
];
// Define the transformation from virtual_rect (zoomed-in space) to UI space
// Scale and translate based on the virtual rect
let scale_x = img_w / self.virtual_rect.width();
let scale_y = img_h / self.virtual_rect.height();
// Calculate the offset in logical space
let offset_x =
(img_w / 2.0) - (self.virtual_rect.min.x + self.virtual_rect.width() / 2.0) * scale_x;
let offset_y =
(img_h / 2.0) - (self.virtual_rect.min.y + self.virtual_rect.height() / 2.0) * scale_y;
log::debug!(
"Scale X: {}, Scale Y: {}, Offset X: {}, Offset Y: {}",
scale_x,
scale_y,
offset_x,
offset_y
);
// Calculate the center of the image for rotation
let mesh_center = rect.center();
// let center =
// Pos2::new(rect.min.x + img_w / 2.0 + offset_x, rect.min.y + img_h / 2.0 + offset_y);
// Define corners of the image relative to its center
let half_size = Vec2::new(img_w / 2.0, img_h / 2.0);
let corners = [
Vec2::new(-half_size.x, -half_size.y),
Vec2::new(half_size.x, -half_size.y),
Vec2::new(half_size.x, half_size.y),
Vec2::new(-half_size.x, half_size.y),
];
// let corners = [
// Vec2::new(0.0, 0.0),
// Vec2::new(img_w , 0.0),
// Vec2::new(img_w, img_h),
// Vec2::new(0.0, img_h),
// ];
// Apply scaling, translation, and rotation to the corners
let transformed_corners: Vec<Pos2> = corners
.iter()
.map(|corner| {
// Scale the corner
let scaled = Vec2::new(corner.x * scale_x, corner.y * scale_y);
// Rotate the corner around the mesh center
let cos_angle = self.rotation.cos();
let sin_angle = self.rotation.sin();
let rotated = Vec2::new(
scaled.x * cos_angle - scaled.y * sin_angle,
scaled.x * sin_angle + scaled.y * cos_angle,
);
Pos2::new(
mesh_center.x + rotated.x + offset_x,
mesh_center.y + rotated.y + offset_y,
)
})
.collect();
// Rotate corners
// let transformed_corners: Vec<Pos2> = corners
// .iter()
// .map(|corner| {
// let cos_angle = self.rotation.cos();
// let sin_angle = self.rotation.sin();
// let rotated = Vec2::new(
// corner.x * cos_angle - corner.y * sin_angle,
// corner.x * sin_angle + corner.y * cos_angle,
// );
// Pos2::new(center.x + rotated.x, center.y + rotated.y)
// })
// .collect();
// Create a mesh for the rotated image
let mut mesh = Mesh::default();
let vertices = transformed_corners
.iter()
.zip(&uv)
.map(|(&pos, &uv)| egui::epaint::Vertex {
pos,
uv,
color: Color32::WHITE,
})
.collect::<Vec<_>>();
mesh.vertices.extend(vertices);
// Indices for the two triangles forming the rectangle
mesh.indices.extend(&[0, 1, 2, 2, 3, 0]);
// Assign the texture ID
mesh.texture_id = texture.id();
// Add the mesh to the painter
painter.add(Shape::Mesh(mesh));
}
if response.secondary_clicked() {
log::debug!("Secondary click detected!");
}
if let Some(mouse_pos) = response.hover_pos() {
let x = mouse_pos.x - rect.min.x;
let y = mouse_pos.y - rect.min.y;
if x >= 0.0 && x < img_w && y >= 0.0 && y < img_h {
if let Some(on_hover) = on_hover {
on_hover(&response, x, y);
}
}
}
inner_response = Some(response);
});
inner_response
})
.inner
}
else {
log::debug!("No texture to draw.");
None
}
}
pub fn get_required_data_size(&self) -> usize {
PixelCanvas::calc_slice_size(self.view_dimensions, self.bpp)
}
pub fn update_data(&mut self, data: &[u8]) {
let slice_size = PixelCanvas::calc_slice_size(self.view_dimensions, self.bpp);
log::trace!(
"PixelCanvas::update_data(): Updating data with {} bytes for slice of {}",
data.len(),
slice_size
);
let shortfall = slice_size.saturating_sub(data.len());
self.data_buf.clear();
self.data_buf
.extend_from_slice(&data[0..std::cmp::min(slice_size, data.len())]);
if shortfall > 0 {
self.data_buf.extend_from_slice(&vec![0; shortfall]);
}
assert_eq!(self.data_buf.len(), slice_size);
// if self.texture.is_none() {
// log::debug!("PixelCanvas::update_data(): Creating initial texture...");
// self.texture = Some(self.create_texture());
// }
self.unpack_pixels();
self.update_texture();
}
pub fn update_device_palette(&mut self, palette: Vec<Color32>) {
let depth = match palette.len() {
256 => Some(PixelCanvasDepth::EightBpp),
16 => Some(PixelCanvasDepth::FourBpp),
4 => Some(PixelCanvasDepth::TwoBpp),
2 => Some(PixelCanvasDepth::OneBpp),
_ => None,
};
if let Some(depth) = depth {
self.device_palette.colors = palette;
self.device_palette.depth = depth;
self.unpack_pixels();
self.update_texture();
}
}
pub fn has_texture(&self) -> bool {
self.texture.is_some()
}
pub fn update_texture(&mut self) {
self.update_imagedata();
if let Some(texture) = &mut self.texture {
//log::trace!("PixelCanvas::update_texture(): Updating texture with new data...");
texture.set(self.image_data.clone(), self.texture_opts);
}
}
pub fn set_bpp(&mut self, bpp: PixelCanvasDepth) {
self.bpp = bpp;
self.data_unpacked = false;
}
pub fn set_zoom(&mut self, zoom: f32) {
self.zoom = zoom;
}
pub fn resize(&mut self, dims: (u32, u32)) {
self.view_dimensions = dims;
self.data_buf = vec![0; PixelCanvas::calc_slice_size(dims, self.bpp)];
self.backing_buf = vec![Color32::BLACK; (dims.0 * dims.1) as usize];
self.texture = Some(self.create_texture());
self.data_unpacked = false;
}
// pub fn save_buffer(&mut self, path: &Path) -> Result<(), Error> {
// let byte_slice: &[u8] = bytemuck::cast_slice(&self.backing_buf);
// image::save_buffer(
// path,
// byte_slice,
// self.view_dimensions.0,
// self.view_dimensions.1,
// image::ColorType::Rgba8,
// )?;
// Ok(())
// }
fn unpack_pixels(&mut self) {
//let dims = self.view_dimensions.0 * self.view_dimensions.1;
//let max_index = std::cmp::min(dims as usize, self.data_buf.len());
match self.bpp {
PixelCanvasDepth::OneBpp => {
for i in 0..self.view_dimensions.0 * self.view_dimensions.1 {
let byte = self.data_buf[(i / 8) as usize];
let bit = 1 << (i % 8);
self.backing_buf[i as usize] = if byte & bit != 0 {
Color32::WHITE
}
else {
Color32::BLACK
};
}
}
PixelCanvasDepth::TwoBpp => {
for i in 0..self.view_dimensions.0 * self.view_dimensions.1 {
let byte = self.data_buf[(i / 4) as usize];
let shift = (i % 4) * 2;
let color = (byte >> (6 - shift)) & 0x03;
self.backing_buf[i as usize] = PALETTE_2BPP[color as usize];
}
}
PixelCanvasDepth::FourBpp => {
for i in 0..self.view_dimensions.0 * self.view_dimensions.1 {
let byte = self.data_buf[(i / 2) as usize];
let shift = (i % 2) * 4;
let color = (byte >> shift) & 0x0F;
self.backing_buf[i as usize] = PALETTE_4BPP[color as usize];
}
}
PixelCanvasDepth::EightBpp => {
let pal = if self.use_device_palette && self.device_palette.colors.len() == 256 {
&self.device_palette.colors[0..]
}
else {
&GRAYSCALE_RAMP
};
for i in 0..self.view_dimensions.0 * self.view_dimensions.1 {
let byte = self.data_buf[i as usize];
self.backing_buf[i as usize] = pal[byte as usize];
}
}
PixelCanvasDepth::Rgb => {
for i in 0..self.view_dimensions.0 * self.view_dimensions.1 {
let idx = (i * 3) as usize;
let r = self.data_buf[idx];
let g = self.data_buf[idx + 1];
let b = self.data_buf[idx + 2];
self.backing_buf[i as usize] = Color32::from_rgb(r, g, b);
}
}
PixelCanvasDepth::Rgba => {
log::debug!("PixelCanvas::unpack_pixels(): Unpacking RGBA data...");
for i in 0..self.view_dimensions.0 * self.view_dimensions.1 {
let idx = (i * 4) as usize;
let r = self.data_buf[idx];
let g = self.data_buf[idx + 1];
let b = self.data_buf[idx + 2];
let a = self.data_buf[idx + 3];
self.backing_buf[i as usize] = Color32::from_rgba_premultiplied(r, g, b, a);
}
}
}
self.data_unpacked = true;
}
pub fn to_png(&self) -> Vec<u8> {
use ::image::{ImageBuffer, ImageFormat, Rgba};
let mut img = ImageBuffer::new(self.view_dimensions.0, self.view_dimensions.1);
for (x, y, pixel) in img.enumerate_pixels_mut() {
let idx = (x + y * self.view_dimensions.0) as usize;
*pixel = Rgba([
self.backing_buf[idx].r(),
self.backing_buf[idx].g(),
self.backing_buf[idx].b(),
self.backing_buf[idx].a(),
]);
}
let mut buf = Cursor::new(Vec::new());
img.write_to(&mut buf, ImageFormat::Png).unwrap();
buf.into_inner()
}
}
| rust | MIT | b4c04b51746e5fe7769f49a1b32b8caad426fc81 | 2026-01-04T20:24:04.021295Z | false |
dbalsom/fluxfox | https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/crates/ff_egui_lib/src/controls/sector_status.rs | crates/ff_egui_lib/src/controls/sector_status.rs | /*
fluxfox
https://github.com/dbalsom/fluxfox
Copyright 2024-2025 Daniel Balsom
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the “Software”),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
--------------------------------------------------------------------------
Implements a custom control that displays a sector status indicator.
*/
use crate::widgets::{chs::ChsWidget, pill::PillWidget};
use egui::*;
use fluxfox::SectorMapEntry;
//let pal_medium_green = Color::from_rgba8(0x38, 0xb7, 0x64, 0xff);
const COLOR_SECTOR_OK: Color32 = Color32::from_rgb(0x38, 0xb7, 0x64);
const COLOR_BAD_CRC: Color32 = Color32::from_rgb(0xef, 0x7d, 0x57);
const COLOR_DELETED_DATA: Color32 = Color32::from_rgb(0x25, 0x71, 0x79);
//const COLOR_BAD_DELETED_DATA: Color32 = Color32::from_rgb(0xb1, 0x3e, 0x53);
const COLOR_BAD_HEADER: Color32 = Color32::RED;
const COLOR_NO_DAM: Color32 = Color32::GRAY;
/// Simple color swatch widget. Used for palette register display.
pub fn sector_status(ui: &mut Ui, entry: &SectorMapEntry, open: bool) -> Response {
let size = ui.spacing().interact_size;
let size = Vec2 { x: size.y, y: size.y }; // Make square
let (rect, response) = ui.allocate_exact_size(
size,
Sense {
click: true,
drag: false,
focusable: false,
},
);
//response.widget_info(|| WidgetInfo::new(WidgetType::ColorButton));
ui.spacing_mut().item_spacing = vec2(0.0, 0.0);
ui.spacing_mut().button_padding = vec2(0.0, 0.0);
if ui.is_rect_visible(rect) {
let visuals = if open {
&ui.visuals().widgets.open
}
else {
ui.style().interact(&response)
};
//let rect = rect.expand(visuals.expansion);
//painter.rect_filled(rect, 0.0, color);
let rounding = visuals.rounding.at_most(2.0);
// pub chsn: DiskChsn,
// pub address_crc_valid: bool,
// pub data_crc_valid: bool,
// pub deleted_mark: bool,
// pub no_dam: bool,
let color = match (
!entry.attributes.address_error,
!entry.attributes.data_error,
entry.attributes.deleted_mark,
entry.attributes.no_dam,
) {
(true, true, false, false) => COLOR_SECTOR_OK,
(true, true, true, _) => COLOR_DELETED_DATA,
(true, false, _, _) => COLOR_BAD_CRC,
(true, true, false, true) => COLOR_NO_DAM,
(false, _, _, _) => COLOR_BAD_HEADER,
};
ui.painter().rect_filled(rect, rounding, color);
ui.painter().rect_stroke(rect, rounding, (2.0, visuals.bg_fill)); // fill is intentional, because default style has no border
}
// We don't use hovered_ui as it implements a delay.
if response.hovered() {
show_tooltip(
&response.ctx,
ui.layer_id(),
response.id.with("sector_attributes_tooltip"),
|ui| {
ui.vertical(|ui| {
ui.label(RichText::new("Click square to view sector").italics());
Grid::new("popup_sector_attributes_grid").show(ui, |ui| {
ui.label("ID");
ui.add(ChsWidget::from_chsn(entry.chsn));
ui.end_row();
ui.label("Size");
ui.label(entry.chsn.n_size().to_string());
ui.end_row();
let good_color = Color32::DARK_GREEN;
let bad_color = Color32::DARK_RED;
ui.label("Address integrity");
match entry.attributes.address_error {
true => ui.add(PillWidget::new("Bad").with_fill(bad_color)),
false => ui.add(PillWidget::new("Good").with_fill(good_color)),
};
ui.end_row();
ui.label("Data integrity");
match entry.attributes.data_error {
true => ui.add(PillWidget::new("Bad").with_fill(bad_color)),
false => ui.add(PillWidget::new("Good").with_fill(good_color)),
};
ui.end_row();
ui.label("Sector type");
match entry.attributes.deleted_mark {
true => ui.add(PillWidget::new("Deleted data").with_fill(bad_color)),
false => ui.label("Normal data"),
};
ui.end_row();
});
});
},
);
}
response
}
| rust | MIT | b4c04b51746e5fe7769f49a1b32b8caad426fc81 | 2026-01-04T20:24:04.021295Z | false |
dbalsom/fluxfox | https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/crates/ff_egui_lib/src/controls/track_timing_chart.rs | crates/ff_egui_lib/src/controls/track_timing_chart.rs | /*
FluxFox
https://github.com/dbalsom/fluxfox
Copyright 2024-2025 Daniel Balsom
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the “Software”),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
--------------------------------------------------------------------------
*/
use egui::{Ui, Vec2b};
use egui_plot::{Line, MarkerShape, Plot, PlotPoints, Points};
use fluxfox::flux::pll::PllMarkerEntry;
#[derive(Default)]
pub struct TrackTimingChart {
flux_times: Vec<f64>,
markers: Vec<PllMarkerEntry>,
draw_markers: bool,
}
impl TrackTimingChart {
/// Create a new FluxTimingDiagram
pub fn new(flux_times: &[f64], markers: Option<&[PllMarkerEntry]>) -> Self {
Self {
flux_times: flux_times.to_vec(),
markers: markers.unwrap_or_default().to_vec(),
draw_markers: true,
}
}
pub fn marker_enable_mut(&mut self) -> &mut bool {
&mut self.draw_markers
}
/// Draw the widget
pub fn show(&self, ui: &mut Ui) {
let mut points = Vec::new();
let mut running_total = 0.0;
for &flux_time in &self.flux_times {
let ms = flux_time * 1e3; // Convert to milliseconds
let us = flux_time * 1e6; // Convert to microseconds
running_total += ms;
points.push([running_total, us]);
}
let scatter = Points::new(PlotPoints::from(points))
.color(egui::Color32::YELLOW) // LIGHT_YELLOW without transparency
.shape(MarkerShape::Circle)
.radius(1.5); // Set circle radius
let mut markers = Vec::new();
for marker in &self.markers {
let x = marker.time * 1_000.0;
markers.push(Line::new(PlotPoints::from(vec![[x, 0.0], [x, 10.0]])).color(egui::Color32::LIGHT_BLUE));
}
Plot::new("flux_timing_diagram")
.x_axis_label("Time (ms)")
.y_axis_label("Transition (µs)")
.include_x(0.0)
.include_y(0.0) // Pin y-axis min to 0
.include_x(running_total)
.include_y(10.0) // Pin y-axis max to 10
.allow_scroll(Vec2b::new(false, false))
.allow_zoom(Vec2b::new(true, false))
.allow_drag(Vec2b::new(true, false))
.allow_boxed_zoom(false)
.auto_bounds(Vec2b::new(true, false))
.show(ui, |plot_ui| {
if self.draw_markers {
for marker_line in markers {
plot_ui.line(marker_line);
}
}
plot_ui.points(scatter)
});
}
}
| rust | MIT | b4c04b51746e5fe7769f49a1b32b8caad426fc81 | 2026-01-04T20:24:04.021295Z | false |
dbalsom/fluxfox | https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/crates/ff_egui_lib/src/controls/track_list.rs | crates/ff_egui_lib/src/controls/track_list.rs | /*
FluxFox
https://github.com/dbalsom/fluxfox
Copyright 2024-2025 Daniel Balsom
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the “Software”),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
--------------------------------------------------------------------------
*/
use crate::{
controls::{header_group::HeaderGroup, sector_status::sector_status},
widgets::chs::ChsWidget,
SectorSelection,
TrackListSelection,
TrackSelection,
TrackSelectionScope,
};
use egui::{ScrollArea, TextStyle};
use fluxfox::{prelude::*, track::TrackInfo};
pub const TRACK_ENTRY_WIDTH: f32 = 480.0;
pub const SECTOR_STATUS_WRAP: usize = 18;
#[derive(PartialEq, Default)]
pub enum HeadFilter {
Zero,
One,
#[default]
Both,
}
impl HeadFilter {
pub fn predicate(&self, ch: DiskCh) -> bool {
match self {
HeadFilter::Zero => ch.h() == 0,
HeadFilter::One => ch.h() == 1,
HeadFilter::Both => true,
}
}
}
struct TrackListItem {
ch: DiskCh,
info: TrackInfo,
sectors: Vec<SectorMapEntry>,
}
#[derive(Default)]
pub struct TrackListWidget {
heads: u8,
head_filter: HeadFilter,
track_list: Vec<TrackListItem>,
}
impl TrackListWidget {
pub fn new() -> Self {
Self {
heads: 2,
head_filter: HeadFilter::default(),
track_list: Vec::new(),
}
}
pub fn reset(&mut self) {
self.track_list.clear();
}
pub fn update(&mut self, disk: &DiskImage) {
self.track_list.clear();
self.heads = disk.heads();
if self.heads == 1 {
self.head_filter = HeadFilter::Both;
}
for track in disk.track_iter() {
self.track_list.push(TrackListItem {
ch: track.ch(),
info: track.info(),
sectors: track.sector_list(),
});
}
}
pub fn show(&mut self, ui: &mut egui::Ui) -> Option<TrackListSelection> {
let mut new_selection = None;
let mut new_selection2 = None;
let scroll_area = ScrollArea::vertical()
.id_salt("track_list_scrollarea")
.auto_shrink([true, false]);
ui.vertical(|ui| {
ui.heading(egui::RichText::new("Track List").color(ui.visuals().strong_text_color()));
if self.heads > 1 {
ui.horizontal(|ui| {
ui.label("Show heads:");
if ui
.add(egui::RadioButton::new(self.head_filter == HeadFilter::Both, "Both"))
.clicked()
{
self.head_filter = HeadFilter::Both;
}
if ui
.add(egui::RadioButton::new(self.head_filter == HeadFilter::Zero, "Head 0"))
.clicked()
{
self.head_filter = HeadFilter::Zero;
}
if ui
.add(egui::RadioButton::new(self.head_filter == HeadFilter::One, "Head 1"))
.clicked()
{
self.head_filter = HeadFilter::One;
}
});
}
scroll_area.show(ui, |ui| {
ui.vertical(|ui| {
for (ti, track) in self
.track_list
.iter()
.filter(|tli| self.head_filter.predicate(tli.ch))
.enumerate()
{
HeaderGroup::new(&format!("{} Track", track.info.encoding))
.strong()
.show(
ui,
|ui| {
ui.vertical(|ui| {
ui.set_width(TRACK_ENTRY_WIDTH);
egui::Grid::new(format!("track_list_grid_{}", ti)).striped(true).show(
ui,
|ui| match track.info.resolution {
TrackDataResolution::FluxStream => {
egui::CollapsingHeader::new(
egui::RichText::new(format!(
"FluxStream Track: {} Bitcells",
track.info.bit_length
))
.color(ui.visuals().hyperlink_color),
)
.id_salt(format!("fluxstream_trk{}", ti))
.default_open(false)
.show(
ui,
|ui| {
if let Some(flux_info) = &track.info.flux_info {
egui::Grid::new(format!("fluxstream_trk_grid_{}", ti))
.striped(true)
.show(ui, |ui| {
ui.label("Revolutions:");
ui.label(format!("{}", flux_info.revolutions));
ui.end_row();
ui.label("Flux transitions:");
ui.label(format!(
"{}",
flux_info.transitions
[flux_info.best_revolution]
));
ui.end_row();
ui.label("Bitcells:");
ui.label(format!("{}", track.info.bit_length));
ui.end_row();
});
};
},
);
}
TrackDataResolution::BitStream => {
ui.label(
egui::RichText::new(format!(
"BitStream Track: {} Bitcells",
track.info.bit_length
))
.color(ui.visuals().warn_fg_color),
);
ui.end_row();
}
TrackDataResolution::MetaSector => {
ui.label("MetaSector Track");
ui.end_row();
}
},
);
ui.label(format!("{} Sectors:", track.sectors.len()));
egui::Grid::new(format!("track_list_sector_grid_{}", ti))
.min_col_width(0.0)
.show(ui, |ui| {
let mut previous_id: Option<u8> = None;
for (si, sector) in track.sectors.iter().enumerate() {
ui.vertical_centered(|ui| {
let sid = sector.chsn.s();
let consecutive_sector = match previous_id {
Some(prev) => {
sid != u8::MAX && sid == prev.saturating_add(1)
}
None => sid == 1,
};
previous_id = Some(sid);
let label_height = TextStyle::Body.resolve(ui.style()).size; // Use the normal label height for consistency
let small_size = TextStyle::Small.resolve(ui.style()).size;
let padding = ui.spacing().item_spacing.y;
ui.vertical(|ui| {
ui.set_min_height(label_height + padding);
ui.allocate_ui_with_layout(
egui::Vec2::new(
ui.available_width(),
label_height + padding,
),
egui::Layout::centered_and_justified(
egui::Direction::TopDown,
),
|ui| {
if sid > 99 {
let mut text =
egui::RichText::new(format!("{:03}", sid))
.size(small_size);
if !consecutive_sector {
text =
text.color(ui.visuals().warn_fg_color);
}
ui.label(text);
}
else {
let mut text =
egui::RichText::new(format!("{}", sid));
if !consecutive_sector {
text =
text.color(ui.visuals().warn_fg_color);
}
ui.label(text);
}
},
);
});
if sector_status(ui, sector, true).clicked() {
log::debug!("Sector clicked!");
new_selection =
Some(TrackListSelection::Sector(SectorSelection {
phys_ch: track.ch,
sector_id: sector.chsn,
bit_offset: None,
}));
}
});
if si % SECTOR_STATUS_WRAP == SECTOR_STATUS_WRAP - 1 {
ui.end_row();
}
}
});
});
},
Some(|ui: &mut egui::Ui, text| {
ui.horizontal(|ui| {
ui.set_width(TRACK_ENTRY_WIDTH);
ui.heading(text);
ui.add(ChsWidget::from_ch(track.ch));
ui.menu_button("⏷", |ui| match track.info.resolution {
TrackDataResolution::FluxStream => {
if ui.button("View Track Elements").clicked() {
new_selection2 = Some(TrackListSelection::Track(TrackSelection {
sel_scope: TrackSelectionScope::Elements,
phys_ch: track.ch,
}));
ui.close_menu();
}
if ui.button("View Track Data Stream").clicked() {
new_selection2 = Some(TrackListSelection::Track(TrackSelection {
sel_scope: TrackSelectionScope::DecodedDataStream,
phys_ch: track.ch,
}));
ui.close_menu();
}
if ui.button("View Track Flux Timings").clicked() {
new_selection2 = Some(TrackListSelection::Track(TrackSelection {
sel_scope: TrackSelectionScope::Timings,
phys_ch: track.ch,
}));
ui.close_menu();
}
}
TrackDataResolution::BitStream => {
if ui.button("View Track Elements").clicked() {
new_selection2 = Some(TrackListSelection::Track(TrackSelection {
sel_scope: TrackSelectionScope::Elements,
phys_ch: track.ch,
}));
}
if ui.button("View Track Data Stream").clicked() {
new_selection2 = Some(TrackListSelection::Track(TrackSelection {
sel_scope: TrackSelectionScope::DecodedDataStream,
phys_ch: track.ch,
}));
}
}
TrackDataResolution::MetaSector => {}
});
});
// ui.set_max_width(TRACK_ENTRY_WIDTH - 8.0);
// ui.allocate_ui_with_layout(
// egui::Vec2::new(ui.available_width(), ui.available_height()),
// egui::Layout::right_to_left(egui::Align::TOP),
// |ui| {
// ui.add(ChsWidget::from_ch(track.ch));
// ui.menu_button("⏷", |ui| match track.info.resolution {
// TrackDataResolution::FluxStream => {
// if ui.button("View Track Elements").clicked() {
// new_selection2 =
// Some(TrackListSelection::Track(TrackSelection {
// sel_scope: TrackSelectionScope::Elements,
// phys_ch: track.ch,
// }));
// ui.close_menu();
// }
//
// if ui.button("View Track Data Stream").clicked() {
// new_selection2 =
// Some(TrackListSelection::Track(TrackSelection {
// sel_scope: TrackSelectionScope::DecodedDataStream,
// phys_ch: track.ch,
// }));
// ui.close_menu();
// }
//
// if ui.button("View Track Flux Timings").clicked() {
// new_selection2 =
// Some(TrackListSelection::Track(TrackSelection {
// sel_scope: TrackSelectionScope::Timings,
// phys_ch: track.ch,
// }));
// ui.close_menu();
// }
// }
// TrackDataResolution::BitStream => {
// if ui.button("View Track Elements").clicked() {
// new_selection2 =
// Some(TrackListSelection::Track(TrackSelection {
// sel_scope: TrackSelectionScope::Elements,
// phys_ch: track.ch,
// }));
// }
//
// if ui.button("View Track Data Stream").clicked() {
// new_selection2 =
// Some(TrackListSelection::Track(TrackSelection {
// sel_scope: TrackSelectionScope::DecodedDataStream,
// phys_ch: track.ch,
// }));
// }
// }
// TrackDataResolution::MetaSector => {}
// });
// },
// );
}),
);
ui.add_space(8.0);
}
});
});
});
new_selection.or(new_selection2)
}
}
| rust | MIT | b4c04b51746e5fe7769f49a1b32b8caad426fc81 | 2026-01-04T20:24:04.021295Z | false |
dbalsom/fluxfox | https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/crates/ff_egui_lib/src/controls/tab_group.rs | crates/ff_egui_lib/src/controls/tab_group.rs | /*
fluxfox
https://github.com/dbalsom/fluxfox
Copyright 2024-2025 Daniel Balsom
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the “Software”),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
--------------------------------------------------------------------------
Implements a custom widget that emulates a tab group with clickable
labels.
*/
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub struct TabGroup {
tab_labels: Vec<String>,
selected_tab: usize,
}
impl TabGroup {
pub fn new() -> Self {
Self {
tab_labels: Vec::new(),
selected_tab: 0,
}
}
pub fn with_tab(mut self, label: &str) -> Self {
self.add_tab(label);
self
}
pub fn add_tab(&mut self, label: &str) {
self.tab_labels.push(label.to_string());
}
pub fn select_tab(&mut self, index: usize) {
if index < self.tab_labels.len() {
self.selected_tab = index;
}
}
pub fn selected_tab(&self) -> usize {
self.selected_tab
}
pub fn show(&mut self, ui: &mut egui::Ui) -> egui::InnerResponse<()> {
let selected_color = ui.visuals().widgets.active.fg_stroke.color;
let response = ui.horizontal(|ui| {
for (li, label_text) in self.tab_labels.iter().enumerate() {
let label_text = if li == self.selected_tab {
egui::RichText::new(label_text).color(selected_color)
}
else {
egui::RichText::new(label_text)
};
if ui
.add(
egui::Label::new(label_text)
.selectable(false)
.sense(egui::Sense::click()),
)
.clicked()
{
log::debug!("Tab clicked: {}", li);
self.selected_tab = li;
}
if li < self.tab_labels.len() - 1 {
ui.separator();
}
}
});
response
}
}
| rust | MIT | b4c04b51746e5fe7769f49a1b32b8caad426fc81 | 2026-01-04T20:24:04.021295Z | false |
dbalsom/fluxfox | https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/crates/ff_egui_lib/src/controls/boot_sector.rs | crates/ff_egui_lib/src/controls/boot_sector.rs | /*
FluxFox
https://github.com/dbalsom/fluxfox
Copyright 2024-2025 Daniel Balsom
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the “Software”),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
--------------------------------------------------------------------------
src/widgets/boot_sector.rs
Disk Info widget for displaying boot sector information, including the
BIOS Parameter Block and the boot sector marker.
*/
use crate::{controls::error_banner::ErrorBanner, UiEvent};
use fluxfox::{
boot_sector::{BiosParameterBlock2, BiosParameterBlock3, BootSignature},
prelude::*,
};
pub struct BootSectorWidget {
pub loaded: bool,
pub format: Option<StandardFormat>,
pub pb2: BiosParameterBlock2,
pub pb2_valid: bool,
pub pb3: BiosParameterBlock3,
pub sig: BootSignature,
}
impl Default for BootSectorWidget {
fn default() -> Self {
Self::new()
}
}
impl BootSectorWidget {
pub fn new() -> Self {
Self {
loaded: false,
format: None,
pb2: BiosParameterBlock2::default(),
pb2_valid: false,
pb3: BiosParameterBlock3::default(),
sig: BootSignature::default(),
}
}
pub fn update(&mut self, disk: &DiskImage) {
if let Some(bs) = disk.boot_sector() {
self.format = bs.standard_format();
self.pb2 = bs.bpb2();
self.pb2_valid = self.pb2.is_valid();
self.pb3 = bs.bpb3();
self.sig = bs.boot_signature();
self.loaded = true;
}
}
pub fn show(&self, ui: &mut egui::Ui) -> Option<UiEvent> {
let new_event = None;
ui.vertical(|ui| {
if !self.loaded {
ErrorBanner::new("No disk loaded").small().show(ui);
}
if let Some(format) = self.format {
ui.label(format!("Disk format: {}", format));
}
else {
ui.label("Disk format: Unknown");
ui.label("Possible Booter disk");
}
egui::CollapsingHeader::new("BIOS Parameter Block v2").show(ui, |ui| {
if !self.pb2_valid {
ErrorBanner::new("Invalid BPB v2!").small().show(ui);
}
egui::Grid::new("disk_bpb_grid").striped(true).show(ui, |ui| {
ui.label("Bytes per sector:");
ui.label(self.pb2.bytes_per_sector.to_string());
ui.end_row();
ui.label("Sectors per cluster:");
ui.label(self.pb2.sectors_per_cluster.to_string());
ui.end_row();
ui.label("Reserved sectors:");
ui.label(self.pb2.reserved_sectors.to_string());
ui.end_row();
ui.label("Number of FATs:");
ui.label(self.pb2.number_of_fats.to_string());
ui.end_row();
ui.label("Root Entries:");
ui.label(self.pb2.root_entries.to_string());
ui.end_row();
ui.label("Total Sectors:");
ui.label(self.pb2.total_sectors.to_string());
ui.end_row();
ui.label("Media descriptor:");
ui.label(format!("{:02X}", self.pb2.media_descriptor));
ui.end_row();
ui.label("Sectors per FAT:");
ui.label(self.pb2.sectors_per_fat.to_string());
ui.end_row();
});
});
egui::CollapsingHeader::new("BIOS Parameter Block v3").show(ui, |ui| {
egui::Grid::new("disk_bpb_grid").striped(true).show(ui, |ui| {
ui.label("Sectors per Track:");
ui.label(self.pb3.sectors_per_track.to_string());
ui.end_row();
ui.label("Number of heads:");
ui.label(self.pb3.number_of_heads.to_string());
ui.end_row();
ui.label("Hidden sectors:");
ui.label(self.pb3.hidden_sectors.to_string());
ui.end_row();
});
});
egui::CollapsingHeader::new("Boot Sector Signature").show(ui, |ui| {
let marker_text =
egui::RichText::new(format!("{:02X} {:02X}", self.sig.bytes()[0], self.sig.bytes()[1])).monospace();
if !self.sig.is_valid() {
ErrorBanner::new("Invalid boot signature!").small().show(ui);
}
ui.label(marker_text);
});
});
new_event
}
}
| rust | MIT | b4c04b51746e5fe7769f49a1b32b8caad426fc81 | 2026-01-04T20:24:04.021295Z | false |
dbalsom/fluxfox | https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/crates/ff_egui_lib/src/controls/mod.rs | crates/ff_egui_lib/src/controls/mod.rs | /*
FluxFox
https://github.com/dbalsom/fluxfox
Copyright 2024-2025 Daniel Balsom
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the “Software”),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
--------------------------------------------------------------------------
*/
pub mod boot_sector;
pub mod canvas;
pub mod data_table;
pub mod data_visualizer;
pub mod dir_tree;
pub mod disk_info;
pub mod disk_visualization;
pub mod error_banner;
pub mod file_list;
pub mod filesystem;
pub mod header_group;
pub mod path_selection;
pub mod sector_status;
pub mod source_map;
pub mod tab_group;
pub mod track_list;
#[cfg(feature = "egui_plot")]
pub mod track_timing_chart;
pub mod vector_disk_visualizer;
| rust | MIT | b4c04b51746e5fe7769f49a1b32b8caad426fc81 | 2026-01-04T20:24:04.021295Z | false |
dbalsom/fluxfox | https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/crates/ff_egui_lib/src/controls/data_visualizer.rs | crates/ff_egui_lib/src/controls/data_visualizer.rs | /*
MartyPC
https://github.com/dbalsom/martypc
Copyright 2022-2024 Daniel Balsom
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the “Software”),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
---------------------------------------------------------------------------
egui::data_visualizer.rs
Implements a data visualizer that interprets data as a bitmap.
Utilizes the pixel_canvas widget to display the data as a bitmap.
*/
use crate::controls::canvas::{HoverCallback, PixelCanvas, PixelCanvasDepth};
use std::fmt::Display;
use strum::IntoEnumIterator;
use strum_macros::EnumIter;
pub const DEFAULT_WIDTH: u32 = 128;
pub const DEFAULT_HEIGHT: u32 = 128;
pub const MIN_WIDTH: u32 = 4;
pub const MIN_HEIGHT: u32 = 4;
pub const MAX_WIDTH: u32 = 2048;
pub const MAX_HEIGHT: u32 = 1024;
pub const ZOOM_LEVELS: usize = 4;
pub const DEFAULT_ZOOM: usize = 0;
pub const ZOOM_LUT: [f32; ZOOM_LEVELS] = [1.0, 2.0, 4.0, 8.0];
pub const ZOOM_STR_LUT: [&str; ZOOM_LEVELS] = ["1x", "2x", "4x", "8x"];
pub const DEFAULT_BPP: usize = 1;
pub const BPP_LUT: [PixelCanvasDepth; 4] = [
PixelCanvasDepth::OneBpp,
PixelCanvasDepth::TwoBpp,
PixelCanvasDepth::FourBpp,
PixelCanvasDepth::EightBpp,
];
pub const BPP_STR_LUT: [&str; 4] = ["1bpp", "2bpp", "4bpp", "8bpp"];
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
#[derive(EnumIter, Copy, Clone, PartialEq, Eq, Default)]
pub enum VizPreset {
CgaLowRes320x200,
CgaLowRes320x800,
#[default]
CgaHighRes640x200,
EgaLowRes320x200,
EgaLowRes320x1600,
EgaRes640x350,
VgaRes640x400,
VgaRes640x480,
Mode13h320x200,
}
impl Display for VizPreset {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
VizPreset::CgaLowRes320x200 => write!(f, "320x200 LowRes 2bpp"),
VizPreset::CgaLowRes320x800 => write!(f, "320x800 LowRes 2bpp"),
VizPreset::CgaHighRes640x200 => write!(f, "640x200 HighRes"),
VizPreset::EgaLowRes320x200 => write!(f, "320x200 EGA"),
VizPreset::EgaLowRes320x1600 => write!(f, "320x1600 EGA"),
VizPreset::EgaRes640x350 => write!(f, "640x350 EGA"),
VizPreset::VgaRes640x400 => write!(f, "640x400 VGA"),
VizPreset::VgaRes640x480 => write!(f, "640x480 VGA"),
VizPreset::Mode13h320x200 => write!(f, "320x200 Mode13h"),
}
}
}
pub struct PresetParameters {
pub w: u32,
pub h: u32,
pub bpp: PixelCanvasDepth,
pub zoom: usize,
}
impl VizPreset {
pub fn params(&self) -> PresetParameters {
match self {
VizPreset::CgaLowRes320x200 => PresetParameters {
w: 320,
h: 200,
bpp: PixelCanvasDepth::TwoBpp,
zoom: 2,
},
VizPreset::CgaLowRes320x800 => PresetParameters {
w: 320,
h: 800,
bpp: PixelCanvasDepth::TwoBpp,
zoom: 2,
},
VizPreset::CgaHighRes640x200 => PresetParameters {
w: 640,
h: 200,
bpp: PixelCanvasDepth::OneBpp,
zoom: 0,
},
VizPreset::EgaLowRes320x200 => PresetParameters {
w: 320,
h: 200,
bpp: PixelCanvasDepth::FourBpp,
zoom: 2,
},
VizPreset::EgaLowRes320x1600 => PresetParameters {
w: 320,
h: 1600,
bpp: PixelCanvasDepth::FourBpp,
zoom: 2,
},
VizPreset::EgaRes640x350 => PresetParameters {
w: 640,
h: 350,
bpp: PixelCanvasDepth::FourBpp,
zoom: 0,
},
VizPreset::VgaRes640x400 => PresetParameters {
w: 640,
h: 400,
bpp: PixelCanvasDepth::FourBpp,
zoom: 0,
},
VizPreset::VgaRes640x480 => PresetParameters {
w: 640,
h: 480,
bpp: PixelCanvasDepth::FourBpp,
zoom: 0,
},
VizPreset::Mode13h320x200 => PresetParameters {
w: 320,
h: 200,
bpp: PixelCanvasDepth::EightBpp,
zoom: 2,
},
}
}
}
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub struct DataVisualizerWidget {
pub address_input: String,
pub address: String,
pub zoom_str: String,
pub zoom_idx: usize,
pub bpp: PixelCanvasDepth,
w: u32,
h: u32,
offset: usize,
row_offset: usize,
row_span: usize,
use_device_palette: bool,
#[serde(skip)]
canvas: Option<PixelCanvas>,
record: bool,
active_preset: VizPreset,
}
impl DataVisualizerWidget {
pub fn new(ctx: &egui::Context, id: &str) -> Self {
let active_preset = VizPreset::default();
let params = active_preset.params();
let mut new = Self {
address_input: format!("{:05X}", 0),
address: format!("{:05X}", 0),
zoom_str: ZOOM_STR_LUT[params.zoom].to_string(),
zoom_idx: params.zoom,
bpp: params.bpp,
w: params.w,
h: params.h,
offset: 0,
row_offset: 0,
row_span: 0,
use_device_palette: true,
canvas: None,
record: false,
active_preset,
};
new.init(ctx.clone(), id);
new
}
pub fn init(&mut self, ctx: egui::Context, id: &str) {
if self.canvas.is_none() {
let mut canvas = PixelCanvas::new((self.w, self.h), ctx, id);
canvas.set_bpp(self.bpp);
canvas.set_zoom(ZOOM_LUT[self.zoom_idx]);
self.canvas = Some(canvas);
}
}
pub fn get_address(&self) -> (&str, usize) {
let row_size_bits;
let row_size_bytes;
let offset;
row_size_bits = self.w as usize * self.bpp.bits();
row_size_bytes = row_size_bits / 8;
offset = self.row_offset * row_size_bytes + self.offset;
// log::warn!(
// "Calculated row size: Bitmap w: {}, bits: {}, bytes: {} offset: {:05X}",
// self.w,
// row_size_bits,
// row_size_bytes,
// offset
// );
(&self.address_input, offset)
}
pub fn get_required_data_size(&self) -> usize {
if let Some(canvas) = &self.canvas {
canvas.get_required_data_size()
}
else {
0
}
}
pub fn update_data(&mut self, data: &[u8]) {
if let Some(canvas) = &mut self.canvas {
canvas.update_data(data);
// if let Some(dump_path) = &self.dump_path {
// if self.record {
// let filename = find_unique_filename(dump_path, "viz_dump", "png");
// match canvas.save_buffer(&filename) {
// Ok(_) => log::info!("Saved visualization to file: {}", filename.display()),
// Err(e) => log::error!("Error saving visualization to file: {}", e),
// }
// }
// }
}
}
pub fn update_palette_u8(&mut self, palette: Vec<[u8; 4]>) {
let pal = palette
.iter()
.map(|p| egui::Color32::from_rgb(p[0], p[1], p[2]))
.collect();
if let Some(canvas) = &mut self.canvas {
canvas.update_device_palette(pal);
}
}
// pub fn set_dump_path(&mut self, path: PathBuf) {
// self.dump_path = Some(path);
// }
pub fn show(&mut self, ui: &mut egui::Ui) {
if let Some(canvas) = &mut self.canvas {
ui.set_width(canvas.width());
}
ui.horizontal(|ui| {
ui.label("Address:");
ui.add(egui::TextEdit::singleline(&mut self.address_input).desired_width(50.0));
//ui.text_edit_singleline(&mut self.address_input);
if ui
.add(
egui::DragValue::new(&mut self.offset)
.range(0..=0xFFFFF)
.hexadecimal(5, false, true)
.prefix("byte_offs:")
.speed(0.5)
.update_while_editing(false),
)
.changed()
{
// Do stuff when offset changes
}
if ui
.add(
egui::DragValue::new(&mut self.row_offset)
.range(0..=0xFFFFF)
.hexadecimal(5, false, true)
.prefix("row_offs:")
.speed(0.5)
.update_while_editing(false),
)
.changed()
{
// Do stuff when offset changes
}
egui::ComboBox::from_id_salt("viz_zoom_combo")
.selected_text(ZOOM_STR_LUT[self.zoom_idx])
.show_ui(ui, |ui| {
for i in 0..ZOOM_LUT.len() {
if ui.selectable_value(&mut self.zoom_idx, i, ZOOM_STR_LUT[i]).clicked() {
if let Some(canvas) = &mut self.canvas {
canvas.set_zoom(ZOOM_LUT[self.zoom_idx]);
}
}
}
});
egui::ComboBox::from_id_salt("viz_bpp_combo")
.selected_text(BPP_STR_LUT[self.bpp as usize])
.show_ui(ui, |ui| {
for i in 0..BPP_LUT.len() {
if ui.selectable_value(&mut self.bpp, BPP_LUT[i], BPP_STR_LUT[i]).clicked() {
if let Some(canvas) = &mut self.canvas {
canvas.set_bpp(self.bpp);
}
}
}
});
});
let mut resize = false;
ui.horizontal(|ui| {
ui.label("Preset:");
egui::ComboBox::from_id_salt("viz_preset_combo")
.selected_text(&self.active_preset.to_string())
.show_ui(ui, |ui| {
for preset in VizPreset::iter() {
if ui
.selectable_value(&mut self.active_preset, preset, preset.to_string())
.clicked()
{
let params = self.active_preset.params();
self.w = params.w;
self.h = params.h;
self.bpp = params.bpp;
if let Some(canvas) = &mut self.canvas {
canvas.set_bpp(self.bpp);
}
resize = true;
}
}
});
if ui
.add(
egui::DragValue::new(&mut self.w)
.range(MIN_WIDTH..=MAX_WIDTH)
.prefix("w:")
.suffix("px")
.speed(0.25)
.update_while_editing(false),
)
.changed()
{
resize = true;
}
if ui
.add(
egui::DragValue::new(&mut self.h)
.range(MIN_HEIGHT..=MAX_HEIGHT)
.prefix("h:")
.suffix("px")
.speed(0.25)
.update_while_editing(false),
)
.changed()
{
resize = true;
}
if ui.checkbox(&mut self.use_device_palette, "Device Palette").changed() {
if let Some(canvas) = &mut self.canvas {
canvas.use_device_palette(self.use_device_palette);
}
}
// if ui
// .button("SavePNG")
// .on_hover_text("Save visualization to file.")
// .clicked()
// {
// if let Some(canvas) = self.canvas.as_mut() {
// if let Some(dump_path) = &self.dump_path {
// let filename = find_unique_filename(dump_path, "viz_dump", "png");
//
// match canvas.save_buffer(&filename) {
// Ok(_) => log::info!("Saved visualization to file: {}", filename.display()),
// Err(e) => log::error!("Error saving visualization to file: {}", e),
// }
// }
// }
// }
ui.checkbox(&mut self.record, "Record")
.on_hover_text("Dump each frame produced.");
});
if resize {
if let Some(canvas) = &mut self.canvas {
canvas.resize((self.w, self.h));
}
}
if let Some(canvas) = &mut self.canvas {
ui.separator();
ui.set_width(canvas.width());
canvas.show(ui, None::<HoverCallback>);
}
}
}
| rust | MIT | b4c04b51746e5fe7769f49a1b32b8caad426fc81 | 2026-01-04T20:24:04.021295Z | false |
dbalsom/fluxfox | https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/crates/ff_egui_lib/src/controls/error_banner.rs | crates/ff_egui_lib/src/controls/error_banner.rs | /*
FluxFox
https://github.com/dbalsom/fluxfox
Copyright 2024-2025 Daniel Balsom
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the “Software”),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
--------------------------------------------------------------------------
src/widgets/error_banner.rs
Displays a dismissible error banner.
*/
#[allow(dead_code)]
pub enum ErrorBannerSize {
Small,
Medium,
Large,
}
#[allow(dead_code)]
pub struct ErrorBannerLayout {
rounding: f32,
margin: f32,
icon: f32,
text: f32,
}
impl ErrorBannerSize {
pub fn layout(&self) -> ErrorBannerLayout {
match self {
ErrorBannerSize::Small => ErrorBannerLayout {
rounding: 4.0,
margin: 4.0,
icon: 16.0,
text: 14.0,
},
ErrorBannerSize::Medium => ErrorBannerLayout {
rounding: 6.0,
margin: 6.0,
icon: 24.0,
text: 18.0,
},
ErrorBannerSize::Large => ErrorBannerLayout {
rounding: 8.0,
margin: 8.0,
icon: 32.0,
text: 24.0,
},
}
}
}
pub struct ErrorBanner {
message0: Option<String>,
message1: Option<String>,
size: ErrorBannerSize,
dismiss_button: bool,
}
impl ErrorBanner {
pub fn new(text: &str) -> Self {
let messages = Self::split_message(text);
Self {
message0: Some(messages.0),
message1: messages.1,
size: ErrorBannerSize::Medium,
dismiss_button: false,
}
}
pub fn dismissable(mut self) -> Self {
self.dismiss_button = true;
self
}
pub fn small(mut self) -> Self {
self.size = ErrorBannerSize::Small;
self
}
pub fn medium(mut self) -> Self {
self.size = ErrorBannerSize::Medium;
self
}
pub fn large(mut self) -> Self {
self.size = ErrorBannerSize::Large;
self
}
fn split_message(text: &str) -> (String, Option<String>) {
if let Some((message0, message1)) = text.split_once(':').map(|(a, b)| (a.trim(), b.trim())) {
//log::debug!("ErrorBanner: message0: {}, message1: {}", message0, message1);
(message0.to_string(), Some(message1.to_string()))
}
else {
//log::debug!("ErrorBanner: message0: {}", text);
(text.to_string(), None)
}
}
pub fn set_message(&mut self, text: &str) {
let messages = Self::split_message(text);
self.message0 = Some(messages.0);
self.message1 = messages.1;
}
pub fn dismiss(&mut self) {
self.message0 = None;
self.message1 = None;
}
pub fn show(&mut self, ui: &mut egui::Ui) {
if let Some(message) = self.message0.clone() {
let ErrorBannerLayout {
rounding,
margin,
icon,
text,
} = self.size.layout();
egui::Frame::none()
.fill(egui::Color32::DARK_RED)
.rounding(rounding)
.inner_margin(margin)
.stroke(egui::Stroke::new(1.0, egui::Color32::GRAY))
.show(ui, |ui| {
ui.horizontal(|ui| {
ui.label(egui::RichText::new("🗙").color(egui::Color32::WHITE).size(icon));
ui.vertical(|ui| {
ui.add(egui::Label::new(
egui::RichText::new(message).color(egui::Color32::WHITE).size(text),
));
// Show the sub-error message if it exists
if let Some(message1) = &self.message1 {
ui.add(egui::Label::new(
egui::RichText::new(message1).color(egui::Color32::WHITE),
));
}
});
if self.dismiss_button {
ui.button("Dismiss")
.on_hover_ui(|ui| {
ui.ctx().output_mut(|o| o.cursor_icon = egui::CursorIcon::PointingHand);
})
.clicked()
.then(|| {
self.dismiss();
});
}
});
});
}
}
}
| rust | MIT | b4c04b51746e5fe7769f49a1b32b8caad426fc81 | 2026-01-04T20:24:04.021295Z | false |
dbalsom/fluxfox | https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/crates/ff_egui_lib/src/controls/disk_visualization.rs | crates/ff_egui_lib/src/controls/disk_visualization.rs | /*
FluxFox
https://github.com/dbalsom/fluxfox
Copyright 2024-2025 Daniel Balsom
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the “Software”),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
--------------------------------------------------------------------------
*/
use std::{
collections::HashMap,
default::Default,
f32::consts::TAU,
ops::Range,
sync::{mpsc, Arc, Mutex, RwLock},
};
use crate::{
controls::{
canvas::{PixelCanvas, PixelCanvasDepth},
header_group::{HeaderFn, HeaderGroup},
},
visualization::viz_elements::paint_elements,
widgets::chs::ChsWidget,
SaveFileCallbackFn,
SectorSelection,
TrackListSelection,
UiError,
UiEvent,
UiLockContext,
};
use fluxfox::{
prelude::*,
track_schema::GenericTrackElement,
visualization::{prelude::*, rasterize_disk::rasterize_disk_selection},
FoxHashMap,
};
#[cfg(feature = "svg")]
use fluxfox_svg::prelude::*;
use fluxfox_tiny_skia::{
render_display_list::render_data_display_list,
render_elements::skia_render_display_list,
styles::{default_skia_styles, SkiaStyle},
tiny_skia::{BlendMode, Color, FilterQuality, Paint, Pixmap, PixmapPaint, Transform},
};
use egui::{emath::RectTransform, Align, Layout, Pos2, Rect, Vec2};
// Conditional thread stuff
use crate::tracking_lock::TrackingLock;
#[cfg(target_arch = "wasm32")]
use rayon::spawn;
#[cfg(not(target_arch = "wasm32"))]
use std::thread::spawn;
pub const VIZ_DATA_SUPERSAMPLE: u32 = 2;
pub const VIZ_RESOLUTION: u32 = 512;
pub const VIZ_SUPER_RESOLUTION: u32 = VIZ_RESOLUTION * VIZ_DATA_SUPERSAMPLE;
#[allow(dead_code)]
pub enum RenderMessage {
DataRenderComplete(u8),
DataRenderError(String),
}
#[derive(Copy, Clone, PartialEq)]
pub enum VizEvent {
NewSectorSelected { c: u8, h: u8, s_idx: u8 },
SectorDeselected,
}
struct VisualizationContext<'a> {
side_rects: [Rect; 2],
got_hit: [bool; 2],
context_menu_open: &'a mut bool,
hover_rect_opt: &'a mut Option<Rect>,
display_list_opt: &'a mut Option<VizElementDisplayList>,
hover_display_list_opt: &'a mut Option<VizElementDisplayList>,
ui_sender: &'a mut Option<mpsc::SyncSender<UiEvent>>,
events: &'a mut Vec<VizEvent>,
common_viz_params: &'a mut CommonVizParams,
selection: &'a mut Option<SelectionContext>,
hover_selection: Option<SelectionContext>,
}
#[derive(Clone)]
struct SelectionContext {
mouse_pos: Pos2,
side: u8,
c: u16,
bitcell_idx: usize,
angle: f32,
element_type: GenericTrackElement,
element_range: Range<usize>,
element_idx: usize,
element_chsn: Option<DiskChsn>,
}
pub struct DiskVisualization {
pub disk: Option<TrackingLock<DiskImage>>,
pub ui_sender: Option<mpsc::SyncSender<UiEvent>>,
pub resolution: u32,
pub common_viz_params: CommonVizParams,
pub compatible: bool,
pub supersample: u32,
pub data_img: [Arc<Mutex<Pixmap>>; 2],
pub meta_img: [Arc<RwLock<Pixmap>>; 2],
pub selection_img: [Arc<Mutex<Pixmap>>; 2],
pub composite_img: [Pixmap; 2],
pub meta_palette: HashMap<GenericTrackElement, VizColor>,
pub meta_display_list: [Arc<Mutex<Option<VizElementDisplayList>>>; 2],
pub have_render: [bool; 2],
pub canvas: [Option<PixelCanvas>; 2],
pub sides: usize,
pub render_sender: mpsc::SyncSender<RenderMessage>,
pub render_receiver: mpsc::Receiver<RenderMessage>,
pub decode_data_layer: bool,
pub show_data_layer: bool,
pub show_metadata_layer: bool,
#[allow(dead_code)]
pub show_error_layer: bool,
#[allow(dead_code)]
pub show_weak_layer: bool,
#[allow(dead_code)]
pub show_selection_layer: bool,
pub selection_display_list: Option<VizElementDisplayList>,
pub hover_display_list: Option<VizElementDisplayList>,
last_event: Option<VizEvent>,
context_menu_open: bool,
/// A list of events that have occurred since the last frame.
/// The main app should drain this list and process all events.
events: Vec<VizEvent>,
/// A flag indicating whether we received a hit-tested selection.
got_hit: bool,
/// The response rect received from the pixel canvas when we got a hit-tested selection.
selection_rect_opt: Option<Rect>,
angle: f32,
zoom_quadrant: [Option<usize>; 2],
selection: Option<SelectionContext>,
save_file_callback: Option<SaveFileCallbackFn>,
}
impl Default for DiskVisualization {
#[rustfmt::skip]
fn default() -> Self {
let (render_sender, render_receiver) = mpsc::sync_channel(2);
Self {
disk: None,
ui_sender: None,
resolution: VIZ_RESOLUTION,
common_viz_params: CommonVizParams::default(),
compatible: false,
supersample: VIZ_DATA_SUPERSAMPLE,
data_img: [
Arc::new(Mutex::new(Pixmap::new(VIZ_SUPER_RESOLUTION, VIZ_SUPER_RESOLUTION).unwrap())),
Arc::new(Mutex::new(Pixmap::new(VIZ_SUPER_RESOLUTION, VIZ_SUPER_RESOLUTION).unwrap())),
],
meta_img: [
Arc::new(RwLock::new(Pixmap::new(VIZ_RESOLUTION, VIZ_RESOLUTION).unwrap())),
Arc::new(RwLock::new(Pixmap::new(VIZ_RESOLUTION, VIZ_RESOLUTION).unwrap())),
],
selection_img: [
Arc::new(Mutex::new(Pixmap::new(VIZ_RESOLUTION, VIZ_RESOLUTION).unwrap())),
Arc::new(Mutex::new(Pixmap::new(VIZ_RESOLUTION, VIZ_RESOLUTION).unwrap())),
],
composite_img: [
Pixmap::new(VIZ_RESOLUTION, VIZ_RESOLUTION).unwrap(),
Pixmap::new(VIZ_RESOLUTION, VIZ_RESOLUTION).unwrap(),
],
meta_palette: HashMap::new(),
meta_display_list: [Arc::new(Mutex::new(None)), Arc::new(Mutex::new(None))],
have_render: [false; 2],
canvas: [None, None],
sides: 1,
render_sender,
render_receiver,
decode_data_layer: true,
show_data_layer: true,
show_metadata_layer: true,
show_error_layer: false,
show_weak_layer: false,
show_selection_layer: true,
selection_display_list: None,
hover_display_list: None,
last_event: None,
context_menu_open: false,
events: Vec::new(),
got_hit: false,
selection_rect_opt: None,
angle: 0.0,
zoom_quadrant: [None, None],
selection: None,
save_file_callback: None,
}
}
}
impl DiskVisualization {
pub fn new(ctx: egui::Context, resolution: u32) -> Self {
assert_eq!(resolution % 2, 0);
let viz_light_red: VizColor = VizColor::from_rgba8(180, 0, 0, 255);
//let viz_orange: Color = Color::from_rgba8(255, 100, 0, 255);
let vis_purple: VizColor = VizColor::from_rgba8(180, 0, 180, 255);
//let viz_cyan: Color = Color::from_rgba8(70, 200, 200, 255);
//let vis_light_purple: Color = Color::from_rgba8(185, 0, 255, 255);
let pal_medium_green = VizColor::from_rgba8(0x38, 0xb7, 0x64, 0xff);
let pal_dark_green = VizColor::from_rgba8(0x25, 0x71, 0x79, 0xff);
//let pal_dark_blue = Color::from_rgba8(0x29, 0x36, 0x6f, 0xff);
let pal_medium_blue = VizColor::from_rgba8(0x3b, 0x5d, 0xc9, 0xff);
let pal_light_blue = VizColor::from_rgba8(0x41, 0xa6, 0xf6, 0xff);
//let pal_dark_purple = Color::from_rgba8(0x5d, 0x27, 0x5d, 0xff);
let pal_orange = VizColor::from_rgba8(0xef, 0x7d, 0x57, 0xff);
//let pal_dark_red = Color::from_rgba8(0xb1, 0x3e, 0x53, 0xff);
// let mut meta_pixmap_pool = Vec::new();
// for _ in 0..4 {
// let pixmap = Arc::new(Mutex::new(Pixmap::new(resolution / 2, resolution / 2).unwrap()));
// meta_pixmap_pool.push(pixmap);
// }
let mut canvas0 = PixelCanvas::new((resolution, resolution), ctx.clone(), "head0_canvas");
canvas0.set_bpp(PixelCanvasDepth::Rgba);
let mut canvas1 = PixelCanvas::new((resolution, resolution), ctx.clone(), "head1_canvas");
canvas1.set_bpp(PixelCanvasDepth::Rgba);
log::warn!("Creating visualization state...");
Self {
meta_palette: FoxHashMap::from([
(GenericTrackElement::SectorData, pal_medium_green),
(GenericTrackElement::SectorBadData, pal_orange),
(GenericTrackElement::SectorDeletedData, pal_dark_green),
(GenericTrackElement::SectorBadDeletedData, viz_light_red),
(GenericTrackElement::SectorHeader, pal_light_blue),
(GenericTrackElement::SectorBadHeader, pal_medium_blue),
(GenericTrackElement::Marker, vis_purple),
]),
canvas: [Some(canvas0), Some(canvas1)],
..DiskVisualization::default()
}
}
pub fn set_save_file_callback(&mut self, callback: SaveFileCallbackFn) {
self.save_file_callback = Some(callback);
}
pub fn set_event_sender(&mut self, sender: mpsc::SyncSender<UiEvent>) {
log::warn!("Setting event sender...");
self.ui_sender = Some(sender);
}
#[allow(dead_code)]
pub fn compatible(&self) -> bool {
self.compatible
}
pub fn update_disk(&mut self, disk_lock: TrackingLock<DiskImage>) {
let disk = disk_lock.read(UiLockContext::DiskVisualization).unwrap();
self.compatible = disk.can_visualize();
self.sides = disk.heads() as usize;
self.disk = Some(disk_lock.clone());
// Reset selections
self.selection = None;
self.selection_display_list = None;
self.hover_display_list = None;
}
pub fn render_visualization(&mut self, side: usize) -> Result<(), UiError> {
// if self.meta_pixmap_pool.len() < 4 {
// return Err(anyhow!("Pixmap pool not initialized"));
// }
if self.disk.is_none() {
// No disk to render.
return Ok(());
}
let render_lock = self.disk.as_ref().unwrap().clone();
let render_sender = self.render_sender.clone();
let render_target = self.data_img[side].clone();
let render_meta_display_list = self.meta_display_list[side].clone();
let disk = self
.disk
.as_ref()
.unwrap()
.read(UiLockContext::DiskVisualization)
.unwrap();
self.compatible = disk.can_visualize();
if !self.compatible {
return Err(UiError::VisualizationError("Incompatible disk resolution".to_string()));
}
let head = side as u8;
let min_radius_fraction = 0.30;
let render_track_gap = 0.0;
let direction = match head {
0 => TurningDirection::Clockwise,
_ => TurningDirection::CounterClockwise,
};
let track_ct = disk.track_ct(side.into());
if side >= disk.heads() as usize {
// Ignore request for non-existent side.
return Ok(());
}
self.common_viz_params = CommonVizParams {
radius: Some(VIZ_SUPER_RESOLUTION as f32 / 2.0),
max_radius_ratio: 1.0,
min_radius_ratio: min_radius_fraction,
pos_offset: None,
index_angle: 0.0,
track_limit: Some(track_ct),
pin_last_standard_track: true,
track_gap: render_track_gap,
direction,
..CommonVizParams::default()
};
let inner_common_params = self.common_viz_params.clone();
let inner_decode_data = self.decode_data_layer;
let inner_angle = self.common_viz_params.index_angle;
// Render the main data layer.
spawn(move || {
let data_params = RenderTrackDataParams {
side: head,
decode: inner_decode_data,
slices: 1440,
..Default::default()
};
let vector_params = RenderVectorizationParams::default();
let disk = render_lock.read(UiLockContext::DiskVisualization).unwrap();
let mut render_pixmap = render_target.lock().unwrap();
render_pixmap.fill(Color::TRANSPARENT);
match vectorize_disk_data(&disk, &inner_common_params, &data_params, &vector_params) {
Ok(display_list) => {
log::debug!(
"render worker: Data layer vectorized for side {}, created display list of {} elements",
head,
display_list.len()
);
// Disable antialiasing to reduce moiré. For antialiasing, use supersampling.
let mut paint = Paint {
anti_alias: false,
..Default::default()
};
match render_data_display_list(&mut render_pixmap, &mut paint, inner_angle, &display_list) {
Ok(_) => {
log::debug!("render worker: Data display list rendered for side {}", head);
render_sender.send(RenderMessage::DataRenderComplete(head)).unwrap();
}
Err(e) => {
log::error!("Error rendering display list: {}", e);
}
}
}
Err(e) => {
log::error!("Error rendering tracks: {}", e);
}
};
});
// Clear pixmap before rendering
self.meta_img[side].write().unwrap().fill(Color::TRANSPARENT);
let render_params = RenderTrackMetadataParams {
// Render all quadrants
quadrant: None,
side: head,
geometry: RenderGeometry::Sector,
winding: Default::default(),
draw_empty_tracks: false,
draw_sector_lookup: false,
};
// let rasterize_params = RenderRasterizationParams {
// image_size: VizDimensions::from((VIZ_RESOLUTION, VIZ_RESOLUTION)),
// supersample: VIZ_DATA_SUPERSAMPLE,
// image_bg_color: None,
// disk_bg_color: None,
// mask_color: None,
// palette: Some(self.meta_palette.clone()),
// pos_offset: None,
// };
// Update the common viz params for metadata rendering. Metadata is not super-sampled
self.common_viz_params.radius = Some(VIZ_RESOLUTION as f32 / 2.0);
let mut display_list_guard = render_meta_display_list.lock().unwrap();
let display_list = vectorize_disk_elements_by_quadrants(&disk, &self.common_viz_params, &render_params)
.map_err(|e| {
log::error!("Error vectorizing disk elements: {}", e);
UiError::VisualizationError(format!("Error vectorizing disk elements: {}", e))
})?;
let mut paint = Paint::default();
let styles = default_skia_styles();
skia_render_display_list(
&mut self.meta_img[head as usize].write().unwrap(),
&mut paint,
&Transform::identity(),
&display_list,
&SkiaStyle::default(),
&styles,
);
*display_list_guard = Some(display_list);
if let Some(canvas) = &mut self.canvas[side] {
if canvas.has_texture() {
log::debug!("Updating canvas...");
canvas.update_data(self.meta_img[side].read().unwrap().data());
self.have_render[side] = true;
}
else {
log::debug!("Canvas not initialized, deferring update...");
//self.draw_deferred = true;
}
}
Ok(())
}
pub fn set_zoom(&mut self, side: usize, zoom: f32) {
if let Some(canvas) = &mut self.canvas[side] {
canvas.set_zoom(zoom);
}
}
pub fn set_quadrant(&mut self, side: usize, quadrant: Option<usize>) {
if let Some(canvas) = &mut self.canvas[side] {
if let Some(quadrant) = quadrant {
let resolution = Vec2::new(self.resolution as f32, self.resolution as f32);
let view_rect = match quadrant & 0x03 {
0 => Rect::from_min_size(Pos2::new(resolution.x / 2.0, 0.0), resolution / 2.0),
1 => Rect::from_min_size(Pos2::ZERO, resolution / 2.0),
2 => Rect::from_min_size(Pos2::new(0.0, resolution.y / 2.0), resolution / 2.0),
3 => Rect::from_min_size(Pos2::new(resolution.x / 2.0, resolution.y / 2.0), resolution / 2.0),
_ => unreachable!(),
};
log::debug!("Setting virtual rect for quadrant {}: {:?}", quadrant & 0x03, view_rect);
canvas.set_virtual_rect(view_rect);
}
else {
canvas.set_virtual_rect(Rect::from_min_size(
Pos2::ZERO,
Vec2::new(self.resolution as f32, self.resolution as f32),
));
}
}
self.zoom_quadrant[side] = quadrant;
}
pub fn clear_selection(&mut self, side: usize) {
if let Ok(mut pixmap) = self.selection_img[side].try_lock() {
pixmap.fill(Color::TRANSPARENT);
}
}
pub fn update_selection(&mut self, c: u8, h: u8, s_idx: u8) {
if self.disk.is_none() {
// No disk to render.
return;
}
self.clear_selection(h as usize);
let side = h as usize;
let mut do_composite = false;
match self.disk.as_ref().unwrap().read(UiLockContext::DiskVisualization) {
Ok(disk) => {
// If we can acquire the selection image mutex, we can composite the data and metadata layers.
match self.selection_img[side].try_lock() {
Ok(mut data) => {
let render_selection_params = RenderDiskSelectionParams {
selection_type: RenderDiskSelectionType::Sector,
ch: DiskCh::new(c as u16, h),
sector_idx: s_idx as usize,
color: VizColor::from_rgba8(255, 255, 255, 255),
};
match rasterize_disk_selection(
&disk,
&mut data,
&self.common_viz_params,
&render_selection_params,
) {
Ok(_) => {
log::debug!("Sector selection rendered for side {}", side);
}
Err(e) => {
log::error!("Error rendering sector selection: {}", e);
}
}
do_composite = true;
}
Err(_) => {
log::debug!("Data pixmap locked, deferring selection update...");
}
}
}
Err(e) => {
log::debug!(
"Disk image could not be locked for reading! Locked by {:?}, deferring sector selection...",
e
);
return;
}
};
if do_composite {
self.composite(side);
}
}
fn composite(&mut self, side: usize) {
// If we can acquire the data mutex, we can composite the data and metadata layers.
match self.data_img[side].try_lock() {
Ok(data) => {
let mut paint = PixmapPaint {
quality: FilterQuality::Bilinear,
..Default::default()
};
// Scale the data pixmap down to the composite size with bilinear filtering.
if self.show_data_layer {
log::debug!(">>>> Compositing data layer for side {}", side);
let scale = 1.0 / self.supersample as f32;
let transform = Transform::from_scale(scale, scale);
self.composite_img[side].fill(Color::TRANSPARENT);
self.composite_img[side].draw_pixmap(0, 0, data.as_ref(), &paint, transform, None);
}
else {
self.composite_img[side].fill(Color::TRANSPARENT);
}
if self.show_metadata_layer {
paint = PixmapPaint {
opacity: 1.0,
blend_mode: BlendMode::Color,
quality: FilterQuality::Nearest,
};
self.composite_img[side].draw_pixmap(
0,
0,
self.meta_img[side].read().unwrap().as_ref(),
&paint,
Transform::identity(),
None,
);
}
}
Err(_) => {
log::debug!("Data pixmap locked, deferring compositing...");
let paint = PixmapPaint::default();
self.composite_img[side].fill(Color::TRANSPARENT);
if self.show_metadata_layer {
self.composite_img[side].draw_pixmap(
0,
0,
self.meta_img[side].read().unwrap().as_ref(),
&paint,
Transform::identity(),
None,
);
}
}
}
// Finally, composite the sector selection.
match self.selection_img[side].try_lock() {
Ok(selection) => {
let paint = PixmapPaint {
opacity: 1.0,
blend_mode: BlendMode::Overlay,
quality: FilterQuality::Nearest,
};
if self.show_metadata_layer {
self.composite_img[side].draw_pixmap(0, 0, selection.as_ref(), &paint, Transform::identity(), None);
}
}
Err(_) => {
log::debug!("Selection pixmap locked, deferring compositing...");
}
}
if let Some(canvas) = &mut self.canvas[side] {
if canvas.has_texture() {
log::debug!("composite(): Updating canvas...");
canvas.update_data(self.composite_img[side].data());
self.have_render[side] = true;
}
}
}
#[allow(dead_code)]
pub(crate) fn is_open(&self) -> bool {
self.have_render[0]
}
pub fn enable_data_layer(&mut self, state: bool) {
self.show_data_layer = state;
for side in 0..self.sides {
self.composite(side);
}
}
pub fn enable_metadata_layer(&mut self, state: bool) {
self.show_metadata_layer = state;
for side in 0..self.sides {
self.composite(side);
}
}
#[allow(dead_code)]
pub(crate) fn enable_error_layer(&mut self, state: bool) {
self.show_error_layer = state;
for side in 0..self.sides {
self.composite(side);
}
}
#[allow(dead_code)]
pub(crate) fn enable_weak_layer(&mut self, state: bool) {
self.show_weak_layer = state;
for side in 0..self.sides {
self.composite(side);
}
}
pub fn save_side_as_png(&mut self, filename: &str, side: usize) {
if let (Some(canvas), Some(callback)) = (&mut self.canvas[side], self.save_file_callback.as_ref()) {
let png_data = canvas.to_png();
_ = callback(filename, &png_data);
}
}
#[cfg(feature = "svg")]
pub fn save_side_as_svg(&self, filename: &str, side: usize) -> Result<(), UiError> {
if !(self.show_data_layer || self.show_metadata_layer) {
// Nothing to render
return Err(UiError::VisualizationError("No layers enabled".to_string()));
}
let mut renderer = SvgRenderer::new()
.with_side(side as u8)
.with_radius_ratios(0.3, 1.0)
.with_track_gap(0.1)
.with_data_layer(self.show_data_layer, None)
.with_metadata_layer(self.show_metadata_layer)
.with_layer_stack(true)
.with_initial_turning(TurningDirection::Clockwise)
.with_blend_mode(fluxfox_svg::prelude::BlendMode::Color)
.with_side_view_box(VizRect::from((
0.0,
0.0,
self.resolution as f32,
self.resolution as f32,
)));
if let Some(disk) = self
.disk
.as_ref()
.and_then(|d| d.read(UiLockContext::DiskVisualization).ok())
{
renderer = renderer
.render(&disk)
.map_err(|e| UiError::VisualizationError(format!("Error rendering SVG: {}", e)))?;
}
else {
return Err(UiError::VisualizationError(
"Couldn't lock disk for reading".to_string(),
));
}
let documents = renderer
.create_documents()
.map_err(|e| UiError::VisualizationError(format!("Error creating SVG document: {}", e)))?;
if documents.is_empty() {
return Err(UiError::VisualizationError("No SVG documents created".to_string()));
}
let svg_data = documents[0].document.to_string();
if let Some(callback) = self.save_file_callback.as_ref() {
_ = callback(filename, svg_data.as_bytes());
}
Ok(())
}
pub fn show(&mut self, ui: &mut egui::Ui) -> Option<VizEvent> {
let mut new_event = None;
#[cfg(feature = "svg")]
let mut svg_context = None;
// Receive render events
while let Ok(msg) = self.render_receiver.try_recv() {
match msg {
RenderMessage::DataRenderComplete(head) => {
log::debug!("Data render of head {} complete", head);
self.composite(head as usize);
}
RenderMessage::DataRenderError(e) => {
log::error!("Data render error: {}", e);
}
}
}
// Clear the hover selection display list every frame. This avoids "sticky" ghost selections
// if the mouse cursor rapidly leaves the window
self.hover_display_list = None;
let mut context = VisualizationContext {
side_rects: [Rect::ZERO, Rect::ZERO],
got_hit: [false, false],
context_menu_open: &mut self.context_menu_open,
hover_rect_opt: &mut self.selection_rect_opt,
display_list_opt: &mut self.selection_display_list,
hover_display_list_opt: &mut self.hover_display_list,
ui_sender: &mut self.ui_sender,
events: &mut self.events,
common_viz_params: &mut self.common_viz_params,
selection: &mut self.selection,
hover_selection: None,
};
ui.horizontal(|ui| {
ui.set_min_width(400.0);
ui.label("Index Angle:");
ui.add(egui::Slider::new(&mut self.angle, 0.0..=TAU).step_by((TAU / 360.0) as f64));
});
ui.horizontal(|ui| {
for side in 0..self.sides {
context.common_viz_params.direction = TurningDirection::from(side as u8);
if self.have_render[side] {
if let Some(canvas) = &mut self.canvas[side] {
// Adjust the angle for the turning direction of this side, then
// set the canvas rotation angle.
canvas.set_rotation(TurningDirection::from(side as u8).opposite().adjust_angle(self.angle));
let layer_id = ui.layer_id();
let response = canvas.show_as_mesh2(
ui,
Some(|response: &egui::Response, _screen_pos: Pos2, virtual_pos: Pos2| {
// Create a rotation transformation for the current side, turning and angle
// This really should be done for us by the canvas, I think.
let rotation = VizRotation::new(
TurningDirection::from(side as u8).adjust_angle(self.angle),
VizPoint2d::new(VIZ_RESOLUTION as f32 / 2.0, VIZ_RESOLUTION as f32 / 2.0),
);
let hit_test_params = RenderDiskHitTestParams {
side: side as u8,
selection_type: RenderDiskSelectionType::Sector,
geometry: RenderGeometry::Arc,
point: VizPoint2d::new(virtual_pos.x, virtual_pos.y).rotate(&rotation),
};
if let Some(disk) = self
.disk
.as_ref()
.and_then(|d| d.read(UiLockContext::DiskVisualization).ok())
{
Self::perform_hit_test(&disk, side, &hit_test_params, &mut context);
}
else {
log::warn!("Couldn't lock disk for reading.");
}
if !*context.context_menu_open {
if let Some(selection) = &context.hover_selection {
egui::popup::show_tooltip(
&response.ctx,
layer_id,
response.id.with("render_hover_tooltip"),
|ui| {
ui.horizontal(|ui| {
ui.label(format!("{}", selection.element_type));
});
},
);
}
}
}),
);
if let Some(response) = response {
//log::debug!("setting side {} rect: {:?}", side, response.rect);
context.side_rects[side] = response.rect;
if response.clicked() {
if let Some(selection) = &context.hover_selection {
// Send the selection event to the main app
if let Some(sender) = context.ui_sender {
if let Some(chsn) = selection.element_chsn {
let event =
UiEvent::SelectionChange(TrackListSelection::Sector(SectorSelection {
| rust | MIT | b4c04b51746e5fe7769f49a1b32b8caad426fc81 | 2026-01-04T20:24:04.021295Z | true |
dbalsom/fluxfox | https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/crates/ff_egui_lib/src/character_encoding/mod.rs | crates/ff_egui_lib/src/character_encoding/mod.rs | /*
FluxFox
https://github.com/dbalsom/fluxfox
Copyright 2024-2025 Daniel Balsom
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the “Software”),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
--------------------------------------------------------------------------
*/
//! Encoding and decoding utilities for various character sets / code pages.
pub mod cp_437;
pub mod iec8559_1;
use std::fmt::{self, Display, Formatter};
use cp_437::CP437;
use iec8559_1::ISO_IEC_8859_1;
const UNPRINTABLE: char = '.';
/// A simple enum to represent printable and unprintable characters.
/// The enum value contains the actual character if required.
/// The `display` method returns a display-compatible character, substituting
/// unprintable characters with the character specified by `UNPRINTABLE`.
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub enum Chr {
P(char),
C(char),
}
impl Chr {
fn display(&self) -> char {
match self {
Chr::P(c) => *c,
Chr::C(_) => UNPRINTABLE,
}
}
#[allow(dead_code)]
#[inline]
fn encode(&self) -> char {
match self {
Chr::P(c) => *c,
Chr::C(c) => *c,
}
}
}
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
#[derive(Copy, Clone, Default, Debug, PartialEq, strum::EnumIter)]
pub enum CharacterEncoding {
Cp437,
#[default]
IsoIec8559_1,
}
use CharacterEncoding::*;
impl Display for CharacterEncoding {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match self {
Cp437 => write!(f, "IBM OEM CP437"),
IsoIec8559_1 => write!(f, "ISO/IEC 8859-1"),
}
}
}
impl CharacterEncoding {
pub fn display_byte(&self, byte: u8) -> char {
match self {
Cp437 => CP437[byte as usize].display(),
IsoIec8559_1 => ISO_IEC_8859_1[byte as usize].display(),
}
}
pub fn slice_to_string(&self, bytes: &[u8]) -> String {
let mut result = String::new();
for byte in bytes.iter() {
let char = match self {
Cp437 => CP437[*byte as usize].display(),
IsoIec8559_1 => ISO_IEC_8859_1[*byte as usize].display(),
};
result.push(char);
}
result
}
}
| rust | MIT | b4c04b51746e5fe7769f49a1b32b8caad426fc81 | 2026-01-04T20:24:04.021295Z | false |
dbalsom/fluxfox | https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/crates/ff_egui_lib/src/character_encoding/cp_437.rs | crates/ff_egui_lib/src/character_encoding/cp_437.rs | /*
FluxFox
https://github.com/dbalsom/fluxfox
Copyright 2024-2025 Daniel Balsom
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the “Software”),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
--------------------------------------------------------------------------
*/
//! Byte -> Unicode mapping for IBM OEM Code Page 437 - the original character
//! set of the IBM PC.
//! https://en.wikipedia.org/wiki/Code_page_437
use crate::character_encoding::Chr;
pub const CP437: [Chr; 256] = [
Chr::C('\x00'),
Chr::C('\x01'),
Chr::C('\x02'),
Chr::C('\x03'),
Chr::C('\x04'),
Chr::C('\x05'),
Chr::C('\x06'),
Chr::C('\x07'),
Chr::C('\x08'),
Chr::C('\x09'),
Chr::C('\x0A'),
Chr::C('\x0B'),
Chr::C('\x0C'),
Chr::C('\x0D'),
Chr::C('\x0E'),
Chr::C('\x0F'),
Chr::C('\x10'),
Chr::C('\x11'),
Chr::C('\x12'),
Chr::C('\x13'),
Chr::C('\x14'),
Chr::C('\x15'),
Chr::C('\x16'),
Chr::C('\x17'),
Chr::C('\x18'),
Chr::C('\x19'),
Chr::C('\x1A'),
Chr::C('\x1B'),
Chr::C('\x1C'),
Chr::C('\x1D'),
Chr::C('\x1E'),
Chr::C('\x1F'),
Chr::P(' '),
Chr::P('!'),
Chr::P('"'),
Chr::P('#'),
Chr::P('$'),
Chr::P('%'),
Chr::P('&'),
Chr::P('\''),
Chr::P('('),
Chr::P(')'),
Chr::P('*'),
Chr::P('+'),
Chr::P(','),
Chr::P('-'),
Chr::P('.'),
Chr::P('/'),
Chr::P('0'),
Chr::P('1'),
Chr::P('2'),
Chr::P('3'),
Chr::P('4'),
Chr::P('5'),
Chr::P('6'),
Chr::P('7'),
Chr::P('8'),
Chr::P('9'),
Chr::P(':'),
Chr::P(';'),
Chr::P('<'),
Chr::P('='),
Chr::P('>'),
Chr::P('?'),
Chr::P('@'),
Chr::P('A'),
Chr::P('B'),
Chr::P('C'),
Chr::P('D'),
Chr::P('E'),
Chr::P('F'),
Chr::P('G'),
Chr::P('H'),
Chr::P('I'),
Chr::P('J'),
Chr::P('K'),
Chr::P('L'),
Chr::P('M'),
Chr::P('N'),
Chr::P('O'),
Chr::P('P'),
Chr::P('Q'),
Chr::P('R'),
Chr::P('S'),
Chr::P('T'),
Chr::P('U'),
Chr::P('V'),
Chr::P('W'),
Chr::P('X'),
Chr::P('Y'),
Chr::P('Z'),
Chr::P('['),
Chr::P('\\'),
Chr::P(']'),
Chr::P('^'),
Chr::P('_'),
Chr::P('`'),
Chr::P('a'),
Chr::P('b'),
Chr::P('c'),
Chr::P('d'),
Chr::P('e'),
Chr::P('f'),
Chr::P('g'),
Chr::P('h'),
Chr::P('i'),
Chr::P('j'),
Chr::P('k'),
Chr::P('l'),
Chr::P('m'),
Chr::P('n'),
Chr::P('o'),
Chr::P('p'),
Chr::P('q'),
Chr::P('r'),
Chr::P('s'),
Chr::P('t'),
Chr::P('u'),
Chr::P('v'),
Chr::P('w'),
Chr::P('x'),
Chr::P('y'),
Chr::P('z'),
Chr::P('{'),
Chr::P('|'),
Chr::P('}'),
Chr::P('~'),
Chr::C('\x7F'),
Chr::P('\u{00C7}'),
Chr::P('\u{00FC}'),
Chr::P('\u{00E9}'),
Chr::P('\u{00E2}'),
Chr::P('\u{00E4}'),
Chr::P('\u{00E0}'),
Chr::P('\u{00E5}'),
Chr::P('\u{00E7}'),
Chr::P('\u{00EA}'),
Chr::P('\u{00EB}'),
Chr::P('\u{00E8}'),
Chr::P('\u{00EF}'),
Chr::P('\u{00EE}'),
Chr::P('\u{00EC}'),
Chr::P('\u{00C4}'),
Chr::P('\u{00C5}'),
Chr::P('\u{00C9}'),
Chr::P('\u{00E6}'),
Chr::P('\u{00C6}'),
Chr::P('\u{00F4}'),
Chr::P('\u{00F6}'),
Chr::P('\u{00F2}'),
Chr::P('\u{00FB}'),
Chr::P('\u{00F9}'),
Chr::P('\u{00FF}'),
Chr::P('\u{00D6}'),
Chr::P('\u{00DC}'),
Chr::P('\u{00A2}'),
Chr::P('\u{00A3}'),
Chr::P('\u{00A5}'),
Chr::P('\u{20A7}'),
Chr::P('\u{0192}'),
Chr::P('\u{00E1}'),
Chr::P('\u{00ED}'),
Chr::P('\u{00F3}'),
Chr::P('\u{00FA}'),
Chr::P('\u{00F1}'),
Chr::P('\u{00D1}'),
Chr::P('\u{00AA}'),
Chr::P('\u{00BA}'),
Chr::P('\u{00BF}'),
Chr::P('\u{00AE}'),
Chr::P('\u{00AC}'),
Chr::P('\u{00BD}'),
Chr::P('\u{00BC}'),
Chr::P('\u{00A1}'),
Chr::P('\u{00AB}'),
Chr::P('\u{00BB}'),
Chr::P('\u{2591}'),
Chr::P('\u{2592}'),
Chr::P('\u{2593}'),
Chr::P('\u{2502}'),
Chr::P('\u{2524}'),
Chr::P('\u{2561}'),
Chr::P('\u{2562}'),
Chr::P('\u{2556}'),
Chr::P('\u{2555}'),
Chr::P('\u{2563}'),
Chr::P('\u{2551}'),
Chr::P('\u{2557}'),
Chr::P('\u{255D}'),
Chr::P('\u{255C}'),
Chr::P('\u{255B}'),
Chr::P('\u{2510}'),
Chr::P('\u{2514}'),
Chr::P('\u{2534}'),
Chr::P('\u{252C}'),
Chr::P('\u{251C}'),
Chr::P('\u{2500}'),
Chr::P('\u{253C}'),
Chr::P('\u{255E}'),
Chr::P('\u{255F}'),
Chr::P('\u{255A}'),
Chr::P('\u{2554}'),
Chr::P('\u{2569}'),
Chr::P('\u{2566}'),
Chr::P('\u{2560}'),
Chr::P('\u{2550}'),
Chr::P('\u{256C}'),
Chr::P('\u{2567}'),
Chr::P('\u{2568}'),
Chr::P('\u{2564}'),
Chr::P('\u{2565}'),
Chr::P('\u{2559}'),
Chr::P('\u{2558}'),
Chr::P('\u{2552}'),
Chr::P('\u{2553}'),
Chr::P('\u{256B}'),
Chr::P('\u{256A}'),
Chr::P('\u{2518}'),
Chr::P('\u{250C}'),
Chr::P('\u{2588}'),
Chr::P('\u{2584}'),
Chr::P('\u{258C}'),
Chr::P('\u{2590}'),
Chr::P('\u{2580}'),
Chr::P('\u{03B1}'),
Chr::P('\u{00DF}'),
Chr::P('\u{0393}'),
Chr::P('\u{03C0}'),
Chr::P('\u{03A3}'),
Chr::P('\u{03C3}'),
Chr::P('\u{00B5}'),
Chr::P('\u{03C4}'),
Chr::P('\u{03A6}'),
Chr::P('\u{0398}'),
Chr::P('\u{03A9}'),
Chr::P('\u{03B4}'),
Chr::P('\u{221E}'),
Chr::P('\u{03C6}'),
Chr::P('\u{03B5}'),
Chr::P('\u{2229}'),
Chr::P('\u{2261}'),
Chr::P('\u{00B1}'),
Chr::P('\u{2265}'),
Chr::P('\u{2264}'),
Chr::P('\u{2320}'),
Chr::P('\u{2321}'),
Chr::P('\u{00F7}'),
Chr::P('\u{2248}'),
Chr::P('\u{00B0}'),
Chr::P('\u{2219}'),
Chr::P('\u{00B7}'),
Chr::P('\u{221A}'),
Chr::P('\u{207F}'),
Chr::P('\u{00B2}'),
Chr::P('\u{25A0}'),
Chr::P('\u{00A0}'),
];
| rust | MIT | b4c04b51746e5fe7769f49a1b32b8caad426fc81 | 2026-01-04T20:24:04.021295Z | false |
dbalsom/fluxfox | https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/crates/ff_egui_lib/src/character_encoding/iec8559_1.rs | crates/ff_egui_lib/src/character_encoding/iec8559_1.rs | /*
FluxFox
https://github.com/dbalsom/fluxfox
Copyright 2024-2025 Daniel Balsom
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the “Software”),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
--------------------------------------------------------------------------
*/
//! Byte -> Unicode mapping for ISO/IEC 8859-1 (Latin-1) character set.
//! Used by several platforms.
//! https://en.wikipedia.org/wiki/ISO/IEC_8859-1
//!
use crate::character_encoding::Chr;
pub const ISO_IEC_8859_1: [Chr; 256] = [
Chr::C('\x00'),
Chr::C('\x01'),
Chr::C('\x02'),
Chr::C('\x03'),
Chr::C('\x04'),
Chr::C('\x05'),
Chr::C('\x06'),
Chr::C('\x07'),
Chr::C('\x08'),
Chr::C('\x09'),
Chr::C('\x0A'),
Chr::C('\x0B'),
Chr::C('\x0C'),
Chr::C('\x0D'),
Chr::C('\x0E'),
Chr::C('\x0F'),
Chr::C('\x10'),
Chr::C('\x11'),
Chr::C('\x12'),
Chr::C('\x13'),
Chr::C('\x14'),
Chr::C('\x15'),
Chr::C('\x16'),
Chr::C('\x17'),
Chr::C('\x18'),
Chr::C('\x19'),
Chr::C('\x1A'),
Chr::C('\x1B'),
Chr::C('\x1C'),
Chr::C('\x1D'),
Chr::C('\x1E'),
Chr::C('\x1F'),
Chr::P(' '),
Chr::P('!'),
Chr::P('"'),
Chr::P('#'),
Chr::P('$'),
Chr::P('%'),
Chr::P('&'),
Chr::P('\''),
Chr::P('('),
Chr::P(')'),
Chr::P('*'),
Chr::P('+'),
Chr::P(','),
Chr::P('-'),
Chr::P('.'),
Chr::P('/'),
Chr::P('0'),
Chr::P('1'),
Chr::P('2'),
Chr::P('3'),
Chr::P('4'),
Chr::P('5'),
Chr::P('6'),
Chr::P('7'),
Chr::P('8'),
Chr::P('9'),
Chr::P(':'),
Chr::P(';'),
Chr::P('<'),
Chr::P('='),
Chr::P('>'),
Chr::P('?'),
Chr::P('@'),
Chr::P('A'),
Chr::P('B'),
Chr::P('C'),
Chr::P('D'),
Chr::P('E'),
Chr::P('F'),
Chr::P('G'),
Chr::P('H'),
Chr::P('I'),
Chr::P('J'),
Chr::P('K'),
Chr::P('L'),
Chr::P('M'),
Chr::P('N'),
Chr::P('O'),
Chr::P('P'),
Chr::P('Q'),
Chr::P('R'),
Chr::P('S'),
Chr::P('T'),
Chr::P('U'),
Chr::P('V'),
Chr::P('W'),
Chr::P('X'),
Chr::P('Y'),
Chr::P('Z'),
Chr::P('['),
Chr::P('\\'),
Chr::P(']'),
Chr::P('^'),
Chr::P('_'),
Chr::P('`'),
Chr::P('a'),
Chr::P('b'),
Chr::P('c'),
Chr::P('d'),
Chr::P('e'),
Chr::P('f'),
Chr::P('g'),
Chr::P('h'),
Chr::P('i'),
Chr::P('j'),
Chr::P('k'),
Chr::P('l'),
Chr::P('m'),
Chr::P('n'),
Chr::P('o'),
Chr::P('p'),
Chr::P('q'),
Chr::P('r'),
Chr::P('s'),
Chr::P('t'),
Chr::P('u'),
Chr::P('v'),
Chr::P('w'),
Chr::P('x'),
Chr::P('y'),
Chr::P('z'),
Chr::P('{'),
Chr::P('|'),
Chr::P('}'),
Chr::P('~'),
Chr::C('\x7F'),
Chr::C('\u{0080}'),
Chr::C('\u{0081}'),
Chr::C('\u{0082}'),
Chr::C('\u{0083}'),
Chr::C('\u{0084}'),
Chr::C('\u{0085}'),
Chr::C('\u{0086}'),
Chr::C('\u{0087}'),
Chr::C('\u{0088}'),
Chr::C('\u{0089}'),
Chr::C('\u{008A}'),
Chr::C('\u{008B}'),
Chr::C('\u{008C}'),
Chr::C('\u{008D}'),
Chr::C('\u{008E}'),
Chr::C('\u{008F}'),
Chr::C('\u{0090}'),
Chr::C('\u{0091}'),
Chr::C('\u{0092}'),
Chr::C('\u{0093}'),
Chr::C('\u{0094}'),
Chr::C('\u{0095}'),
Chr::C('\u{0096}'),
Chr::C('\u{0097}'),
Chr::C('\u{0098}'),
Chr::C('\u{0099}'),
Chr::C('\u{009A}'),
Chr::C('\u{009B}'),
Chr::C('\u{009C}'),
Chr::C('\u{009D}'),
Chr::C('\u{009E}'),
Chr::C('\u{009F}'),
Chr::P('\u{00A0}'),
Chr::P('\u{00A1}'),
Chr::P('\u{00A2}'),
Chr::P('\u{00A3}'),
Chr::P('\u{00A4}'),
Chr::P('\u{00A5}'),
Chr::P('\u{00A6}'),
Chr::P('\u{00A7}'),
Chr::P('\u{00A8}'),
Chr::P('\u{00A9}'),
Chr::P('\u{00AA}'),
Chr::P('\u{00AB}'),
Chr::P('\u{00AC}'),
Chr::P('\u{00AD}'),
Chr::P('\u{00AE}'),
Chr::P('\u{00AF}'),
Chr::P('\u{00B0}'),
Chr::P('\u{00B1}'),
Chr::P('\u{00B2}'),
Chr::P('\u{00B3}'),
Chr::P('\u{00B4}'),
Chr::P('\u{00B5}'),
Chr::P('\u{00B6}'),
Chr::P('\u{00B7}'),
Chr::P('\u{00B8}'),
Chr::P('\u{00B9}'),
Chr::P('\u{00BA}'),
Chr::P('\u{00BB}'),
Chr::P('\u{00BC}'),
Chr::P('\u{00BD}'),
Chr::P('\u{00BE}'),
Chr::P('\u{00BF}'),
Chr::P('\u{00C0}'),
Chr::P('\u{00C1}'),
Chr::P('\u{00C2}'),
Chr::P('\u{00C3}'),
Chr::P('\u{00C4}'),
Chr::P('\u{00C5}'),
Chr::P('\u{00C6}'),
Chr::P('\u{00C7}'),
Chr::P('\u{00C8}'),
Chr::P('\u{00C9}'),
Chr::P('\u{00CA}'),
Chr::P('\u{00CB}'),
Chr::P('\u{00CC}'),
Chr::P('\u{00CD}'),
Chr::P('\u{00CE}'),
Chr::P('\u{00CF}'),
Chr::P('\u{00D0}'),
Chr::P('\u{00D1}'),
Chr::P('\u{00D2}'),
Chr::P('\u{00D3}'),
Chr::P('\u{00D4}'),
Chr::P('\u{00D5}'),
Chr::P('\u{00D6}'),
Chr::P('\u{00D7}'),
Chr::P('\u{00D8}'),
Chr::P('\u{00D9}'),
Chr::P('\u{00DA}'),
Chr::P('\u{00DB}'),
Chr::P('\u{00DC}'),
Chr::P('\u{00DD}'),
Chr::P('\u{00DE}'),
Chr::P('\u{00DF}'),
Chr::P('\u{00E0}'),
Chr::P('\u{00E1}'),
Chr::P('\u{00E2}'),
Chr::P('\u{00E3}'),
Chr::P('\u{00E4}'),
Chr::P('\u{00E5}'),
Chr::P('\u{00E6}'),
Chr::P('\u{00E7}'),
Chr::P('\u{00E8}'),
Chr::P('\u{00E9}'),
Chr::P('\u{00EA}'),
Chr::P('\u{00EB}'),
Chr::P('\u{00EC}'),
Chr::P('\u{00ED}'),
Chr::P('\u{00EE}'),
Chr::P('\u{00EF}'),
Chr::P('\u{00F0}'),
Chr::P('\u{00F1}'),
Chr::P('\u{00F2}'),
Chr::P('\u{00F3}'),
Chr::P('\u{00F4}'),
Chr::P('\u{00F5}'),
Chr::P('\u{00F6}'),
Chr::P('\u{00F7}'),
Chr::P('\u{00F8}'),
Chr::P('\u{00F9}'),
Chr::P('\u{00FA}'),
Chr::P('\u{00FB}'),
Chr::P('\u{00FC}'),
Chr::P('\u{00FD}'),
Chr::P('\u{00FE}'),
Chr::P('\u{00FF}'),
];
| rust | MIT | b4c04b51746e5fe7769f49a1b32b8caad426fc81 | 2026-01-04T20:24:04.021295Z | false |
dbalsom/fluxfox | https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/crates/ff_egui_lib/src/range_check/mod.rs | crates/ff_egui_lib/src/range_check/mod.rs | /*
FluxFox
https://github.com/dbalsom/fluxfox
Copyright 2024-2025 Daniel Balsom
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the “Software”),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
--------------------------------------------------------------------------
src/range_check.rs
Implement an O(log n) range checker for detecting if a value is within a range.
*/
#[derive(Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub(crate) struct RangeChecker {
events: Vec<(usize, i32, usize)>, // (value, type), where type is +1 for start, -1 for end
}
impl RangeChecker {
pub fn new(ranges: &[(usize, usize)]) -> Self {
let mut events = Vec::with_capacity(ranges.len() * 2);
for (i, &(start, end)) in ranges.iter().enumerate() {
events.push((start, 1, i)); // Start of range
events.push((end + 1, -1, i)); // End of range, exclusive
}
events.sort_unstable();
RangeChecker { events }
}
pub fn contains(&self, value: usize) -> Option<usize> {
let mut active_ranges = 0;
let mut current_range = None;
for &(point, event_type, range_index) in &self.events {
if point > value {
break;
}
active_ranges += event_type;
if event_type == 1 {
current_range = Some(range_index); // Entering a range
}
else if event_type == -1 && current_range == Some(range_index) {
current_range = None; // Exiting the range
}
}
if active_ranges > 0 {
current_range
}
else {
None
}
}
}
| rust | MIT | b4c04b51746e5fe7769f49a1b32b8caad426fc81 | 2026-01-04T20:24:04.021295Z | false |
dbalsom/fluxfox | https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/crates/png2disk/src/args.rs | crates/png2disk/src/args.rs | /*
FluxFox
https://github.com/dbalsom/fluxfox
Copyright 2024-2025 Daniel Balsom
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the “Software”),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
--------------------------------------------------------------------------
examples/imgviz/src/args.rs
Argument parsers for imgviz.
*/
use std::path::PathBuf;
use bpaf::{construct, long, short, OptionParser, Parser};
use fluxfox::{types::StandardFormatParam, visualization::prelude::VizColor, StandardFormat};
#[allow(dead_code)]
#[derive(Debug, Clone)]
pub(crate) struct Out {
pub(crate) debug: bool,
pub(crate) in_disk: Option<PathBuf>,
pub(crate) in_image0: PathBuf,
pub(crate) in_image1: Option<PathBuf>,
pub(crate) out_disk: PathBuf,
pub(crate) hole_ratio: Option<f32>,
pub(crate) angle: f32,
pub(crate) cc: bool,
pub(crate) skip: u16,
pub(crate) disk_format: StandardFormatParam,
pub(crate) formatted: bool,
pub(crate) sectors_only: bool,
pub(crate) applesauce: bool,
pub(crate) grayscale: bool,
}
/// Set up bpaf argument parsing.
pub(crate) fn opts() -> OptionParser<Out> {
let debug = short('d').long("debug").help("Print debug messages").switch();
let in_disk = long("in_disk")
.help("Filename of disk image to read")
.argument::<PathBuf>("INPUT_DISK_IMAGE")
.optional();
let in_image0 = long("in_image0")
.help("Filename of PNG image to use for head 0")
.argument::<PathBuf>("INPUT_PNG_IMAGE0");
let in_image1 = long("in_image1")
.help("Filename of PNG image to use for head 1")
.argument::<PathBuf>("INPUT_PNG_IMAGE1")
.optional();
let out_disk = short('o')
.long("out_disk")
.help("Filename of disk image to write")
.argument::<PathBuf>("OUTPUT_DISK_IMAGE");
let skip = long("skip")
.help("Number of tracks to skip. Default is 0")
.argument::<u16>("SKIP")
.fallback(0);
let hole_ratio = short('h')
.long("hole_ratio")
.help("Ratio of inner radius to outer radius")
.argument::<f32>("RATIO")
.optional();
let angle = short('a')
.long("angle")
.help("Angle of rotation")
.argument::<f32>("ANGLE")
.fallback(0.0);
let cc = long("cc").help("Wrap data counter-clockwise").switch();
let disk_format = standard_format_parser();
let formatted = long("formatted")
.help("If no input disk image was specified, create a formatted image")
.switch();
let sectors_only = long("sectors_only").help("Only render image into sector data").switch();
let applesauce = long("applesauce")
.help("Use presets for Applesauce disk visualization (default HxC/fluxfox)")
.switch();
let grayscale = long("grayscale").help("Render grayscale image (slower)").switch();
construct!(Out {
debug,
in_disk,
in_image0,
in_image1,
out_disk,
hole_ratio,
angle,
cc,
skip,
disk_format,
formatted,
sectors_only,
applesauce,
grayscale,
})
.to_options()
.descr("imgviz: generate a graphical visualization of a disk image")
}
// Implement a parser for `StandardFormat`
fn standard_format_parser() -> impl Parser<StandardFormatParam> {
long("disk_format")
.help("Specify a standard disk format (e.g., 160k, 1440k)")
.argument::<String>("STANDARD_DISK_FORMAT")
.parse(|input| input.parse())
.fallback(StandardFormatParam(StandardFormat::PcFloppy1200))
}
/// Parse a color from either a hex string (`#RRGGBBAA` or `#RRGGBB`) or an RGBA string (`R,G,B,A`).
#[allow(dead_code)]
pub(crate) fn parse_color(input: &str) -> Result<VizColor, String> {
if input.starts_with('#') {
// Parse hex color: #RRGGBBAA or #RRGGBB
let hex = input.strip_prefix('#').ok_or("Invalid hex color")?;
match hex.len() {
6 => {
let r = u8::from_str_radix(&hex[0..2], 16).map_err(|_| "Invalid hex color")?;
let g = u8::from_str_radix(&hex[2..4], 16).map_err(|_| "Invalid hex color")?;
let b = u8::from_str_radix(&hex[4..6], 16).map_err(|_| "Invalid hex color")?;
Ok(VizColor::from_rgba8(r, g, b, 255))
}
8 => {
let r = u8::from_str_radix(&hex[0..2], 16).map_err(|_| "Invalid hex color")?;
let g = u8::from_str_radix(&hex[2..4], 16).map_err(|_| "Invalid hex color")?;
let b = u8::from_str_radix(&hex[4..6], 16).map_err(|_| "Invalid hex color")?;
let a = u8::from_str_radix(&hex[6..8], 16).map_err(|_| "Invalid hex color")?;
Ok(VizColor::from_rgba8(r, g, b, a))
}
_ => Err("Hex color must be in the format #RRGGBB or #RRGGBBAA".to_string()),
}
}
else {
// Parse RGBA color: R,G,B,A
let parts: Vec<&str> = input.split(',').collect();
if parts.len() != 4 {
return Err("RGBA color must be in the format R,G,B,A".to_string());
}
let r = parts[0].parse::<u8>().map_err(|_| "Invalid RGBA color component")?;
let g = parts[1].parse::<u8>().map_err(|_| "Invalid RGBA color component")?;
let b = parts[2].parse::<u8>().map_err(|_| "Invalid RGBA color component")?;
let a = parts[3].parse::<u8>().map_err(|_| "Invalid RGBA color component")?;
Ok(VizColor::from_rgba8(r, g, b, a))
}
}
| rust | MIT | b4c04b51746e5fe7769f49a1b32b8caad426fc81 | 2026-01-04T20:24:04.021295Z | false |
dbalsom/fluxfox | https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/crates/png2disk/src/main.rs | crates/png2disk/src/main.rs | /*
FluxFox
https://github.com/dbalsom/fluxfox
Copyright 2024-2025 Daniel Balsom
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the “Software”),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
--------------------------------------------------------------------------
*/
//! png2disk
//! An entirely useless utility that writes PNG files to disk images, mostly
//! because we can. Have fun making floppy art!
mod args;
mod disk;
use std::io::Cursor;
use fluxfox::{format_from_ext, prelude::*, visualization::prelude::*, DiskImage, ImageBuilder, ImageWriter};
use crate::{args::opts, disk::repair_crcs};
use fluxfox_tiny_skia::tiny_skia::Pixmap;
use tiny_skia::{PixmapPaint, PixmapRef, Transform};
fn main() {
env_logger::init();
// Get the command line options.
let opts = opts().run();
let mut disk = if let Some(in_disk) = opts.in_disk {
let mut file_vec = match std::fs::read(in_disk.clone()) {
Ok(file_vec) => file_vec,
Err(e) => {
eprintln!("Error reading file: {}", e);
std::process::exit(1);
}
};
let mut reader = Cursor::new(&mut file_vec);
let disk_image_type = match DiskImage::detect_format(&mut reader, Some(&in_disk)) {
Ok(disk_image_type) => disk_image_type,
Err(e) => {
eprintln!("Error detecting disk image type: {}", e);
std::process::exit(1);
}
};
println!("Reading disk image: {}", in_disk.display());
println!("Detected disk image type: {}", disk_image_type);
match DiskImage::load(&mut reader, Some(&in_disk), None, None) {
Ok(disk) => disk,
Err(e) => {
eprintln!("Error loading disk image: {}", e);
std::process::exit(1);
}
}
}
else {
match ImageBuilder::new()
.with_resolution(TrackDataResolution::BitStream)
.with_standard_format(opts.disk_format)
.with_formatted(opts.formatted)
.build()
{
Ok(disk) => disk,
Err(e) => {
eprintln!("Error creating disk image: {}", e);
std::process::exit(1);
}
}
};
// Load the image for the first side.
let mut pixmap0 = match Pixmap::load_png(&opts.in_image0) {
Ok(pixmap) => pixmap,
Err(e) => {
eprintln!("Error loading PNG image: {}", e);
std::process::exit(1);
}
};
// Load the image for the second side, if specified.
let mut pixmap1_opt = if let Some(in_image1) = opts.in_image1 {
let pixmap = match Pixmap::load_png(&in_image1) {
Ok(pixmap) => pixmap,
Err(e) => {
eprintln!("Error loading PNG image: {}", e);
std::process::exit(1);
}
};
Some(pixmap)
}
else {
None
};
if opts.applesauce {
pixmap0 = rotate_pixmap(pixmap0.as_ref(), 90.0);
if let Some(pixmap1) = pixmap1_opt.as_mut() {
*pixmap1 = rotate_pixmap(pixmap1.as_ref(), 90.0);
}
}
let mut common_params = CommonVizParams {
radius: Some(pixmap0.height() as f32 / 2.0),
max_radius_ratio: opts.hole_ratio.unwrap_or(match opts.applesauce {
false => 0.3, // Good hole ratio for HxC and fluxfox
true => 0.27, // Applesauce has slightly smaller hole
}),
min_radius_ratio: 1.0,
pos_offset: None,
index_angle: opts.angle,
track_limit: Some(disk.tracks(0) as usize),
pin_last_standard_track: false,
track_gap: 0.0,
direction: TurningDirection::Clockwise,
..CommonVizParams::default()
};
let mut data_params = RenderTrackDataParams {
side: 0,
// Not used
decode: false,
// Whether to mask the image to sector data areas
sector_mask: opts.sectors_only,
// Not used
resolution: Default::default(),
// Not used
slices: 0,
overlap: 0.0,
};
// let mut data_params = RenderTrackDataParams {
// image_size: (pixmap0.width(), pixmap0.height()),
// image_pos: (0, 0),
// side: 0,
// track_limit: disk.tracks(0) as usize,
// min_radius_ratio: opts.hole_ratio.unwrap_or(match opts.applesauce {
// false => 0.3, // Good hole ratio for HxC and fluxfox
// true => 0.27, // Applesauce has slightly smaller hole
// }),
// index_angle: opts.angle,
// direction: TurningDirection::Clockwise,
// sector_mask: opts.sectors_only,
// ..Default::default()
// };
// If the user specified initial counter-clockwise rotation, change the direction.
if opts.cc {
common_params.direction = TurningDirection::CounterClockwise;
}
let pixmap_params = PixmapToDiskParams {
skip_tracks: opts.skip,
..Default::default()
};
let render = |pixmap: &Pixmap,
disk: &mut DiskImage,
common_params: &CommonVizParams,
pixmap_params: &PixmapToDiskParams,
data_params: &RenderTrackDataParams| {
match opts.grayscale {
true => match render_pixmap_to_disk_grayscale(pixmap, disk, common_params, data_params, pixmap_params) {
Ok(_) => (),
Err(e) => {
eprintln!("Error rendering pixmap to disk: {}", e);
std::process::exit(1);
}
},
false => match render_pixmap_to_disk(pixmap, disk, common_params, data_params, pixmap_params) {
Ok(_) => (),
Err(e) => {
eprintln!("Error rendering pixmap to disk: {}", e);
std::process::exit(1);
}
},
}
};
println!("Rendering side 0...");
// Render the first side.
render(&pixmap0, &mut disk, &common_params, &pixmap_params, &data_params);
// Render the second side, if present.
if let Some(pixmap1) = pixmap1_opt {
if disk.heads() > 1 {
// Applesauce doesn't change the rotation direction for the second side.
if !opts.applesauce {
common_params.direction = common_params.direction.opposite();
}
common_params.track_limit = Some(disk.tracks(1) as usize);
data_params.side = 1;
common_params.index_angle = common_params.direction.adjust_angle(opts.angle);
println!("Rendering side 1...");
render(
&pixmap1.to_owned(),
&mut disk,
&common_params,
&pixmap_params,
&data_params,
);
}
}
//If we rendered to sector data, repair the sector CRCs now.
if opts.sectors_only {
match repair_crcs(&mut disk) {
Ok(_) => println!("Successfully repaired sector CRCs."),
Err(e) => {
eprintln!("Error repairing sector CRCs: {}", e);
std::process::exit(1);
}
}
}
// Get extension from output filename
let output_format = opts
.out_disk
.extension()
.and_then(|ext| ext.to_str())
.and_then(format_from_ext)
.unwrap_or_else(|| {
eprintln!("Error: Invalid or unknown output file extension!");
std::process::exit(1);
});
match ImageWriter::new(&mut disk)
.with_format(output_format)
.with_path(opts.out_disk)
.write()
{
Ok(_) => {
println!("Successfully wrote disk image.");
}
Err(e) => {
eprintln!("Error writing disk image: {}", e);
std::process::exit(1);
}
}
}
fn rotate_pixmap(pixmap: PixmapRef, angle: f32) -> Pixmap {
let mut new_pixmap = Pixmap::new(pixmap.height(), pixmap.width()).unwrap();
new_pixmap.draw_pixmap(
0,
0,
pixmap,
&PixmapPaint::default(),
Transform::from_rotate(angle).post_translate(pixmap.height() as f32, 0.0),
None,
);
new_pixmap
}
| rust | MIT | b4c04b51746e5fe7769f49a1b32b8caad426fc81 | 2026-01-04T20:24:04.021295Z | false |
dbalsom/fluxfox | https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/crates/png2disk/src/disk.rs | crates/png2disk/src/disk.rs | /*
FluxFox
https://github.com/dbalsom/fluxfox
Copyright 2024-2025 Daniel Balsom
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the “Software”),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
--------------------------------------------------------------------------
*/
use anyhow::Result;
use fluxfox::prelude::*;
pub fn repair_crcs(disk: &mut DiskImage) -> Result<()> {
let tracks = disk.track_ch_iter().collect::<Vec<_>>();
for ch in tracks {
if let Some(track) = disk.track_mut(ch) {
for sector in track.sector_list() {
track.recalculate_sector_crc(DiskChsnQuery::from(sector.chsn), None)?;
}
}
}
Ok(())
}
| rust | MIT | b4c04b51746e5fe7769f49a1b32b8caad426fc81 | 2026-01-04T20:24:04.021295Z | false |
dbalsom/fluxfox | https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/crates/fluxfox_cli/src/args.rs | crates/fluxfox_cli/src/args.rs | /*
fftool
https://github.com/dbalsom/fluxfox
Copyright 2024-2025 Daniel Balsom
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the “Software”),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
--------------------------------------------------------------------------
*/
use std::{
fmt::{Display, Formatter},
io::Write,
path::PathBuf,
str::FromStr,
};
use crate::{
convert::args::{convert_parser, ConvertParams},
create::args::{create_parser, CreateParams},
dump::args::{dump_parser, DumpParams},
find::args::{find_parser, FindParams},
info::args::{info_parser, InfoParams},
};
use bpaf::*;
use fluxfox::prelude::*;
#[derive(Debug, Clone, Copy)]
pub enum DumpFormat {
Binary,
Hex,
Ascii,
}
impl FromStr for DumpFormat {
type Err = &'static str;
fn from_str(input: &str) -> Result<Self, Self::Err> {
match input.to_lowercase().as_str() {
"binary" => Ok(DumpFormat::Binary),
"hex" => Ok(DumpFormat::Hex),
"ascii" => Ok(DumpFormat::Ascii),
_ => Err("Invalid format; expected 'binary', 'hex', or 'ascii'"),
}
}
}
#[derive(Clone, Debug)]
pub(crate) enum Command {
Version,
Convert(ConvertParams),
Create(CreateParams),
Dump(DumpParams),
Find(FindParams),
Info(InfoParams),
}
impl Display for Command {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
Command::Version => write!(f, "version"),
Command::Convert(_) => write!(f, "convert"),
Command::Create(_) => write!(f, "create"),
Command::Dump(_) => write!(f, "dump"),
Command::Find(_) => write!(f, "find"),
Command::Info(_) => write!(f, "info"),
}
}
}
#[derive(Debug)]
pub(crate) struct AppParams {
pub global: GlobalOptions,
pub command: Command,
}
#[derive(Debug)]
pub struct GlobalOptions {
pub silent: bool,
}
impl GlobalOptions {
pub fn loud<F: FnMut()>(&self, mut f: F) {
if !self.silent {
f();
std::io::stdout().flush().unwrap();
}
}
}
pub fn global_options_parser() -> impl Parser<GlobalOptions> {
let silent = long("silent")
.help("Suppress all output except required output")
.switch(); // Switch returns a bool, true if the flag is present
construct!(GlobalOptions { silent })
}
pub(crate) fn in_file_parser() -> impl Parser<PathBuf> {
long("in_file")
.short('i')
.argument::<PathBuf>("INPUT_FILE")
.help("Path to input file")
}
pub(crate) fn out_file_parser() -> impl Parser<PathBuf> {
long("out_file")
.short('o')
.argument::<PathBuf>("OUTPUT_FILE")
.help("Path to output file")
}
pub(crate) fn command_parser() -> impl Parser<AppParams> {
let global = global_options_parser();
let version = pure(Command::Version)
.to_options()
.command("version")
.help("Display version information and exit");
let convert = construct!(Command::Convert(convert_parser()))
.to_options()
.command("convert")
.help("Convert a disk image to a different format");
let create = construct!(Command::Create(create_parser()))
.to_options()
.command("create")
.help("Create a new disk image");
let dump = construct!(Command::Dump(dump_parser()))
.to_options()
.command("dump")
.help("Dump data from a disk image");
let find = construct!(Command::Find(find_parser()))
.to_options()
.command("find")
.help("Find data in a disk image");
let info = construct!(Command::Info(info_parser()))
.to_options()
.command("info")
.help("Display information about a disk image");
let command = construct!([version, convert, create, dump, find, info]);
construct!(AppParams { global, command })
}
pub(crate) fn sector_parser() -> impl Parser<u8> {
long("sector")
.short('s')
.argument::<u8>("SECTOR")
.help("Specify the sector number to dump")
}
pub(crate) fn cylinder_parser() -> impl Parser<u16> {
long("cylinder")
.short('c')
.argument::<u16>("CYLINDER")
.help("Specify the cylinder number to dump")
}
pub(crate) fn phys_cylinder_parser() -> impl Parser<u16> {
long("p_cylinder")
.argument::<u16>("PHYSICAL_CYLINDER")
.help("Specify the physical cylinder number to dump")
}
pub(crate) fn phys_head_parser() -> impl Parser<u8> {
long("p_head")
.argument::<u8>("PHYSICAL_HEAD")
.help("Specify the physical head number to dump")
}
pub(crate) fn head_parser() -> impl Parser<u8> {
long("head")
.short('h')
.argument::<u8>("HEAD")
.help("Specify the head number to dump")
.guard(|&head| head == 0 || head == 1, "Head must be either 0 or 1")
}
pub(crate) fn n_parser() -> impl Parser<u8> {
long("size")
.short('n')
.argument::<u8>("SECTOR_SIZE")
.help("Specify the size of the sector to dump. 0=128 bytes, 1=256 bytes, 2=512 bytes ... 6=8192 bytes")
.guard(|&size| size <= 6, "Size must be between 0 and 6")
}
pub(crate) fn rev_parser() -> impl Parser<u8> {
long("rev")
.short('r')
.argument::<u8>("REVOLUTION_NUMBER")
.help("Specify the revolution to target. Only applicable to flux images.")
}
pub(crate) fn dump_format_parser() -> impl Parser<DumpFormat> {
long("format")
.short('f')
.argument::<DumpFormat>("FORMAT")
.help("Specify the dump format: binary, hex, or ascii")
}
pub(crate) fn row_size_parser() -> impl Parser<u8> {
long("row_size")
.argument::<u8>("DUMP_ROW_SIZE")
.help("Specify the number of elements per row in dump output")
.guard(|&size| (8..=128).contains(&size), "Size must be between 8 and 128")
}
// Implement a parser for `StandardFormat`
pub(crate) fn standard_format_parser() -> impl Parser<StandardFormatParam> {
let valid_formats = StandardFormatParam::list()
.iter()
.map(|(param_name, desc)| format!(" {}\t({})", param_name, desc))
.collect::<Vec<String>>()
.join("\n");
long("disk_format")
.help(
format!(
"Specify a standard disk format.\n Valid values include:\n{}",
valid_formats
)
.as_str(),
)
.argument::<String>("STANDARD_DISK_FORMAT")
.parse(|input| input.parse())
}
| rust | MIT | b4c04b51746e5fe7769f49a1b32b8caad426fc81 | 2026-01-04T20:24:04.021295Z | false |
dbalsom/fluxfox | https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/crates/fluxfox_cli/src/prompt.rs | crates/fluxfox_cli/src/prompt.rs | /*
FluxFox - fftool
https://github.com/dbalsom/fluxfox
Copyright 2024-2025 Daniel Balsom
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the “Software”),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
--------------------------------------------------------------------------
prompt.rs
Implement a simple prompt that requires the user to enter 'y' or 'n'.
*/
use std::{io, io::Write};
pub fn prompt(message: &str) -> bool {
loop {
// Display the prompt message without a newline at the end
print!("{}", message);
// Ensure the prompt is shown immediately
io::stdout().flush().expect("Failed to flush stdout");
// Read the user's input
let mut input = String::new();
io::stdin().read_line(&mut input).expect("Failed to read line");
// Process the input: trim whitespace and convert to lowercase
let input = input.trim().to_lowercase();
// Match the input against accepted responses
match input.as_str() {
"y" | "yes" => return true, // User answered 'yes'
"n" | "no" => return false, // User answered 'no'
_ => {
// Invalid input, prompt again
println!("Please enter 'y' or 'n'.");
}
}
}
}
| rust | MIT | b4c04b51746e5fe7769f49a1b32b8caad426fc81 | 2026-01-04T20:24:04.021295Z | false |
dbalsom/fluxfox | https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/crates/fluxfox_cli/src/main.rs | crates/fluxfox_cli/src/main.rs | /*
fftool
https://github.com/dbalsom/fluxfox
Copyright 2024-2025 Daniel Balsom
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the “Software”),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
--------------------------------------------------------------------------
*/
pub mod args;
pub mod convert;
pub mod create;
pub mod dump;
mod find;
pub mod info;
mod prompt;
use anyhow::Error;
use bpaf::Parser;
use std::{io::Cursor, path::Path};
use crate::args::Command;
use args::command_parser;
fn main() -> Result<(), Error> {
env_logger::init();
let app_params = command_parser().run();
let command_result = match &app_params.command {
Command::Version => {
println!("fftool v{}", env!("CARGO_PKG_VERSION"));
Ok(())
}
Command::Find(params) => find::run(&app_params.global, params),
Command::Convert(params) => convert::run(&app_params.global, params),
Command::Create(params) => create::run(&app_params.global, params),
Command::Dump(params) => dump::run(&app_params.global, params),
Command::Info(params) => info::run(&app_params.global, params),
};
match command_result {
Ok(_) => Ok(()),
Err(e) => {
eprintln!("Command '{}' failed: {}", app_params.command, e);
for cause in e.chain().skip(1) {
eprintln!("Caused by: {}", cause);
}
std::process::exit(1);
}
}
}
pub(crate) fn read_file(path: &Path) -> Result<Cursor<Vec<u8>>, Error> {
let buffer = std::fs::read(path)?;
Ok(Cursor::new(buffer))
}
| rust | MIT | b4c04b51746e5fe7769f49a1b32b8caad426fc81 | 2026-01-04T20:24:04.021295Z | false |
dbalsom/fluxfox | https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/crates/fluxfox_cli/src/find/args.rs | crates/fluxfox_cli/src/find/args.rs | /*
fluxfox - fftool
https://github.com/dbalsom/fluxfox
Copyright 2024-2025 Daniel Balsom
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the “Software”),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
--------------------------------------------------------------------------
*/
use crate::args::{
cylinder_parser,
dump_format_parser,
head_parser,
in_file_parser,
phys_cylinder_parser,
phys_head_parser,
row_size_parser,
sector_parser,
DumpFormat,
};
use bpaf::{construct, long, Parser};
use std::path::PathBuf;
#[allow(dead_code)]
#[derive(Clone, Debug)]
pub(crate) struct FindParams {
pub(crate) in_file: PathBuf,
pub(crate) ascii: Option<String>,
pub(crate) hex: Option<String>,
pub(crate) head: Option<u8>,
pub(crate) cylinder: Option<u16>,
pub(crate) sector: Option<u8>,
pub(crate) phys_head: Option<u8>,
pub(crate) phys_cylinder: Option<u16>,
pub(crate) dump: bool,
pub(crate) format: Option<DumpFormat>,
pub(crate) row_size: Option<u8>,
}
fn dump_parser() -> impl Parser<bool> {
long("dump")
.short('d')
.help("Dump the sector where the match is found")
.switch()
}
fn ascii_parser() -> impl Parser<String> {
long("ascii")
.argument::<String>("ASCII_STRING")
.help("Search for ASCII string")
}
fn hex_parser() -> impl Parser<String> {
long("hex")
.argument::<String>("HEX_STRING")
.help("Search for hexadecimal string")
}
pub(crate) fn find_parser() -> impl Parser<FindParams> {
//let path = positional::<String>("PATH").help("Path to the file to dump");
let in_file = in_file_parser();
let head = head_parser().optional();
let ascii = ascii_parser().optional();
let hex = hex_parser().optional();
let cylinder = cylinder_parser().optional();
let phys_cylinder = phys_cylinder_parser().optional();
let phys_head = phys_head_parser().optional();
let sector = sector_parser().optional();
let dump = dump_parser();
let format = dump_format_parser().optional();
let row_size = row_size_parser().optional();
construct!(FindParams {
in_file,
ascii,
hex,
head,
cylinder,
sector,
phys_head,
phys_cylinder,
dump,
format,
row_size
})
.guard(
|params| params.ascii.is_some() || params.hex.is_some(),
"Either --ascii or --hex must be specified",
)
}
| rust | MIT | b4c04b51746e5fe7769f49a1b32b8caad426fc81 | 2026-01-04T20:24:04.021295Z | false |
dbalsom/fluxfox | https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/crates/fluxfox_cli/src/find/mod.rs | crates/fluxfox_cli/src/find/mod.rs | /*
fluxfox - fftool
https://github.com/dbalsom/fluxfox
Copyright 2024-2025 Daniel Balsom
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the “Software”),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
--------------------------------------------------------------------------
*/
use crate::{args::GlobalOptions, find::args::FindParams};
use anyhow::Error;
pub mod args;
pub(crate) fn run(_global: &GlobalOptions, _params: &FindParams) -> Result<(), Error> {
println!("Find command not implemented yet");
Ok(())
}
| rust | MIT | b4c04b51746e5fe7769f49a1b32b8caad426fc81 | 2026-01-04T20:24:04.021295Z | false |
dbalsom/fluxfox | https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/crates/fluxfox_cli/src/dump/args.rs | crates/fluxfox_cli/src/dump/args.rs | /*
fftool
https://github.com/dbalsom/fluxfox
Copyright 2024-2025 Daniel Balsom
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the “Software”),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
--------------------------------------------------------------------------
*/
use crate::args::*;
use bpaf::{construct, long, Parser};
use std::path::PathBuf;
#[derive(Clone, Debug)]
pub(crate) struct DumpParams {
pub(crate) in_file: PathBuf,
pub(crate) head: u8,
pub(crate) cylinder: u16,
pub(crate) sector: Option<u8>,
pub(crate) n: Option<u8>,
pub(crate) phys_head: Option<u8>,
pub(crate) phys_cylinder: Option<u16>,
#[allow(dead_code)]
pub(crate) format: Option<DumpFormat>,
pub(crate) dupe_mark: bool,
pub(crate) row_size: Option<u8>,
pub(crate) raw: bool,
pub(crate) rev: Option<u8>,
pub(crate) clock_map: bool,
pub(crate) bit_address: bool,
}
fn dupe_mark_parser() -> impl Parser<bool> {
long("dupe_mark").help("Dump the duplication mark if present").switch()
}
fn raw_parser() -> impl Parser<bool> {
long("raw")
.help("Dump the raw sector data (only valid for bitstream images or higher)")
.switch()
}
fn clock_map_parser() -> impl Parser<bool> {
long("clock_map")
.help("Dump the track clock map (only valid for bitstream images or higher)")
.switch()
}
fn bit_address_parser() -> impl Parser<bool> {
long("bit_address")
.help("Show dump address as track bitcell offset")
.switch()
}
pub(crate) fn dump_parser() -> impl Parser<DumpParams> {
//let path = positional::<String>("PATH").help("Path to the file to dump");
let in_file = in_file_parser();
let head = head_parser();
let cylinder = cylinder_parser();
let n = n_parser().optional();
let phys_cylinder = phys_cylinder_parser().optional();
let phys_head = phys_head_parser().optional();
let sector = sector_parser().optional();
let format = dump_format_parser().optional();
let dupe_mark = dupe_mark_parser();
let row_size = row_size_parser().optional();
let raw = raw_parser();
let rev = rev_parser().optional();
let clock_map = clock_map_parser();
let bit_address = bit_address_parser();
construct!(DumpParams {
in_file,
head,
cylinder,
sector,
n,
phys_head,
phys_cylinder,
format,
dupe_mark,
row_size,
raw,
rev,
clock_map,
bit_address
})
}
| rust | MIT | b4c04b51746e5fe7769f49a1b32b8caad426fc81 | 2026-01-04T20:24:04.021295Z | false |
dbalsom/fluxfox | https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/crates/fluxfox_cli/src/dump/mod.rs | crates/fluxfox_cli/src/dump/mod.rs | /*
fluxfox - fftool
https://github.com/dbalsom/fluxfox
Copyright 2024-2025 Daniel Balsom
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the “Software”),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
--------------------------------------------------------------------------
*/
pub(crate) mod args;
use crate::{args::GlobalOptions, dump::args::DumpParams, read_file};
use anyhow::{bail, Error, Result};
use fluxfox::prelude::*;
use std::io::{BufWriter, Write};
pub(crate) fn run(global: &GlobalOptions, params: &args::DumpParams) -> Result<(), Error> {
let row_size = params.row_size.unwrap_or(16) as usize;
let mut cursor = read_file(¶ms.in_file)?;
let disk_image_type = match DiskImage::detect_format(&mut cursor, Some(¶ms.in_file)) {
Ok(disk_image_type) => disk_image_type,
Err(e) => {
eprintln!("Error detecting disk image type: {}", e);
std::process::exit(1);
}
};
if !global.silent {
println!("Detected disk image type: {}", disk_image_type);
}
let mut disk = match DiskImage::load(&mut cursor, Some(¶ms.in_file), None, None) {
Ok(disk) => disk,
Err(e) => {
eprintln!("Error loading disk image: {}", e);
std::process::exit(1);
}
};
let mut buf = BufWriter::new(std::io::stdout());
if params.dupe_mark {
if let Some((dupe_ch, dupe_chsn)) = disk.find_duplication_mark() {
let _rsr = match disk.read_sector(
dupe_ch,
DiskChsnQuery::from(dupe_chsn),
None,
None,
RwScope::DataOnly,
true,
) {
Ok(rsr) => rsr,
Err(e) => {
bail!("Error reading sector: {}", e);
}
};
let dump_string = match disk.dump_sector_string(dupe_ch, DiskChsnQuery::from(dupe_chsn), None, None) {
Ok(dump_string) => dump_string,
Err(e) => {
bail!("Error dumping sector: {}", e);
}
};
//println!("Duplication mark found at {} with ID {}", dupe_ch, dupe_chsn);
println!("{}", dump_string);
std::process::exit(0);
}
else {
println!("No duplication mark found.");
}
}
// Specify the physical cylinder and head. If these are not explicitly provided, we assume
// that the physical cylinder and head are the same as the target cylinder and head.
let mut phys_ch = DiskCh::new(params.cylinder, params.head);
if let Some(phys_cylinder) = params.phys_cylinder {
phys_ch.set_c(phys_cylinder);
}
if let Some(phys_head) = params.phys_head {
phys_ch.set_h(phys_head);
}
let track_mut_opt = disk.track_mut(phys_ch);
let track_mut = match track_mut_opt {
Some(track_mut) => track_mut,
None => {
bail!("Specified track: {} not found.", phys_ch);
}
};
if let Some(rev) = params.rev {
if let Some(flux_track) = track_mut.as_fluxstream_track_mut() {
flux_track.set_revolution(rev as usize);
}
else {
bail!("Revolution number specified but track is not a flux track.");
}
}
// If sector was provided, dump the sector.
if let Some(sector) = params.sector {
// Dump the specified sector in hex format to stdout.
let id_chs = DiskChs::new(params.cylinder, params.head, sector);
let scope = RwScope::DataOnly;
let calc_crc = false;
// let (scope, calc_crc) = match params.structure {
// true => (RwSectorScope::DataBlock, true),
// false => (RwSectorScope::DataOnly, false),
// };
_ = writeln!(&mut buf, "reading sector...");
_ = buf.flush();
let rsr = match disk.read_sector(phys_ch, DiskChsnQuery::from(id_chs), params.n, None, scope, true) {
Ok(rsr) => rsr,
Err(e) => {
bail!("Error reading sector: {}", e);
}
};
_ = writeln!(
&mut buf,
"Data idx: {} length: {}",
rsr.data_range.start,
rsr.data_range.len()
);
let data_slice = rsr.data();
if !global.silent {
println!(
"Dumping sector from track {} with id {} in hex format, with scope {:?}:",
phys_ch,
DiskChsn::from((id_chs, params.n.unwrap_or(2))),
scope
);
}
if data_slice.len() >= 16 {
log::debug!("read buf: {:02X?}", &rsr.read_buf[0..16]);
log::debug!("data slice: {:02X?}", &data_slice[0..16]);
}
_ = fluxfox::util::dump_slice(data_slice, 0, row_size, 1, &mut buf);
// If we requested DataBlock scope, we can independently calculate the CRC, so do that now.
if calc_crc {
let calculated_crc = fluxfox::util::crc_ibm_3740(&data_slice[0..0x104], None);
_ = writeln!(&mut buf, "Calculated CRC: {:04X}", calculated_crc);
}
Ok(())
}
else {
// No sector was provided, dump the whole track.
let ch = DiskCh::new(params.cylinder, params.head);
if params.clock_map {
dump_clock_map(&mut disk, row_size, ch, &mut buf, global, params)?;
}
else {
dump_track(&mut disk, row_size, ch, &mut buf, global, params)?;
}
Ok(())
}
}
fn dump_track<W: Write>(
disk: &mut DiskImage,
row_size: usize,
ch: DiskCh,
buf: &mut W,
global: &GlobalOptions,
params: &DumpParams,
) -> Result<()> {
if params.raw {
let track = match disk.track_mut(ch) {
Some(track) => track,
None => {
bail!("Specified track: {} not found.", ch);
}
};
if !global.silent {
println!(
"Dumping track {} ({}, {} bits), raw, in hex format:",
ch,
track.info().encoding,
track.info().bit_length
);
}
let rtr = match track.read_raw(None) {
Ok(rtr) => {
//println!("* read track raw *");
rtr
}
Err(e) => {
bail!("Error reading track: {}", e);
}
};
// In raw format, one byte = 8 bits, and it takes 2 bytes to represent 1 decoded byte.
let element_size = match params.bit_address {
true => 8,
false => 2,
};
_ = fluxfox::util::dump_slice(&rtr.read_buf, 0, row_size, element_size, buf);
}
else {
let track = match disk.track_mut(ch) {
Some(track) => track,
None => {
bail!("Specified track: {} not found.", ch);
}
};
if !global.silent {
println!(
"Dumping track {} ({}, {} bits), decoded, in hex format:",
ch,
track.info().encoding,
track.info().bit_length
);
}
let rtr = match disk.read_track(ch, None) {
Ok(rtr) => {
//println!("* read track *");
rtr
}
Err(e) => {
bail!("Error reading track: {}", e);
}
};
// Each byte of the track is 16 MFM bits.
let element_size = match params.bit_address {
true => 16,
false => 1,
};
_ = fluxfox::util::dump_slice(&rtr.read_buf, 0, row_size, element_size, buf);
};
Ok(())
}
fn dump_clock_map<W: Write>(
disk: &mut DiskImage,
row_size: usize,
ch: DiskCh,
buf: &mut W,
global: &GlobalOptions,
_params: &DumpParams,
) -> Result<()> {
let track = match disk.track_mut(ch) {
Some(track) => track,
None => {
bail!("Specified track: {} not found.", ch);
}
};
if !global.silent {
println!(
"Dumping clock map for track {} ({}, {} bits), raw, in hex format:",
ch,
track.info().encoding,
track.info().bit_length
);
}
if let Some(codec) = track.stream_mut() {
let map_vec = codec.clock_map().to_bytes();
_ = fluxfox::util::dump_slice(&map_vec, 0, row_size, 8, buf);
}
else {
bail!("Failed to resolve track codec");
}
Ok(())
}
| rust | MIT | b4c04b51746e5fe7769f49a1b32b8caad426fc81 | 2026-01-04T20:24:04.021295Z | false |
dbalsom/fluxfox | https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/crates/fluxfox_cli/src/create/args.rs | crates/fluxfox_cli/src/create/args.rs | /*
fftool
https://github.com/dbalsom/fluxfox
Copyright 2024-2025 Daniel Balsom
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the “Software”),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
--------------------------------------------------------------------------
*/
use crate::args::*;
use bpaf::{construct, long, Parser};
use fluxfox::prelude::*;
use std::path::PathBuf;
#[derive(Clone, Debug)]
pub(crate) struct CreateParams {
pub(crate) out_file: PathBuf,
pub(crate) disk_format: StandardFormatParam,
pub(crate) formatted: bool,
pub(crate) sector_test: bool,
}
pub(crate) fn create_parser() -> impl Parser<CreateParams> {
let out_file = out_file_parser();
let disk_format = standard_format_parser();
let formatted = long("formatted").switch().help("Format the new disk image.");
let sector_test = long("sector_test")
.switch()
.help("Create a sector test image [internal use].");
construct!(CreateParams {
out_file,
disk_format,
formatted,
sector_test,
})
}
| rust | MIT | b4c04b51746e5fe7769f49a1b32b8caad426fc81 | 2026-01-04T20:24:04.021295Z | false |
dbalsom/fluxfox | https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/crates/fluxfox_cli/src/create/mod.rs | crates/fluxfox_cli/src/create/mod.rs | /*
fftool
https://github.com/dbalsom/fluxfox
Copyright 2024-2025 Daniel Balsom
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the “Software”),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
--------------------------------------------------------------------------
*/
pub mod args;
use crate::args::GlobalOptions;
use anyhow::{anyhow, bail, Error};
use fluxfox::prelude::*;
pub(crate) fn run(global: &GlobalOptions, params: &args::CreateParams) -> Result<(), Error> {
// Get extension from output filename
let ext_str = params
.out_file
.extension()
.and_then(|ext| ext.to_str())
.ok_or_else(|| anyhow!("Error: Invalid or missing output file extension!"))?;
let output_format =
format_from_ext(ext_str).ok_or_else(|| anyhow!("Error: Unknown output file extension: {}", ext_str))?;
global.loud(|| println!("Output disk image format requested: {}", output_format));
if matches!(
output_format.can_write(None),
ParserWriteCompatibility::UnsupportedFormat
) {
bail!("Requested format {} does not support image writing.", output_format);
}
// Override the resolution for raw sector images, at least until we implement formatting MetaSector images.
let create_resolution = match output_format {
DiskImageFileFormat::RawSectorImage => TrackDataResolution::BitStream,
_ => output_format.resolution(),
};
global.loud(|| println!("Creating disk image of resolution {:?}", create_resolution));
// Create a DiskImage using ImageBuilder
let mut disk = match ImageBuilder::new()
.with_resolution(create_resolution)
.with_standard_format(params.disk_format)
.with_formatted(params.formatted | params.sector_test)
.build()
{
Ok(disk) => {
log::debug!("Disk image created of Ch: {}", disk.geometry());
global.loud(|| println!("Disk image created of Ch: {}", disk.geometry()));
disk
}
Err(e) => {
bail!("Error creating disk image: {}", e);
}
};
// Create a sector test image if requested.
if params.sector_test {
// Iterate through all sectors, skipping the boot sector, and write the sector index to the sector.
let layout = StandardFormat::from(params.disk_format).layout();
for (idx, sector) in layout.chsn_iter().skip(1).enumerate() {
let sector_value = (idx + 1) as u8; // Let the sector value roll over at 255.
// Write the sector value to the sector.
match disk.write_sector_basic(sector.ch(), sector.into(), None, &vec![sector_value; layout.size()]) {
Ok(()) => {
global.loud(|| println!("Wrote sector {} with value {}", sector, sector_value));
}
Err(e) => {
bail!("Error writing sector {}: {}", sector, e);
}
}
}
}
// Write the image with an ImageWriter
match ImageWriter::new(&mut disk)
.with_format(output_format)
.with_path(params.out_file.clone())
.write()
{
Ok(()) => {
global.loud(|| println!("Disk image successfully written to {}", params.out_file.display()));
Ok(())
}
Err(e) => {
bail!("Error opening disk image for writing: {}", e);
}
}
}
| rust | MIT | b4c04b51746e5fe7769f49a1b32b8caad426fc81 | 2026-01-04T20:24:04.021295Z | false |
dbalsom/fluxfox | https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/crates/fluxfox_cli/src/info/args.rs | crates/fluxfox_cli/src/info/args.rs | /*
fftool
https://github.com/dbalsom/fluxfox
Copyright 2024-2025 Daniel Balsom
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the “Software”),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
--------------------------------------------------------------------------
*/
use crate::args::in_file_parser;
use bpaf::{construct, Parser};
use std::path::PathBuf;
#[derive(Clone, Debug)]
pub(crate) struct InfoParams {
// Define specific parameters for `info`
pub(crate) in_file: PathBuf,
pub(crate) sector_list: bool,
pub(crate) track_list: bool,
pub(crate) rev_list: bool,
}
fn sector_list_parser() -> impl Parser<bool> {
bpaf::long("sector-list")
.help("List all sectors in the disk image")
.switch()
}
fn track_list_parser() -> impl Parser<bool> {
bpaf::long("track-list")
.help("List all tracks in the disk image")
.switch()
}
fn rev_list_parser() -> impl Parser<bool> {
bpaf::long("rev-list")
.help("List all revolutions in the disk image")
.switch()
}
pub(crate) fn info_parser() -> impl Parser<InfoParams> {
let in_file = in_file_parser();
let sector_list = sector_list_parser();
let track_list = track_list_parser();
let rev_list = rev_list_parser();
construct!(InfoParams {
in_file,
sector_list,
track_list,
rev_list,
})
}
| rust | MIT | b4c04b51746e5fe7769f49a1b32b8caad426fc81 | 2026-01-04T20:24:04.021295Z | false |
dbalsom/fluxfox | https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/crates/fluxfox_cli/src/info/mod.rs | crates/fluxfox_cli/src/info/mod.rs | /*
fftool
https://github.com/dbalsom/fluxfox
Copyright 2024-2025 Daniel Balsom
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the “Software”),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
--------------------------------------------------------------------------
*/
use crate::{args::GlobalOptions, read_file};
use anyhow::{bail, Error};
use fluxfox::{flux::FluxRevolutionType, prelude::*};
pub mod args;
pub(crate) fn run(_global: &GlobalOptions, params: &args::InfoParams) -> Result<(), Error> {
let mut reader = read_file(¶ms.in_file)?;
let disk_image_type = match DiskImage::detect_format(&mut reader, Some(¶ms.in_file)) {
Ok(disk_image_type) => disk_image_type,
Err(e) => {
bail!("Error detecting disk image type: {}", e);
}
};
println!("Detected disk image type: {}", disk_image_type);
let mut disk = match DiskImage::load(&mut reader, Some(¶ms.in_file), None, None) {
Ok(disk) => disk,
Err(e) => {
bail!("Error loading disk image: {}", e);
}
};
println!("Disk image info:");
println!("{}", "-".repeat(79));
let _ = disk.dump_info(&mut std::io::stdout());
println!();
println!("Disk analysis:");
println!("{}", "-".repeat(79));
let _ = disk.dump_analysis(&mut std::io::stdout());
println!("Image can be represented by the following formats with write support:");
let formats = disk.compatible_formats(true);
for format in formats {
println!(" {} [{}]", format.0, format.1.join(", "));
}
if let Some(bootsector) = disk.boot_sector() {
println!("Disk has a boot sector");
if bootsector.has_valid_bpb() {
println!("Boot sector with valid BPB detected:");
println!("{}", "-".repeat(79));
let _ = bootsector.dump_bpb(&mut std::io::stdout());
}
else {
println!("Boot sector has an invalid BPB");
}
}
println!();
if params.track_list || params.sector_list || params.rev_list {
let _ = dump_track_map(&mut std::io::stdout(), &disk, params.sector_list, params.rev_list);
}
Ok(())
}
pub fn dump_track_map<W: std::io::Write>(
mut out: W,
disk: &DiskImage,
sectors: bool,
revolutions: bool,
) -> Result<(), Error> {
let head_map = disk.sector_map();
for (head_idx, head) in head_map.iter().enumerate() {
out.write_fmt(format_args!("Head {} [{} tracks]\n", head_idx, head.len()))?;
for (track_idx, track) in head.iter().enumerate() {
let ch = DiskCh::new(track_idx as u16, head_idx as u8);
if let Some(track_ref) = disk.track(ch) {
match track_ref.resolution() {
TrackDataResolution::MetaSector => {
out.write_fmt(format_args!("\tTrack {}\n", track_idx))?;
}
TrackDataResolution::FluxStream | TrackDataResolution::BitStream => {
let stream = track_ref.stream().expect("Couldn't retrieve track stream!");
out.write_fmt(format_args!(
"\tTrack {}: [{} encoding, {} bits]\n",
track_idx,
track_ref.encoding(),
stream.len()
))?;
}
}
if revolutions {
if let Some(flux_track) = track_ref.as_fluxstream_track() {
let source_ct = flux_track
.revolution_iter()
.filter(|r| matches!(r.stats().rev_type, FluxRevolutionType::Source))
.count();
out.write_fmt(format_args!("\t\tSource Revolutions ({}):\n", source_ct))?;
for revolution in flux_track
.revolution_iter()
.filter(|r| matches!(r.stats().rev_type, FluxRevolutionType::Source))
{
let rev_stats = revolution.stats();
out.write_fmt(format_args!(
"\t\t\tFlux ct: {} Bitcells: {} First ft: {:.4} Last ft: {:.4}\n",
rev_stats.ft_ct,
rev_stats.bitcell_ct,
rev_stats.first_ft * 1e6,
rev_stats.last_ft * 1e6
))?;
}
let synthetic_count = flux_track.revolution_ct() - source_ct;
if synthetic_count > 0 {
out.write_fmt(format_args!(
"\t\tSynthetic Revolutions ({}):\n",
flux_track.revolution_ct() - source_ct
))?;
for revolution in flux_track
.revolution_iter()
.filter(|r| matches!(r.stats().rev_type, FluxRevolutionType::Synthetic))
{
let rev_stats = revolution.stats();
out.write_fmt(format_args!(
"\t\t\tFlux ct: {} Bitcells: {} First ft: {:.4} Last ft: {:.4}\n",
rev_stats.ft_ct,
rev_stats.bitcell_ct,
rev_stats.first_ft * 1e6,
rev_stats.last_ft * 1e6
))?;
}
}
}
}
if sectors {
out.write_fmt(format_args!("\t\tSectors ({}):\n", track.len()))?;
for sector in track {
out.write_fmt(format_args!(
"\t\t\t{} address_crc_valid: {} data_crc_valid: {} deleted: {}\n",
sector.chsn,
!sector.attributes.address_error,
!sector.attributes.data_error,
sector.attributes.deleted_mark
))?;
}
}
}
}
}
Ok(())
}
| rust | MIT | b4c04b51746e5fe7769f49a1b32b8caad426fc81 | 2026-01-04T20:24:04.021295Z | false |
dbalsom/fluxfox | https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/crates/fluxfox_cli/src/convert/args.rs | crates/fluxfox_cli/src/convert/args.rs | /*
fftool
https://github.com/dbalsom/fluxfox
Copyright 2024-2025 Daniel Balsom
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the “Software”),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
--------------------------------------------------------------------------
*/
use crate::args::*;
use bpaf::{construct, long, Parser};
use std::path::PathBuf;
#[derive(Clone, Debug)]
pub(crate) struct ConvertParams {
pub(crate) in_file: PathBuf,
pub(crate) out_file: PathBuf,
#[allow(dead_code)]
pub(crate) weak_to_holes: bool,
pub(crate) prolok: bool,
}
fn weak_to_holes_parser() -> impl Parser<bool> {
long("weak-to-holes").switch().help("Convert weak bits to holes")
}
fn prolok_parser() -> impl Parser<bool> {
long("prolok")
.switch()
.help("Convert weak bits to holes on Prolok-protected tracks")
}
pub(crate) fn convert_parser() -> impl Parser<ConvertParams> {
//let path = positional::<String>("PATH").help("Path to the file to dump");
let in_file = in_file_parser();
let out_file = out_file_parser();
let weak_to_holes = weak_to_holes_parser();
let prolok = prolok_parser();
construct!(ConvertParams {
in_file,
out_file,
weak_to_holes,
prolok,
})
}
| rust | MIT | b4c04b51746e5fe7769f49a1b32b8caad426fc81 | 2026-01-04T20:24:04.021295Z | false |
dbalsom/fluxfox | https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/crates/fluxfox_cli/src/convert/mod.rs | crates/fluxfox_cli/src/convert/mod.rs | /*
fftool
https://github.com/dbalsom/fluxfox
Copyright 2024-2025 Daniel Balsom
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the “Software”),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
--------------------------------------------------------------------------
*/
pub mod args;
use crate::{args::GlobalOptions, prompt, read_file};
use anyhow::{bail, Error};
use fluxfox::prelude::*;
use std::io::Cursor;
pub(crate) fn run(global: &GlobalOptions, params: &args::ConvertParams) -> Result<(), Error> {
let mut reader = read_file(¶ms.in_file.clone())?;
let disk_image_type = match DiskImage::detect_format(&mut reader, Some(¶ms.in_file)) {
Ok(disk_image_type) => disk_image_type,
Err(e) => {
bail!("Error detecting input disk image type: {}", e);
}
};
if !global.silent {
println!("Input disk image type: {}", disk_image_type);
}
// Get extension from output filename
let output_extension = match params.out_file.extension() {
Some(ext) => ext,
None => {
bail!("Error: A file extension is required for the output file!");
}
};
let ext_str = match output_extension.to_str() {
Some(ext) => ext,
None => {
bail!("Error: Invalid output file extension!");
}
};
let output_format = match format_from_ext(ext_str) {
Some(format) => format,
None => {
bail!("Error: Unknown output file extension: {}", ext_str);
}
};
println!("Output disk image type: {}", output_format);
//std::process::exit(0);
// Load disk image
let mut in_disk = match DiskImage::load(&mut reader, Some(¶ms.in_file), None, None) {
Ok(disk) => disk,
Err(e) => {
bail!("Error loading disk image: {}", e);
}
};
if in_disk.has_weak_bits() {
println!("Input disk image contains a weak bit mask.");
}
if params.prolok {
in_disk.set_flag(fluxfox::types::DiskImageFlags::PROLOK);
println!("PROLOK holes will be created in output image.");
}
match output_format.can_write(Some(&in_disk)) {
ParserWriteCompatibility::Ok => {
println!("Output format is compatible with input image.");
}
ParserWriteCompatibility::Incompatible | ParserWriteCompatibility::UnsupportedFormat => {
eprintln!("Error: Output format {} cannot write specified image!", output_format);
std::process::exit(1);
}
ParserWriteCompatibility::DataLoss => {
eprintln!("Warning: Output format {} may lose data!", output_format);
prompt::prompt("Continue with potential data loss? (y/n)");
}
}
// Create an output buffer
let mut out_buffer = Cursor::new(Vec::new());
match output_format.save_image(&mut in_disk, &ParserWriteOptions::default(), &mut out_buffer) {
Ok(_) => {
let out_inner: Vec<u8> = out_buffer.into_inner();
match std::fs::write(params.out_file.clone(), out_inner) {
Ok(_) => {
println!("Output image saved to {}", params.out_file.display());
Ok(())
}
Err(e) => {
bail!("Error saving output image: {}", e);
}
}
}
Err(e) => {
bail!("Error saving output image: {}", e);
}
}
}
| rust | MIT | b4c04b51746e5fe7769f49a1b32b8caad426fc81 | 2026-01-04T20:24:04.021295Z | false |
dbalsom/fluxfox | https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/crates/fluxfox_svg/src/render_display_list.rs | crates/fluxfox_svg/src/render_display_list.rs | /*
FluxFox
https://github.com/dbalsom/fluxfox
Copyright 2024-2025 Daniel Balsom
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the “Software”),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
--------------------------------------------------------------------------
*/
use crate::{render_elements::*, styles::ElementStyle};
use fluxfox::{
track_schema::GenericTrackElement,
visualization::{
prelude::VizRect,
types::display_list::{VizDataSliceDisplayList, VizElementDisplayList},
},
FoxHashMap,
};
use svg::node::element::Group;
pub fn render_display_list_as_svg(
viewbox: VizRect<f32>,
angle: f32,
display_list: &VizElementDisplayList,
track_style: &ElementStyle,
element_styles: &FoxHashMap<GenericTrackElement, ElementStyle>,
) -> Group {
let center = viewbox.center();
let angle_degrees = angle.to_degrees();
// Rotate around the center of the viewbox
let mut group = Group::new().set(
"transform",
format!("rotate({} {:.3} {:.3})", angle_degrees, center.x, center.y),
);
for element in display_list.iter() {
let node = svg_render_element(element, track_style, element_styles);
match node {
RenderNode::Path(path) => {
group = group.add(path);
}
RenderNode::Circle(circle) => {
group = group.add(circle);
}
}
}
group
}
pub fn render_data_display_list_as_svg(
viewbox: VizRect<f32>,
angle: f32,
display_list: &VizDataSliceDisplayList,
) -> Group {
let center = viewbox.center();
let angle_degrees = angle.to_degrees();
// Rotate around the center of the viewbox
let mut group = Group::new().set(
"transform",
format!("rotate({} {:.3} {:.3})", angle_degrees, center.x, center.y),
);
for slice in display_list.iter() {
let path = svg_render_data_slice(slice, display_list.track_width);
group = group.add(path);
}
// Turn off antialiasing to avoid moiré artifacts
group.set("shape-rendering", "crispEdges")
}
| rust | MIT | b4c04b51746e5fe7769f49a1b32b8caad426fc81 | 2026-01-04T20:24:04.021295Z | false |
dbalsom/fluxfox | https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/crates/fluxfox_svg/src/prelude.rs | crates/fluxfox_svg/src/prelude.rs | /*
FluxFox
https://github.com/dbalsom/fluxfox
Copyright 2024-2025 Daniel Balsom
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the “Software”),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
--------------------------------------------------------------------------
*/
pub use crate::{document::*, overlays::*, renderer::SvgRenderer, styles::*};
| rust | MIT | b4c04b51746e5fe7769f49a1b32b8caad426fc81 | 2026-01-04T20:24:04.021295Z | false |
dbalsom/fluxfox | https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/crates/fluxfox_svg/src/lib.rs | crates/fluxfox_svg/src/lib.rs | /*
FluxFox
https://github.com/dbalsom/fluxfox
Copyright 2024-2025 Daniel Balsom
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the “Software”),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
--------------------------------------------------------------------------
*/
pub mod prelude;
mod document;
mod overlays;
mod render_display_list;
mod render_elements;
mod render_overlays;
mod renderer;
mod styles;
// Re-export svg
pub use svg;
pub const DEFAULT_DATA_SLICES: usize = 1440;
pub const DEFAULT_VIEW_BOX: f32 = 512.0;
| rust | MIT | b4c04b51746e5fe7769f49a1b32b8caad426fc81 | 2026-01-04T20:24:04.021295Z | false |
dbalsom/fluxfox | https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/crates/fluxfox_svg/src/render_elements.rs | crates/fluxfox_svg/src/render_elements.rs | /*
FluxFox
https://github.com/dbalsom/fluxfox
Copyright 2024-2025 Daniel Balsom
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the “Software”),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
--------------------------------------------------------------------------
*/
use crate::styles::ElementStyle;
use fluxfox::{
track_schema::GenericTrackElement,
visualization::{
prelude::{VizArc, VizColor, VizDataSlice, VizElement, VizQuadraticArc, VizSector},
types::shapes::{VizElementFlags, VizShape},
},
FoxHashMap,
};
use svg::node::{
element::{path::Data, Circle, Path},
Value,
};
#[derive(Clone, Debug)]
pub enum RenderNode {
Path(Path),
Circle(Circle),
}
pub(crate) fn viz_color_to_value(color: VizColor) -> Value {
if color.a == 0 {
// Fully transparent, return 'none' to prevent rendering
Value::from("none")
}
else if color.a < 255 {
// Convert to rgba() string if alpha is present
Value::from(format!(
"rgba({}, {}, {}, {:.3})",
color.r,
color.g,
color.b,
color.a as f32 / 255.0 // Alpha normalized to [0.0, 1.0]
))
}
else {
// Convert to hex string if fully opaque
Value::from(format!("#{:02X}{:02X}{:02X}", color.r, color.g, color.b))
}
}
fn svg_render_arc(data: Data, arc: &VizArc, line_to: bool) -> Data {
let data = if line_to {
data.line_to((arc.start.x, arc.start.y)) // Draw a line to start
}
else {
data.move_to((arc.start.x, arc.start.y)) // Move without drawing
};
data.cubic_curve_to(((arc.cp1.x, arc.cp1.y), (arc.cp2.x, arc.cp2.y), (arc.end.x, arc.end.y)))
}
fn svg_render_quadratic_arc(data: Data, arc: &VizQuadraticArc, line_to: bool) -> Data {
let data = if line_to {
data.line_to((arc.start.x, arc.start.y)) // Draw a line to start
}
else {
data.move_to((arc.start.x, arc.start.y)) // Move without drawing
};
data.quadratic_curve_to(((arc.cp.x, arc.cp.y), (arc.end.x, arc.end.y)))
}
fn svg_render_sector(data: Data, sector: &VizSector) -> Data {
let mut data = svg_render_arc(data, §or.inner, false);
data = svg_render_arc(data, §or.outer, true);
data.line_to((sector.inner.start.x, sector.inner.start.y))
}
/// Render shapes as paths. Notably we do not render circles here as they are not paths!
fn svg_render_shape(data: Data, shape: &VizShape) -> Data {
match shape {
VizShape::CubicArc(arc, _h) => svg_render_arc(data, arc, false),
VizShape::QuadraticArc(arc, _h) => svg_render_quadratic_arc(data, arc, false),
VizShape::Sector(sector) => svg_render_sector(data, sector),
_ => data,
}
}
pub fn svg_render_element(
element: &VizElement,
track_style: &ElementStyle,
element_styles: &FoxHashMap<GenericTrackElement, ElementStyle>,
) -> RenderNode {
let mut data = Data::new();
let default_style = ElementStyle::default();
let style = match element.info.element_type {
GenericTrackElement::NullElement => {
// Check if this is a track-level element
if element.flags.contains(VizElementFlags::TRACK) {
track_style
}
else {
&default_style
}
}
_ => element_styles.get(&element.info.element_type).unwrap_or(&default_style),
};
match element.shape {
VizShape::CubicArc(_, _) | VizShape::QuadraticArc(_, _) | VizShape::Sector(_) => {
data = svg_render_shape(data, &element.shape);
}
VizShape::Circle(circle, _) => {
// Circles are not paths, so we do not add to data.
let new_circle = Circle::new()
.set("cx", circle.center.x)
.set("cy", circle.center.y)
.set("r", circle.radius)
.set("fill", viz_color_to_value(style.fill))
.set("stroke", viz_color_to_value(style.stroke))
.set("stroke-width", style.stroke_width);
return RenderNode::Circle(new_circle);
}
_ => {}
};
RenderNode::Path(
Path::new()
.set("d", data)
.set("fill", viz_color_to_value(style.fill))
.set("stroke", viz_color_to_value(style.stroke))
.set("stroke-width", style.stroke_width),
)
}
/// Render a single data slice as an SVG path. Unlike a sector element, a data slice is a single
/// arc with a stroke rendered at the track width.
pub fn svg_render_data_slice(slice: &VizDataSlice, stroke: f32) -> Path {
let mut data = Data::new();
data = svg_render_quadratic_arc(data, &slice.arc, false);
//let adjusted_density = (slice.density * 1.5).clamp(0.0, 1.0);
let value_u8 = slice.mapped_density;
let fill_color = VizColor::from_value(value_u8, 255);
Path::new()
.set("d", data)
.set("stroke", viz_color_to_value(fill_color))
.set("stroke-width", stroke)
}
| rust | MIT | b4c04b51746e5fe7769f49a1b32b8caad426fc81 | 2026-01-04T20:24:04.021295Z | false |
dbalsom/fluxfox | https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/crates/fluxfox_svg/src/renderer.rs | crates/fluxfox_svg/src/renderer.rs | /*
FluxFox
https://github.com/dbalsom/fluxfox
Copyright 2024-2025 Daniel Balsom
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the “Software”),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
--------------------------------------------------------------------------
*/
use fluxfox::{prelude::*, track_schema::GenericTrackElement, visualization::prelude::*, FoxHashMap};
use svg::Document;
use web_time::Instant;
use crate::{
render_display_list::{render_data_display_list_as_svg, render_display_list_as_svg},
styles::{default_element_styles, BlendMode, ElementStyle},
DEFAULT_DATA_SLICES,
DEFAULT_VIEW_BOX,
};
use crate::{
document::DocumentLayer,
overlays::Overlay,
prelude::{DocumentSide, RenderedDocument},
render_elements::viz_color_to_value,
render_overlays::svg_to_group,
};
use svg::node::element::Group;
#[derive(Clone, Default)]
pub struct SvgRenderer {
// The view box for a single head. This should be square.
side_view_box: VizRect<f32>,
// The view box for the entire visualization. This can be rectangular.
global_view_box: VizRect<f32>,
// Margins as top, right, bottom, left.
global_margins: (f32, f32, f32, f32),
// Whether to render the data layer.
render_data: bool,
// Maximum outer radius (should not exceed side_view_box.width / 2).
// Will be overridden if outer_radius_ratio is set.
outer_radius: f32,
// The direct inner radius (should not exceed max_outer_radius). Will be overridden if
// inner_radius_ratio is set.
inner_radius: f32,
// Whether to decode the data layer.
decode_data: bool,
// Whether to disable antialiasing for data groups (recommended: true, avoids moiré patterns).
data_crisp: bool,
// The number of segments to render the data layer with. Default is 1440.
data_slices: Option<usize>,
// Whether to render the metadata layer.
render_metadata: bool,
// Whether to render data and metadata layers to separate files,
// or to render them together in a single file.
render_layered: bool,
// Whether to render the sides side-by-side. If false, the sides will be rendered
// in separate documents.
render_side_by_side: bool,
// The spacing between sides when rendering side-by-side. Default is 0.
side_spacing: f32,
// The CSS blend mode to apply to the metadata layer if `render_layered` is enabled.
layer_blend_mode: BlendMode,
// The total number of sides to render. Default is 1. Will be overridden if `side_to_render`
// is set.
total_sides_to_render: u8,
// The side to render. Default is 0. If set, this will override `total_sides_to_render`
// to 1.
side_to_render: Option<u8>,
// Specify a single track to render. If isolate_track is set, the track will be rendered with
// width between outer and inner radii.
track_to_render: Option<u16>,
// Specify a single sector to render. If isolate_track is set, the sector will be rendered in
// position on its enclosing track, with the track width between the specified inner and outer
// radii. Otherwise, it will be rendered at its normal position on the disk.
// The second parameter in the tuple is an optional bitcell address, to allow selection of
// sectors when duplicate sector IDs are present. If None, the first matching sector will be
// rendered.
sector_to_render: (Option<DiskChsn>, Option<usize>),
// Flag to control whether turning direction is reversed for the second side.
reverse_turning: bool,
// Style mappings for generic elements. If not set, a default set of styles will be used.
element_styles: FoxHashMap<GenericTrackElement, ElementStyle>,
// Default style for track elements - a solid ring that is the background of each track.
// Default is transparent fill and 0 stroke.
track_style: ElementStyle,
// Internal state
common_params: CommonVizParams,
overlay: Option<Overlay>,
overlay_style: ElementStyle,
data_groups: [Option<Group>; 2],
metadata_groups: [Option<Group>; 2],
overlay_groups: [Option<Group>; 2],
composited_group: Option<Group>,
export_path: Option<String>,
build_error: bool,
error_message: Option<String>,
}
impl SvgRenderer {
pub fn new() -> Self {
Self {
side_view_box: VizRect::from_tuple((0.0, 0.0), (DEFAULT_VIEW_BOX, DEFAULT_VIEW_BOX)),
global_view_box: VizRect::from_tuple((0.0, 0.0), (DEFAULT_VIEW_BOX, DEFAULT_VIEW_BOX)),
element_styles: default_element_styles(),
data_crisp: true,
reverse_turning: true,
// Start at 2 and take the minimum of image heads and 2.
// This can also get set to 1 if a specific side is set.
total_sides_to_render: 2,
overlay_style: Overlay::default_style(),
..Default::default()
}
}
/// Set the view box for a single side. This effectively controls the default "resolution"
/// of the rendered image. The view box should be square, unless you really want a distorted
/// image. If radius is not set, radius will be set to half the height of the view box.
pub fn with_side_view_box(mut self, view_box: VizRect<f32>) -> Self {
self.common_params.radius = Some(view_box.height() / 2.0);
self.side_view_box = view_box;
self
}
/// Set the value of the track gap - ie, the inverse factor if the track width to render.
/// 0.5 will render tracks half as wide as the calculated track width.
/// 0.0 will render tracks at the calculated track width.
/// Value is clamped to the range [0.0, 0.9].
pub fn with_track_gap(mut self, gap: f32) -> Self {
// clamp the value
self.common_params.track_gap = gap.clamp(0.0, 0.9);
self
}
/// Set the global view box. You could use this to control margins, but it's probably better
/// to use the `with_margins` method instead.
pub fn with_global_view_box(mut self, view_box: VizRect<f32>) -> Self {
self.global_view_box = view_box;
self
}
/// Set a flag to render the data layer representation. In vector format, this will render
/// the data layer as a series of segments, stroked with a color representing the average flux
/// density for that segment.
/// # Arguments
/// * `state` - A boolean flag to enable or disable rendering of the data layer.
/// * `segments` - An optional parameter to specify the number of segments to render. If None,
/// the default number of segments will be used. If a value is provided, it will be clamped
/// to the range [360, 2880].
pub fn with_data_layer(mut self, state: bool, segments: Option<usize>) -> Self {
self.render_data = state;
self.data_slices = segments;
self
}
/// The angle in radians at which the index position will be rendered, from the perspective of
/// the specified turning direction. The default is 0.0, which will render the index position
/// at the 3 o'clock position. The angle is specified in radians.
///
/// Note that this value is ignored when generating metadata display lists - in general,
/// rotation should be handled by the renderer. For SVG output we emit a transformation to
/// rotate the entire group.
pub fn with_index_angle(mut self, angle: f32) -> Self {
self.common_params.index_angle = angle;
self
}
/// Specify a specific side to be rendered instead of the entire disk. The value must be
/// 0 or 1. If the value is 0, the bottom side will be rendered. If the value is 1, the top
/// side will be rendered.
pub fn with_side(mut self, side: u8) -> Self {
if side > 1 {
self.build_error = true;
self.error_message = Some("Invalid side to render.".to_string());
}
self.side_to_render = Some(side);
self.total_sides_to_render = 1;
self
}
/// Set the initial data turning direction. The default is Clockwise. This value represents
/// how the data wraps on the visualization from the viewer's perspective. It is the reverse
/// of the physical rotation direction of the disk.
pub fn with_initial_turning(mut self, turning: TurningDirection) -> Self {
self.common_params.direction = turning;
self
}
/// Specify whether the turning direction should be reversed for the second side. The default
/// is true. This will apply to the second side even if only the second side is rendered, for
/// consistency.
pub fn with_turning_side_flip(mut self, state: bool) -> Self {
self.reverse_turning = state;
self
}
/// Specify a single track to be rendered instead of the entire disk.
/// This will render the same track number on both sides unless a specific side is specified.
pub fn with_rendered_track(mut self, track: u16) -> Self {
self.track_to_render = Some(track);
self
}
/// Set the total number of sides to render. This value can be either 1 or 2, but this method
/// is typically used to set the rendering to 2 sides as 1 side is assumed when the side is
/// specified with `render_side`.
fn render_side(mut self, sides: u8) -> Self {
if sides < 1 || sides > 2 {
self.build_error = true;
self.error_message = Some("Invalid number of sides to render.".to_string());
}
else {
self.total_sides_to_render = sides;
if sides == 2 {
// If we're rendering both sides, clear the side to render.
// We shouldn't have really set this in the first place, but whatever.
self.side_to_render = None;
}
}
self
}
/// Flag to decode the data layer when rendering. Currently only supported for MFM tracks.
/// It will be ignored for GCR tracks.
pub fn decode_data(mut self, state: bool) -> Self {
self.decode_data = state;
self
}
/// Render the metadata layer.
pub fn with_metadata_layer(mut self, state: bool) -> Self {
self.render_metadata = state;
self
}
/// Render metadata on top of data layers, using the specified blend mode.
/// The default is true. If false, separate documents will be created for data and metadata
/// layers.
pub fn with_layer_stack(mut self, state: bool) -> Self {
self.render_layered = state;
self
}
/// Set a flag to render both sides of the disk in a single document, with the sides rendered
/// side-by-side, using the specified value of `spacing` between the two sides.
/// The default is true. If false, separate documents will be created for each side, and
/// potentially up to four documents may be created if `render_layered` is false and metadata
/// layer rendering is enabled.
pub fn side_by_side(mut self, state: bool, spacing: f32) -> Self {
self.render_side_by_side = state;
self.side_spacing = spacing;
self
}
/// Expand the global view box by the specified margins.
pub fn with_margins(mut self, top: f32, right: f32, bottom: f32, left: f32) -> Self {
self.global_margins = (top, right, bottom, left);
self
}
/// Specify the blend mode to use when rendering both data and metadata layers as a stack.
/// The default is `BlendMode::Normal`, which will hide the data layer when metadata is
/// present - be sure to set it to your desired mode if you want to see both layers.
pub fn with_blend_mode(mut self, mode: BlendMode) -> Self {
log::trace!("Setting blend mode to {:?}", mode);
self.layer_blend_mode = mode;
self
}
/// Specify an SVG overlay to apply to the rendered visualization. This overlay will be
/// added to the final document as the last group.
pub fn with_overlay(mut self, overlay: Overlay) -> Self {
self.overlay = Some(overlay);
self
}
/// Specify the inner and outer radius ratios, as a fraction of the side view box width.
pub fn with_radius_ratios(mut self, inner: f32, outer: f32) -> Self {
self.common_params.min_radius_ratio = inner;
self.common_params.max_radius_ratio = outer;
self
}
/// Override the default styles with a custom set of styles. This must be a hash map of
/// `GenericTrackElement` to `ElementStyle`.
pub fn with_styles(mut self, _styles: FoxHashMap<GenericTrackElement, ElementStyle>) -> Self {
self
}
/// Override the default track style. Useful if you want to render metadata on its own,
/// with some sort of background.
pub fn with_track_style(mut self, style: ElementStyle) -> Self {
self.track_style = style;
self
}
fn render_data_group(&mut self, disk: &DiskImage, side: u8) -> Result<Group, String> {
log::trace!("Vectorizing data group for side {}...", side);
let data_params = RenderTrackDataParams {
side,
decode: self.decode_data,
sector_mask: false,
slices: self.data_slices.unwrap_or(DEFAULT_DATA_SLICES),
..Default::default()
};
let vector_params = RenderVectorizationParams {
view_box: self.side_view_box.clone(),
image_bg_color: None,
disk_bg_color: None,
mask_color: None,
pos_offset: None,
};
// Reverse the turning direction for side 1, if reverse turning is enabled (default true)
if side > 0 && self.reverse_turning {
self.common_params.direction = self.common_params.direction.opposite();
}
let display_list = vectorize_disk_data(disk, &self.common_params, &data_params, &vector_params)
.map_err(|e| format!("Failed to vectorize data for side {}: {}", side, e))?;
log::trace!(
"vectorize_disk_data() returned a display list of length {} for side {}",
display_list.len(),
side,
);
let mut group = render_data_display_list_as_svg(
self.side_view_box.clone(),
self.common_params.index_angle,
&display_list,
);
// Move this side's group over if we're rendering side-by-side, this the second side, and
// we are rendering two sides.
if (side > 0) && (self.total_sides_to_render > 1) && self.render_side_by_side {
group = group.set(
"transform",
format!("translate({:.3}, 0)", self.side_spacing + self.side_view_box.width()),
);
}
Ok(group)
}
fn render_metadata_group(&mut self, disk: &DiskImage, side: u8) -> Result<Group, String> {
log::debug!("Vectorizing metadata group for side {}...", side);
let metadata_params = RenderTrackMetadataParams {
quadrant: None,
side,
geometry: RenderGeometry::Sector,
winding: Default::default(),
draw_empty_tracks: false,
draw_sector_lookup: false,
};
let display_list = match vectorize_disk_elements_by_quadrants(disk, &self.common_params, &metadata_params) {
Ok(display_list) => display_list,
Err(e) => {
eprintln!("Error rendering metadata: {}", e);
std::process::exit(1);
}
};
let mut group = render_display_list_as_svg(
self.side_view_box.clone(),
0.0,
&display_list,
&self.track_style,
&self.element_styles,
);
// Directly apply our blend mode to this group - blend modes cannot be inherited!
// Only apply the blend mode if we have a data layer to blend with, and layered rendering
// is enabled.
if self.render_data && self.render_layered {
let mode = self.layer_blend_mode.to_string();
group = group.set("style", format!("mix-blend-mode: {};", mode));
}
// Move this side's group over if we're rendering side-by-side, this the second side, and
// we are rendering two sides.
if (side > 0) && (self.total_sides_to_render > 1) && self.render_side_by_side {
group = group.set(
"transform",
format!("translate({:.3}, 0)", self.side_spacing + self.side_view_box.width()),
);
}
Ok(group)
}
pub fn render(mut self, disk: &DiskImage) -> Result<Self, String> {
if self.build_error {
return Err(self.error_message.unwrap_or("Unknown error.".to_string()));
}
self.total_sides_to_render = std::cmp::min(self.total_sides_to_render, disk.heads());
// Render each side
let starting_side = self.side_to_render.unwrap_or(0);
log::trace!(
"render(): starting side: {} sides to render: {}",
starting_side,
self.total_sides_to_render
);
for si in 0..self.total_sides_to_render {
let side = si + starting_side;
assert!(side < 2, "Invalid side!");
// Render data group
if self.render_data {
log::trace!("render(): Rendering data layer group for side {}", side);
let data_timer = Instant::now();
self.data_groups[side as usize] = Some(self.render_data_group(disk, side)?);
log::trace!(
"render(): Rendering data for side {} took {:.3}ms",
side,
data_timer.elapsed().as_secs_f64() * 1000.0
);
}
// Render metadata group
if self.render_metadata {
log::trace!("render(): Rendering metadata layer group for side {}", side);
let metadata_timer = Instant::now();
self.metadata_groups[side as usize] = Some(self.render_metadata_group(disk, side)?);
log::trace!(
"render(): Rendering metadata for side {} took {:.3}ms",
side,
metadata_timer.elapsed().as_secs_f64() * 1000.0
);
}
// Render overlay group
if let Some(overlay) = &self.overlay {
log::trace!("render(): Rendering overlay layer group for side {}", side);
self.overlay_groups[side as usize] = Some(svg_to_group(
overlay.svg(side),
&self.side_view_box,
&self.overlay_style,
)?);
}
}
Ok(self)
}
/// Create a vector of SVG documents after rendering using the specified parameters.
/// Up to four documents may be created, depending on the rendering parameters.
/// For example if layered rendering and side by side rendering are both disabled, four
/// documents will be created for a dual-sided disk, one for each side and layer.
pub fn create_documents(mut self) -> Result<Vec<RenderedDocument>, String> {
let mut output_documents: Vec<RenderedDocument> = Vec::with_capacity(4);
// We won't be splitting documents in half by side, as we either only have one side or
// we're rendering both sides in a single document.
if self.total_sides_to_render == 1 || self.render_side_by_side {
log::debug!("create_documents(): Rendering all sides together.");
let data_group = {
// Put both sides in a single document
// First, check if we even rendered two sides:
let mut data_sides = Vec::with_capacity(2);
for (i, group) in self.data_groups.iter().enumerate() {
if group.is_some() {
data_sides.push(i);
}
}
if data_sides.len() > 1 {
let mut group = Group::new();
for idx in data_sides {
group = group.add(self.data_groups[idx].take().unwrap());
}
Some(group)
}
else if !data_sides.is_empty() {
// Only one side was rendered, so just return that side's group.
self.data_groups.into_iter().flatten().next()
}
else {
// No sides were rendered, so return None
None
}
};
let metadata_group = {
// Put both sides in a single document
// First, check if we even rendered two sides:
let mut metadata_sides = Vec::with_capacity(2);
for (i, group) in self.metadata_groups.iter().enumerate() {
if group.is_some() {
metadata_sides.push(i);
}
}
if metadata_sides.len() > 1 {
let mut group = Group::new();
for idx in metadata_sides {
group = group.add(self.metadata_groups[idx].take().unwrap());
}
group = group
.set("fill", viz_color_to_value(self.overlay_style.fill))
.set("stroke", viz_color_to_value(self.overlay_style.stroke))
.set("stroke-width", self.overlay_style.stroke_width);
Some(group)
}
else if !metadata_sides.is_empty() {
// Only one side was rendered, so just return that side's group.
self.metadata_groups.into_iter().flatten().next()
}
else {
// No sides were rendered, so return None
None
}
};
let overlay_group = {
// Put both sides in a single document
// First, check if we even rendered two sides:
let mut overlay_sides = Vec::with_capacity(2);
for (i, group) in self.overlay_groups.iter().enumerate() {
if group.is_some() {
overlay_sides.push(i);
}
}
if overlay_sides.len() > 1 {
let mut group = Group::new();
for idx in overlay_sides {
group = group.add(self.overlay_groups[idx].take().unwrap());
}
Some(group)
}
else if !overlay_sides.is_empty() {
// Only one side was rendered, so just return that side's group.
Some(self.overlay_groups[0].take().unwrap())
}
else {
// No sides were rendered, so return None
None
}
};
log::trace!(
"create_documents(): Got data layer?: {} Got metadata layer? {}.",
data_group.is_some(),
metadata_group.is_some()
);
if self.total_sides_to_render == 2 {
// Expand the global view box to accommodate both sides, plus spacing and margin.
// Calculate new width
let new_box_width = self.side_view_box.width() * 2.0
+ self.side_spacing
+ self.global_margins.1
+ self.global_margins.3;
// Calculate new height
let new_box_height = self.side_view_box.height() + self.global_margins.0 + self.global_margins.2;
// Set global view box if isn't big enough
if self.global_view_box.width() < new_box_width || self.global_view_box.height() < new_box_height {
self.global_view_box = VizRect::from_tuple((0.0, 0.0), (new_box_width, new_box_height));
}
}
else {
// Set the global view box to the side view box, plus margins.
self.global_view_box = VizRect::from_tuple(
(0.0, 0.0),
(
self.side_view_box.width() + self.global_margins.1 + self.global_margins.3,
self.side_view_box.height() + self.global_margins.0 + self.global_margins.2,
),
);
}
// We may now have a data group and a metadata group. If layered rendering is enabled,
// combine them into the same document.
if self.render_layered {
log::trace!(
"Rendering metadata layer on top of data layer with blend mode: {:?}",
self.layer_blend_mode
);
let mut document = Document::new().set("viewBox", self.global_view_box.to_tuple());
if let Some(group) = data_group {
document = document.add(group);
}
if let Some(group) = metadata_group {
document = document.add(group);
}
if let Some(group) = overlay_group {
document = document.add(group);
}
output_documents.push(RenderedDocument {
side: DocumentSide::Both,
layer: DocumentLayer::Composite,
document,
});
}
else {
log::trace!("Rendering data and metadata layers in separate documents.");
// If layered rendering is disabled, we need to create separate documents for each
// layer. We'll start with the data layer.
if let Some(group) = data_group {
let mut document = Document::new().set("viewBox", self.global_view_box.to_tuple());
document = document.add(group);
output_documents.push(RenderedDocument {
side: DocumentSide::Both,
layer: DocumentLayer::Data,
document,
});
}
// Now we'll create a document for the metadata layer.
if let Some(group) = metadata_group {
let mut document = Document::new().set("viewBox", self.global_view_box.to_tuple());
document = document.add(group);
output_documents.push(RenderedDocument {
side: DocumentSide::Both,
layer: DocumentLayer::Metadata,
document,
});
}
}
}
else {
// We're rendering two sides in separate documents.
log::warn!("Rendering two sides in separate documents is not yet supported.");
println!("Rendering two sides in separate documents is not yet supported.");
}
Ok(output_documents)
}
}
| rust | MIT | b4c04b51746e5fe7769f49a1b32b8caad426fc81 | 2026-01-04T20:24:04.021295Z | false |
dbalsom/fluxfox | https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/crates/fluxfox_svg/src/document.rs | crates/fluxfox_svg/src/document.rs | /*
FluxFox
https://github.com/dbalsom/fluxfox
Copyright 2024-2025 Daniel Balsom
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the “Software”),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
--------------------------------------------------------------------------
*/
use svg::Document;
#[derive(Debug, Clone)]
pub enum DocumentSide {
Single(u8),
Both,
}
#[derive(Debug, Clone)]
pub enum DocumentLayer {
Data,
Metadata,
Composite,
}
#[derive(Debug, Clone)]
pub struct RenderedDocument {
pub side: DocumentSide,
pub layer: DocumentLayer,
pub document: Document,
}
| rust | MIT | b4c04b51746e5fe7769f49a1b32b8caad426fc81 | 2026-01-04T20:24:04.021295Z | false |
dbalsom/fluxfox | https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/crates/fluxfox_svg/src/styles.rs | crates/fluxfox_svg/src/styles.rs | /*
FluxFox
https://github.com/dbalsom/fluxfox
Copyright 2024-2025 Daniel Balsom
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the “Software”),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
--------------------------------------------------------------------------
*/
use fluxfox::{track_schema::GenericTrackElement, visualization::prelude::VizColor, FoxHashMap};
use std::fmt::{self, Display, Formatter};
/// All supported SVG `style` tag blending modes.
/// https://developer.mozilla.org/en-US/docs/Web/CSS/mix-blend-mode
///
/// If the `serde` feature is enabled these will be available for deserialization,
/// such as from a config file (see the `imgviz` example for an example of this).
///
/// The blending mode is applied to the metadata layer when metadata visualization
/// is enabled in addition to data visualization.
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "lowercase"))]
#[derive(Copy, Clone, Debug, Default)]
pub enum BlendMode {
#[default]
Normal,
Multiply,
Screen,
Overlay,
Darken,
Lighten,
ColorDodge,
ColorBurn,
HardLight,
SoftLight,
Difference,
Exclusion,
Hue,
Saturation,
Color,
Luminosity,
}
impl Display for BlendMode {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match self {
BlendMode::Normal => write!(f, "normal"),
BlendMode::Multiply => write!(f, "multiply"),
BlendMode::Screen => write!(f, "screen"),
BlendMode::Overlay => write!(f, "overlay"),
BlendMode::Darken => write!(f, "darken"),
BlendMode::Lighten => write!(f, "lighten"),
BlendMode::ColorDodge => write!(f, "color-dodge"),
BlendMode::ColorBurn => write!(f, "color-burn"),
BlendMode::HardLight => write!(f, "hard-light"),
BlendMode::SoftLight => write!(f, "soft-light"),
BlendMode::Difference => write!(f, "difference"),
BlendMode::Exclusion => write!(f, "exclusion"),
BlendMode::Hue => write!(f, "hue"),
BlendMode::Saturation => write!(f, "saturation"),
BlendMode::Color => write!(f, "color"),
BlendMode::Luminosity => write!(f, "luminosity"),
}
}
}
/// Define style attributes for SVG elements.
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Copy, Clone, Debug, Default)]
pub struct ElementStyle {
/// The color to fill the element with. If no fill is desired, use `VizColor::TRANSPARENT`.
pub fill: VizColor,
/// The color to use to stroke the element path. If no stroke is desired, use `VizColor::TRANSPARENT`.
/// or set stroke_width to 0.0 (probably do both).
pub stroke: VizColor,
/// The width of the stroke. If no stroke is desired, set to 0.0.
pub stroke_width: f32,
}
/// Return a default mapping between [GenericTrackElement]s and [VizColor]s.
fn default_element_palette() -> FoxHashMap<GenericTrackElement, VizColor> {
// Defined colors
let viz_light_red: VizColor = VizColor::from_rgba8(180, 0, 0, 255);
let vis_purple: VizColor = VizColor::from_rgba8(180, 0, 180, 255);
let pal_medium_green = VizColor::from_rgba8(0x38, 0xb7, 0x64, 0xff);
let pal_dark_green = VizColor::from_rgba8(0x25, 0x71, 0x79, 0xff);
let pal_medium_blue = VizColor::from_rgba8(0x3b, 0x5d, 0xc9, 0xff);
let pal_light_blue = VizColor::from_rgba8(0x41, 0xa6, 0xf6, 0xff);
let pal_orange = VizColor::from_rgba8(0xef, 0x7d, 0x57, 0xff);
#[rustfmt::skip]
let palette = FoxHashMap::from([
(GenericTrackElement::SectorData, pal_medium_green),
(GenericTrackElement::SectorBadData, pal_orange),
(GenericTrackElement::SectorDeletedData, pal_dark_green),
(GenericTrackElement::SectorBadDeletedData, viz_light_red),
(GenericTrackElement::SectorHeader, pal_light_blue),
(GenericTrackElement::SectorBadHeader, pal_medium_blue),
(GenericTrackElement::Marker, vis_purple),
]);
palette
}
/// Return a default mapping between [GenericTrackElement]s and [ElementStyle]s.
pub(crate) fn default_element_styles() -> FoxHashMap<GenericTrackElement, ElementStyle> {
let palette = default_element_palette();
let mut styles = FoxHashMap::new();
for (element, color) in palette.iter() {
styles.insert(
*element,
ElementStyle {
fill: *color,
stroke: VizColor::TRANSPARENT,
stroke_width: 0.0,
},
);
}
styles
}
| rust | MIT | b4c04b51746e5fe7769f49a1b32b8caad426fc81 | 2026-01-04T20:24:04.021295Z | false |
dbalsom/fluxfox | https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/crates/fluxfox_svg/src/render_overlays.rs | crates/fluxfox_svg/src/render_overlays.rs | /*
FluxFox
https://github.com/dbalsom/fluxfox
Copyright 2024-2025 Daniel Balsom
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the “Software”),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
--------------------------------------------------------------------------
*/
//! Module to render an SVG file as a Document to be drawn as an overlay over
//! a side visualization. These overlays are typically wireframe depictions of
//! physical floppy media.
use crate::{render_elements::viz_color_to_value, styles::ElementStyle};
use fluxfox::visualization::prelude::VizRect;
use svg::{
node::element::{Circle, Group, Path},
parser::Event,
};
pub fn svg_to_group(svg_data: &str, viewbox: &VizRect<f32>, style: &ElementStyle) -> Result<Group, String> {
log::debug!("svg_to_group: Got svg string: {:?}", svg_data);
let parser = svg::read(svg_data).map_err(|e| format!("Failed to parse overlay SVG: {}", e))?;
//Scale overlay viewbox (0,0)-(100,100) to the provided viewbox
let scale_x = viewbox.width() / 100.0;
let scale_y = viewbox.height() / 100.0;
let transform = format!("scale({:.3},{:.3})", scale_x, scale_y);
let mut group = Group::new().set("transform", transform);
//let mut group = Group::new();
for event in parser {
match event {
// Handle <path> elements
Event::Tag("path", _, attributes) => {
if let Some(d) = attributes.get("d") {
let path = Path::new()
.set("d", d.clone())
.set("fill", viz_color_to_value(style.fill))
.set("stroke", viz_color_to_value(style.stroke))
.set("stroke-width", style.stroke_width);
group = group.add(path);
}
}
// Handle <circle> elements
Event::Tag("circle", _, attributes) => {
let cx = attributes
.get("cx")
.map(|v| v.parse::<f32>().unwrap_or(0.0))
.unwrap_or(0.0);
let cy = attributes
.get("cy")
.map(|v| v.parse::<f32>().unwrap_or(0.0))
.unwrap_or(0.0);
let r = attributes
.get("r")
.map(|v| v.parse::<f32>().unwrap_or(0.0))
.unwrap_or(0.0);
let circle = Circle::new()
.set("cx", cx)
.set("cy", cy)
.set("r", r)
.set("fill", viz_color_to_value(style.fill))
.set("stroke", viz_color_to_value(style.stroke))
.set("stroke-width", style.stroke_width);
group = group.add(circle);
}
_ => {}
}
}
Ok(group)
}
| rust | MIT | b4c04b51746e5fe7769f49a1b32b8caad426fc81 | 2026-01-04T20:24:04.021295Z | false |
dbalsom/fluxfox | https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/crates/fluxfox_svg/src/overlays/mod.rs | crates/fluxfox_svg/src/overlays/mod.rs | /*
FluxFox
https://github.com/dbalsom/fluxfox
Copyright 2024-2025 Daniel Balsom
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the “Software”),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
--------------------------------------------------------------------------
*/
use crate::styles::ElementStyle;
use fluxfox::visualization::prelude::VizColor;
pub const SVG_OVERLAY_5_25_FLOPPY_SIDE0: &str = include_str!("5_25_side0_03.svg");
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Clone, Debug)]
pub enum Overlay {
Overlay8,
Overlay5_25,
Overlay3_5,
}
impl Overlay {
pub fn svg(&self, h: u8) -> &'static str {
match self {
Overlay::Overlay8 => match h {
0 => "",
_ => "",
},
Overlay::Overlay5_25 => match h {
0 => SVG_OVERLAY_5_25_FLOPPY_SIDE0,
_ => "",
},
Overlay::Overlay3_5 => match h {
0 => "",
_ => "",
},
}
}
pub fn default_style() -> ElementStyle {
ElementStyle {
fill: Default::default(),
stroke: VizColor::BLACK,
stroke_width: 0.5,
}
}
}
| rust | MIT | b4c04b51746e5fe7769f49a1b32b8caad426fc81 | 2026-01-04T20:24:04.021295Z | false |
dbalsom/fluxfox | https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/crates/pbm2track/src/prng.rs | crates/pbm2track/src/prng.rs | /*
FluxFox
https://github.com/dbalsom/fluxfox
Copyright 2024-2026 Daniel Balsom
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the “Software”),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
--------------------------------------------------------------------------
*/
/// Tiny deterministic RNG (xorshift64*) for jitter without deps
#[derive(Clone, Copy)]
pub struct Rng(u64);
impl Rng {
pub fn new(seed: u64) -> Self {
Self(seed | 1)
}
pub fn next_u64(&mut self) -> u64 {
let mut x = self.0;
x ^= x >> 12;
x ^= x << 25;
x ^= x >> 27;
self.0 = x;
x.wrapping_mul(0x2545F4914F6CDD1D)
}
pub fn next_f64(&mut self) -> f64 {
// 53 random bits -> [0,1)
let v = self.next_u64() >> 11; // keep top 53 bits
(v as f64) / ((1u64 << 53) as f64)
}
pub fn uniform_range(&mut self, lo: f64, hi: f64) -> f64 {
lo + (hi - lo) * self.next_f64()
}
}
| rust | MIT | b4c04b51746e5fe7769f49a1b32b8caad426fc81 | 2026-01-04T20:24:04.021295Z | false |
dbalsom/fluxfox | https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/crates/pbm2track/src/main.rs | crates/pbm2track/src/main.rs | /*
FluxFox
https://github.com/dbalsom/fluxfox
Copyright 2024-2026 Daniel Balsom
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the “Software”),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
--------------------------------------------------------------------------
*/
mod kfx;
mod pbm;
mod prng;
mod sampler;
use std::{fs, io::Write, path::Path};
use crate::{
prng::Rng,
sampler::{synthesize_flux_from_pbm, YMode},
};
use bpaf::Bpaf;
use pbm::Pbm;
use kfx::{DEFAULT_ICK_HZ, DEFAULT_SCK_HZ};
use regex::Regex;
#[derive(Clone, Debug, Bpaf)]
#[bpaf(options, version)]
/// Convert a PBM (P1/P4) into a KryoFlux raw-stream file (.kfs)
struct Cli {
/// Total samples across one full track (e.g. 100000)
#[bpaf(long("samples"), argument("N"))]
samples: usize,
/// Minimum flux transition duration, microseconds
#[bpaf(long("min-ft"), argument("US"))]
min_ft_us: f64,
/// Maximum flux transition duration, microseconds
#[bpaf(long("max-ft"), argument("US"))]
max_ft_us: f64,
/// Uniform random jitter added to EACH flux (±J µs)
#[bpaf(long("jitter-us"), argument("US"))]
jitter_us: Option<f64>,
/// RNG seed (u64)
#[bpaf(long("seed"), argument("S"), fallback(0x00C0_FFEEu64))]
seed: u64,
/// Vertical sampling: alternate|centroid|bottom|top|random
#[bpaf(long("y-mode"), argument("MODE"), fallback(YMode::Random))]
y_mode: YMode,
/// Output KryoFlux raw-stream file
#[bpaf(long("out"), argument("OUT"))]
out: String,
/// Sample clock (Hz)
#[bpaf(long("sck-hz"), argument("HZ"), fallback(DEFAULT_SCK_HZ))]
sck_hz: f64,
/// Index clock (Hz)
#[bpaf(long("ick-hz"), argument("HZ"), fallback(DEFAULT_ICK_HZ))]
ick_hz: f64,
/// Starting Index Counter (u32)
#[bpaf(long("index-seed"), argument("SEED"), fallback(123_456_789u32))]
index_seed: u32,
/// Number of revolutions to export (repeat flux)
#[bpaf(long("revs"), argument("N"), fallback(3usize))]
revs: usize,
/// KFInfo 'name'
#[bpaf(long("kf-name"), argument("NAME"), fallback("pbm2track".to_string()))]
kf_name: String,
/// KFInfo 'version'
#[bpaf(long("kf-version"), argument("VER"), fallback("1.0".to_string()))]
kf_version: String,
/// PBM path (P1 ASCII or P4 binary)
#[bpaf(positional("PBM"))]
pbm_path: String,
}
fn main() {
let cli = cli().run();
let pbm = match Pbm::load(&cli.pbm_path) {
Ok(p) => p,
Err(e) => {
eprintln!("Failed to load PBM: {e:?}");
std::process::exit(3);
}
};
let min_ft_seconds = cli.min_ft_us * 1e-6;
let max_ft_seconds = cli.max_ft_us * 1e-6;
let max_offset_seconds = max_ft_seconds - min_ft_seconds;
if max_offset_seconds < 0.0 {
eprintln!("Error: --max-ft must be >= --min-ft");
std::process::exit(1);
}
let jitter_seconds = match cli.jitter_us {
Some(us) => us * 1e-6,
None => {
if pbm.height > 0 {
max_offset_seconds / (pbm.height as f64) / 2.0
}
else {
0.0
}
}
};
let mut rng = Rng::new(cli.seed);
let one_rev_flux = match synthesize_flux_from_pbm(
&pbm,
cli.samples,
min_ft_seconds,
max_offset_seconds,
jitter_seconds,
&mut rng,
cli.y_mode,
) {
Ok(v) => v,
Err(e) => {
eprintln!("Flux synthesis error: {e:?}");
std::process::exit(4);
}
};
// Create encoder
let encoder = kfx::KfxEncoder::new(cli.sck_hz, cli.ick_hz);
// Encode multi-revolution stream
// I tried using one stream just book-ended with index markers, but some tools complained
// Giving them three revolutions seems to appease them
let bytes = match encoder.encode_multi_revs(&one_rev_flux, cli.revs) {
Ok(v) => v,
Err(e) => {
eprintln!("Encode error: {e:?}");
std::process::exit(5);
}
};
// Validate output filename contains track/head like "00.0" before the final ".raw"
// Ensure callers provide an output filename that includes the two-digit track and single-digit head
// e.g. out00.0.raw — importers need the NN.H.raw format.
if let Some(file_name) = Path::new(&cli.out).file_name().and_then(|s| s.to_str()) {
let re = Regex::new(r"\d{2}\.\d\.raw$").expect("invalid regex");
if !re.is_match(file_name) {
eprintln!("Output filename '{}' does not contain a track/head spec like '00.0' before .raw. Please use a name like: nameNN.H.raw (e.g. out00.0.raw)", file_name);
std::process::exit(2);
}
}
else {
eprintln!("Invalid output path: '{}'", cli.out);
std::process::exit(2);
}
if let Err(e) = fs::File::create(Path::new(&cli.out)).and_then(|mut f| f.write_all(&bytes)) {
eprintln!("Write error: {e}");
std::process::exit(6);
}
println!("OK: wrote {} bytes, {} rev(s) to {}", bytes.len(), cli.revs, cli.out);
let total_time_s: f64 = one_rev_flux.iter().sum();
println!(
"Track length: {:.4}ms ({:.2}) RPM",
total_time_s * 1000.0,
60.0 / total_time_s
);
println!("Total flux transitions: {}", one_rev_flux.len());
println!("Jitter: {:.4} us", jitter_seconds * 1e6);
}
| rust | MIT | b4c04b51746e5fe7769f49a1b32b8caad426fc81 | 2026-01-04T20:24:04.021295Z | false |
dbalsom/fluxfox | https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/crates/pbm2track/src/sampler.rs | crates/pbm2track/src/sampler.rs | /*
FluxFox
https://github.com/dbalsom/fluxfox
Copyright 2024-2026 Daniel Balsom
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the “Software”),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
--------------------------------------------------------------------------
*/
use crate::{pbm::Pbm, prng::Rng};
#[derive(Clone, Copy, Debug)]
pub enum YMode {
Alternate,
Centroid,
Bottom,
Top,
Random,
}
impl std::str::FromStr for YMode {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.trim().to_ascii_lowercase().as_str() {
"alternate" => Ok(YMode::Alternate),
"centroid" => Ok(YMode::Centroid),
"bottom" => Ok(YMode::Bottom),
"top" => Ok(YMode::Top),
"random" => Ok(YMode::Random),
other => Err(format!(
"unknown y-mode {other:?} (expected: alternate|centroid|bottom|top|random)"
)),
}
}
}
// --------------------------------------
// Flux synthesis from image columns
// --------------------------------------
#[derive(Debug)]
pub enum SynthError {
EmptyImage,
}
pub fn synthesize_flux_from_pbm(
pbm: &Pbm,
samples: usize,
min_ft_seconds: f64,
max_offset_seconds: f64,
jitter_seconds: f64,
rng: &mut Rng,
y_mode: YMode,
) -> Result<Vec<f64>, SynthError> {
if pbm.width == 0 || pbm.height == 0 {
return Err(SynthError::EmptyImage);
}
let w = pbm.width;
let h = pbm.height;
let mut acc: f64 = 0.0;
let mut flux: Vec<f64> = Vec::with_capacity(samples / 2);
let mut multi_alt: usize = 0;
for x in 0..samples {
let sx = ((x as u128) * (w as u128) / (samples as u128)) as usize;
let sx = sx.min(w - 1);
let mut rows: Vec<usize> = Vec::with_capacity(h);
for r_from_bottom in 0..h {
let y = (h - 1) - r_from_bottom;
if pbm.at(sx, y) {
rows.push(r_from_bottom);
}
}
if rows.is_empty() {
acc += min_ft_seconds;
continue;
}
// Choose vertical position -> fractional [0,1] from bottom to top
let row_frac: f64 = match y_mode {
YMode::Alternate => {
let chosen = if rows.len() == 1 {
rows[0]
}
else {
let idx = multi_alt % rows.len();
multi_alt = multi_alt.wrapping_add(1);
rows[idx]
};
if h > 1 {
(chosen as f64) / ((h - 1) as f64)
}
else {
0.0
}
}
YMode::Random => {
let idx = (rng.next_u64() as usize) % rows.len();
let chosen = rows[idx];
if h > 1 {
(chosen as f64) / ((h - 1) as f64)
}
else {
0.0
}
}
YMode::Centroid => {
let sum: usize = rows.iter().copied().sum();
let mean = (sum as f64) / (rows.len() as f64);
if h > 1 {
mean / ((h - 1) as f64)
}
else {
0.0
}
}
YMode::Bottom => {
let m = *rows.iter().min().unwrap();
if h > 1 {
(m as f64) / ((h - 1) as f64)
}
else {
0.0
}
}
YMode::Top => {
let m = *rows.iter().max().unwrap();
if h > 1 {
(m as f64) / ((h - 1) as f64)
}
else {
0.0
}
}
};
let extra = row_frac * max_offset_seconds;
let mut delta = acc + min_ft_seconds + extra;
acc = 0.0;
if jitter_seconds > 0.0 {
let j = rng.uniform_range(-jitter_seconds, jitter_seconds);
delta += j;
}
// Ensure delta is positive.
if delta <= 0.0 {
delta = 1e-9;
}
flux.push(delta);
}
Ok(flux)
}
| rust | MIT | b4c04b51746e5fe7769f49a1b32b8caad426fc81 | 2026-01-04T20:24:04.021295Z | false |
dbalsom/fluxfox | https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/crates/pbm2track/src/kfx/mod.rs | crates/pbm2track/src/kfx/mod.rs | /*
FluxFox
https://github.com/dbalsom/fluxfox
Copyright 2024-2026 Daniel Balsom
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the “Software”),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
--------------------------------------------------------------------------
*/
#[derive(Debug)]
#[allow(dead_code)]
pub enum EncodeError {
NonFiniteTime { index: usize, value: f64 },
NegativeTime { index: usize, value: f64 },
Overflow { index: usize, seconds: f64, sck: f64 },
}
pub const DEFAULT_SCK_HZ: f64 = 24_027_428.57142857;
pub const DEFAULT_ICK_HZ: f64 = 3_003_428.571428571;
pub struct KfxEncoder {
pub sck_hz: f64,
pub ick_hz: f64,
pub index_seed: u32,
pub kfinfo_name: String,
pub kfinfo_version: String,
}
impl KfxEncoder {
pub fn new(sck_hz: f64, ick_hz: f64 ) -> Self {
Self {
sck_hz,
ick_hz,
index_seed: 123_456_789,
kfinfo_name: "FluxPaint".to_string(),
kfinfo_version: "1.0".to_string(),
}
}
pub fn with_index_seed(mut self, index_seed: u32) -> Self {
self.index_seed = index_seed;
self
}
pub fn with_kfinfo(mut self, name: &str, version: &str) -> Self {
self.kfinfo_name = name.to_string();
self.kfinfo_version = version.to_string();
self
}
pub fn encode_multi_revs(
&self,
one_rev_times_sec: &[f64],
revs: usize,
) -> Result<Vec<u8>, EncodeError> {
let (isb_one, total_sck_ticks_u64) = self.encode_one_revolution_isb(one_rev_times_sec)?;
let isb_one_len = isb_one.len() as u32;
let delta_index_u32 = ((total_sck_ticks_u64 as f64) * (self.ick_hz / self.sck_hz)).round() as u32;
let mut out: Vec<u8> = Vec::with_capacity(isb_one.len() * revs + 128);
let info = format!(
"name={}, version={}, sck={}, ick={}, revs={}",
self.kfinfo_name, self.kfinfo_version, self.sck_hz, self.ick_hz, revs
);
Self::push_kfinfo(&mut out, &info);
let mut stream_pos: u32 = 0;
let mut index_counter: u32 = self.index_seed;
Self::push_index(&mut out, stream_pos, 0, index_counter);
for _ in 0..revs {
out.extend_from_slice(&isb_one);
stream_pos = stream_pos.wrapping_add(isb_one_len);
index_counter = index_counter.wrapping_add(delta_index_u32);
Self::push_index(&mut out, stream_pos, 0, index_counter);
}
Self::push_stream_end_and_eof(&mut out, stream_pos);
Ok(out)
}
fn encode_one_revolution_isb(&self, times_sec: &[f64]) -> Result<(Vec<u8>, u64), EncodeError> {
let mut isb: Vec<u8> = Vec::with_capacity(times_sec.len() * 2);
let mut total_ticks: u64 = 0;
for (i, &t) in times_sec.iter().enumerate() {
if !t.is_finite() {
return Err(EncodeError::NonFiniteTime { index: i, value: t });
}
if t < 0.0 {
return Err(EncodeError::NegativeTime { index: i, value: t });
}
let ticks_f = t * self.sck_hz;
if ticks_f > (u64::MAX as f64) {
return Err(EncodeError::Overflow {
index: i,
seconds: t,
sck: self.sck_hz,
});
}
let ticks = ticks_f.round() as u64;
total_ticks = total_ticks.wrapping_add(ticks);
Self::push_flux_value(ticks, &mut isb);
}
Ok((isb, total_ticks))
}
fn push_flux_value(mut ticks: u64, out: &mut Vec<u8>) {
while ticks > 0xFFFF {
out.push(0x0B);
ticks -= 0x10000;
}
let v = ticks as u32;
if (0x0E..=0xFF).contains(&v) {
out.push(v as u8);
} else if (v <= 0x000D) || ((0x0100..=0x07FF).contains(&v)) {
let hi = ((v >> 8) & 0x07) as u8;
let lo = (v & 0xFF) as u8;
out.push(hi);
out.push(lo);
} else {
out.push(0x0C);
out.push(((v >> 8) & 0xFF) as u8);
out.push((v & 0xFF) as u8);
}
}
fn push_kfinfo(out: &mut Vec<u8>, info: &str) {
out.push(0x0D);
out.push(0x04);
let size = (info.len() as u16) + 1;
out.extend_from_slice(&size.to_le_bytes());
out.extend_from_slice(info.as_bytes());
out.push(0);
}
fn push_index(out: &mut Vec<u8>, stream_pos: u32, sample_counter: u32, index_counter: u32) {
out.push(0x0D);
out.push(0x02);
out.extend_from_slice(&0x000Cu16.to_le_bytes());
out.extend_from_slice(&stream_pos.to_le_bytes());
out.extend_from_slice(&sample_counter.to_le_bytes());
out.extend_from_slice(&index_counter.to_le_bytes());
}
fn push_stream_end_and_eof(out: &mut Vec<u8>, stream_pos: u32) {
out.push(0x0D);
out.push(0x03);
out.extend_from_slice(&0x0008u16.to_le_bytes());
out.extend_from_slice(&stream_pos.to_le_bytes());
out.extend_from_slice(&0u32.to_le_bytes());
out.push(0x0D);
out.push(0x0D);
out.extend_from_slice(&0x0D0Du16.to_le_bytes());
}
}
impl Default for KfxEncoder {
fn default() -> Self {
Self::new(DEFAULT_SCK_HZ, DEFAULT_ICK_HZ)
}
} | rust | MIT | b4c04b51746e5fe7769f49a1b32b8caad426fc81 | 2026-01-04T20:24:04.021295Z | false |
dbalsom/fluxfox | https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/crates/pbm2track/src/pbm/mod.rs | crates/pbm2track/src/pbm/mod.rs | /*
FluxFox
https://github.com/dbalsom/fluxfox
Copyright 2024-2026 Daniel Balsom
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the “Software”),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
--------------------------------------------------------------------------
*/
use std::{fs, io};
use std::io::Read;
#[derive(Debug)]
#[allow(dead_code)]
pub enum PbmError {
Io(io::Error),
BadMagic,
BadHeader,
NotEnoughPixels,
}
impl From<io::Error> for PbmError {
fn from(e: io::Error) -> Self {
PbmError::Io(e)
}
}
#[derive(Debug)]
pub struct Pbm {
pub width: usize,
pub height: usize,
/// true = white (flux), false = black (no flux)
/// row-major, y:0 -> top, y:height-1 -> bottom
pixels_white: Vec<bool>,
}
impl Pbm {
pub fn at(&self, x: usize, y: usize) -> bool {
self.pixels_white[y * self.width + x]
}
pub fn load(path: &str) -> Result<Pbm, PbmError> {
let mut f = fs::File::open(path)?;
let mut buf = Vec::new();
f.read_to_end(&mut buf)?;
if buf.len() < 3 {
return Err(PbmError::BadMagic);
}
if !(buf[0] == b'P' && (buf[1] == b'1' || buf[1] == b'4')) {
return Err(PbmError::BadMagic);
}
let binary = buf[1] == b'4';
// Tokenizer over ASCII part (header and P1 data).
let mut i = 2usize;
while i < buf.len() && buf[i].is_ascii_whitespace() {
i += 1;
}
let next_token = |start: &mut usize| -> Option<String> {
let n = buf.len();
let mut s = *start;
loop {
while s < n && buf[s].is_ascii_whitespace() {
s += 1;
}
if s >= n {
return None;
}
if buf[s] == b'#' {
while s < n && buf[s] != b'\n' {
s += 1;
}
continue;
}
let mut e = s;
while e < n && !buf[e].is_ascii_whitespace() {
e += 1;
}
let tok = String::from_utf8_lossy(&buf[s..e]).to_string();
*start = e;
return Some(tok);
}
};
let w: usize = next_token(&mut i)
.ok_or(PbmError::BadHeader)?
.parse()
.map_err(|_| PbmError::BadHeader)?;
let h: usize = next_token(&mut i)
.ok_or(PbmError::BadHeader)?
.parse()
.map_err(|_| PbmError::BadHeader)?;
let mut pixels_white = vec![false; w * h];
if !binary {
// P1: '0' = white, '1' = black
for y in 0..h {
for x in 0..w {
let t = next_token(&mut i).ok_or(PbmError::NotEnoughPixels)?;
match t.as_str() {
"0" => pixels_white[y * w + x] = true,
"1" => pixels_white[y * w + x] = false,
_ => return Err(PbmError::BadHeader),
}
}
}
}
else {
// P4: rows top->bottom, MSB first, 1=black, 0=white
while i < buf.len() && buf[i].is_ascii_whitespace() {
i += 1;
}
let bpr = (w + 7) / 8;
let need = h * bpr;
if buf.len() < i + need {
return Err(PbmError::NotEnoughPixels);
}
let mut k = i;
for y in 0..h {
for xb in 0..bpr {
let byte = buf[k];
k += 1;
for bit in 0..8 {
let x = xb * 8 + bit;
if x >= w {
break;
}
let v = (byte >> (7 - bit)) & 1;
pixels_white[y * w + x] = v == 0;
}
}
}
}
Ok(Pbm {
width: w,
height: h,
pixels_white,
})
}
} | rust | MIT | b4c04b51746e5fe7769f49a1b32b8caad426fc81 | 2026-01-04T20:24:04.021295Z | false |
dbalsom/fluxfox | https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/crates/ffedit/src/app.rs | crates/ffedit/src/app.rs | /*
ffedit
https://github.com/dbalsom/fluxfox
Copyright 2024-2025 Daniel Balsom
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the “Software”),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
--------------------------------------------------------------------------
*/
use std::{
cell::RefCell,
io,
path::PathBuf,
rc::Rc,
time::{Duration, Instant},
};
pub use crate::app_context::AppContext;
use crate::{
cmd_interpreter::{CommandInterpreter, CommandResult},
components::{data_block::DataBlock, history::HistoryWidget},
disk_selection::DiskSelection,
logger::{init_logger, LogEntry},
modal::ModalState,
widget::{FoxWidget, TabSelectableWidget},
CmdParams,
};
use crossbeam_channel::Receiver;
use crossterm::{
event,
event::{Event, KeyCode, KeyEventKind, KeyModifiers, MouseEvent, MouseEventKind},
};
use fluxfox::DiskImage;
use ratatui::{
prelude::*,
widgets::{Gauge, Paragraph},
DefaultTerminal,
};
use tui_popup::{Popup, SizedWrapper};
// Application state to support different modes
#[derive(Default)]
pub(crate) enum ApplicationState {
#[default]
Normal,
Modal(ModalState),
}
pub(crate) enum AppEvent {
LoadingStatus(f64),
DiskImageLoaded(DiskImage, PathBuf),
DiskImageLoadingFailed(String),
DiskSelectionChanged,
Log(LogEntry),
OpenFileRequest(PathBuf),
}
pub(crate) struct UiContext {
pub(crate) dragging: bool,
pub(crate) split_percentage: u16,
}
pub(crate) struct App {
pub(crate) params: CmdParams,
pub(crate) input: String,
pub(crate) ci: CommandInterpreter,
pub(crate) history: Rc<RefCell<HistoryWidget>>,
pub(crate) widgets: Vec<Rc<RefCell<dyn FoxWidget>>>,
pub(crate) receiver: Receiver<AppEvent>,
pub(crate) ctx: AppContext,
pub(crate) ui_ctx: UiContext,
pub(crate) selected_widget: usize,
}
impl App {
pub fn new(params: CmdParams) -> App {
let (sender, receiver) = crossbeam_channel::unbounded::<AppEvent>();
init_logger(sender.clone()).unwrap();
log::info!("Logger initialized!");
let db = Rc::new(RefCell::new(DataBlock::default()));
let history = Rc::new(RefCell::new(HistoryWidget::new(None)));
// history gets selected by default.
history.borrow_mut().select();
let widgets = vec![
history.clone() as Rc<RefCell<dyn FoxWidget>>,
db.clone() as Rc<RefCell<dyn FoxWidget>>,
];
let mut app = App {
params,
input: String::new(),
ci: CommandInterpreter::new(),
history,
receiver,
ctx: AppContext {
selection: DiskSelection::default(),
state: ApplicationState::Normal,
di: None,
di_name: None,
sender,
db,
},
ui_ctx: UiContext {
dragging: false,
split_percentage: 50,
},
widgets,
selected_widget: 0,
};
if let Some(ref in_file) = app.params.in_filename {
app.ctx.load_disk_image(in_file.clone());
}
app
}
fn select_next_widget(&mut self) {
//log::debug!("select_next_widget()... Selecting next widget");
self.widgets[self.selected_widget].borrow_mut().deselect();
self.selected_widget = (self.selected_widget + 1) % self.widgets.len();
self.widgets[self.selected_widget].borrow_mut().select();
}
fn draw(&mut self, f: &mut Frame) {
let app_layout = Layout::default()
.direction(Direction::Vertical)
.constraints(
[
Constraint::Length(1), // for title
Constraint::Min(1),
Constraint::Length(1), // for input box
]
.as_ref(),
)
.split(f.area());
let horiz_split = Layout::default()
.direction(Direction::Horizontal)
.constraints(
[
Constraint::Percentage(self.ui_ctx.split_percentage), // Dynamic split for the history
Constraint::Percentage(100 - self.ui_ctx.split_percentage), // Remaining space for the data pane
]
.as_ref(),
)
.split(app_layout[1]);
//let history_height = app_layout[0].height as usize;
let image_name = if let Some(di_name) = &self.ctx.di_name {
format!("{}", di_name.to_string_lossy())
}
else {
"No Disk Image".to_string()
};
let image_resolution = if let Some(di) = &self.ctx.di {
format!("{:?}", di.resolution())
}
else {
"".to_string()
};
let mut title_line = Line::from(vec![
Span::styled("ffedit ", Style::light_blue(Style::default())),
Span::styled(image_name, Style::default()),
]);
if !image_resolution.is_empty() {
title_line.push_span(Span::styled(" [", Style::default()));
title_line.push_span(Span::styled(image_resolution, Style::light_blue(Style::default())));
title_line.push_span(Span::styled("]", Style::default()));
}
f.render_widget(Paragraph::new(title_line), app_layout[0]);
self.draw_history(f, horiz_split[0]);
self.draw_data_pane(f, horiz_split[1]);
//
// // Account for the 2 lines taken by the border (top and bottom)
// let visible_height = if history_height > 2 { history_height - 2 } else { 0 };
//
// // Calculate the start index to show the last N lines, where N is the visible widget height
// let start_index = if self.history.len() > visible_height {
// self.history.len() - visible_height
// } else {
// 0
// };
//
// // Build the visible history to display
// let visible_history: Vec<Line> = self.history[start_index..]
// .iter()
// .map(|entry| match entry {
// HistoryEntry::UserCommand(cmd) => Line::from(Span::styled(format!("> {}", cmd), Style::default())),
// HistoryEntry::CommandResponse(resp) => {
// Line::from(Span::styled(resp.clone(), Style::default().fg(Color::Cyan)))
// }
// })
// .collect();
//
// let history_paragraph =
// Paragraph::new(visible_history).block(Block::default().borders(Borders::ALL).title("History"));
// f.render_widget(history_paragraph, app_layout[1]);
// Display prompt and input on a single line below the history
let prompt_with_input = format!("{}>{}", self.prompt(), self.input);
let input_line = Line::from(vec![Span::styled(prompt_with_input, Style::default())]);
f.render_widget(Paragraph::new(input_line), app_layout[2]);
match &self.ctx.state {
ApplicationState::Normal => {}
ApplicationState::Modal(modal_state) => {
match modal_state {
ModalState::ProgressBar(title, progress) => {
// Display a progress bar
let gauge = Gauge::default().ratio(*progress);
let sized = SizedWrapper {
inner: gauge,
width: (f.area().width / 2) as usize,
height: 1,
};
let popup = Popup::new(sized)
.title(title.clone())
.style(Style::new().white().on_black());
f.render_widget(&popup, f.area());
}
}
}
}
}
pub fn run(&mut self, terminal: &mut DefaultTerminal) -> Result<(), io::Error> {
let tick_rate = Duration::from_millis(250);
let mut last_tick = Instant::now();
loop {
// Draw the UI
terminal.draw(|f| self.draw(f))?;
// Receive AppEvents
self.handle_app_events();
// Handle input
if event::poll(tick_rate.saturating_sub(last_tick.elapsed()))? {
match event::read()? {
Event::Key(key) => {
if key.kind == KeyEventKind::Press {
// Check for key press event only
if let Some(result) = self.on_key(key.code, key.modifiers) {
// We may add other options later
#[allow(clippy::collapsible_match)]
if let CommandResult::UserExit = result {
break Ok(());
}
}
}
}
Event::Mouse(mouse_event) => {
if let Ok(size) = terminal.size() {
self.on_mouse(mouse_event, size);
}
}
_ => {}
}
}
if last_tick.elapsed() >= tick_rate {
last_tick = Instant::now();
}
}
}
fn on_key(&mut self, code: KeyCode, modifiers: KeyModifiers) -> Option<CommandResult> {
match &self.ctx.state {
ApplicationState::Normal => self.on_key_normal(code, modifiers),
ApplicationState::Modal(modal_state) => {
if modal_state.input_enabled() {
self.on_key_normal(code, modifiers)
}
else {
None
}
}
}
}
fn on_key_normal(&mut self, code: KeyCode, modifiers: KeyModifiers) -> Option<CommandResult> {
match code {
KeyCode::Char(c) if c == 'c' && modifiers.contains(KeyModifiers::CONTROL) => {
return Some(CommandResult::UserExit);
}
KeyCode::Char(c) => self.input.push(c),
KeyCode::Backspace => {
self.input.pop();
}
KeyCode::Enter => {
if !self.input.is_empty() {
let mut history = self.history.borrow_mut();
let command = self.input.clone();
history.push_user_cmd(&command);
// Process the command and get the result
let result = self.ci.process_command(&mut self.ctx, &command);
match result {
CommandResult::Success(response) => {
history.push_cmd_response(&response);
}
CommandResult::Error(response) => {
history.push_cmd_response(&response);
}
CommandResult::UserExit => {
return Some(CommandResult::UserExit);
}
}
// Clear input after processing
self.input.clear();
}
}
KeyCode::BackTab => {
self.select_next_widget();
}
KeyCode::PageUp => {
self.widgets[self.selected_widget].borrow_mut().page_up();
}
KeyCode::PageDown => {
self.widgets[self.selected_widget].borrow_mut().page_down();
}
_ => {}
}
None
}
fn on_mouse(&mut self, event: MouseEvent, size: Size) {
match event.kind {
MouseEventKind::Down(_) => {
log::debug!("mouse down");
// Start dragging if mouse is near the split
if event.column >= (self.ui_ctx.split_percentage - 2)
&& event.column <= (self.ui_ctx.split_percentage + 2)
{
self.ui_ctx.dragging = true;
}
}
MouseEventKind::Drag(_) => {
if self.ui_ctx.dragging {
// Update split based on mouse position
self.ui_ctx.split_percentage = (event.column as f64 / size.width as f64 * 100.0) as u16;
}
}
MouseEventKind::Up(_) => {
self.ui_ctx.dragging = false;
}
_ => {}
}
}
// Generate the prompt based on current head, cylinder, and sector selection
fn prompt(&self) -> String {
self.ctx.selection.to_string()
}
fn draw_history(&self, f: &mut Frame, area: Rect) {
f.render_widget_ref(&*self.history.borrow(), area);
}
fn draw_data_pane(&self, f: &mut Frame, area: Rect) {
// Display data pane content here
//let block = Block::default().borders(Borders::ALL).title("Data Pane");
f.render_widget_ref(&*self.ctx.db.borrow(), area);
}
}
| rust | MIT | b4c04b51746e5fe7769f49a1b32b8caad426fc81 | 2026-01-04T20:24:04.021295Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.