chore: initial commit

This commit is contained in:
wfx 2026-01-07 20:22:49 +01:00
commit ab93f649bd
31 changed files with 9918 additions and 0 deletions

39
src/app/document/file.rs Normal file
View file

@ -0,0 +1,39 @@
// SPDX-License-Identifier: MPL-2.0 OR Apache-2.0
// src/app/document/file.rs
//
// Opening files and dispatching to the correct concrete document type.
use std::path::PathBuf;
use anyhow::anyhow;
use super::portable::PortableDocument;
use super::raster::RasterDocument;
use super::vector::VectorDocument;
use super::{DocumentContent, DocumentKind};
/// Open a document from a file path and dispatch to the correct type.
///
/// Raster formats are delegated to the `image` crate, which decides
/// based on enabled codecs (e.g. default-formats).
pub fn open_document(path: PathBuf) -> anyhow::Result<DocumentContent> {
let kind = DocumentKind::from_path(&path)
.ok_or_else(|| anyhow!("Unsupported document type: {:?}", path))?;
let content = match kind {
DocumentKind::Raster => {
let raster = RasterDocument::open(path)?;
DocumentContent::Raster(raster)
}
DocumentKind::Vector => {
let vector = VectorDocument::open(path)?;
DocumentContent::Vector(vector)
}
DocumentKind::Portable => {
let portable = PortableDocument::open(path)?;
DocumentContent::Portable(portable)
}
};
Ok(content)
}

2
src/app/document/meta.rs Normal file
View file

@ -0,0 +1,2 @@
// SPDX-License-Identifier: MPL-2.0
// src/app/document/meta.rs

112
src/app/document/mod.rs Normal file
View file

@ -0,0 +1,112 @@
// SPDX-License-Identifier: MPL-2.0 OR Apache-2.0
// src/app/document/mod.rs
//
// Document module root: common enums and type erasure for document kinds.
pub mod file;
pub mod meta;
pub mod portable;
pub mod raster;
pub mod transform;
pub mod utils;
pub mod vector;
use cosmic::iced::widget::image as iced_image;
use cosmic::iced_renderer::graphics::image::image_rs::ImageFormat as CosmicImageFormat;
use std::fmt;
use std::path::{Path, PathBuf};
use self::portable::PortableDocument;
use self::raster::RasterDocument;
use self::vector::VectorDocument;
/// High-level classification of documents.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DocumentKind {
Raster,
Vector,
Portable,
}
/// Unified document type used by the application.
pub enum DocumentContent {
Raster(RasterDocument),
Vector(VectorDocument),
Portable(PortableDocument),
}
impl fmt::Debug for DocumentContent {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
DocumentContent::Raster(_) => f.write_str("DocumentContent::Raster(..)"),
DocumentContent::Vector(_) => f.write_str("DocumentContent::Vector(..)"),
DocumentContent::Portable(_) => f.write_str("DocumentContent::Portable(..)"),
}
}
}
impl DocumentKind {
/// Derive document kind from file extension.
///
/// - `pdf` => Portable
/// - `svg` => Vector
/// - supported image extensions (via libcosmic/image_rs ImageFormat)
/// => Raster
///
/// Returns `None` if the extension is not recognized as any supported kind.
pub fn from_path(path: &Path) -> Option<Self> {
let ext_os = path.extension()?;
let ext_str = ext_os.to_str()?;
let ext_lower = ext_str.to_ascii_lowercase();
match ext_lower.as_str() {
"pdf" => return Some(DocumentKind::Portable),
"svg" => return Some(DocumentKind::Vector),
_ => {}
}
// Ask libcosmic/image_rs if this extension corresponds to a known image
// format. If yes, we treat it as a raster document.
if CosmicImageFormat::from_extension(ext_os).is_some() {
return Some(DocumentKind::Raster);
}
None
}
}
impl DocumentContent {
/// Returns a cloneable image handle for rendering.
///
/// This is intentionally linear: every concrete document type
/// owns some kind of `iced_image::Handle`, and the canvas can
/// just call `doc.handle()` without additional branching.
pub fn handle(&self) -> iced_image::Handle {
match self {
DocumentContent::Raster(doc) => doc.handle.clone(),
DocumentContent::Vector(doc) => doc.handle.clone(),
DocumentContent::Portable(doc) => doc.handle.clone(),
}
}
/// Returns the underlying filesystem path of this document, if any.
pub fn path(&self) -> Option<&PathBuf> {
match self {
DocumentContent::Raster(doc) => doc.path.as_ref(),
DocumentContent::Vector(doc) => Some(&doc.path),
DocumentContent::Portable(doc) => Some(&doc.path),
}
}
/// Returns the native dimensions (width, height) of the document in pixels.
///
/// For raster images this is the actual pixel size.
/// For vector/portable documents this is the rasterized size at default DPI.
pub fn dimensions(&self) -> (u32, u32) {
match self {
DocumentContent::Raster(doc) => doc.dimensions(),
DocumentContent::Vector(doc) => doc.dimensions(),
DocumentContent::Portable(doc) => doc.dimensions(),
}
}
}

View file

