diff options
| author | Johannes Hofmann <Johannes.Hofmann@gmx.de> | 2026-10-26 20:05:20 +0100 |
|---|---|---|
| committer | Johannes Hofmann <Johannes.Hofmann@gmx.de> | 2026-10-26 20:05:20 +0100 |
| commit | 375d87a9b0ec1cf2fffd705adb870c86144d2400 (patch) | |
| tree | 1e8e05e7cd58686628d0f4622622456613a42e4d /crates/gipfel-app | |
| parent | 45425dd047b791fe63f13a46a3251c529cfffc94 (diff) | |
Replace the C++ implementation with the Rust port
The Rust port (formerly gipfel-rs) is now the official successor to the
FLTK/GSL C++ code base. This squashes the port into a single commit and
removes the C++ sources (they remain in the git history below).
Layout:
crates/gipfel-core headless core: hills, panorama geometry, projections
(maxima-generated derivatives), pure-Rust LM fit,
gipfel: JPEG comment + EXIF I/O, profiles, stitching
crates/gipfel-cli command-line tools (export, info, stitch, profiles)
crates/gipfel-app Cosmic DE (libcosmic) GUI, binary name `gipfel`
codegen/ maxima scripts + regen.sh for the projection code
tests/ golden files + C++ reference harnesses (historical)
The original README is kept for now; it will be updated to describe the
Rust build. gipfel.dat, AUTHORS, ChangeLog and NEWS are unchanged.
Diffstat (limited to 'crates/gipfel-app')
| -rw-r--r-- | crates/gipfel-app/Cargo.toml | 19 | ||||
| -rw-r--r-- | crates/gipfel-app/data/org.gipfel.App.desktop | 13 | ||||
| -rw-r--r-- | crates/gipfel-app/src/compass.rs | 611 | ||||
| -rw-r--r-- | crates/gipfel-app/src/dump.rs | 285 | ||||
| -rw-r--r-- | crates/gipfel-app/src/main.rs | 1805 | ||||
| -rw-r--r-- | crates/gipfel-app/src/viewport.rs | 659 |
6 files changed, 3392 insertions, 0 deletions
diff --git a/crates/gipfel-app/Cargo.toml b/crates/gipfel-app/Cargo.toml new file mode 100644 index 0000000..22589c1 --- /dev/null +++ b/crates/gipfel-app/Cargo.toml @@ -0,0 +1,19 @@ +[package] +name = "gipfel-app" +version = "0.1.0" +edition = "2021" +description = "gipfel port to Cosmic DE" +license = "GPL-2.0-or-later" + +[[bin]] +name = "gipfel" +path = "src/main.rs" + +[dependencies] +gipfel-core = { path = "../gipfel-core" } +libcosmic = { git = "https://github.com/pop-os/libcosmic.git", rev = "430f3d48a97d8779f9c1985473912e594ccca1ae", default-features = false, features = ["winit", "wgpu", "tokio", "a11y", "xdg-portal"] } +image.workspace = true +fontdue = "0.9" +cosmic-text = "0.19" +fontdb = "0.23" +tokio = { version = "1", features = ["time"] } diff --git a/crates/gipfel-app/data/org.gipfel.App.desktop b/crates/gipfel-app/data/org.gipfel.App.desktop new file mode 100644 index 0000000..b20c468 --- /dev/null +++ b/crates/gipfel-app/data/org.gipfel.App.desktop @@ -0,0 +1,13 @@ +[Desktop Entry] +Type=Application +Name=gipfel +GenericName=Panorama annotator +Comment=Annotate mountain panoramas +Exec=gipfel %U +TryExec=gipfel +Icon=org.gipfel.App +Terminal=false +Categories=Graphics;Photography; +Keywords=mountain;panorama;photo;annotation; +MimeType=image/jpeg;image/png; +StartupNotify=true diff --git a/crates/gipfel-app/src/compass.rs b/crates/gipfel-app/src/compass.rs new file mode 100644 index 0000000..a17cd5c --- /dev/null +++ b/crates/gipfel-app/src/compass.rs @@ -0,0 +1,611 @@ +//! Experimental compass strip: shows N/E/S/W at their projected positions +//! relative to the view direction; drag horizontally to change the direction. +//! +//! Two experimental styles (switchable from the View menu): +//! - `Aligned`: the strip shares the image's horizontal transform, so each +//! direction appears exactly above its position in the image. Grab-drag +//! keeps the direction under the cursor fixed. +//! - `Ruler`: a fixed 0..360° ruler across the widget width; press or drag +//! sets the direction to the value under the cursor. The shaded band marks +//! the current horizontal field of view. +//! +//! Layout (top to bottom): direction labels, center marker, tick scale on a +//! baseline. The whole strip sits on a secondary-container background so it +//! is visually distinct from the image (pan) area. + +use std::cell::RefCell; +use std::rc::Rc; + +use cosmic::iced::advanced::graphics::geometry::Renderer as _; +use cosmic::iced::advanced::renderer::Style as RendererStyle; +use cosmic::iced::advanced::text::{self as adv_text, paragraph::Plain, LineHeight}; +use cosmic::iced::advanced::widget::{tree, Tree, Widget as WidgetTrait}; +use cosmic::iced::advanced::{Clipboard, Layout, Shell}; +use cosmic::iced::mouse::{self, Button, Cursor, Interaction}; +use cosmic::iced::widget::canvas::{Frame, Path, Stroke}; +use cosmic::iced::advanced::graphics::geometry::Style as GeoStyle; +use cosmic::iced::{alignment, Color, Event, Length, Pixels, Point, Rectangle, Size}; +use cosmic::Renderer as R; +use cosmic::Theme; + +use gipfel_core::projection::{ + projection_from_type, Projection, ProjArgs, ProjectionType, ViewParams, +}; + +pub const STRIP_H: f32 = 56.0; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum CompassStyle { + Off, + Aligned, + Ruler, +} + +/// inverse: azimuth whose image x is `x_img`, measured with `c_ref` as +/// center angle. Analytic base inverse + damped Newton refinement so lens +/// distortion is honoured. +/// Damped, clamped Newton iteration for a scalar inverse projection: find +/// `a` such that `f(a) ≈ target`. `f` returns `None` where the forward +/// projection is undefined (the iteration stops there). The step is clamped +/// to ±0.3 rad and `a` kept in `[lo, hi]` to stay off the projection poles. +pub(crate) fn newton_inverse( + target: f64, + mut f: impl FnMut(f64) -> Option<f64>, + seed: f64, + lo: f64, + hi: f64, +) -> f64 { + let mut a = seed.clamp(lo, hi); + for _ in 0..6 { + let Some(y) = f(a) else { break }; + let resid = y - target; + let h = 1e-5; + let (Some(y1), Some(y2)) = (f(a + h), f(a - h)) else { + break; + }; + let d = (y1 - y2) / (2.0 * h); + if !d.is_finite() || d.abs() < 1e-9 { + break; + } + let step = (resid / d).clamp(-0.3, 0.3); + a = (a - step).clamp(lo, hi); + if step.abs() < 1e-10 { + break; + } + } + a +} + +pub fn alph_at_img_x( + ptype: ProjectionType, + proj: &dyn Projection, + parms: &ViewParams, + x_img: f64, + c_ref: f64, +) -> f64 { + let mut p = *parms; + p.a_center = c_ref; + // analytic base inverse (ignores distortion); Newton refines it + let seed = match ptype { + ProjectionType::Rectilinear => c_ref + (x_img / p.scale).atan(), + ProjectionType::Cylindrical => c_ref + x_img / p.scale, + }; + // rectilinear has a pole at |alph - center| = 90°; keep Newton inside + let (lo, hi) = match ptype { + ProjectionType::Rectilinear => (c_ref - 1.55, c_ref + 1.55), + ProjectionType::Cylindrical => (c_ref - 3.1, c_ref + 3.1), + }; + newton_inverse( + x_img, + |a| Some(proj.mac_x(ProjArgs::from_params(&p, a, 0.0))), + seed, + lo, + hi, + ) +} + +pub struct Compass<M: Clone + Send + 'static> { + pub style: CompassStyle, + pub center_deg: f64, + pub zoom: f32, + pub pan_x: f32, + pub parms: ViewParams, + pub ptype: ProjectionType, + /// horizontal field of view of the image, degrees (Ruler shading) + pub fov_deg: f64, + /// lens field-of-view half-angle limit in radians (0 = none). Ticks and + /// direction labels beyond this are dropped: a distortion model can fold + /// out-of-view directions back onto the strip, showing bogus ticks. + pub max_view_angle: f64, + pub on_change: Rc<dyn Fn(f64) -> M>, +} + +impl<M: Clone + Send + 'static> Clone for Compass<M> { + fn clone(&self) -> Self { + Compass { + style: self.style, + center_deg: self.center_deg, + zoom: self.zoom, + pan_x: self.pan_x, + parms: self.parms, + ptype: self.ptype, + fov_deg: self.fov_deg, + max_view_angle: self.max_view_angle, + on_change: self.on_change.clone(), + } + } +} + +#[derive(Default)] +struct CompassState { + /// (press x, center angle at press) + drag: Option<(f32, f64)>, + /// strong refs: the text pipeline only keeps a Weak to each paragraph + paragraphs: RefCell<Vec<Plain<<R as adv_text::Renderer>::Paragraph>>>, +} + +const DIRS: [(f64, &str); 8] = [ + (0.0, "N"), + (45.0, "NE"), + (90.0, "E"), + (135.0, "SE"), + (180.0, "S"), + (225.0, "SW"), + (270.0, "W"), + (315.0, "NW"), +]; + +/// one text to draw: content, x, y, center around x?, color +struct Txt { + text: String, + x: f32, + y: f32, + centered: bool, + color: Color, +} + +fn stroke_tick(frame: &mut Frame<R>, x: f32, y0: f32, h: f32, w: f32, color: Color) { + if !x.is_finite() { + return; + } + // snap thin lines to integer coords for crisp 1 px strokes + let x = if w < 1.5 { x.round() } else { x }; + let p = Path::new(|p| { + p.move_to(Point::new(x, y0)); + p.line_to(Point::new(x, y0 - h)); + }); + frame.stroke( + &p, + Stroke { + width: w, + style: GeoStyle::Solid(color), + ..Default::default() + }, + ); +} + +impl<M: Clone + Send + 'static> Compass<M> { + /// image-space x of azimuth `alph` (on the horizon), current parms + fn x_img_at(&self, proj: &dyn Projection, alph: f64) -> f64 { + proj.get_coordinates(alph, 0.0, &self.parms).0 + } + + fn alph_at_img_x( + &self, + proj: &dyn Projection, + x_img: f64, + c_ref: f64, + ) -> f64 { + alph_at_img_x(self.ptype, proj, &self.parms, x_img, c_ref) + } + + /// screen x of the image center for the Aligned style + fn center_x(&self, b: Rectangle) -> f32 { + b.x + b.width / 2.0 + self.pan_x + } +} + +impl<M: Clone + Send + 'static> WidgetTrait<M, Theme, R> for Compass<M> { + fn size(&self) -> Size<Length> { + Size::new(Length::Fill, Length::Fixed(STRIP_H)) + } + + fn tag(&self) -> tree::Tag { + tree::Tag::of::<CompassState>() + } + + fn state(&self) -> tree::State { + tree::State::new(CompassState::default()) + } + + fn layout( + &mut self, + _tree: &mut Tree, + _renderer: &R, + limits: &cosmic::iced::advanced::layout::Limits, + ) -> cosmic::iced::advanced::layout::Node { + cosmic::iced::advanced::layout::Node::new(Size::new(limits.max().width, STRIP_H)) + } + + fn draw( + &self, + tree: &Tree, + renderer: &mut R, + theme: &Theme, + _style: &RendererStyle, + layout: Layout<'_>, + _cursor: Cursor, + _viewport: &Rectangle, + ) { + use cosmic::iced::advanced::text::Renderer as _; + + let b = layout.bounds(); + let _ = theme; + // dark instrument panel, clearly distinct from the image area + let on: Color = Color::from_rgb(0.85, 0.85, 0.85); + let bg: Color = Color::from_rgb(0.16, 0.16, 0.16); + let divider: Color = Color::from_rgb(0.32, 0.32, 0.32); + let red = Color::from_rgb(1.0, 0.4, 0.25); + + // geometry rows (snapped so lines stay crisp) + let label_y = (b.y + 5.0).round(); + let y0 = (b.y + STRIP_H - 10.0).round(); // baseline + let tri_y = (b.y + 25.0).round(); + let z = self.zoom; + let proj = projection_from_type(self.ptype); + + let mut texts: Vec<Txt> = Vec::new(); + let mut frame = Frame::with_bounds(renderer, b); + + // panel background + top divider: clearly a separate, draggable area + let panel = Path::new(|p| p.rectangle(b.position(), b.size())); + frame.fill(&panel, bg); + let sep = Path::new(|p| { + p.move_to(Point::new(b.x, b.y + 0.5)); + p.line_to(Point::new(b.x + b.width, b.y + 0.5)); + }); + frame.stroke( + &sep, + Stroke { + width: 1.0, + style: GeoStyle::Solid(divider), + ..Default::default() + }, + ); + + match self.style { + CompassStyle::Off => return, + CompassStyle::Aligned => { + let cx = self.center_x(b); + let c = self.parms.a_center; + // pixels per degree at the center + let ppd = ((self.x_img_at(&*proj, c + 1f64.to_radians()) + - self.x_img_at(&*proj, c - 1f64.to_radians())) + * z as f64 + / 2.0) + .abs(); + let step = [1.0f64, 2.0, 5.0, 10.0, 15.0, 30.0, 45.0, 90.0] + .into_iter() + .find(|s| s * ppd >= 6.0) + .unwrap_or(90.0); + + let a_lo = self + .alph_at_img_x(&*proj, ((b.x - cx) / z) as f64, c) + .min(c - std::f64::consts::PI); + let a_hi = self + .alph_at_img_x(&*proj, ((b.x + b.width - cx) / z) as f64, c) + .max(c + std::f64::consts::PI); + // the rectilinear projection folds directions behind the + // camera onto the same pixels (tan has 180 deg period); + // never draw beyond +-88 deg of the center. Cylindrical is + // linear in azimuth and may legitimately span > 180 deg. + let fold = match self.ptype { + ProjectionType::Rectilinear => 1.535, + ProjectionType::Cylindrical => std::f64::consts::PI, + }; + // additionally clamp to the lens FOV so distortion-folded + // out-of-view directions do not get ticks/labels + let fold = if self.max_view_angle > 0.0 { + fold.min(self.max_view_angle) + } else { + fold + }; + let a_lo = a_lo.max(c - fold); + let a_hi = a_hi.min(c + fold); + + // baseline + let line = Path::new(|p| { + p.move_to(Point::new(b.x, y0 + 0.5)); + p.line_to(Point::new(b.x + b.width, y0 + 0.5)); + }); + frame.stroke( + &line, + Stroke { + width: 1.0, + style: GeoStyle::Solid(on), + ..Default::default() + }, + ); + + // ticks (rise from the baseline, stay below the labels); + // `a` is radians, `step` degrees -> convert once + let step_rad = step.to_radians(); + let mut a = (a_lo / step_rad).floor() * step_rad; + while a <= a_hi { + let x = cx + self.x_img_at(&*proj, a) as f32 * z; + let rem = a.to_degrees().rem_euclid(45.0); + let major = rem.min(45.0 - rem) < step / 2.0; + stroke_tick(&mut frame, x, y0, if major { 12.0 } else { 6.0 }, 1.0, on); + a += step_rad; + } + + // direction labels on the top row; skip directions outside + // the +-88 deg window (they would fold onto the same pixel) + for (deg, name) in DIRS { + let alph = deg.to_radians(); + let rel = (alph - c + std::f64::consts::PI).rem_euclid(std::f64::consts::TAU) + - std::f64::consts::PI; + if rel.abs() > fold { + continue; + } + let x = cx + self.x_img_at(&*proj, alph) as f32 * z; + if !x.is_finite() || x < b.x - 20.0 || x > b.x + b.width + 20.0 { + continue; + } + let color = if deg == 0.0 { red } else { on }; + texts.push(Txt { + text: name.to_string(), + x, + y: label_y, + centered: true, + color, + }); + } + + // center marker: triangle + hairline (tick area only) + let tri = Path::new(|p| { + p.move_to(Point::new(cx - 6.0, tri_y)); + p.line_to(Point::new(cx + 6.0, tri_y)); + p.line_to(Point::new(cx, tri_y + 8.0)); + p.close(); + }); + frame.fill(&tri, red); + let hair = Path::new(|p| { + p.move_to(Point::new(cx.round(), tri_y + 8.0)); + p.line_to(Point::new(cx.round(), y0)); + }); + frame.stroke( + &hair, + Stroke { + width: 1.0, + style: GeoStyle::Solid(red), + ..Default::default() + }, + ); + + let deg = self.center_deg.rem_euclid(360.0); + texts.push(Txt { + text: format!("{deg:05.1}°"), + x: cx + 10.0, + y: tri_y - 3.0, + centered: false, + color: red, + }); + } + CompassStyle::Ruler => { + let bx = b.x; + let f = |alph_deg: f64| { + bx + (alph_deg.rem_euclid(360.0) / 360.0) as f32 * b.width + }; + let center = self.center_deg.rem_euclid(360.0); + let mx = f(center); + + // FOV band (between label row and baseline) + let half = (self.fov_deg / 2.0 / 360.0) as f32 * b.width; + let x0 = (mx - half).max(bx); + let x1 = (mx + half).min(bx + b.width); + if x1 > x0 { + let band = Path::new(|p| { + p.rectangle( + Point::new(x0, tri_y), + Size::new(x1 - x0, y0 - tri_y), + ); + }); + frame.fill(&band, Color::from_rgba(0.4, 0.65, 1.0, 0.20)); + } + + // baseline + ticks every 5 deg + let line = Path::new(|p| { + p.move_to(Point::new(bx, y0 + 0.5)); + p.line_to(Point::new(bx + b.width, y0 + 0.5)); + }); + frame.stroke( + &line, + Stroke { + width: 1.0, + style: GeoStyle::Solid(on), + ..Default::default() + }, + ); + for deg in (0..360).step_by(5) { + let major = deg % 45 == 0; + stroke_tick( + &mut frame, + f(deg as f64), + y0, + if major { 12.0 } else { 6.0 }, + 1.0, + on, + ); + } + for (deg, name) in DIRS { + let color = if deg == 0.0 { red } else { on }; + texts.push(Txt { + text: name.to_string(), + x: f(deg), + y: label_y, + centered: true, + color, + }); + } + + // marker + let tri = Path::new(|p| { + p.move_to(Point::new(mx - 6.0, tri_y)); + p.line_to(Point::new(mx + 6.0, tri_y)); + p.line_to(Point::new(mx, tri_y + 8.0)); + p.close(); + }); + frame.fill(&tri, red); + texts.push(Txt { + text: format!("{center:05.1}°"), + x: mx + 10.0, + y: tri_y - 3.0, + centered: false, + color: red, + }); + } + } + + renderer.draw_geometry(frame.into_geometry()); + + // text (kept alive in state until next frame; positions rounded + // so glyphs land on pixel boundaries) + let font = renderer.default_font(); + let state = tree.state.downcast_ref::<CompassState>(); + { + let mut paras = state.paragraphs.borrow_mut(); + paras.clear(); + for t in texts.iter() { + paras.push(Plain::<<R as adv_text::Renderer>::Paragraph>::new(adv_text::Text { + content: t.text.clone(), + bounds: Size::new(120.0, 20.0), + size: Pixels(13.0), + line_height: LineHeight::default(), + font, + align_x: alignment::Horizontal::Left.into(), + align_y: alignment::Vertical::Top.into(), + shaping: adv_text::Shaping::Basic, + wrapping: adv_text::Wrapping::None, + ellipsize: adv_text::Ellipsize::None, + })); + } + } + let paras = state.paragraphs.borrow(); + for (gi, t) in texts.iter().enumerate() { + let para = ¶s[gi]; + let w = para.min_bounds().width; + let x = if t.centered { t.x - w / 2.0 } else { t.x }; + renderer.fill_paragraph( + para.raw(), + Point::new(x.round(), t.y.round()), + t.color, + b, + ); + } + } + + fn update( + &mut self, + tree: &mut Tree, + event: &Event, + layout: Layout<'_>, + cursor: Cursor, + _renderer: &R, + _clipboard: &mut dyn Clipboard, + shell: &mut Shell<'_, M>, + _viewport: &Rectangle, + ) { + let state = tree.state.downcast_mut::<CompassState>(); + let b = layout.bounds(); + let proj = projection_from_type(self.ptype); + + match event { + Event::Mouse(mouse::Event::ButtonPressed(Button::Left)) => { + let Some(p) = cursor.position_over(b) else { return }; + state.drag = Some((p.x, self.center_deg)); + if self.style == CompassStyle::Ruler { + let alph = ((p.x - b.x) / b.width * 360.0) as f64; + shell.publish((self.on_change)(alph)); + } + } + Event::Mouse(mouse::Event::ButtonReleased(Button::Left)) => { + state.drag = None; + } + Event::Mouse(mouse::Event::CursorMoved { .. }) => { + let Some((x0, c0)) = state.drag else { return }; + let Some(p) = cursor.position() else { return }; + match self.style { + CompassStyle::Aligned => { + let cx = self.center_x(b); + let z = self.zoom; + let a0 = + self.alph_at_img_x(&*proj, ((x0 - cx) / z) as f64, c0.to_radians()); + let a1 = + self.alph_at_img_x(&*proj, ((p.x - cx) / z) as f64, c0.to_radians()); + let new_c = (c0.to_radians() - (a1 - a0)).to_degrees(); + shell.publish((self.on_change)(new_c)); + } + CompassStyle::Ruler => { + let alph = ((p.x - b.x) / b.width * 360.0) as f64; + shell.publish((self.on_change)(alph)); + } + CompassStyle::Off => {} + } + } + _ => {} + } + } + + fn mouse_interaction( + &self, + _tree: &Tree, + layout: Layout<'_>, + cursor: Cursor, + _viewport: &Rectangle, + _renderer: &R, + ) -> Interaction { + if cursor.position_over(layout.bounds()).is_some() { + Interaction::Grab + } else { + Interaction::None + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn roundtrip(ptype: ProjectionType, k0: f64, k1: f64, x0: f64) { + let proj = projection_from_type(ptype); + let mut parms = ViewParams::new(); + parms.a_center = 0.3; + parms.scale = 3000.0; + parms.k0 = k0; + parms.k1 = k1; + parms.x0 = x0; + for x in [-2500.0, -800.0, -50.0, 0.0, 120.0, 900.0, 2400.0] { + let a = alph_at_img_x(ptype, &*proj, &parms, x, parms.a_center); + let (x2, _) = proj.get_coordinates(a, 0.0, &parms); + assert!( + (x2 - x).abs() < 1e-6, + "{ptype:?} x={x}: round-trips to {x2} (alph {a})" + ); + } + } + + #[test] + fn inverse_rectilinear() { + roundtrip(ProjectionType::Rectilinear, 0.0, 0.0, 0.0); + } + #[test] + fn inverse_rectilinear_distorted() { + // realistic magnitudes: x0 is in normalized (pre-scale) units + roundtrip(ProjectionType::Rectilinear, 0.002, -0.0003, 0.01); + } + #[test] + fn inverse_cylindrical() { + roundtrip(ProjectionType::Cylindrical, 0.0, 0.0, 0.0); + } +} diff --git a/crates/gipfel-app/src/dump.rs b/crates/gipfel-app/src/dump.rs new file mode 100644 index 0000000..0bcfe56 --- /dev/null +++ b/crates/gipfel-app/src/dump.rs @@ -0,0 +1,285 @@ +//! Screen dump: render markers/labels onto the photo and save as PNG/JPEG. +//! Replaces FLTK's window capture from the original "Screen Dump" menu item. + +use image::RgbaImage; +use std::path::Path; + +pub struct DumpMarker { + pub x: f64, + pub y: f64, + pub name: String, + pub known: bool, + pub hidden: bool, +} + +pub struct DumpTrackPt { + pub x: f64, + pub y: f64, + pub hidden: bool, + pub width: f64, +} + +fn px(img: &mut RgbaImage, x: i64, y: i64, c: [u8; 4]) { + if x >= 0 && y >= 0 && (x as u32) < img.width() && (y as u32) < img.height() { + img.put_pixel(x as u32, y as u32, image::Rgba(c)); + } +} + +fn line(img: &mut RgbaImage, x0: f64, y0: f64, x1: f64, y1: f64, c: [u8; 4], w: i64) { + let dx = x1 - x0; + let dy = y1 - y0; + let n = (dx.hypot(dy) as i64).max(1); + for i in 0..=n { + let t = i as f64 / n as f64; + let (x, y) = (x0 + dx * t, y0 + dy * t); + for oy in -w..=w { + for ox in -w..=w { + px(img, x.round() as i64 + ox, y.round() as i64 + oy, c); + } + } + } +} + +fn circle(img: &mut RgbaImage, cx: f64, cy: f64, r: f64, c: [u8; 4]) { + let n = (2.0 * std::f64::consts::PI * r.max(1.0)) as i64; + for i in 0..=n { + let a = i as f64 / n as f64 * 2.0 * std::f64::consts::PI; + px(img, (cx + r * a.cos()).round() as i64, (cy + r * a.sin()).round() as i64, c); + px(img, (cx + (r + 1.0) * a.cos()).round() as i64, (cy + (r + 1.0) * a.sin()).round() as i64, c); + } +} + +fn tri(img: &mut RgbaImage, p: [(f64, f64); 3], c: [u8; 4]) { + let ymin = p.iter().map(|q| q.y() as i64).min().unwrap(); + let ymax = p.iter().map(|q| q.y() as i64).max().unwrap(); + for y in ymin..=ymax { + let mut xmin = i64::MAX; + let mut xmax = i64::MIN; + for i in 0..3 { + let a = p[i]; + let b = p[(i + 1) % 3]; + if (a.y() as i64) == (b.y() as i64) { + continue; + } + if y >= (a.y() as i64).min(b.y() as i64) && y <= (a.y() as i64).max(b.y() as i64) { + let t = (y as f64 - a.y()) / (b.y() - a.y()); + let x = a.x() + t * (b.x() - a.x()); + xmin = xmin.min(x.round() as i64); + xmax = xmax.max(x.round() as i64); + } + } + for x in xmin..=xmax { + px(img, x, y, c); + } + } +} + +trait XY { + fn x(self) -> f64; + fn y(self) -> f64; +} +impl XY for (f64, f64) { + fn x(self) -> f64 { + self.0 + } + fn y(self) -> f64 { + self.1 + } +} + +fn load_font(family: &str) -> Option<fontdue::Font> { + // Resolve the COSMIC interface font (or system sans-serif fallback) through + // the same font discovery cosmic's text engine uses, then hand the bytes to + // fontdue for the bitmap dump. + static FS: std::sync::OnceLock<std::sync::Mutex<cosmic_text::FontSystem>> = + std::sync::OnceLock::new(); + let mut fs = FS + .get_or_init(|| std::sync::Mutex::new(cosmic_text::FontSystem::new())) + .lock() + .unwrap(); + let fam = [fontdb::Family::Name(family)]; + let id = fs + .db() + .query(&fontdb::Query { families: &fam, ..Default::default() }) + .or_else(|| fs.db().query(&fontdb::Query::default()))?; + let font = fs.get_font(id, fontdb::Weight::NORMAL)?; + fontdue::Font::from_bytes( + font.data().to_vec(), + fontdue::FontSettings { scale: 64.0, ..Default::default() }, + ) + .ok() +} + +struct GlyphBlit { + x: f32, + y: f32, + width: usize, + #[allow(dead_code)] + height: usize, + pixels: Vec<u8>, +} + +fn layout_text(font: &fontdue::Font, text: &str, size: f32) -> Vec<GlyphBlit> { + use fontdue::layout::{CoordinateSystem, Layout as FontLayout, TextStyle}; + let mut l = FontLayout::new(CoordinateSystem::PositiveYDown); + l.append(&[font], &TextStyle::new(text, size, 0)); + l.glyphs() + .iter() + .map(|g| { + let (m, pixels) = font.rasterize_config(g.key); + GlyphBlit { x: g.x, y: g.y, width: m.width, height: m.height, pixels } + }) + .collect() +} + +fn draw_text(img: &mut RgbaImage, font: &fontdue::Font, x: f64, y: f64, text: &str, c: [u8; 4], size: f32) { + for glyph in layout_text(font, text, size) { + let gx0 = (x + glyph.x as f64).round() as i64; + let gy0 = (y + glyph.y as f64).round() as i64; + for (i, &alpha) in glyph.pixels.iter().enumerate() { + if alpha == 0 { + continue; + } + let gx = gx0 + (i % glyph.width) as i64; + let gy = gy0 + (i / glyph.width) as i64; + if gx < 0 || gy < 0 || gx >= img.width() as i64 || gy >= img.height() as i64 { + continue; + } + let a = alpha as u32; + let old = img.get_pixel(gx as u32, gy as u32).0; + let blend = |o: u8, n: u8| ((o as u32 * (255 - a) + n as u32 * a) / 255) as u8; + px(img, gx, gy, [blend(old[0], c[0]), blend(old[1], c[1]), blend(old[2], c[2]), 255]); + } + } +} + +fn text_width(font: &fontdue::Font, text: &str, size: f32) -> f64 { + layout_text(font, text, size) + .iter() + .map(|g| (g.x + g.width as f32) as f64) + .fold(0.0, f64::max) +} + +/// Compose the dump: photo + crosses/leaders/labels + track. +/// +/// `font_size` is the on-screen label font size in screen pixels, `scale` +/// converts screen pixels to image pixels (1 / zoom): the overlay geometry +/// is specified in screen pixels (as seen on the display) but the dump is +/// rendered at the image's native resolution, so every size must be scaled +/// accordingly. Label placement runs the exact same collision-avoiding +/// layout as the on-screen viewport (in screen space, then mapped back to +/// image space), so the dump shows the labels at the same positions. +pub fn render( + img: &RgbaImage, + markers: &[DumpMarker], + track: &[DumpTrackPt], + out: &Path, + font_size: f32, + scale: f64, + font_family: &str, +) -> Result<(), String> { + let mut canvas = img.clone(); + let (w, h) = (img.width() as f64, img.height() as f64); + let (cx, cy) = (w / 2.0, h / 2.0); + let s = scale.max(0.1); + let font_img = f64::from(font_size) * s; + let font = load_font(font_family); + + // track + for win in track.windows(2) { + let (a, b) = (&win[0], &win[1]); + let c = if a.hidden { [51, 102, 255, 255] } else { [255, 51, 51, 255] }; + line(&mut canvas, cx + a.x, cy + a.y, cx + b.x, cy + b.y, c, (a.width as i64).max(1)); + } + + // label layout: the exact same collision-avoiding code as the on-screen + // viewport (see viewport::layout_label_y). It runs in screen space + // (marker positions / scale, screen font size); the resulting offsets + // are mapped back to image space with s. Needed for the leader lines + // and the label drawing below. + let line_h = f64::from(font_size) * 1.3 + 2.0; + let in_img: Vec<bool> = markers + .iter() + .map(|m| m.x.abs() * 2.0 <= w && m.y.abs() * 2.0 <= h) + .collect(); + let layout: Option<Vec<(f32, f32)>> = font.as_ref().map(|font| { + let sx: Vec<f32> = markers.iter().map(|m| (m.x / s) as f32).collect(); + let sy: Vec<f32> = markers.iter().map(|m| (m.y / s) as f32).collect(); + let widths: Vec<f32> = markers + .iter() + .map(|m| text_width(font, &m.name, font_size) as f32) + .collect(); + crate::viewport::layout_label_y(&sx, &sy, &widths, &in_img, line_h as f32) + }); + + let yellow = [255, 230, 51, 255]; + // ~1 screen pixel stroke at image resolution + let lw = ((s - 1.0) / 2.0).round().max(0.0) as i64; + // like the screen: known-hill flags in red + let flag_color = [255, 64, 64, 255]; + for (i, m) in markers.iter().enumerate() { + let (x, y) = (cx + m.x, cy + m.y); + if x < -10.0 || y < -10.0 || x > w + 10.0 || y > h + 10.0 || !in_img[i] { + continue; + } + // yellow cross + leader line up to the label (screen section 3) + let d = 4.0 * s; + line(&mut canvas, x - d, y, x + d, y, yellow, lw); + if let Some(lay) = &layout { + let (lx, ly) = lay[i]; + let label_line = y + (f64::from(ly) - line_h) * s; + line(&mut canvas, x, y, x, label_line, yellow, lw); + line(&mut canvas, x, label_line, x + f64::from(lx) * s, label_line, yellow, lw); + } + } + // known-hill flags (pole + pennant + circle), on top of all leaders + for (i, m) in markers.iter().enumerate() { + if !m.known || !in_img[i] { + continue; + } + let (x, y) = (cx + m.x, cy + m.y); + if x < -10.0 || y < -10.0 || x > w + 10.0 || y > h + 10.0 { + continue; + } + let pole = 16.0 * s; + line(&mut canvas, x, y, x, y - pole, flag_color, (s.round() as i64).max(1)); + tri( + &mut canvas, + [(x, y - pole), (x + 10.0 * s, y - pole * 0.8), (x, y - pole * 0.625)], + flag_color, + ); + circle(&mut canvas, x, y, 3.0 * s, flag_color); + } + + if let (Some(font), Some(layout)) = (&font, &layout) { + for (i, m) in markers.iter().enumerate() { + if !in_img[i] { + continue; + } + let (_, ly) = layout[i]; + let (x, y) = (cx + m.x + 2.0 * s, cy + m.y + (f64::from(ly) - line_h) * s); + if x < 0.0 || y < 0.0 || x > w || y > h { + continue; + } + let tw = text_width(font, &m.name, font_img as f32); + for yy in (y - 2.0 * s) as i64..=(y + font_img + 2.0 * s) as i64 { + for xx in (x - 1.0 * s) as i64..=(x + tw + 1.0 * s) as i64 { + px(&mut canvas, xx, yy, [0, 0, 0, 160]); + } + } + let c = if m.hidden { [102, 153, 255, 255] } else { [255, 255, 255, 255] }; + draw_text(&mut canvas, font, x, y, &m.name, c, font_img as f32); + } + } + + if out + .extension() + .is_some_and(|e| e.eq_ignore_ascii_case("jpg") || e.eq_ignore_ascii_case("jpeg")) + { + let rgb = image::DynamicImage::ImageRgba8(canvas).to_rgb8(); + rgb.save(out.with_extension("jpg")).map_err(|e| e.to_string())?; + } else { + canvas.save(out.with_extension("png")).map_err(|e| e.to_string())?; + } + Ok(()) +} diff --git a/crates/gipfel-app/src/main.rs b/crates/gipfel-app/src/main.rs new file mode 100644 index 0000000..4cf0c63 --- /dev/null +++ b/crates/gipfel-app/src/main.rs @@ -0,0 +1,1805 @@ +//! gipfel for the COSMIC desktop: annotate mountain panoramas. +//! +//! M2/M3: full app skeleton (menus, dialogs, settings sidebar) plus the +//! interactive viewport (marker placement, refit, context menu, track). + +mod compass; +mod dump; +mod viewport; + +use std::marker::PhantomData; +use std::path::{Path, PathBuf}; +use std::rc::Rc; + +use cosmic::app::{Core, Task}; +use cosmic::iced::keyboard::{self, Key}; +use cosmic::iced::window::Event as WinEvent; +use cosmic::iced::{event, Color, Event, Length, Subscription, Vector}; +use cosmic::widget::{self, menu, menu::action::MenuAction}; +use cosmic::{Application, ApplicationExt, Element, Theme}; + +use gipfel_core::hill::{self, Hill, FLAG_DUPLIC, FLAG_HIDDEN, FLAG_TRACK_POINT, FLAG_VISIBLE}; +use gipfel_core::metadata::ImageMetaData; +use gipfel_core::panorama::Panorama; +use gipfel_core::projection::ProjectionType; +use gipfel_core::stitch; +use gipfel_core::track; + +use compass::{Compass, CompassStyle, STRIP_H}; + +use viewport::{Marker, TrackPt, ViewportWidget, VpMsg}; + +/// actions of the right-click popover menu on the viewport. +/// The click position / hit index are baked into the action at menu-build +/// time (like cosmic-files bakes its entity), so the handler never depends +/// on state that may have changed while the menu was open. +#[derive(Clone, Copy, PartialEq)] +pub enum CtxAction { + /// image-space position of the right-click + FindPeak(f64, f64), + /// hill index of the clicked marker + ToggleHidden(usize), +} + +impl Eq for CtxAction {} + +impl MenuAction for CtxAction { + type Message = Message; + + fn message(&self) -> Message { + match self { + CtxAction::FindPeak(x, y) => Message::ContextFindPeak(*x, *y), + CtxAction::ToggleHidden(i) => Message::ContextToggleHidden(*i), + } + } +} + +pub struct Flags { + pub data: Option<PathBuf>, + pub image: Option<PathBuf>, +} + +pub struct Gipfel { + core: Core, + pan: Panorama, + project: Option<Project>, + /// hill indices of the known (flagged) markers + known: Vec<usize>, + /// hill indices of the GPS track points, in file order + track: Vec<usize>, + // viewport state + zoom: f32, + fit: bool, + panv: Vector, + hover: Option<usize>, + ctrl: bool, + version: u64, + win_w: f64, + win_h: f64, + vp_w: f64, + vp_h: f64, + // sidebar state + lat_in: String, + lon_in: String, + height_in: String, + k0_in: String, + k1_in: String, + x0_in: String, + profile_in: String, + profiles: Vec<String>, + profile_overwrite: bool, + track_width: f64, + show_hidden: bool, + fit_distortion: bool, + label_font: f32, + compass_style: CompassStyle, + status: String, + // overlays + picker: Option<Picker>, + context: Option<ContextState>, + /// peak info shown in the status bar while the mouse hovers a marker + hover_info: Option<String>, + about: bool, +} + +struct Project { + path: PathBuf, + handle: cosmic::widget::image::Handle, + w: u32, + h: u32, + md: ImageMetaData, +} + +struct Picker { + title: String, + query: String, + mode: PickerMode, +} + +#[derive(Clone, Copy)] +enum PickerMode { + Viewpoint, + FindPeak { img_x: f64, img_y: f64 }, +} + +struct ContextState { + img_x: f64, + img_y: f64, + hit: Option<usize>, +} + +#[derive(Debug, Clone)] +pub enum Message { + Vp(VpMsg), + Event(Event), + WinResized(f64, f64), + FileDropped(Vec<PathBuf>), + + OpenImage, + OpenPath(Option<PathBuf>), + ImageLoaded(Box<Result<LoadedImage, String>>), + SaveImage, + SavePath(Option<PathBuf>), + ImageSaved(Option<PathBuf>), + DumpImage, + ImageDumped(Box<Result<PathBuf, String>>), + StitchTiff, + StitchDone(Box<Result<PathBuf, String>>), + LoadTrack, + TrackLoaded(Box<Result<Vec<Hill>, String>>), + + ChooseViewpoint, + PickerQuery(String), + PickerPick(usize), + PickerClose, + ContextFindPeak(f64, f64), + ContextToggleHidden(usize), + Surface(cosmic::surface::Action<Message>), + Redraw, + + Center(f64), + Pitch(f64), + Roll(f64), + LabelFont(f32), + Focal(f64), + Visibility(f64), + TrackWidth(f64), + Lat(String), + Lon(String), + Height(String), + ViewApply, + K0(String), + K1(String), + X0(String), + DistortionApply, + ProfileName(String), + ProfileSave, + ProfileLoad, + ProfileSelect(usize), + Projection(ProjectionType), + ToggleShowHidden, + FitDistortion(bool), + ToggleNav, + CompassStyle(CompassStyle), + + Fit, + ZoomIn, + ZoomOut, + About(bool), + Quit, +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +enum Action { + Open, + Save, + Dump, + Stitch, + LoadTrack, + Quit, + ChooseViewpoint, + ShowHidden, + Fit, + ZoomIn, + ZoomOut, + ProjNormal, + ProjPanoramic, + CompassAligned, + CompassRuler, + CompassOff, + About, +} + +impl MenuAction for Action { + type Message = Message; + fn message(&self) -> Message { + match self { + Action::Open => Message::OpenImage, + Action::Save => Message::SaveImage, + Action::Dump => Message::DumpImage, + Action::Stitch => Message::StitchTiff, + Action::LoadTrack => Message::LoadTrack, + Action::Quit => Message::Quit, + Action::ChooseViewpoint => Message::ChooseViewpoint, + Action::ShowHidden => Message::ToggleShowHidden, + Action::Fit => Message::Fit, + Action::ZoomIn => Message::ZoomIn, + Action::ZoomOut => Message::ZoomOut, + Action::ProjNormal => Message::Projection(ProjectionType::Rectilinear), + Action::ProjPanoramic => Message::Projection(ProjectionType::Cylindrical), + Action::CompassAligned => Message::CompassStyle(CompassStyle::Aligned), + Action::CompassRuler => Message::CompassStyle(CompassStyle::Ruler), + Action::CompassOff => Message::CompassStyle(CompassStyle::Off), + Action::About => Message::About(true), + } + } +} + +impl From<VpMsg> for Message { + fn from(m: VpMsg) -> Self { + Message::Vp(m) + } +} + +#[derive(Clone)] +pub struct LoadedImage { + path: PathBuf, + w: u32, + h: u32, + handle: cosmic::widget::image::Handle, + md: ImageMetaData, +} + +impl std::fmt::Debug for LoadedImage { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "LoadedImage({})", self.path.display()) + } +} + +/// Load a GPS track from a `.gpx` (GPS Exchange) or `.csv`/`.dat` (gipfel +/// hill-CSV) file, returning hills flagged as track points. +fn load_track_file(path: &Path) -> Result<Vec<Hill>, String> { + if path.extension().is_some_and(|e| e.eq_ignore_ascii_case("gpx")) { + track::load_gpx(&path.to_string_lossy(), 2000) + } else { + let mut hs = hill::load(&path.to_string_lossy()).map_err(|e| e.to_string())?; + for h in hs.iter_mut() { + h.flags |= FLAG_TRACK_POINT; + } + Ok(hs) + } +} + +fn data_candidates(flag: Option<&Path>) -> Vec<PathBuf> { + let mut v = Vec::new(); + if let Some(p) = flag { + v.push(p.to_path_buf()); + } + if let Ok(e) = std::env::var("GIPFEL_DATA") { + v.push(PathBuf::from(e)); + } + v.push(PathBuf::from("gipfel.dat")); + if let Some(home) = std::env::var_os("HOME") { + v.push(PathBuf::from(home).join(".local/share/gipfel/gipfel.dat")); + } + v.push(PathBuf::from("/usr/local/share/gipfel/gipfel.dat")); + v.push(PathBuf::from("/usr/share/gipfel/gipfel.dat")); + v +} + +/// Inverse projection for the vertical axis: the elevation whose projected +/// pixel row (image-centered coords, center column) is `y_img`. Shares the +/// damped Newton iteration with the compass strip (`compass::newton_inverse`). +fn elev_at_img_y(pan: &Panorama, y_img: f64) -> f64 { + let c = pan.parms.a_center; + let p = pan.parms.a_pitch; + let seed = p - (y_img / pan.parms.scale).atan(); + compass::newton_inverse( + y_img, + |e| pan.project_point(c, e).map(|v| v.1), + seed, + p - 1.535, + p + 1.535, + ) +} + +impl Gipfel { + fn bump(&mut self) { + // keep the visibility limit in sync with the lens' actual field of + // view: the angle at which the (distorted) projection reaches the + // image edge. Directions beyond it cannot be inside the photo, even + // if the distortion model folds their projection back into it. + let limit = self.view_angle_limit(); + if (limit - self.pan.max_view_angle).abs() > 1e-9 { + self.pan.max_view_angle = limit; + // keep the user-placed marker positions (observations) intact + self.pan.update_visible_mountains(Some(&self.known)); + } + self.version += 1; + } + + /// Reload the stored profile names from the prefs file. + fn refresh_profiles(&mut self) { + self.profiles = gipfel_core::profile::list().into_iter().map(|(n, _)| n).collect(); + } + + /// Load a stored profile and apply its distortion parameters. + fn apply_profile(&mut self, name: &str) { + match gipfel_core::profile::load(name) { + Ok(p) => { + self.pan.set_distortion_params(p.k0, p.k1, p.x0); + self.sync_inputs(); + self.bump(); + self.status = format!("loaded profile '{name}'"); + } + Err(e) => self.status = format!("profile '{name}': {e}"), + } + } + + /// half-angle (radians) the projection maps the image's right edge to, + /// i.e. the horizontal FOV of the lens including fitted distortion. + /// 0 = no image loaded / not computable. + fn view_angle_limit(&self) -> f64 { + let Some(p) = &self.project else { + return 0.0; + }; + let proj = gipfel_core::projection::projection_from_type(self.pan.projection_type); + let c = self.pan.parms.a_center; + let a_edge = compass::alph_at_img_x( + self.pan.projection_type, + &*proj, + &self.pan.parms, + p.w as f64 / 2.0, + c, + ); + (a_edge - c).abs() + } + + fn img_max(&self) -> f64 { + self.project + .as_ref() + .map(|p| p.w.max(p.h) as f64) + .unwrap_or(1000.0) + } + + fn focal_35mm(&self) -> f64 { + self.pan.get_scale() * 35.0 / self.img_max() + } + + fn set_focal_35mm(&mut self, f: f64) { + self.pan.set_scale(f * self.img_max() / 35.0); + } + + fn sync_inputs(&mut self) { + self.lat_in = format!("{:.5}", self.pan.get_view_lat()); + self.lon_in = format!("{:.5}", self.pan.get_view_long()); + self.height_in = format!("{:.0}", self.pan.get_view_height()); + self.k0_in = format!("{:.5}", self.pan.parms.k0); + self.k1_in = format!("{:.5}", self.pan.parms.k1); + self.x0_in = format!("{:.1}", self.pan.parms.x0); + } + + fn fit_zoom(&self) -> f32 { + let p = match &self.project { + Some(p) => p, + None => return 1.0, + }; + if self.vp_w < 10.0 || self.vp_h < 10.0 { + return 1.0; + } + (self.vp_w / p.w as f64).min(self.vp_h / p.h as f64) as f32 + } + + fn markers(&self) -> Rc<Vec<Marker>> { + let mut v = Vec::new(); + for &i in &self.pan.visible { + let h = &self.pan.hills[i]; + if h.is_track_point() || h.flags & FLAG_DUPLIC != 0 { + continue; + } + let hidden = h.flags & FLAG_HIDDEN != 0; + if hidden && !self.show_hidden { + continue; + } + v.push(Marker { + x: h.x, + y: h.y, + name: h.name.as_str().into(), + idx: i, + known: self.known.contains(&i), + hidden, + }); + } + Rc::new(v) + } + + fn track_pts(&self) -> Rc<Vec<TrackPt>> { + let v = self + .track + .iter() + .filter(|&&i| self.pan.hills[i].flags & FLAG_VISIBLE != 0) + .map(|&i| { + let h = &self.pan.hills[i]; + // C: max(scale * track_width / (dist_m * 10), 1) - distance in + // meters. (Was wrongly divided by km here, inflating widths + // 1000x and breaking stroke triangulation.) Clamped high so + // near-camera points can't produce absurd strokes. + let dist_m = self.pan.get_real_distance(i).max(1.0); + let width = + (self.pan.get_scale() * self.track_width / (dist_m * 10.0)).clamp(1.0, 1000.0); + TrackPt { + x: h.x, + y: h.y, + hidden: h.flags & FLAG_HIDDEN != 0, + width, + } + }) + .collect(); + Rc::new(v) + } + + /// recompute viewport metrics from window size, nav and compass state + fn remeasure(&mut self) { + let nav = if self.core().nav_bar_active() { 340.0 } else { 0.0 }; + let strip = if self.project.is_some() && self.compass_style != CompassStyle::Off { + STRIP_H as f64 + } else { + 0.0 + }; + self.vp_w = (self.win_w - nav).max(100.0); + self.vp_h = (self.win_h - 100.0 - strip).max(100.0); + if self.fit { + self.zoom = self.fit_zoom(); + } + } + + fn refit(&mut self) { + if self.known.is_empty() { + return; + } + if let Err(e) = self.pan.comp_params(&self.known, self.fit_distortion) { + self.status = format!("refit failed: {e}"); + } + self.sync_inputs(); + self.bump(); + } + + fn md_from_state(&self) -> ImageMetaData { + let mut md = ImageMetaData::new(); + if let Some(p) = &self.project { + md.manufacturer = p.md.manufacturer.clone(); + md.model = p.md.model.clone(); + } + md.longitude = self.pan.get_view_long(); + md.latitude = self.pan.get_view_lat(); + md.height = self.pan.get_view_height(); + md.direction = self.pan.get_center_angle(); + md.pitch = self.pan.get_pitch_angle(); + md.roll = self.pan.get_roll_angle(); + md.focal_length_35mm = self.focal_35mm(); + md.projection_type = self.pan.projection_type as i32; + md.k0 = self.pan.parms.k0; + md.k1 = self.pan.parms.k1; + md.x0 = self.pan.parms.x0; + md + } + + fn open_image(&mut self, path: PathBuf) -> Task<Message> { + let task = async move { + let img = image::open(&path).map_err(|e| format!("{}: {e}", path.display()))?; + let (w, h) = (img.width(), img.height()); + let rgba = img.to_rgba8(); + let handle = cosmic::widget::image::Handle::from_rgba(w, h, rgba.into_raw()); + let mut md = ImageMetaData::new(); + md.load_image(&path.to_string_lossy()); + Ok(LoadedImage { path, w, h, handle, md }) + }; + cosmic::task::future(async move { Message::ImageLoaded(Box::new(task.await)) }) + } + + fn picker_entries(&self, p: &Picker) -> Vec<(String, usize)> { + let mut idxs: Vec<usize> = match p.mode { + PickerMode::Viewpoint => (0..self.pan.hills.len()).collect(), + PickerMode::FindPeak { .. } => self.pan.close.clone(), + }; + let q = p.query.to_uppercase(); + let mut entries: Vec<(String, usize)> = idxs + .drain(..) + .filter(|&i| { + let h = &self.pan.hills[i]; + h.flags & (FLAG_DUPLIC | FLAG_TRACK_POINT) == 0 + && (q.is_empty() || h.name.to_uppercase().contains(&q)) + }) + .map(|i| (format!("{} ({} m)", self.pan.hills[i].name, self.pan.hills[i].height as i64), i)) + .collect(); + entries.sort_by(|a, b| a.0.cmp(&b.0)); + entries.truncate(300); + entries + } + + fn update_vp(&mut self, msg: VpMsg) -> Task<Message> { + match msg { + VpMsg::ZoomAt { factor, img } => { + let new_zoom = (self.zoom * factor).clamp(0.02, 16.0); + let z = self.zoom as f64; + let nz = new_zoom as f64; + self.panv = Vector::new( + self.panv.x + (img.x as f64 * (z - nz)) as f32, + self.panv.y + (img.y as f64 * (z - nz)) as f32, + ); + self.zoom = new_zoom; + self.fit = false; + } + VpMsg::PanBy { delta } => { + self.panv = Vector::new(self.panv.x + delta.x, self.panv.y + delta.y); + self.fit = false; + } + VpMsg::PanTo { pan } => { + self.panv = pan; + self.fit = false; + } + VpMsg::MoveMarker { idx, img } => { + if idx < self.pan.hills.len() { + self.pan.hills[idx].x = img.x as f64; + self.pan.hills[idx].y = img.y as f64; + self.bump(); + } + } + VpMsg::DragEnd { had_marker } => { + if had_marker { + self.refit(); + } + } + VpMsg::ToggleKnown(hit) => { + if let Some(i) = hit { + if let Some(pos) = self.known.iter().position(|&k| k == i) { + self.known.remove(pos); + } else { + self.known.push(i); + } + self.refit(); + } + } + VpMsg::ContextAt { img, hit } => { + self.context = Some(ContextState { img_x: img.x as f64, img_y: img.y as f64, hit }); + } + VpMsg::Hover(h) => { + if h != self.hover { + self.hover = h; + self.hover_info = h.map(|i| { + let hm = &self.pan.hills[i]; + format!( + "{} ({} m), distance {:.2} km", + hm.name, + hm.height as i64, + self.pan.get_real_distance(i) / 1000.0 + ) + }); + } + } + } + Task::none() + } +} + +impl Application for Gipfel { + type Executor = cosmic::executor::Default; + type Flags = Flags; + type Message = Message; + const APP_ID: &'static str = "org.gipfel.App"; + + fn core(&self) -> &Core { + &self.core + } + + fn core_mut(&mut self) -> &mut Core { + &mut self.core + } + + fn init(core: Core, flags: Flags) -> (Self, Task<Message>) { + let mut pan = Panorama::new(); + let mut status = String::from("no hill database loaded"); + for c in data_candidates(flags.data.as_deref()) { + if c.is_file() { + match pan.load_data(&c.to_string_lossy()) { + Ok(()) => { + status = format!("{} hills loaded", pan.hills.len()); + break; + } + Err(e) => status = format!("cannot read {}: {e}", c.display()), + } + } + } + + let mut app = Gipfel { + core, + pan, + project: None, + known: Vec::new(), + track: Vec::new(), + zoom: 1.0, + fit: true, + panv: Vector::ZERO, + hover: None, + ctrl: false, + version: 0, + win_w: 1280.0, + win_h: 800.0, + vp_w: 0.0, + vp_h: 0.0, + lat_in: String::new(), + lon_in: String::new(), + height_in: String::new(), + k0_in: String::new(), + k1_in: String::new(), + x0_in: String::new(), + profile_in: String::new(), + profiles: gipfel_core::profile::list().into_iter().map(|(n, _)| n).collect(), + profile_overwrite: false, + track_width: 200.0, + show_hidden: false, + label_font: viewport::DEFAULT_LABEL_FONT, + fit_distortion: false, + compass_style: CompassStyle::Aligned, + status, + picker: None, + context: None, + hover_info: None, + about: false, + }; + app.sync_inputs(); + + let task = match flags.image { + Some(p) => app.open_image(p), + None => Task::none(), + }; + (app, task) + } + + fn header_start(&self) -> Vec<Element<'_, Message>> { + let mut kb = std::collections::HashMap::new(); + use cosmic::widget::menu::key_bind::{KeyBind, Modifier}; + let kb = &mut kb; + for (ch, action) in [ + ("o", Action::Open), + ("s", Action::Save), + ("d", Action::Dump), + ("t", Action::LoadTrack), + ("v", Action::ChooseViewpoint), + ("f", Action::Fit), + ("q", Action::Quit), + ] { + kb.insert( + KeyBind { modifiers: vec![Modifier::Ctrl], key: Key::Character(ch.into()) }, + action, + ); + } + + let file = menu::Tree::with_children( + cosmic::widget::RcElementWrapper::new(menu::root("File").into()), + menu::items( + kb, + vec![ + menu::Item::Button("Open Image…", None, Action::Open), + menu::Item::Button("Save Image…", None, Action::Save), + menu::Item::Button("Screen Dump…", None, Action::Dump), + menu::Item::Button("Stitch Cylindrical TIFF…", None, Action::Stitch), + menu::Item::Divider, + menu::Item::Button("Load GPX Track…", None, Action::LoadTrack), + menu::Item::Divider, + menu::Item::Button("Quit", None, Action::Quit), + ], + ), + ); + let view = menu::Tree::with_children( + cosmic::widget::RcElementWrapper::new(menu::root("View").into()), + menu::items( + kb, + vec![ + menu::Item::Button("Choose Viewpoint…", None, Action::ChooseViewpoint), + menu::Item::CheckBox( + "Show Hidden", + None, + self.show_hidden, + Action::ShowHidden, + ), + menu::Item::Divider, + menu::Item::Button("Zoom In", None, Action::ZoomIn), + menu::Item::Button("Zoom Out", None, Action::ZoomOut), + menu::Item::Button("Fit", None, Action::Fit), + menu::Item::Divider, + menu::Item::CheckBox( + "Compass strip", + None, + self.compass_style == CompassStyle::Aligned, + Action::CompassAligned, + ), + menu::Item::CheckBox( + "Compass ruler", + None, + self.compass_style == CompassStyle::Ruler, + Action::CompassRuler, + ), + menu::Item::CheckBox( + "Compass off", + None, + self.compass_style == CompassStyle::Off, + Action::CompassOff, + ), + ], + ), + ); + let projection = menu::Tree::with_children( + cosmic::widget::RcElementWrapper::new(menu::root("Projection").into()), + menu::items( + kb, + vec![ + menu::Item::CheckBox( + "Normal", + None, + self.pan.projection_type == ProjectionType::Rectilinear, + Action::ProjNormal, + ), + menu::Item::CheckBox( + "Panoramic", + None, + self.pan.projection_type == ProjectionType::Cylindrical, + Action::ProjPanoramic, + ), + ], + ), + ); + let help = menu::Tree::with_children( + cosmic::widget::RcElementWrapper::new(menu::root("Help").into()), + menu::items(kb, vec![menu::Item::Button("About gipfel", None, Action::About)]), + ); + + vec![ + widget::nav_bar_toggle() + .active(self.core().nav_bar_active()) + .on_toggle(Message::ToggleNav) + .into(), + menu::bar(vec![file, view, projection, help]) + .item_height(menu::ItemHeight::Dynamic(40)) + .item_width(menu::ItemWidth::Uniform(260)) + .spacing(4.0) + .into(), + ] + } + + fn subscription(&self) -> Subscription<Message> { + event::listen_with(|event, _status, _id| match event { + Event::Keyboard(keyboard::Event::ModifiersChanged(m)) => { + Some(Message::Event(Event::Keyboard(keyboard::Event::ModifiersChanged(m)))) + } + Event::Keyboard(keyboard::Event::KeyPressed { key, modifiers, .. }) => { + if modifiers.control() { + if let Key::Character(c) = &key { + match c.as_str() { + "o" | "O" => return Some(Message::OpenImage), + "s" | "S" => return Some(Message::SaveImage), + "d" | "D" => return Some(Message::DumpImage), + "t" | "T" => return Some(Message::LoadTrack), + "v" | "V" => return Some(Message::ChooseViewpoint), + "f" | "F" => return Some(Message::Fit), + "q" | "Q" => return Some(Message::Quit), + _ => {} + } + } + } + match key { + Key::Named(cosmic::iced::keyboard::key::Named::Escape) => { + Some(Message::PickerClose) + } + _ => None, + } + } + Event::Window(WinEvent::FileDropped(paths)) => Some(Message::FileDropped(paths)), + Event::Window(WinEvent::Resized(size)) => { + Some(Message::WinResized(size.width as f64, size.height as f64)) + } + _ => None, + }) + } + + fn update(&mut self, message: Message) -> Task<Message> { + use cosmic::dialog::file_chooser::FileFilter; + + match message { + Message::Vp(m) => return self.update_vp(m), + Message::Event(Event::Keyboard(keyboard::Event::ModifiersChanged(m))) => { + self.ctrl = m.control(); + } + Message::Event(_) => {} + Message::ToggleNav => { + self.core_mut().nav_bar_toggle(); + self.remeasure(); + } + Message::WinResized(w, h) => { + self.win_w = w; + self.win_h = h; + self.remeasure(); + } + Message::FileDropped(paths) => { + for p in paths { + let ext = p.extension().and_then(|e| e.to_str()).unwrap_or(""); + if matches!(ext.to_ascii_lowercase().as_str(), "jpg" | "jpeg" | "png") { + return self.open_image(p); + } else if ext.eq_ignore_ascii_case("csv") || ext.eq_ignore_ascii_case("dat") { + // treat as track file + let task = async move { + hill::load(&p.to_string_lossy()) + .map(|mut hs| { + for h in hs.iter_mut() { + h.flags |= FLAG_TRACK_POINT; + } + hs + }) + .map_err(|e| e.to_string()) + }; + return cosmic::task::future(async move { + Message::TrackLoaded(Box::new(task.await)) + }); + } + } + } + Message::OpenImage => { + return cosmic::task::future(async move { + let filter = + FileFilter::new("Images").glob("*.jpg").glob("*.jpeg").glob("*.png"); + Message::OpenPath(pick_open("Open Image", filter).await) + }); + } + Message::OpenPath(Some(p)) => return self.open_image(p), + Message::OpenPath(None) => {} + Message::ImageLoaded(res) => match *res { + Ok(li) => { + let title = li.path.file_name().map(|s| s.to_string_lossy().into_owned()).unwrap_or_default(); + self.set_header_title(title); + let (w, h) = (li.w, li.h); + self.project = Some(Project { + path: li.path, + handle: li.handle, + w, + h, + md: li.md.clone(), + }); + let md = li.md; + let have = gipfel_core::metadata::apply_image_metadata(&mut self.pan, &md, w, h); + self.known.clear(); + self.track.clear(); + self.sync_inputs(); + self.fit = true; + self.remeasure(); + self.zoom = self.fit_zoom(); + self.panv = Vector::ZERO; + self.bump(); + // prefill the profile name the auto-match used (C + // get_distortion_profile_name) and refresh the store list + let auto_profile = gipfel_core::metadata::distortion_profile_name(&md); + self.profile_in = auto_profile.clone().unwrap_or_default(); + self.profile_overwrite = false; + self.refresh_profiles(); + self.status = if have { + format!("loaded (gipfel info found)") + } else { + "loaded (no gipfel info: set viewpoint)".into() + }; + if md.k0.is_nan() { + if let Some(name) = + auto_profile.filter(|n| self.profiles.iter().any(|p| p == n)) + { + self.status = format!("{} - distortion profile '{name}'", self.status); + } + } + // the first frame after the image appears can be drawn + // before the texture is fully uploaded; a late nudge + // guarantees the photo shows without user interaction + return Task::perform( + async { tokio::time::sleep(std::time::Duration::from_millis(150)).await }, + |_| cosmic::Action::App(Message::Redraw), + ); + } + Err(e) => self.status = e, + }, + Message::SaveImage => { + let Some(p) = &self.project else { + self.status = "no image loaded".into(); + return Task::none(); + }; + let _ = p; + return cosmic::task::future(async move { + let filter = FileFilter::new("JPEG").glob("*.jpg"); + Message::SavePath(pick_save("Save Image", filter).await) + }); + } + Message::SavePath(out) => { + let (Some(out), Some(p)) = (out, &self.project) else { return Task::none() }; + let md = self.md_from_state(); + let src = p.path.clone(); + return cosmic::task::future(async move { + match md.save_image(&src.to_string_lossy(), &out.to_string_lossy()) { + Ok(()) => Message::ImageSaved(Some(out)), + Err(e) => { + let _ = e; + Message::ImageSaved(None) + } + } + }); + } + Message::ImageSaved(Some(p)) => { + self.status = format!("saved {}", p.display()); + } + Message::ImageSaved(None) => {} + Message::DumpImage => { + let Some(p) = &self.project else { + self.status = "no image loaded".into(); + return Task::none(); + }; + let path = p.path.clone(); + // the dump is at image resolution; screen-pixel overlay sizes + // must be divided by the current zoom to look like the screen + let zoom = self.zoom.max(0.02) as f64; + let markers: Vec<dump::DumpMarker> = self + .markers() + .iter() + .map(|m| dump::DumpMarker { + x: m.x, + y: m.y, + name: m.name.to_string(), + known: m.known, + hidden: m.hidden, + }) + .collect(); + let track: Vec<dump::DumpTrackPt> = self + .track_pts() + .iter() + .map(|t| dump::DumpTrackPt { x: t.x, y: t.y, hidden: t.hidden, width: t.width }) + .collect(); + let font_size = self.label_font; + let font_family = cosmic::config::interface_font().family; + return cosmic::task::future(async move { + let res: Result<PathBuf, String> = async { + let filter = FileFilter::new("Images").glob("*.png").glob("*.jpg"); + let out = + pick_save("Screen Dump", filter).await.ok_or_else(|| "cancelled".to_string())?; + let img = image::open(&path) + .map(|i| i.to_rgba8()) + .map_err(|e| format!("{e}"))?; + dump::render(&img, &markers, &track, &out, font_size, 1.0 / zoom, &font_family)?; + Ok(out) + } + .await; + Message::ImageDumped(Box::new(res)) + }); + } + Message::ImageDumped(res) => { + self.status = match *res { + Ok(p) => format!("dumped {}", p.display()), + Err(e) => e, + }; + } + Message::StitchTiff => { + let Some(p) = &self.project else { + self.status = "no image loaded".into(); + return Task::none(); + }; + // cylindrical output spanning the lens' actual field of view + let edge = self.view_angle_limit(); // half-angle, radians + if !(edge > 0.0 && edge < 1.5) { + self.status = "cannot determine lens field of view".into(); + return Task::none(); + } + let center = self.pan.get_center_angle(); + let (from, to) = (center - edge.to_degrees(), center + edge.to_degrees()); + // output scale = the source's focal scale (pixels per radian + // at image center): the cylindrical image is 1:1 in the middle + // and slightly downsampled towards the edges (where the + // rectilinear source has increasing angular stretch). Using + // the source width instead would upsample ~5-10% and blur. + let radius = self.pan.get_scale(); + let w_out = (2.0 * edge * radius).round_ties_even().max(16.0) as u32; + // cover the source's vertical extent (may be off-center + // with pitch); output rows are symmetric about elevation 0 + let e_top = elev_at_img_y(&self.pan, -(p.h as f64 / 2.0)); + let e_bot = elev_at_img_y(&self.pan, p.h as f64 / 2.0); + let e_max = e_top.abs().max(e_bot.abs()).min(85f64.to_radians()); + let h_out = (2.0 * radius * e_max.tan()).round_ties_even().max(16.0) as u32; + let path = p.path.clone(); + let pan = self.pan.params_snapshot(); + return cosmic::task::future(async move { + let res: Result<PathBuf, String> = async { + let filter = FileFilter::new("TIFF images").glob("*.tif").glob("*.tiff"); + let out = pick_save("Stitch Cylindrical TIFF", filter) + .await + .ok_or_else(|| "cancelled".to_string())?; + let out_for_task = out.clone(); + tokio::task::spawn_blocking(move || -> Result<(), String> { + let mut src = stitch::StitchSource::load(&path.to_string_lossy())?; + // use the live (possibly adjusted) parameters + src.pan = pan; + let img = stitch::resample( + &[src], + stitch::ScanMode::Bicubic, + w_out, + h_out, + from, + to, + ); + stitch::write_tiff(&out_for_task.to_string_lossy(), &img, true) + }) + .await + .map_err(|e| e.to_string())??; + Ok(out) + } + .await; + Message::StitchDone(Box::new(res)) + }); + } + Message::StitchDone(res) => { + self.status = match *res { + Ok(p) => format!("stitched {}", p.display()), + Err(e) => e, + }; + } + Message::LoadTrack => { + return cosmic::task::future(async move { + let res: Result<Vec<Hill>, String> = async { + let filter = FileFilter::new("Track files") + .glob("*.gpx") + .glob("*.csv") + .glob("*.dat"); + let path = pick_open("Load GPX Track", filter) + .await + .ok_or_else(|| "cancelled".to_string())?; + let hs = load_track_file(&path).map_err(|e| e.to_string())?; + Ok(hs) + } + .await; + Message::TrackLoaded(Box::new(res)) + }); + } + Message::TrackLoaded(res) => match *res { + Ok(hills) => { + // remap known hills by name across the index shift caused by + // removing the old track + let names: Vec<String> = self.known.iter().map(|&i| self.pan.hills[i].name.clone()).collect(); + self.pan.remove_hills(FLAG_TRACK_POINT); + let n = hills.len(); + self.pan.add_hills(&hills); + let base = self.pan.hills.len() - n; + self.track = (base..base + n).collect(); + self.known = names + .iter() + .filter_map(|n| self.pan.get_pos(n)) + .collect(); + self.status = format!("track: {n} points"); + self.bump(); + } + Err(e) => self.status = e, + }, + Message::ChooseViewpoint => { + self.picker = Some(Picker { + title: "Choose Viewpoint".into(), + query: String::new(), + mode: PickerMode::Viewpoint, + }); + } + Message::ContextFindPeak(x, y) => { + self.context = None; + self.picker = Some(Picker { + title: "Find Peak".into(), + query: String::new(), + mode: PickerMode::FindPeak { img_x: x, img_y: y }, + }); + } + Message::PickerQuery(q) => { + if let Some(p) = &mut self.picker { + p.query = q; + } + } + Message::PickerPick(i) => { + if let Some(p) = self.picker.take() { + match p.mode { + PickerMode::Viewpoint => { + self.pan.set_viewpoint(Some(i)); + self.sync_inputs(); + self.bump(); + self.status = format!("viewpoint: {}", self.pan.hills[i].name); + } + PickerMode::FindPeak { img_x, img_y } => { + if !self.known.contains(&i) { + self.known.push(i); + } + self.pan.hills[i].flags |= FLAG_VISIBLE; + if !self.pan.visible.contains(&i) { + self.pan.visible.push(i); + } + self.pan.hills[i].x = img_x; + self.pan.hills[i].y = img_y; + self.refit(); + } + } + } + } + Message::PickerClose => { + self.picker = None; + self.about = false; + self.context = None; + } + Message::ContextToggleHidden(i) => { + self.context = None; + self.pan.hills[i].flags ^= FLAG_HIDDEN; + self.bump(); + } + Message::Surface(action) => { + return cosmic::task::message(cosmic::Action::Surface(action)); + } + Message::Redraw => {} + Message::Center(a) => { + self.pan.set_center_angle(a); + self.bump(); + } + Message::CompassStyle(s) => { + self.compass_style = s; + self.remeasure(); + self.bump(); + } + Message::Pitch(a) => { + self.pan.set_pitch_angle(a); + self.bump(); + } + Message::Roll(a) => { + self.pan.set_roll_angle(a); + self.bump(); + } + Message::LabelFont(s) => { + self.label_font = s; + self.bump(); + } + Message::Focal(f) => { + self.set_focal_35mm(f); + self.bump(); + } + Message::Visibility(v) => { + // the slider shows more visibility to the right; the core + // stores a height/distance threshold (higher = fewer hills) + self.pan.set_height_dist_ratio(0.11 - v); + self.bump(); + } + Message::TrackWidth(w) => self.track_width = w, + Message::Lat(s) => self.lat_in = s, + Message::Lon(s) => self.lon_in = s, + Message::Height(s) => self.height_in = s, + Message::ViewApply => { + if let Ok(v) = self.lat_in.parse() { + self.pan.set_view_lat(v); + } + if let Ok(v) = self.lon_in.parse() { + self.pan.set_view_long(v); + } + if let Ok(v) = self.height_in.parse() { + self.pan.set_view_height(v); + } + self.bump(); + } + Message::K0(s) => self.k0_in = s, + Message::K1(s) => self.k1_in = s, + Message::X0(s) => self.x0_in = s, + Message::DistortionApply => { + let k0 = self.k0_in.parse().unwrap_or(0.0); + let k1 = self.k1_in.parse().unwrap_or(0.0); + let x0 = self.x0_in.parse().unwrap_or(0.0); + self.pan.set_distortion_params(k0, k1, x0); + self.bump(); + } + Message::ProfileName(s) => { + self.profile_in = s; + self.profile_overwrite = false; + } + Message::ProfileSave => { + let name = self.profile_in.trim().to_string(); + if name.is_empty() { + self.status = "enter a profile name".into(); + } else { + let p = gipfel_core::profile::Profile { + k0: self.pan.parms.k0, + k1: self.pan.parms.k1, + x0: self.pan.parms.x0, + }; + let exists = self.profiles.iter().any(|n| *n == name); + if exists && !self.profile_overwrite { + self.profile_overwrite = true; + self.status = + format!("profile '{name}' exists - press Save again to overwrite"); + } else { + match gipfel_core::profile::save(&name, p, true) { + Ok(()) => { + self.status = format!("saved profile '{name}'"); + self.profile_overwrite = false; + self.refresh_profiles(); + } + Err(e) => self.status = format!("save failed: {e}"), + } + } + } + } + Message::ProfileLoad => { + let name = self.profile_in.trim().to_string(); + if !name.is_empty() { + self.apply_profile(&name); + } + } + Message::ProfileSelect(i) => { + if let Some(name) = self.profiles.get(i).cloned() { + self.profile_in = name.clone(); + self.apply_profile(&name); + } + } + Message::Projection(t) => { + self.pan.set_projection(t); + self.bump(); + } + Message::ToggleShowHidden => { + self.show_hidden = !self.show_hidden; + self.bump(); + } + Message::FitDistortion(v) => { + self.fit_distortion = v; + // fitting a newly unlocked calibration takes effect at once + if v && self.known.len() >= 4 { + self.refit(); + } + } + Message::Fit => { + self.fit = true; + self.zoom = self.fit_zoom(); + self.panv = Vector::ZERO; + } + Message::ZoomIn => { + return self.update_vp(VpMsg::ZoomAt { factor: 1.25, img: cosmic::iced::Point::ORIGIN }); + } + Message::ZoomOut => { + return self.update_vp(VpMsg::ZoomAt { factor: 0.8, img: cosmic::iced::Point::ORIGIN }); + } + Message::About(b) => self.about = b, + Message::Quit => { + if let Some(id) = self.core.main_window_id() { + return cosmic::iced::window::close(id); + } + } + } + Task::none() + } + + /// The settings panel lives in the framework-managed left nav slot + /// (standard padding, condensed-mode handling, collapse state). + fn nav_bar(&self) -> Option<Element<'_, cosmic::Action<Message>>> { + if !self.core().nav_bar_active() { + return None; + } + let close: Element<Message> = widget::button::icon( + widget::icon::from_name("pan-start-symbolic").size(16), + ) + .on_press(Message::ToggleNav) + .into(); + let panel: Element<Message> = widget::container( + widget::column::with_children([ + widget::row::with_children([ + widget::text::heading("gipfel").into(), + widget::container(close) + .width(Length::Fill) + .align_x(cosmic::iced::alignment::Horizontal::Right) + .into(), + ]) + .align_y(cosmic::iced::alignment::Vertical::Center) + .spacing(8) + .into(), + widget::scrollable(self.sidebar()).into(), + ]) + .spacing(10), + ) + .padding([10, 12]) + .width(Length::Fixed(340.0)) + .height(Length::Fill) + .class(cosmic::theme::Container::Secondary) + .into(); + Some(panel.map(cosmic::Action::App)) + } + + fn view(&self) -> Element<'_, Message> { + let content: Element<Message> = match &self.project { + Some(p) => { + let vp = ViewportWidget::<Message> { + handle: p.handle.clone(), + img_w: p.w as f32, + img_h: p.h as f32, + zoom: self.zoom, + pan: self.panv, + markers: self.markers(), + track: self.track_pts(), + hover: self.hover, + ctrl: self.ctrl, + font_size: self.label_font, + version: self.version, + _msg: PhantomData, + }; + let vp: Element<Message> = Element::new(vp); + // standard popover context menu (like cosmic-files): opens in + // its own surface, never shifts the main content + let vp: Element<Message> = + cosmic::widget::context_menu(vp, self.context_menu_tree()) + .window_id( + self.core + .main_window_id() + .unwrap_or(cosmic::iced::window::Id::RESERVED), + ) + .on_surface_action(Message::Surface) + .into(); + if self.compass_style == CompassStyle::Off { + vp + } else { + let fov = match self.pan.projection_type { + ProjectionType::Rectilinear => ( + 2.0 * ((p.w as f64 * 0.5) / self.pan.parms.scale).atan() + ) + .to_degrees(), + ProjectionType::Cylindrical => { + (p.w as f64 / self.pan.parms.scale).to_degrees() + } + }; + let strip: Element<Message> = Element::new(Compass { + style: self.compass_style, + center_deg: self.pan.get_center_angle(), + zoom: self.zoom, + pan_x: self.panv.x, + parms: self.pan.parms, + ptype: self.pan.projection_type, + fov_deg: fov, + max_view_angle: self.pan.max_view_angle, + on_change: Rc::new(Message::Center), + }); + widget::column::with_children([vp, strip]).into() + } + } + None => widget::container( + widget::column::with_children([ + widget::text::title2("gipfel").into(), + widget::text("Open a JPEG to start (File ▸ Open Image…, Ctrl+O).").into(), + widget::button::suggested("Open Image…").on_press(Message::OpenImage).into(), + ]) + .spacing(12) + .align_x(cosmic::iced::alignment::Horizontal::Center), + ) + .into(), + }; + + let main: Element<Message> = content; + + let status_text = self.hover_info.as_deref().unwrap_or(&self.status); + let status: Element<Message> = widget::container(widget::text::body(status_text.to_string())) + .padding([4, 10]) + .width(Length::Fill) + .style(|_: &Theme| widget::container::Style { + background: Some(cosmic::iced::Background::Color(Color::from_rgba(0.0, 0.0, 0.0, 0.15))), + ..Default::default() + }) + .into(); + + let body: Element<Message> = widget::column::with_children([main, status]).into(); + + if let Some(picker) = &self.picker { + return self.with_dialog(body, self.view_picker(picker)); + } + if self.about { + return self.with_dialog(body, self.view_about()); + } + body + } +} + +// helpers split out to keep view() readable + +/// settings row with the label above a full-width, easy-grip slider +fn slider_item( + label: &str, + value: String, + slider: impl Into<Element<'static, Message>>, +) -> Element<'static, Message> { + let header: Element<'static, Message> = widget::row::with_children([ + widget::text::body(label.to_string()).into(), + widget::container(widget::text::body(value)) + .width(Length::Fill) + .align_x(cosmic::iced::alignment::Horizontal::Right) + .into(), + ]) + .into(); + let body: Element<'static, Message> = slider.into(); + widget::column::with_children([header, body]) + .spacing(2) + .into() +} + +/// Async file chooser: returns the chosen path, or None if cancelled. +async fn pick_open( + title: &str, + filter: cosmic::dialog::file_chooser::FileFilter, +) -> Option<PathBuf> { + cosmic::dialog::file_chooser::open::Dialog::new() + .title(title.to_string()) + .filter(filter) + .open_file() + .await + .ok()? + .url() + .to_file_path() + .ok() +} + +/// Async save dialog: returns the target path, or None if cancelled. +async fn pick_save( + title: &str, + filter: cosmic::dialog::file_chooser::FileFilter, +) -> Option<PathBuf> { + cosmic::dialog::file_chooser::save::Dialog::new() + .title(title.to_string()) + .filter(filter) + .save_file() + .await + .ok()? + .url() + .and_then(|u| u.to_file_path().ok()) +} + +impl Gipfel { + fn with_dialog<'a>(&self, body: Element<'a, Message>, dialog: Element<'a, Message>) -> Element<'a, Message> { + widget::column::with_children([ + widget::container(dialog).width(Length::Fill).into(), + body, + ]) + .into() + } + + fn view_picker<'a>(&self, p: &'a Picker) -> Element<'a, Message> { + let entries = self.picker_entries(p); + let mut list = widget::column::with_capacity(entries.len()); + let mut empty = true; + for (label, idx) in entries { + empty = false; + list = list.push( + widget::button::text(label) + .on_press(Message::PickerPick(idx)) + .width(Length::Fill), + ); + } + if empty { + list = list.push(widget::text("no matches")); + } + + widget::dialog() + .title(p.title.clone()) + .body("Type to search, click to select.") + .control( + widget::text_input("search…", &p.query) + .on_input(Message::PickerQuery), + ) + .control({ + let el: Element<Message> = list.into(); + widget::scrollable(el).height(Length::Fixed(320.0)) + }) + .secondary_action(widget::button::text("Cancel").on_press(Message::PickerClose)) + .is_overlay(false) + .into() + } + + fn context_menu_tree(&self) -> Option<Vec<menu::Tree<Message>>> { + let ctx = self.context.as_ref()?; + let mut items: Vec<menu::Item<CtxAction, String>> = Vec::new(); + // placing a marker only makes sense on empty image space, not on an + // existing peak marker + if ctx.hit.is_none() { + items.push(menu::Item::Button( + "Find Peak…".to_string(), + None, + CtxAction::FindPeak(ctx.img_x, ctx.img_y), + )); + } + if let Some(i) = ctx.hit { + let h = &self.pan.hills[i]; + items.push(menu::Item::Button( + format!( + "{} {} ({} m)", + if h.flags & FLAG_HIDDEN != 0 { "Unhide" } else { "Hide" }, + h.name, + h.height as i64 + ), + None, + CtxAction::ToggleHidden(i), + )); + } + if items.is_empty() { + return None; + } + Some(menu::items(&std::collections::HashMap::new(), items)) + } + + fn view_about<'a>(&self) -> Element<'a, Message> { + widget::dialog() + .title("About gipfel") + .body("gipfel 0.5.0 (COSMIC preview)") + .control(widget::text("Annotate mountain panoramas.")) + .control(widget::text("Port of gipfel by Johannes Hofmann - mathematical models unchanged.")) .primary_action(widget::button::suggested("Close").on_press(Message::About(false))) + .is_overlay(false) + .into() + } + + fn sidebar(&self) -> Element<'_, Message> { + let has_img = self.project.is_some(); + let focal = self.focal_35mm().clamp(1.0, 300.0); + let pitch = self.pan.get_pitch_angle().clamp(-40.0, 20.0); + let roll = self.pan.get_roll_angle().clamp(-10.0, 10.0); + let vis = self.pan.height_dist_ratio.clamp(0.01, 0.1); + let vis_ui = 0.11 - vis; // slider: right = more hills visible + let label_font = self.label_font; + let center = self.pan.get_center_angle().rem_euclid(360.0); + + let vp_name = self + .pan + .view_name + .clone() + .unwrap_or_else(|| "manual".to_string()); + + let sec_viewpoint = widget::settings::section() + .title("Viewpoint") + .add(widget::settings::item( + "Position", + widget::row::with_children([ + widget::text(vp_name).into(), + widget::button::text("Choose…").on_press(Message::ChooseViewpoint).into(), + ]) + .spacing(8), + )) + .add(widget::settings::item( + "Latitude", + widget::text_input("°", &self.lat_in) + .on_input(Message::Lat) + .on_submit(|_| Message::ViewApply), + )) + .add(widget::settings::item( + "Longitude", + widget::text_input("°", &self.lon_in) + .on_input(Message::Lon) + .on_submit(|_| Message::ViewApply), + )) + .add(widget::settings::item( + "Height (m)", + widget::text_input("m", &self.height_in) + .on_input(Message::Height) + .on_submit(|_| Message::ViewApply), + )); + + let sec_orientation = widget::settings::section() + .title("Orientation") + .add(widget::settings::item( + "Center (deg)", + widget::text(format!("{center:.1}°")), + )) + .add(slider_item( + "Focal length (35mm)", + format!("{focal:.1} mm"), + widget::slider(1.0..=300.0, focal, Message::Focal) + .step(0.01) + .height(30.0), + )) + .add(slider_item( + "Pitch (deg)", + format!("{pitch:.1}°"), + widget::slider(-40.0..=20.0, pitch, Message::Pitch) + .step(0.01) + .height(30.0), + )) + .add(slider_item( + "Roll (deg)", + format!("{roll:.1}°"), + widget::slider(-10.0..=10.0, roll, Message::Roll) + .step(0.01) + .height(30.0), + )); + + let sec_display = widget::settings::section() + .title("Display") + .add(slider_item( + "Visibility", + format!("{:.0}%", (vis_ui - 0.01) / 0.09 * 100.0), + widget::slider(0.01..=0.1, vis_ui, Message::Visibility) + .step(0.001) + .height(30.0), + )) + .add(slider_item( + "Track width", + format!("{:.0} m at 1 km", self.track_width), + widget::slider(1.0..=500.0, self.track_width, Message::TrackWidth) + .step(1.0) + .height(30.0), + )) + .add(slider_item( + "Label size", + format!("{label_font:.0} px"), + widget::slider(8.0f32..=28.0, label_font, Message::LabelFont) + .step(1.0) + .height(30.0), + )) + .add(widget::settings::item( + "Show hidden", + widget::toggler(self.show_hidden).on_toggle(|_| Message::ToggleShowHidden), + )) + .add(widget::row::with_children([ + widget::button::text("Zoom −").on_press(Message::ZoomOut).into(), + widget::button::text("Fit").on_press(Message::Fit).into(), + widget::button::text("Zoom +").on_press(Message::ZoomIn).into(), + widget::text(format!("{:.0}%", self.zoom * 100.0)).into(), + ]) + .spacing(8)); + + let sec_projection = widget::settings::section().title("Projection").add( + widget::row::with_children([ + widget::radio( + "Normal", + ProjectionType::Rectilinear, + Some(self.pan.projection_type), + Message::Projection, + ) + .into(), + widget::radio( + "Panoramic", + ProjectionType::Cylindrical, + Some(self.pan.projection_type), + Message::Projection, + ) + .into(), + ]) + .spacing(16), + ); + + // distortion fitting is locked unless enough markers are placed + let can_fit = self.known.len() >= 4; + let fit_cb = widget::checkbox(self.fit_distortion); + let fit_cb = if can_fit { + fit_cb.on_toggle(Message::FitDistortion) + } else { + fit_cb.on_toggle_maybe(None as Option<fn(bool) -> Message>) + }; + let mut fit_col = vec![fit_cb.into()]; + if !can_fit { + fit_col.push(widget::text("position 4 or more markers to enable").size(11).into()); + } + + // fixed-width label column: every control starts at the same x and + // therefore shares the same width (settings::item sizes labels to + // their text, which made the profile field narrower than k0/k1/x0) + let mut sec_distortion = widget::settings::section() + .title("Distortion") + .add(widget::settings::item_row(vec![ + widget::text("Fit distortion").width(110).into(), + widget::column::with_children(fit_col).spacing(2).into(), + ])) + .add(widget::settings::item_row(vec![ + widget::text("k0").width(110).into(), + widget::text_input("0", &self.k0_in) + .on_input(Message::K0) + .on_submit(|_| Message::DistortionApply) + .into(), + ])) + .add(widget::settings::item_row(vec![ + widget::text("k1").width(110).into(), + widget::text_input("0", &self.k1_in) + .on_input(Message::K1) + .on_submit(|_| Message::DistortionApply) + .into(), + ])) + .add(widget::settings::item_row(vec![ + widget::text("x0").width(110).into(), + widget::text_input("0", &self.x0_in) + .on_input(Message::X0) + .on_submit(|_| Message::DistortionApply) + .into(), + ])) + .add(widget::settings::item_row(vec![ + widget::text("profile").width(110).into(), + widget::text_input("Camera_Model_50.00_mm", &self.profile_in) + .on_input(Message::ProfileName) + .on_submit(|_| Message::ProfileSave) + .into(), + ])) + .add( + widget::row::with_children([ + widget::button::suggested("Save profile") + .on_press(Message::ProfileSave) + .into(), + widget::button::text("Load profile") + .on_press(Message::ProfileLoad) + .into(), + ]) + .spacing(8), + ); + if !self.profiles.is_empty() { + // stored profiles (shared with the C version); selecting one + // loads its parameters + let win = self + .core + .main_window_id() + .unwrap_or(cosmic::iced::window::Id::RESERVED); + sec_distortion = sec_distortion.add(widget::settings::item_row(vec![ + widget::text("stored").width(110).into(), + widget::dropdown::popup_dropdown( + self.profiles.clone(), + None, + Message::ProfileSelect, + win, + Message::Surface, + |m| m, + ) + .into(), + ])); + } + + let mut col = widget::column::with_children([ + sec_viewpoint.into(), + sec_orientation.into(), + sec_projection.into(), + sec_distortion.into(), + sec_display.into(), + ]) + .spacing(12) + .padding(12); + + if !has_img { + col = col.push(widget::text("Load an image to enable the controls.")); + } + col.into() + } +} + +fn main() -> cosmic::iced::Result { + let mut flags = Flags { data: None, image: None }; + let mut args = std::env::args().skip(1); + while let Some(a) = args.next() { + match a.as_str() { + "--data" => flags.data = args.next().map(PathBuf::from), + s if !s.starts_with('-') && flags.image.is_none() => flags.image = Some(PathBuf::from(s)), + _ => {} + } + } + cosmic::app::run::<Gipfel>( + cosmic::app::Settings::default().size(cosmic::iced::Size::new(1280.0, 800.0)), + flags, + ) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn elev_inverse_matches_projection() { + let mut pan = Panorama::new(); + pan.set_projection(ProjectionType::Rectilinear); + pan.set_center_angle(0.0); + pan.set_pitch_angle(0.0); + pan.set_scale(200.0); + // undistorted rectilinear: y = scale * tan(pitch - elev) + for &y in &[-100.0, -30.0, 0.0, 45.0, 120.0] { + let e = elev_at_img_y(&pan, y); + let (_, y_back) = pan.project_point(0.0, e).unwrap(); + assert!((y_back - y).abs() < 0.01, "y={y} -> elev={e} -> {y_back}"); + } + // with pitch the band is asymmetric but still invertible + pan.set_pitch_angle(10.0); + let p = pan.parms.a_pitch; + let top = elev_at_img_y(&pan, -100.0); + let bot = elev_at_img_y(&pan, 100.0); + assert!(top > p && bot < p, "top={top} p={p} bot={bot}"); + let (_, y_back) = pan.project_point(0.0, top).unwrap(); + assert!((y_back + 100.0).abs() < 0.01); + } +} diff --git a/crates/gipfel-app/src/viewport.rs b/crates/gipfel-app/src/viewport.rs new file mode 100644 index 0000000..3001fc4 --- /dev/null +++ b/crates/gipfel-app/src/viewport.rs @@ -0,0 +1,659 @@ +//! The gipfel viewport: a custom widget that draws the photo, hill markers, +//! decluttered labels, GPS track, and handles all canvas interaction. +//! +//! Marker/label placement mirrors the original GipfelWidget::draw/set_labels +//! (image-space coordinates; the screen transform is applied at draw time). + +use std::rc::Rc; +use std::time::Instant; + +use cosmic::iced::advanced::image::{FilterMethod, Handle, Image as CoreImage}; +use cosmic::iced::advanced::renderer::Style as RendererStyle; +use cosmic::iced::advanced::text::{ + self as adv_text, paragraph::Plain, LineHeight, Renderer as _, +}; +use cosmic::iced::advanced::widget::{tree, Tree, Widget as WidgetTrait}; +use cosmic::iced::advanced::{Clipboard, Layout, Shell}; +use cosmic::iced::mouse::{self, Button, Cursor, Interaction, ScrollDelta}; +use cosmic::iced::widget::canvas::{Frame, LineCap, Path, Stroke}; +use cosmic::iced::advanced::graphics::geometry::Style as GeoStyle; +use cosmic::iced::{ + alignment, Color, Event, Length, Pixels, Point, Rectangle, Radians, Size, Vector, +}; + +use cosmic::Renderer as R; +use cosmic::Theme; + +pub const DEFAULT_LABEL_FONT: f32 = 12.0; +const CROSS_SIZE: f64 = 4.0; + +#[derive(Clone, Debug)] +pub struct Marker { + /// image-space coordinates, origin at image center (like C's m->x/m->y) + pub x: f64, + pub y: f64, + pub name: Rc<str>, + pub idx: usize, + pub known: bool, + pub hidden: bool, +} + +#[derive(Clone, Debug)] +pub struct TrackPt { + pub x: f64, + pub y: f64, + pub hidden: bool, + pub width: f64, +} + +#[derive(Debug, Clone)] +pub enum VpMsg { + /// zoom by `factor`, keeping image point `img` under the cursor + ZoomAt { factor: f32, img: Point }, + PanBy { delta: Vector }, + PanTo { pan: Vector }, + MoveMarker { idx: usize, img: Point }, + DragEnd { had_marker: bool }, + /// hill index of the toggled marker (None = clicked empty space) + ToggleKnown(Option<usize>), + ContextAt { img: Point, hit: Option<usize> }, + /// hill index of the hovered marker + Hover(Option<usize>), +} + +#[derive(Clone)] +struct LabelLayout { + version: u64, + font_size: f32, + zoom: f32, + entries: Vec<(f32, f32)>, +} + +#[derive(Default)] +struct DragState { + drag: Drag, + last_click: Option<(Instant, Point)>, + label_cache: std::cell::RefCell<Option<LabelLayout>>, + /// Paragraph primitives must outlive the frame: the renderer stores only a + /// Weak reference, so keep strong refs here until the next draw. + paragraphs: std::cell::RefCell<Vec<Plain<<R as adv_text::Renderer>::Paragraph>>>, +} + +#[derive(Default, Clone)] +enum Drag { + #[default] + None, + Marker(usize), + Pan { start: Point, pan0: Vector }, +} + +pub struct ViewportWidget<M: From<VpMsg> + Send + 'static> { + pub handle: Handle, + pub img_w: f32, + pub img_h: f32, + pub zoom: f32, + pub pan: Vector, + /// hill markers in visible order; label layout depends on this order + pub markers: Rc<Vec<Marker>>, + pub track: Rc<Vec<TrackPt>>, + pub hover: Option<usize>, + pub ctrl: bool, + /// label font size in pixels (UI-tunable) + pub font_size: f32, + /// bump whenever marker positions change to invalidate the label cache + pub version: u64, + pub _msg: std::marker::PhantomData<fn() -> M>, +} + +impl<M: From<VpMsg> + Send + 'static> Clone for ViewportWidget<M> { + fn clone(&self) -> Self { + ViewportWidget { + handle: self.handle.clone(), + img_w: self.img_w, + img_h: self.img_h, + zoom: self.zoom, + pan: self.pan, + markers: self.markers.clone(), + track: self.track.clone(), + hover: self.hover, + ctrl: self.ctrl, + font_size: self.font_size, + version: self.version, + _msg: std::marker::PhantomData, + } + } +} + +impl<M: From<VpMsg> + Send + 'static> ViewportWidget<M> { + /// line height: paragraph metrics (cosmic LineHeight default = 1.3x) plus + /// a 2px gap, so stacked labels never touch + fn line_h(&self) -> f32 { + self.font_size * 1.3 + 2.0 + } + + fn center(bounds: Rectangle, pan: Vector) -> Point { + Point::new( + bounds.x + bounds.width / 2.0 + pan.x, + bounds.y + bounds.height / 2.0 + pan.y, + ) + } + + fn to_img(&self, center: Point, p: Point) -> Point { + Point::new((p.x - center.x) / self.zoom, (p.y - center.y) / self.zoom) + } + + /// hit-test in image space; tolerance scales with zoom (~6 screen px). + /// Returns the *hill index* of the hit marker. + fn hit(&self, center: Point, p: Point) -> Option<usize> { + let img = self.to_img(center, p); + let tol = (6.0 / self.zoom).clamp(2.0, 20.0); + self.markers + .iter() + .find(|m| (m.x as f32 - img.x).abs() < tol && (m.y as f32 - img.y).abs() < tol) + .map(|m| m.idx) + } +} + +impl<M: From<VpMsg> + Send + 'static> WidgetTrait<M, Theme, R> for ViewportWidget<M> { + fn size(&self) -> Size<Length> { + Size::new(Length::Fill, Length::Fill) + } + + fn tag(&self) -> tree::Tag { + tree::Tag::of::<DragState>() + } + + fn state(&self) -> tree::State { + tree::State::new(DragState::default()) + } + + fn layout( + &mut self, + _tree: &mut Tree, + _renderer: &R, + limits: &cosmic::iced::advanced::layout::Limits, + ) -> cosmic::iced::advanced::layout::Node { + cosmic::iced::advanced::layout::Node::new(limits.max()) + } + + fn draw( + &self, + tree: &Tree, + renderer: &mut R, + _theme: &Theme, + _style: &RendererStyle, + layout: Layout<'_>, + _cursor: Cursor, + _viewport: &Rectangle, + ) { + use cosmic::iced::advanced::image::Renderer as _; + use cosmic::iced::advanced::Renderer as _; + + let bounds = layout.bounds(); + let center = Self::center(bounds, self.pan); + let z = self.zoom; + + // 1. photo + let dest = Rectangle::new( + Point::new(center.x - self.img_w * z / 2.0, center.y - self.img_h * z / 2.0), + Size::new(self.img_w * z, self.img_h * z), + ); + renderer.draw_image( + CoreImage { + handle: self.handle.clone(), + filter_method: FilterMethod::Linear, + rotation: Radians(0.0), + border_radius: 0.0.into(), + opacity: 1.0, + snap: false, + }, + dest, + bounds, + ); + + let layout_entries = self.label_layout(tree, renderer); + + // The wgpu renderer draws geometry before images within one layer; + // record the overlay in a fresh layer so it lands on top of the photo. + renderer.start_layer(bounds); + self.draw_overlay(renderer, tree, bounds, center, &layout_entries); + renderer.end_layer(); + } + + fn update( + &mut self, + tree: &mut Tree, + event: &Event, + layout: Layout<'_>, + cursor: Cursor, + _renderer: &R, + _clipboard: &mut dyn Clipboard, + shell: &mut Shell<'_, M>, + _viewport: &Rectangle, + ) { + let bounds = layout.bounds(); + let center = Self::center(bounds, self.pan); + let state = tree.state.downcast_mut::<DragState>(); + + match event { + Event::Mouse(mouse::Event::WheelScrolled { delta }) => { + let Some(p) = cursor.position_over(bounds) else { return }; + let (dx, dy) = match delta { + ScrollDelta::Pixels { x, y } => (*x, *y), + ScrollDelta::Lines { x, y } => (*x * 30.0, *y * 30.0), + }; + if self.ctrl { + shell.publish(M::from(VpMsg::ZoomAt { + factor: (1.0 + dy * 0.0015).clamp(0.5, 2.0), + img: self.to_img(center, p), + })); + } else { + shell.publish(M::from(VpMsg::PanBy { delta: Vector::new(-dx, -dy) })); + } + shell.request_redraw(); + } + Event::Mouse(mouse::Event::ButtonPressed(Button::Left)) => { + let Some(p) = cursor.position_over(bounds) else { return }; + let now = Instant::now(); + let dbl = state + .last_click + .is_some_and(|(t, q)| { + t.elapsed().as_millis() < 400 + && (q.x - p.x).abs() < 6.0 + && (q.y - p.y).abs() < 6.0 + }); + state.last_click = Some((now, p)); + + if dbl { + state.drag = Drag::None; + state.last_click = None; + shell.publish(M::from(VpMsg::ToggleKnown(self.hit(center, p)))); + return; + } + + if let Some(idx) = self.hit(center, p) { + if self.markers.iter().any(|m| m.idx == idx && m.known) { + state.drag = Drag::Marker(idx); + return; + } + } + state.drag = Drag::Pan { start: p, pan0: self.pan }; + } + Event::Mouse(mouse::Event::ButtonReleased(Button::Left)) => { + let had_marker = matches!(state.drag, Drag::Marker(_)); + state.drag = Drag::None; + shell.publish(M::from(VpMsg::DragEnd { had_marker })); + } + Event::Mouse(mouse::Event::ButtonPressed(Button::Middle)) => { + if let Some(p) = cursor.position_over(bounds) { + shell.publish(M::from(VpMsg::ToggleKnown(self.hit(center, p)))); + } + } + Event::Mouse(mouse::Event::ButtonPressed(Button::Right)) => { + if let Some(p) = cursor.position_over(bounds) { + shell.publish(M::from(VpMsg::ContextAt { + img: self.to_img(center, p), + hit: self.hit(center, p), + })); + } + } + Event::Mouse(mouse::Event::CursorMoved { .. }) => { + match state.drag.clone() { + Drag::Marker(idx) => { + if let Some(p) = cursor.position() { + shell.publish(M::from(VpMsg::MoveMarker { + idx, + img: self.to_img(center, p), + })); + shell.request_redraw(); + } + } + Drag::Pan { start, pan0 } => { + if let Some(p) = cursor.position() { + shell.publish(M::from(VpMsg::PanTo { + pan: pan0 + Vector::new(p.x - start.x, p.y - start.y), + })); + shell.request_redraw(); + } + } + Drag::None => { + match cursor.position_over(bounds) { + Some(p) => shell.publish(M::from(VpMsg::Hover(self.hit(center, p)))), + // cursor moved off the viewport (e.g. into the + // sidebar): clear any stale hover info + None => shell.publish(M::from(VpMsg::Hover(None))), + } + } + } + } + _ => {} + } + } + + fn mouse_interaction( + &self, + _tree: &Tree, + layout: Layout<'_>, + cursor: Cursor, + _viewport: &Rectangle, + _renderer: &R, + ) -> Interaction { + let center = Self::center(layout.bounds(), self.pan); + match cursor.position_over(layout.bounds()) { + Some(p) if self.hit(center, p).is_some() => Interaction::Pointer, + Some(_) => Interaction::Grab, + None => Interaction::None, + } + } +} + +impl<M: From<VpMsg> + Send + 'static> ViewportWidget<M> { + fn draw_overlay( + &self, + renderer: &mut R, + tree: &Tree, + bounds: Rectangle, + center: Point, + layout_entries: &[(f32, f32)], + ) { + use cosmic::iced::advanced::graphics::geometry::Renderer as _; + use cosmic::iced::advanced::text::Renderer as _; + + let z = self.zoom; + let to_screen = |p: Point| Point::new(center.x + p.x * z, center.y + p.y * z); + let layout_entries = layout_entries; + let mut frame = Frame::with_bounds(renderer, bounds); + + // 2. GPS track + for w in self.track.windows(2) { + let (a, b) = (&w[0], &w[1]); + let pa = to_screen(Point::new(a.x as f32, a.y as f32)); + let pb = to_screen(Point::new(b.x as f32, b.y as f32)); + let color = if a.hidden { + Color::from_rgb(0.2, 0.4, 1.0) + } else { + Color::from_rgb(1.0, 0.2, 0.2) + }; + let stroke = Stroke { + width: (a.width as f32 * z).max(1.0), + style: GeoStyle::Solid(color), + line_cap: LineCap::Round, + ..Default::default() + }; + let path = Path::new(|bld| { + bld.move_to(pa); + bld.line_to(pb); + }); + frame.stroke(&path, stroke); + } + + // 3. hill markers: crosses + leaders + // C's draw() skips markers outside the image (fabs(x) > w/2 || ...); + // must match label_layout's filter, otherwise off-image markers get + // drawn (in the letterbox area) without ever being laid out. + let in_img = |m: &Marker| { + m.x.abs() * 2.0 <= self.img_w as f64 && m.y.abs() * 2.0 <= self.img_h as f64 + }; + let yellow = Color::from_rgb(1.0, 0.9, 0.2); + for (i, m) in self.markers.iter().enumerate() { + if !in_img(m) { + continue; + } + let p = to_screen(Point::new(m.x as f32, m.y as f32)); + if !bounds.contains(p) { + continue; + } + let (lx, ly) = layout_entries[i]; + let d = CROSS_SIZE as f32; + let label_line = p.y + ly - self.line_h(); + let stroke = Stroke { + width: 1.0, + style: GeoStyle::Solid(yellow), + ..Default::default() + }; + let path = Path::new(|bld| { + bld.move_to(Point::new(p.x - d, p.y)); + bld.line_to(Point::new(p.x + d, p.y)); + bld.move_to(Point::new(p.x, p.y)); + bld.line_to(Point::new(p.x, label_line)); + bld.move_to(Point::new(p.x, label_line)); + bld.line_to(Point::new(p.x + lx, label_line)); + }); + frame.stroke(&path, stroke); + } + + // known-hill flags (pole + pennant + circle) + let flag_color = Color::from_rgb(1.0, 0.25, 0.25); + for m in self.markers.iter().filter(|m| m.known) { + if !in_img(m) { + continue; + } + let p = to_screen(Point::new(m.x as f32, m.y as f32)); + if !bounds.contains(p) { + continue; + } + let stroke = Stroke { + width: 1.5, + style: GeoStyle::Solid(flag_color), + ..Default::default() + }; + let pole = Path::new(|bld| { + bld.move_to(p); + bld.line_to(Point::new(p.x, p.y - 16.0)); + bld.circle(p, 3.0); + }); + let pennant = Path::new(|bld| { + bld.move_to(Point::new(p.x, p.y - 16.0)); + bld.line_to(Point::new(p.x + 10.0, p.y - 13.0)); + bld.line_to(Point::new(p.x, p.y - 10.0)); + bld.close(); + }); + frame.stroke(&pole, stroke.clone()); + frame.fill(&pennant, flag_color); + } + + renderer.draw_geometry(frame.into_geometry()); + + // 4. labels (screen space, constant font size) + let font = renderer.default_font(); + let size = Pixels(self.font_size); + // the renderer keeps only a Weak ref to each paragraph, so hold strong + // refs in the widget state until the next frame replaces them + let state = tree.state.downcast_ref::<DragState>(); + { + let mut paras = state.paragraphs.borrow_mut(); + paras.clear(); + paras.reserve(self.markers.len()); + for m in self.markers.iter() { + paras.push(self.make_paragraph(font, size, &m.name)); + } + } + let paras = state.paragraphs.borrow(); + + for (i, m) in self.markers.iter().enumerate() { + if !in_img(m) { + continue; + } + let p = to_screen(Point::new(m.x as f32, m.y as f32)); + if !bounds.contains(p) { + continue; + } + let (_, ly) = layout_entries[i]; + let pos = Point::new(p.x + 2.0, p.y + ly - self.line_h()); + let is_hover = self.hover == Some(m.idx); + + let para = ¶s[i]; + let mb = para.min_bounds(); + + let mut bg = Frame::with_bounds(renderer, bounds); + let rect = Rectangle::new( + Point::new(p.x + 1.0, pos.y - 1.0), + Size::new(mb.width + 2.0, mb.height + 1.0), + ); + let path = Path::new(|bld| bld.rectangle(rect.position(), rect.size())); + bg.fill( + &path, + if is_hover { + Color::from_rgba(1.0, 0.9, 0.2, 0.95) + } else { + Color::from_rgba(0.0, 0.0, 0.0, 0.55) + }, + ); + renderer.draw_geometry(bg.into_geometry()); + + let color = if is_hover { + Color::BLACK + } else if m.hidden { + Color::from_rgb(0.4, 0.6, 1.0) + } else { + Color::WHITE + }; + renderer.fill_paragraph( + para.raw(), + Point::new(p.x + 2.0, pos.y), + color, + bounds, + ); + } + } + + fn make_paragraph(&self, font: <R as adv_text::Renderer>::Font, size: Pixels, text: &str) -> Plain<<R as adv_text::Renderer>::Paragraph> { + Plain::<<R as adv_text::Renderer>::Paragraph>::new(adv_text::Text { + content: text.to_string(), + bounds: Size::new(600.0, 40.0), + size, + line_height: LineHeight::default(), + font, + align_x: alignment::Horizontal::Left.into(), + align_y: alignment::Vertical::Top.into(), + shaping: adv_text::Shaping::Basic, + wrapping: adv_text::Wrapping::None, + ellipsize: adv_text::Ellipsize::None, + }) + } + + /// C set_labels port: place labels above crosses, pushing colliding ones up. + /// Markers outside the image are skipped entirely (C: fabs(x) > w/2 filter), + /// so off-image peaks never push visible labels up. + fn label_layout(&self, tree: &Tree, renderer: &mut R) -> Vec<(f32, f32)> { + let state = tree.state.downcast_ref::<DragState>(); + if let Some(l) = state.label_cache.borrow().as_ref() { + if l.version == self.version + && l.font_size == self.font_size + && l.zoom == self.zoom + && l.entries.len() == self.markers.len() + { + return l.entries.clone(); + } + } + + let font = renderer.default_font(); + let size = Pixels(self.font_size); + let line_h = self.line_h(); + + let widths: Vec<f32> = self + .markers + .iter() + .map(|m| self.make_paragraph(font, size, &m.name).min_bounds().width) + .collect(); + + // C: fabs(m->x) > img->w()/2 || fabs(m->y) > img->h()/2 -> skip + // (marker coords are center-relative, like C's m->x/m->y) + let in_img: Vec<bool> = self + .markers + .iter() + .map(|m| m.x.abs() * 2.0 <= self.img_w as f64 && m.y.abs() * 2.0 <= self.img_h as f64) + .collect(); + + // Labels are drawn at constant size in *screen* space, so collisions + // depend on the on-screen distance between markers: run the layout on + // zoom-scaled coordinates (C had no zoom, image space == screen space). + let z = self.zoom; + let sx: Vec<f32> = self.markers.iter().map(|m| m.x as f32 * z).collect(); + let sy: Vec<f32> = self.markers.iter().map(|m| m.y as f32 * z).collect(); + + let entries = layout_label_y(&sx, &sy, &widths, &in_img, line_h); + *state.label_cache.borrow_mut() = Some(LabelLayout { + version: self.version, + font_size: self.font_size, + zoom: self.zoom, + entries: entries.clone(), + }); + entries + } +} + +/// Shared label collision-avoidance layout, used for both the on-screen +/// viewport and the screen dump so the dump shows exactly the same label +/// placement (plan.md M3: same code path). +/// +/// `xs`/`ys` are marker positions (center-relative) in one uniform pixel +/// space, `widths` the label widths and `line_h` the line height, all in +/// that same space. Markers must be ordered by x (the sweep breaks on the +/// first non-overlapping predecessor). Returns `(label_width + 1, y_offset)` +/// per marker; the label is drawn at `(marker.x + 2, marker.y + y_offset - +/// line_h)`. +pub fn layout_label_y( + xs: &[f32], + ys: &[f32], + widths: &[f32], + in_img: &[bool], + line_h: f32, +) -> Vec<(f32, f32)> { + let n = xs.len(); + let mut label_x = vec![0.0f32; n]; + let mut label_y = vec![0.0f32; n]; + let cross = CROSS_SIZE as f32; + let overlap = |a1: f32, l1: f32, a2: f32, l2: f32| a1 <= a2 + l2 && a1 + l1 >= a2; + + for i in 0..n { + if !in_img[i] { + continue; + } + label_x[i] = widths[i] + 1.0; + label_y[i] = 0.0; + + let mut colliding: Vec<usize> = Vec::new(); + for j in (0..i).rev() { + if !in_img[j] { + continue; + } + if overlap(xs[i], label_x[i], xs[j] - cross, label_x[j]) { + colliding.push(j); + } else { + break; + } + } + colliding.sort_by(|&a, &b| { + let ya = ys[a] + label_y[a]; + let yb = ys[b] + label_y[b]; + yb.total_cmp(&ya) + }); + // C does a single overwrite pass here, which can leave overlaps + // when a push moves the label into a band that was already + // checked. Iterate to a fixed point instead (converges quickly: + // each round only moves the label up, bounded by the stack). + for _round in 0..64 { + let mut pushed = false; + for &j in &colliding { + if overlap( + ys[i] + label_y[i] - line_h, + line_h, + ys[j] + label_y[j] - line_h, + line_h, + ) || overlap(ys[i] + label_y[i] - line_h, line_h, ys[j] - cross, 2.0 * cross) { + let ny = (ys[j] + label_y[j] - ys[i] - line_h - 2.0).round(); + if ny < label_y[i] { + label_y[i] = ny; + pushed = true; + } + } + } + if !pushed { + break; + } + } + } + + (0..n).map(|i| (label_x[i], label_y[i])).collect() +} |