@ -0,0 +1,65 @@
// SPDX-License-Identifier: MPL-2.0 OR Apache-2.0
// src/app/document/portable.rs
//
// Portable documents (e.g. PDF) basic model and rendering stub.
use std::path::PathBuf;
use cosmic::iced::widget::image as iced_image;
use image::{GenericImageView, DynamicImage};
/// Represents a portable document (PDF).
pub struct PortableDocument {
pub path: PathBuf,
pub page_count: u32,
pub current_page: u32,
pub rotation: i32, // 0, 90, 180, 270; kept for future backend integration
pub rendered: DynamicImage,
pub handle: iced_image::Handle,
// TODO: internal PDF handle from chosen backend
}
impl PortableDocument {
/// Open a portable document and render the first page.
///
/// Currently this uses a dummy 1x1 transparent image as placeholder.
pub fn open(path: PathBuf) -> anyhow::Result<Self> {
// TODO: open PDF and render first page using a proper backend.
let dummy = DynamicImage::new_rgba8(1, 1);
let handle = Self::build_handle(&dummy);
Ok(Self {
path,
page_count: 1, // TODO: query real page count from backend
current_page: 0,
rotation: 0,
rendered: dummy,
handle,
})
}
/// Construct an iced image handle from a DynamicImage.
fn build_handle(img: &DynamicImage) -> iced_image::Handle {
let (w, h) = img.dimensions();
let rgba = img.to_rgba8();
let pixels = rgba.into_raw();
iced_image::Handle::from_rgba(w, h, pixels)
}
/// Rebuild the handle after mutating `rendered`.
pub fn refresh_handle(&mut self) {
self.handle = Self::build_handle(&self.rendered);
}
/// Returns the dimensions of the currently rendered page.
pub fn dimensions(&self) -> (u32, u32) {
self.rendered.dimensions()
}
/// Re-render the current page with the current rotation.
pub fn rerender_page(&mut self) {
// TODO: use PDF backend and self.rotation / self.current_page
// self.rendered = render_page_to_dynamic(...);
// self.refresh_handle();
}
}

View file

@ -0,0 +1,65 @@
// SPDX-License-Identifier: MPL-2.0
// src/app/document/raster.rs
use std::path::PathBuf;
use cosmic::iced::widget::image as iced_image;
use image::{GenericImageView, DynamicImage, ImageReader};
/// Represents a raster image document (PNG, JPEG, WebP, ...).
pub struct RasterDocument {
pub path: Option<PathBuf>,
pub image: DynamicImage,
pub handle: iced_image::Handle,
}
impl RasterDocument {
/// Load a raster document from disk.
pub fn open(path: PathBuf) -> image::ImageResult<Self> {
let img = ImageReader::open(&path)?.decode()?;
let handle = Self::build_handle(&img);
Ok(Self {
path: Some(path),
image: img,
handle,
})
}
/// Construct a handle from a DynamicImage.
fn build_handle(img: &DynamicImage) -> iced_image::Handle {
// Get image dimensions.
let (w, h) = img.dimensions();
// Convert to RGBA8 buffer and extract raw bytes.
let rgba = img.to_rgba8();
let pixels = rgba.into_raw(); // Vec<u8>
// Build an iced image handle from raw RGBA pixels.
iced_image::Handle::from_rgba(w, h, pixels)
}
/// Rebuild the handle after mutating `image`.
pub fn refresh_handle(&mut self) {
self.handle = Self::build_handle(&self.image);
}
/// Returns the native pixel dimensions (width, height).
pub fn dimensions(&self) -> (u32, u32) {
self.image.dimensions()
}
/// Save the current image back to disk (overwrite).
pub fn save(&self) -> image::ImageResult<()> {
if let Some(path) = &self.path {
self.image.save(path)
} else {
// Cant imagine that it happen but caller should handle missing path case.
Err(image::ImageError::Parameter(
image::error::ParameterError::from_kind(image::error::ParameterErrorKind::Generic(
"RasterDocument does not have a path".into(),
)),
))
}
}
}

View file

@ -0,0 +1,112 @@
// SPDX-License-Identifier: MPL-2.0 OR Apache-2.0
// src/app/document/transform.rs
//
// High-level document transformations (rotate, flip, etc.).
use image::{imageops, DynamicImage};
use super::portable::PortableDocument;
use super::raster::RasterDocument;
use super::vector::VectorDocument;
use super::DocumentContent;
/// Rotate current document 90 degrees clockwise.
pub fn rotate_cw(doc: &mut DocumentContent) {
match doc {
DocumentContent::Raster(raster) => rotate_cw_raster(raster),
DocumentContent::Vector(vector) => rotate_cw_vector(vector),
DocumentContent::Portable(portable) => rotate_cw_portable(portable),
}
}
/// Rotate current document 90 degrees counter-clockwise.
pub fn rotate_ccw(doc: &mut DocumentContent) {
match doc {
DocumentContent::Raster(raster) => rotate_ccw_raster(raster),
DocumentContent::Vector(vector) => rotate_ccw_vector(vector),
DocumentContent::Portable(portable) => rotate_ccw_portable(portable),
}
}
/// Flip current document horizontally.
pub fn flip_horizontal(doc: &mut DocumentContent) {
match doc {
DocumentContent::Raster(raster) => flip_horizontal_raster(raster),
DocumentContent::Vector(vector) => flip_horizontal_vector(vector),
DocumentContent::Portable(portable) => flip_horizontal_portable(portable),
}
}
/// Flip current document vertically.
pub fn flip_vertical(doc: &mut DocumentContent) {
match doc {
DocumentContent::Raster(raster) => flip_vertical_raster(raster),
DocumentContent::Vector(vector) => flip_vertical_vector(vector),
DocumentContent::Portable(portable) => flip_vertical_portable(portable),
}
}
// --- Raster implementations ---------------------------------------------------
fn rotate_cw_raster(doc: &mut RasterDocument) {
doc.image = DynamicImage::ImageRgba8(imageops::rotate90(&doc.image));
doc.refresh_handle();
}
fn rotate_ccw_raster(doc: &mut RasterDocument) {
doc.image = DynamicImage::ImageRgba8(imageops::rotate270(&doc.image));
doc.refresh_handle();
}
fn flip_horizontal_raster(doc: &mut RasterDocument) {
doc.image = DynamicImage::ImageRgba8(imageops::flip_horizontal(&doc.image));
doc.refresh_handle();
}
fn flip_vertical_raster(doc: &mut RasterDocument) {
doc.image = DynamicImage::ImageRgba8(imageops::flip_vertical(&doc.image));
doc.refresh_handle();
}
// --- Portable implementations (operate on rendered image) ---------------------
fn rotate_cw_portable(doc: &mut PortableDocument) {
// Keep rotation in sync for a future real PDF backend.
doc.rotation = (doc.rotation + 90).rem_euclid(360);
doc.rendered = DynamicImage::ImageRgba8(imageops::rotate90(&doc.rendered));
doc.refresh_handle();
}
fn rotate_ccw_portable(doc: &mut PortableDocument) {
doc.rotation = (doc.rotation - 90).rem_euclid(360);
doc.rendered = DynamicImage::ImageRgba8(imageops::rotate270(&doc.rendered));
doc.refresh_handle();
}
fn flip_horizontal_portable(doc: &mut PortableDocument) {
doc.rendered = DynamicImage::ImageRgba8(imageops::flip_horizontal(&doc.rendered));
doc.refresh_handle();
}
fn flip_vertical_portable(doc: &mut PortableDocument) {
doc.rendered = DynamicImage::ImageRgba8(imageops::flip_vertical(&doc.rendered));
doc.refresh_handle();
}
// --- Vector implementations (view-transform only, for now) --------------------
fn rotate_cw_vector(_doc: &mut VectorDocument) {
// TODO: either update a rotation property or re-rasterize with rotation.
}
fn rotate_ccw_vector(_doc: &mut VectorDocument) {
// TODO: either update a rotation property or re-rasterize with rotation.
}
fn flip_horizontal_vector(_doc: &mut VectorDocument) {
// TODO: apply horizontal flip to SVG or adjust view transform.
}
fn flip_vertical_vector(_doc: &mut VectorDocument) {
// TODO: apply vertical flip to SVG or adjust view transform.
}

View file

@ -0,0 +1,2 @@
// SPDX-License-Identifier: MPL-2.0
// src/app/document/utils.rs

View file

@ -0,0 +1,48 @@
// SPDX-License-Identifier: MPL-2.0
// src/app/document/vector.rs
//
// Vector documents (SVG, etc.).
use std::path::PathBuf;
use cosmic::iced::widget::image as iced_image;
/// Represents a vector document such as SVG.
/// For now this only stores the raw data and a rasterized handle.
pub struct VectorDocument {
pub path: PathBuf,
pub raw_data: String,
pub handle: iced_image::Handle,
/// Cached dimensions of the rasterized representation.
pub width: u32,
pub height: u32,
}
impl VectorDocument {
pub fn open(path: PathBuf) -> anyhow::Result<Self> {
let raw_data = std::fs::read_to_string(&path)?;
// TODO: proper SVG parsing and rendering.
// For now, use a placeholder size based on a typical default.
let (width, height) = (800, 600);
let handle = iced_image::Handle::from_rgba(1, 1, vec![0, 0, 0, 0]);
Ok(Self {
path,
raw_data,
handle,
width,
height,
})
}
/// Returns the dimensions of the rasterized representation.
pub fn dimensions(&self) -> (u32, u32) {
(self.width, self.height)
}
pub fn refresh_handle(&mut self) {
// TODO: re-render SVG to DynamicImage and rebuild handle.
// Update self.width and self.height accordingly.
}
}

56
src/app/message.rs Normal file
View file

@ -0,0 +1,56 @@
// SPDX-License-Identifier: MPL-2.0 OR Apache-2.0
// src/app/message.rs
//
// Top-level application messages (events, IO, and UI signals).
use std::path::PathBuf;
/// Top-level application messages.
///
/// These are produced by:
/// - UI widgets (buttons, menus, etc.)
/// - keyboard shortcuts
/// - async tasks (file loading, etc.)
#[derive(Debug, Clone)]
pub enum AppMessage {
/// User requested to open a single file.
OpenPath(PathBuf),
/// Navigate to next/previous document in the current folder.
NextDocument,
PrevDocument,
/// Basic view / panel toggles.
ToggleLeftPanel,
ToggleRightPanel,
/// View / zoom control.
ZoomIn,
ZoomOut,
ZoomReset,
ZoomFit,
/// Pan control (Ctrl + arrow keys).
PanLeft,
PanRight,
PanUp,
PanDown,
PanReset,
/// Editing / tool modes.
ToggleCropMode,
ToggleScaleMode,
/// Document transformations.
FlipHorizontal,
FlipVertical,
RotateCW,
RotateCCW,
/// Generic error reporting from lower layers.
ShowError(String),
ClearError,
/// Fallback for unhandled or no-op cases.
NoOp,
}

258
src/app/mod.rs Normal file
View file

@ -0,0 +1,258 @@
// SPDX-License-Identifier: MIT OR Apache-2.0
// src/app/mod.rs
//
// Application module root, re-exports, and COSMIC application wiring.
pub mod document;
pub mod message;
pub mod model;
pub mod update;
// UI is kept as an internal detail of this module.
mod view;
use std::fs;
use std::path::{Path, PathBuf};
use cosmic::app::Core;
use cosmic::iced::keyboard::{self, Key, Modifiers};
use cosmic::iced::keyboard::key::Named;
use cosmic::iced::window;
use cosmic::iced::Subscription;
use cosmic::{Action, Element, Task};
pub use message::AppMessage;
pub use model::AppModel;
use crate::config::AppConfig;
use crate::Args;
/// Flags passed from `main` into the application.
/// Currently we only forward the parsed CLI `Args`.
#[derive(Debug, Clone)]
pub enum Flags {
Args(Args),
}
/// Main application type.
pub struct Noctua {
core: Core,
pub model: AppModel,
}
impl cosmic::Application for Noctua {
type Executor = cosmic::SingleThreadExecutor;
type Flags = Flags;
type Message = AppMessage;
const APP_ID: &'static str = "org.codeberg.wfx.Noctua";
fn core(&self) -> &Core {
&self.core
}
fn core_mut(&mut self) -> &mut Core {
&mut self.core
}
fn init(core: Core, flags: Self::Flags) -> (Self, Task<Action<Self::Message>>) {
// Load persistent configuration at startup.
let config = AppConfig::default();
// Create initial application model from configuration.
let mut model = AppModel::new(config);
// Use CLI arguments from `flags` to open initial file or folder.
let Flags::Args(args) = flags;
if let Some(path) = args.file {
open_initial_path(&mut model, path);
}
(Self { core, model }, Task::none())
}
fn on_close_requested(&self, _id: window::Id) -> Option<Self::Message> {
// Return a message here if you want to handle close requests in update().
None
}
fn update(&mut self, message: Self::Message) -> Task<Action<Self::Message>> {
// Delegate to the domain update logic.
update::update(&mut self.model, message);
Task::none()
}
fn view(&self) -> Element<Self::Message> {
// Main application window view.
view::view(&self.model)
}
fn view_window(&self, _id: window::Id) -> Element<Self::Message> {
// For now, we only have a single window, so reuse the main view.
self.view()
}
fn subscription(&self) -> Subscription<Self::Message> {
// Global keyboard handler: maps key presses to AppMessage.
keyboard::on_key_press(handle_key_press)
}
}
/// Open the initial path passed on the command line.
///
/// If `path` is a directory, this will collect supported documents inside it,
/// open the first one, and initialize navigation state. If it is a file, the
/// file is opened directly and the surrounding folder is scanned.
fn open_initial_path(model: &mut AppModel, path: PathBuf) {
if path.is_dir() {
open_from_directory(model, &path);
} else {
open_single_file(model, &path);
}
}
/// Open the first supported document from the given directory and
/// populate folder navigation state.
fn open_from_directory(model: &mut AppModel, dir: &Path) {
let mut entries: Vec<PathBuf> = Vec::new();
if let Ok(read_dir) = fs::read_dir(dir) {
for entry in read_dir.flatten() {
let path = entry.path();
// Only keep regular files that are recognized as supported documents.
if path.is_file() && document::DocumentKind::from_path(&path).is_some() {
entries.push(path);
}
}
}
entries.sort();
let first = match entries.first().cloned() {
Some(path) => path,
None => {
model.set_error(format!(
"No supported documents found in directory: {}",
dir.display()
));
return;
}
};
model.folder_entries = entries;
model.current_index = Some(0);
open_single_file(model, &first);
}
/// Open a single file, update current path and refresh folder entries.
fn open_single_file(model: &mut AppModel, path: &Path) {
match document::file::open_document(path.to_path_buf()) {
Ok(doc) => {
model.document = Some(doc);
model.current_path = Some(path.to_path_buf());
model.clear_error();
// Reset view state for new document.
model.reset_pan();
model.zoom = 1.0;
model.view_mode = model::ViewMode::Fit;
// Refresh folder listing based on parent directory.
if let Some(parent) = path.parent() {
refresh_folder_entries(model, parent, path);
}
}
Err(err) => {
model.document = None;
model.current_path = None;
model.set_error(err.to_string());
}
}
}
/// Refresh the `folder_entries` list and current index based on the
/// given folder and currently active file.
fn refresh_folder_entries(model: &mut AppModel, folder: &Path, current: &Path) {
let mut entries: Vec<PathBuf> = Vec::new();
if let Ok(read_dir) = fs::read_dir(folder) {
for entry in read_dir.flatten() {
let path = entry.path();
// Only keep regular files that are recognized as supported documents.
if path.is_file() && document::DocumentKind::from_path(&path).is_some() {
entries.push(path);
}
}
}
entries.sort();
// Determine current index.
let current_index = entries.iter().position(|p| p == current);
model.folder_entries = entries;
model.current_index = current_index;
}
/// Map raw key presses + modifiers into high-level application messages.
///
/// This function is used by `keyboard::on_key_press` and must be a plain
/// function pointer (no captures).
fn handle_key_press(key: Key, modifiers: Modifiers) -> Option<AppMessage> {
use AppMessage::*;
// Handle Ctrl + arrow keys for panning.
if modifiers.control() && !modifiers.shift() && !modifiers.alt() && !modifiers.logo() {
return match key.as_ref() {
Key::Named(Named::ArrowLeft) => Some(PanLeft),
Key::Named(Named::ArrowRight) => Some(PanRight),
Key::Named(Named::ArrowUp) => Some(PanUp),
Key::Named(Named::ArrowDown) => Some(PanDown),
_ => None,
};
}
// Ignore key presses when other "command-style" modifiers are pressed,
// so we do not conflict with system- / desktop-level shortcuts.
if modifiers.command() || modifiers.alt() || modifiers.logo() || modifiers.control() {
return None;
}
match key.as_ref() {
// Navigation with arrow keys (no modifiers).
Key::Named(Named::ArrowRight) => Some(NextDocument),
Key::Named(Named::ArrowLeft) => Some(PrevDocument),
// Character keys (case-insensitive where it makes sense).
Key::Character(ch) if ch.eq_ignore_ascii_case("h") => Some(FlipHorizontal),
Key::Character(ch) if ch.eq_ignore_ascii_case("v") => Some(FlipVertical),
Key::Character(ch) if ch.eq_ignore_ascii_case("r") => {
// "r" without Shift => RotateCW
// "r" with Shift => RotateCCW
if modifiers.shift() {
Some(RotateCCW)
} else {
Some(RotateCW)
}
}
// Zoom
Key::Character("+") | Key::Character("=") => Some(ZoomIn),
Key::Character("-") => Some(ZoomOut),
Key::Character("1") => Some(ZoomReset),
Key::Character(ch) if ch.eq_ignore_ascii_case("f") => Some(ZoomFit),
// Tool modes
Key::Character(ch) if ch.eq_ignore_ascii_case("c") => Some(ToggleCropMode),
Key::Character(ch) if ch.eq_ignore_ascii_case("s") => Some(ToggleScaleMode),
// Reset pan with "0"
Key::Character("0") => Some(PanReset),
_ => None,
}
}

105
src/app/model.rs Normal file
View file

@ -0,0 +1,105 @@
// SPDX-License-Identifier: MIT OR Apache-2.0
// src/app/model.rs
//
// Global application state.
use std::path::PathBuf;
use crate::config::AppConfig;
use crate::app::document::DocumentContent;
/// How the document is currently fitted into the window.
#[derive(Debug, Clone)]
pub enum ViewMode {
/// Fit document to available window size.
Fit,
/// Display at 100% (1.0 scale).
ActualSize,
/// Custom zoom factor.
Custom(f32),
}
/// Current editing / interaction mode.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ToolMode {
None,
Crop,
Scale,
}
/// Pan step size in pixels per key press.
pub const PAN_STEP: f32 = 50.0;
/// Global application state.
#[derive(Debug)]
pub struct AppModel {
/// Static configuration loaded at startup.
pub config: AppConfig,
/// Currently opened document (raster/vector/portable).
pub document: Option<DocumentContent>,
/// Path of the currently opened document, if any.
pub current_path: Option<PathBuf>,
/// List of files in the current folder for navigation.
pub folder_entries: Vec<PathBuf>,
/// Index into `folder_entries` of the current file.
pub current_index: Option<usize>,
/// View / zoom state.
pub view_mode: ViewMode,
pub zoom: f32,
/// Pan offset (in pixels, relative to centered position).
pub pan_x: f32,
pub pan_y: f32,
/// Panel visibility.
pub show_left_panel: bool,
pub show_right_panel: bool,
/// Current tool mode.
pub tool_mode: ToolMode,
/// Last error message to be shown in the UI, if any.
pub error: Option<String>,
}
impl AppModel {
/// Construct a new application state from configuration.
pub fn new(config: AppConfig) -> Self {
Self {
config,
document: None,
current_path: None,
folder_entries: Vec::new(),
current_index: None,
view_mode: ViewMode::Fit,
zoom: 1.0,
pan_x: 0.0,
pan_y: 0.0,
show_left_panel: false,
show_right_panel: false,
tool_mode: ToolMode::None,
error: None,
}
}
/// Helper: set an error string.
pub fn set_error<S: Into<String>>(&mut self, msg: S) {
self.error = Some(msg.into());
}
/// Helper: clear current error.
pub fn clear_error(&mut self) {
self.error = None;
}
/// Reset pan offset to center.
pub fn reset_pan(&mut self) {
self.pan_x = 0.0;
self.pan_y = 0.0;
}
}

226
src/app/update.rs Normal file
View file

@ -0,0 +1,226 @@
// SPDX-License-Identifier: MPL-2.0 OR Apache-2.0
// src/app/update.rs
//
// Application update loop: applies messages to the global model state.
use std::fs;
use std::path::{Path, PathBuf};
use super::document;
use super::message::AppMessage;
use super::model::{AppModel, ToolMode, ViewMode, PAN_STEP};
/// Central update function applying messages to the model.
///
/// This is the single place where application state is mutated.
pub fn update(model: &mut AppModel, msg: AppMessage) {
// Debug output: log every received message.
println!("update(): received message: {:?}", msg);
match msg {
// ===== File / navigation ==========================================================
AppMessage::OpenPath(path) => {
open_single_path(model, path);
}
AppMessage::NextDocument => {
go_to_next_document(model);
}
AppMessage::PrevDocument => {
go_to_prev_document(model);
}
// ===== Panels =====================================================================
AppMessage::ToggleLeftPanel => {
model.show_left_panel = !model.show_left_panel;
}
AppMessage::ToggleRightPanel => {
model.show_right_panel = !model.show_right_panel;
}
// ===== View / zoom ===============================================================
AppMessage::ZoomIn => zoom_in(model),
AppMessage::ZoomOut => zoom_out(model),
AppMessage::ZoomReset => {
model.zoom = 1.0;
model.view_mode = ViewMode::ActualSize;
model.reset_pan();
}
AppMessage::ZoomFit => {
model.view_mode = ViewMode::Fit;
model.reset_pan();
}
// ===== Pan control (Ctrl + arrow keys) ===========================================
AppMessage::PanLeft => {
model.pan_x -= PAN_STEP;
}
AppMessage::PanRight => {
model.pan_x += PAN_STEP;
}
AppMessage::PanUp => {
model.pan_y -= PAN_STEP;
}
AppMessage::PanDown => {
model.pan_y += PAN_STEP;
}
AppMessage::PanReset => {
model.reset_pan();
}
// ===== Tools =====================================================================
AppMessage::ToggleCropMode => {
model.tool_mode = if model.tool_mode == ToolMode::Crop {
ToolMode::None
} else {
ToolMode::Crop
};
}
AppMessage::ToggleScaleMode => {
model.tool_mode = if model.tool_mode == ToolMode::Scale {
ToolMode::None
} else {
ToolMode::Scale
};
}
// ===== Document transformations ==================================================
AppMessage::FlipHorizontal => {
if let Some(doc) = &mut model.document {
document::transform::flip_horizontal(doc);
}
}
AppMessage::FlipVertical => {
if let Some(doc) = &mut model.document {
document::transform::flip_vertical(doc);
}
}
AppMessage::RotateCW => {
if let Some(doc) = &mut model.document {
document::transform::rotate_cw(doc);
}
}
AppMessage::RotateCCW => {
if let Some(doc) = &mut model.document {
document::transform::rotate_ccw(doc);
}
}
// ===== Error handling ============================================================
AppMessage::ShowError(msg) => {
model.set_error(msg);
}
AppMessage::ClearError => {
model.clear_error();
}
AppMessage::NoOp => {
// Intentionally do nothing.
}
}
}
/// Open a single path, refreshing navigation context.
fn open_single_path(model: &mut AppModel, path: PathBuf) {
// Try to load the concrete document type (raster/vector/portable).
match document::file::open_document(path.clone()) {
Ok(doc) => {
// Update current document.
model.document = Some(doc);
model.current_path = Some(path.clone());
model.clear_error();
// Reset view state for new document.
model.reset_pan();
model.zoom = 1.0;
model.view_mode = ViewMode::Fit;
// Refresh folder listing based on parent directory.
if let Some(parent) = path.parent() {
refresh_folder_entries(model, parent, &path);
}
}
Err(err) => {
model.document = None;
model.current_path = None;
model.set_error(err.to_string());
}
}
}
/// Refresh the `folder_entries` list and current index.
fn refresh_folder_entries(model: &mut AppModel, folder: &Path, current: &Path) {
let mut entries: Vec<PathBuf> = Vec::new();
if let Ok(read_dir) = fs::read_dir(folder) {
for entry in read_dir.flatten() {
let path = entry.path();
// Only keep files that are recognized as supported documents.
if document::DocumentKind::from_path(&path).is_some() {
entries.push(path);
}
}
}
entries.sort();
// Determine current index.
let current_index = entries.iter().position(|p| p == current);
model.folder_entries = entries;
model.current_index = current_index;
}
/// Go to next document in the current folder, if any.
fn go_to_next_document(model: &mut AppModel) {
let len = model.folder_entries.len();
let Some(idx) = model.current_index else {
return;
};
if len == 0 {
return;
}
let next_idx = (idx + 1) % len;
if let Some(path) = model.folder_entries.get(next_idx).cloned() {
model.current_index = Some(next_idx);
open_single_path(model, path);
}
}
/// Go to previous document in the current folder, if any.
fn go_to_prev_document(model: &mut AppModel) {
let len = model.folder_entries.len();
let Some(idx) = model.current_index else {
return;
};
if len == 0 {
return;
}
let prev_idx = (idx + len - 1) % len;
if let Some(path) = model.folder_entries.get(prev_idx).cloned() {
model.current_index = Some(prev_idx);
open_single_path(model, path);
}
}
/// Increment zoom level.
fn zoom_in(model: &mut AppModel) {
let factor = 1.1_f32;
let new_zoom = (model.zoom * factor).clamp(0.05, 20.0);
model.zoom = new_zoom;
model.view_mode = ViewMode::Custom(new_zoom);
}
/// Decrement zoom level.
fn zoom_out(model: &mut AppModel) {
let factor = 1.0 / 1.1_f32;
let new_zoom = (model.zoom * factor).clamp(0.05, 20.0);
model.zoom = new_zoom;
model.view_mode = ViewMode::Custom(new_zoom);
}

65
src/app/view/canvas.rs Normal file
View file

@ -0,0 +1,65 @@
// SPDX-License-Identifier: MPL-2.0
// src/app/view/canvas.rs
//
// Center canvas for displaying the current document.
use cosmic::iced::{Alignment, Length};
use cosmic::widget::{container, image, text, Column, Row};
use cosmic::Element;
use crate::fl;
use crate::app::model::ViewMode;
use crate::app::{AppMessage, AppModel};
/// Render the center canvas area with the current document.
pub fn view(model: &AppModel) -> Element<'_, AppMessage> {
if let Some(doc) = &model.document {
let handle = doc.handle();
let img_widget = match &model.view_mode {
ViewMode::Fit => {
// Fit mode: image scales to fill container while preserving aspect ratio.
image::Image::new(handle)
.width(Length::Fill)
.height(Length::Fill)
}
ViewMode::ActualSize => {
// 1:1 pixel size.
let (native_w, native_h) = doc.dimensions();
image::Image::new(handle)
.width(Length::Fixed(native_w as f32))
.height(Length::Fixed(native_h as f32))
}
ViewMode::Custom(_) => {
// Custom zoom factor applied to native size.
let (native_w, native_h) = doc.dimensions();
let scaled_w = (native_w as f32 * model.zoom).round();
let scaled_h = (native_h as f32 * model.zoom).round();
image::Image::new(handle)
.width(Length::Fixed(scaled_w))
.height(Length::Fixed(scaled_h))
}
};
// Center the image both horizontally and vertically.
Column::new()
.width(Length::Fill)
.height(Length::Fill)
.align_x(Alignment::Center)
.push(
Row::new()
.push(img_widget)
.width(Length::Fill)
.height(Length::Fill)
.align_y(Alignment::Center),
)
.into()
} else {
container(text(fl!("no_document_loaded")))
.center_x(Length::Fill)
.center_y(Length::Fill)
.width(Length::Fill)
.height(Length::Fill)
.into()
}
}

49
src/app/view/mod.rs Normal file
View file

@ -0,0 +1,49 @@
// SPDX-License-Identifier: MPL-2.0
// src/app/view/mod.rs
//
// Root layout for the main application window.
pub mod canvas;
pub mod panels;
use cosmic::Element;
use cosmic::iced::Length;
use cosmic::widget::{Column, Container, Row};
use crate::app::{AppMessage, AppModel};
/// Main window layout (header, center row, footer).
pub fn view(model: &AppModel) -> Element<'_, AppMessage> {
let header = panels::header(model);
let footer = panels::footer(model);
let left_panel = panels::left_panel(model);
let right_panel = panels::right_panel(model);
let canvas = canvas::view(model);
// Build middle row step by step to handle optional panels.
let mut middle_row = Row::new().spacing(8).height(Length::Fill);
if let Some(left) = left_panel {
middle_row = middle_row.push(left);
}
middle_row = middle_row.push(canvas);
if let Some(right) = right_panel {
middle_row = middle_row.push(right);
}
let content = Column::new()
.spacing(8)
.padding(8)
.width(Length::Fill)
.height(Length::Fill)
.push(header)
.push(middle_row)
.push(footer);
Container::new(content)
.width(Length::Fill)
.height(Length::Fill)
.into()
}

89
src/app/view/panels.rs Normal file
View file

@ -0,0 +1,89 @@
// SPDX-License-Identifier: MPL-2.0
// src/app/view/panels.rs
//
// Header, footer, and side panels composing the main layout.
use cosmic::Element;
use cosmic::iced::{Alignment, Length};
use cosmic::widget::{self, Column, Container, Row, Text};
use crate::fl;
use crate::app::{AppMessage, AppModel};
/// Top header bar (global actions, toggles).
pub fn header(_model: &AppModel) -> Element<'_, AppMessage> {
let content = Row::new().spacing(8).align_y(Alignment::Center);
//.push(Text::new(fl!("noctua-app-name")).size(18));
// In a real implementation, add more buttons/actions here.
Container::new(content)
.width(Length::Fill)
.padding([4, 8])
.into()
}
/// Bottom footer bar (navigation & zoom).
pub fn footer(model: &AppModel) -> Element<'_, AppMessage> {
let nav = Row::new()
.spacing(4)
.align_y(Alignment::Center)
.push(widget::button::standard("<").on_press(AppMessage::PrevDocument))
.push(widget::button::standard(">").on_press(AppMessage::NextDocument));
let zoom_info = Text::new(format!("Zoom: {:.0}%", model.zoom * 100.0));
let content = Row::new()
.spacing(16)
.align_y(Alignment::Center)
.push(nav)
.push(zoom_info);
Container::new(content)
.width(Length::Fill)
.padding([4, 8])
.into()
}
/// Optional left panel (tools).
pub fn left_panel(model: &AppModel) -> Option<Element<'_, AppMessage>> {
if !model.show_left_panel {
return None;
}
let tools = Column::new()
.spacing(4)
.push(Text::new("Tools"))
.push(widget::button::standard("Crop").on_press(AppMessage::ToggleCropMode))
.push(widget::button::standard("Scale").on_press(AppMessage::ToggleScaleMode));
// Later: color pickers, marker tools, text tool, etc.
let panel = Container::new(tools)
.width(Length::Fixed(180.0))
.height(Length::Fill)
.padding(8);
Some(panel.into())
}
/// Optional right panel (metadata, info).
pub fn right_panel(model: &AppModel) -> Option<Element<'_, AppMessage>> {
if !model.show_right_panel {
return None;
}
let meta = Column::new()
.spacing(4)
.push(Text::new("Metadata"))
.push(Text::new(format!(
"Current index: {:?}",
model.current_index
)));
// Later: real EXIF / tags from model.metadata_cache
let panel = Container::new(meta)
.width(Length::Fixed(220.0))
.height(Length::Fill)
.padding(8);
Some(panel.into())
}

22
src/config.rs Normal file
View file

@ -0,0 +1,22 @@
// SPDX-License-Identifier: MPL-2.0
// src/config.rs
use cosmic::cosmic_config::{self, CosmicConfigEntry, cosmic_config_derive::CosmicConfigEntry};
use std::path::PathBuf;
/// Global configuration for the application.
#[derive(Debug, Clone, CosmicConfigEntry, Eq, PartialEq)]
#[version = 1]
pub struct AppConfig {
/// Optional default directory to open images from.
pub default_image_dir: Option<PathBuf>,
}
impl Default for AppConfig {
fn default() -> Self {
Self {
// TODO: Use xdg dir for picture
default_image_dir: Some(PathBuf::from("~/Pictures")),
}
}
}

49
src/i18n.rs Normal file
View file

@ -0,0 +1,49 @@
// SPDX-License-Identifier: MPL-2.0
// src/i18n.rs
use i18n_embed::{
DefaultLocalizer, LanguageLoader, Localizer,
fluent::{FluentLanguageLoader, fluent_language_loader},
unic_langid::LanguageIdentifier,
};
use rust_embed::RustEmbed;
use std::sync::LazyLock;
/// Applies the requested language(s) to requested translations from the `fl!()` macro.
pub fn init(requested_languages: &[LanguageIdentifier]) {
if let Err(why) = localizer().select(requested_languages) {
println!("error while loading fluent localizations: {why}");
}
}
// Get the `Localizer` to be used for localizing this library.
#[must_use]
pub fn localizer() -> Box<dyn Localizer> {
Box::from(DefaultLocalizer::new(&*LANGUAGE_LOADER, &Localizations))
}
#[derive(RustEmbed)]
#[folder = "i18n/"]
struct Localizations;
pub static LANGUAGE_LOADER: LazyLock<FluentLanguageLoader> = LazyLock::new(|| {
let loader: FluentLanguageLoader = fluent_language_loader!();
loader
.load_fallback_language(&Localizations)
.expect("Error while loading fallback language");
loader
});
/// Request a localized string by ID from the i18n/ directory.
#[macro_export]
macro_rules! fl {
($message_id:literal) => {{
i18n_embed_fl::fl!($crate::i18n::LANGUAGE_LOADER, $message_id)
}};
($message_id:literal, $($args:expr),*) => {{
i18n_embed_fl::fl!($crate::i18n::LANGUAGE_LOADER, $message_id, $($args), *)
}};
}

37
src/main.rs Normal file
View file

@ -0,0 +1,37 @@
// SPDX-License-Identifier: MPL-2.0
// src/main.rs
mod app;
mod config;
mod i18n;
use anyhow::Result;
use clap::Parser;
use cosmic::app::Settings;
use crate::app::Noctua;
#[derive(Parser, Debug, Clone)]
#[command(version, about)]
pub struct Args {
/// File to open on startup
#[arg(value_name = "FILE")]
pub file: Option<std::path::PathBuf>,
/// UI language (e.g. "en", "de")
#[arg(short, long, default_value = "en")]
pub language: String,
}
fn main() -> Result<()> {
// Get the system's preferred languages.
let requested_languages = i18n_embed::DesktopLanguageRequester::requested_languages();
// Enable localizations to be applied.
i18n::init(&requested_languages);
env_logger::init();
let args = Args::parse();
cosmic::app::run::<Noctua>(Settings::default(), app::Flags::Args(args))
.map_err(|e| anyhow::anyhow!(e))
}