diff --git a/.gitignore b/.gitignore index b47ce566..4ec12a2e 100644 --- a/.gitignore +++ b/.gitignore @@ -13,3 +13,4 @@ docs/superpowers .codex/ .agents/ .commandcode/ +.nix-dev-profile* \ No newline at end of file diff --git a/Cargo.lock b/Cargo.lock index cf77781a..ee2e83a8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -932,6 +932,8 @@ dependencies = [ "gpui-ce", "gpui-kit", "log", + "png 0.17.16", + "pollster 0.4.0", "rayon", "thiserror 2.0.20", "tokio", diff --git a/assets/icons/image-export.svg b/assets/icons/image-export.svg new file mode 100644 index 00000000..c977e52a --- /dev/null +++ b/assets/icons/image-export.svg @@ -0,0 +1,16 @@ + + + + + + diff --git a/crates/chitin-builtin-shell/src/grammar.rs b/crates/chitin-builtin-shell/src/grammar.rs index 649efbd8..c19ef77e 100644 --- a/crates/chitin-builtin-shell/src/grammar.rs +++ b/crates/chitin-builtin-shell/src/grammar.rs @@ -499,7 +499,8 @@ mod tests { #[test] fn render_requests_should_be_typed_frontend_commands() -> Result<(), CommandLineParseError> { use chitin_command::{ - RenderAtomStyle, RenderCommand, RenderPolymerStyle, RenderSurfaceBackend, RenderSurfaceStyle, + RenderAtomStyle, RenderBackground, RenderCommand, RenderPolymerStyle, RenderRgb, RenderSurfaceBackend, + RenderSurfaceStyle, }; for (input, expected) in [ ("render status", RenderCommand::Status), @@ -543,12 +544,36 @@ mod tests { "render surface backend implicit-scalar-field", RenderCommand::SurfaceBackend(RenderSurfaceBackend::ImplicitScalarField), ), + ( + "render background auto", + RenderCommand::Background(RenderBackground::Auto), + ), + ( + "render background black", + RenderCommand::Background(RenderBackground::Custom(RenderRgb([0, 0, 0]))), + ), + ( + "render background white", + RenderCommand::Background(RenderBackground::Custom(RenderRgb([255, 255, 255]))), + ), + ( + "render background #1e1e1e", + RenderCommand::Background(RenderBackground::Custom(RenderRgb([30, 30, 30]))), + ), + ("render export", RenderCommand::ExportImage { output: None }), + ( + "render export custom.png", + RenderCommand::ExportImage { + output: Some(std::path::PathBuf::from("custom.png")), + }, + ), ] { assert!( matches!(parse_builtin_command_line(input)?, BuiltinCommandLine::Frontend(FrontendCommand::Render(command)) if command == expected) ); } assert!(parse_builtin_command_line("render atom style invalid").is_err()); + assert!(parse_builtin_command_line("render background navy").is_err()); Ok(()) } diff --git a/crates/chitin-builtin-shell/src/render.rs b/crates/chitin-builtin-shell/src/render.rs index 42495726..e38b93e7 100644 --- a/crates/chitin-builtin-shell/src/render.rs +++ b/crates/chitin-builtin-shell/src/render.rs @@ -1,8 +1,8 @@ //! Shell-only grammar for typed molecular presentation commands. use chitin_command::{ - RenderAtomStyle, RenderColorScheme, RenderCommand, RenderLayer, RenderOpacity, RenderPolymerStyle, RenderRgb, - RenderSurfaceBackend, RenderSurfaceStyle, + RenderAtomStyle, RenderBackground, RenderColorScheme, RenderCommand, RenderLayer, RenderOpacity, RenderPolymerStyle, + RenderRgb, RenderSurfaceBackend, RenderSurfaceStyle, }; use clap::Subcommand; @@ -25,6 +25,17 @@ pub(crate) enum RenderArgs { #[command(subcommand)] command: SurfaceArgs, }, + /// Set the viewport clear color; auto follows the light or dark theme. + Background { + /// `auto`, `black`, `white`, or an sRGB color such as #1E1E1E. + color: RenderBackground, + }, + /// Export the current viewport to a PNG under the workspace. + Export { + /// Optional file name or path; relative paths resolve inside the workspace. + #[arg(value_name = "PATH")] + output: Option, + }, } #[derive(Debug, Subcommand)] @@ -112,6 +123,8 @@ impl RenderArgs { Self::Surface { command: SurfaceArgs::Backend { backend }, } => RenderCommand::SurfaceBackend(backend), + Self::Background { color } => RenderCommand::Background(color), + Self::Export { output } => RenderCommand::ExportImage { output }, } } } diff --git a/crates/chitin-command/src/model/catalog.rs b/crates/chitin-command/src/model/catalog.rs index b5272e58..0627bab0 100644 --- a/crates/chitin-command/src/model/catalog.rs +++ b/crates/chitin-command/src/model/catalog.rs @@ -245,6 +245,30 @@ define_commands! { command_panel: false, frontend: [] }, + /// Set Viewport Background. + RenderBackground { + name: "render.background", + title: "Set Viewport Background", + category: CommandCategory::Structure, + domain: CommandExecutionDomain::Frontend, + requires_arguments: true, + keywords: &["render", "background", "canvas", "theme", "color"], + shortcut: None, + command_panel: false, + frontend: [] + }, + /// Export Protein Image. + RenderExportImage { + name: "render.export_image", + title: "Export Protein Image", + category: CommandCategory::Structure, + domain: CommandExecutionDomain::Frontend, + requires_arguments: false, + keywords: &["render", "export", "image", "png", "protein"], + shortcut: None, + command_panel: false, + frontend: [super::RenderCommand::ExportImage { output: None }] + }, /// Focus the previous project entry. WorkspaceFocusPrevious { name: "workspace.focus_previous_entry", diff --git a/crates/chitin-command/src/model/mod.rs b/crates/chitin-command/src/model/mod.rs index a4a58886..1c461f5a 100644 --- a/crates/chitin-command/src/model/mod.rs +++ b/crates/chitin-command/src/model/mod.rs @@ -17,8 +17,8 @@ pub use chemdraw::{ChemdrawCommand, ChemdrawInput, ChemdrawStyle, DrawingLength} pub use database::{DatabaseCommand, RcsbDownloadArguments}; pub use panel_tab::PanelTabCommand; pub use render::{ - RenderAtomStyle, RenderColorScheme, RenderCommand, RenderLayer, RenderOpacity, RenderPolymerStyle, RenderRgb, - RenderSurfaceBackend, RenderSurfaceStyle, + RenderAtomStyle, RenderBackground, RenderColorScheme, RenderCommand, RenderLayer, RenderOpacity, RenderPolymerStyle, + RenderRgb, RenderSurfaceBackend, RenderSurfaceStyle, }; pub use selection::{AtomSpec, SelectionCommand, SelectionMode}; pub use structure::{ diff --git a/crates/chitin-command/src/model/render.rs b/crates/chitin-command/src/model/render.rs index b057cf9c..33b83741 100644 --- a/crates/chitin-command/src/model/render.rs +++ b/crates/chitin-command/src/model/render.rs @@ -1,5 +1,7 @@ //! Frontend-only molecular presentation requests, independent of GPU/UI types. +use std::path::PathBuf; + /// Display style for the atom-and-bond layer. #[derive(Clone, Copy, Debug, PartialEq, Eq, clap::ValueEnum)] pub enum RenderAtomStyle { @@ -41,7 +43,7 @@ pub enum RenderSurfaceBackend { } /// One presentation operation applied to an explicitly resolved rendering tab. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[derive(Clone, Debug, PartialEq, Eq)] pub enum RenderCommand { /// Read the current presentation settings. Status, @@ -61,11 +63,18 @@ pub enum RenderCommand { }, /// Change a layer's opacity without disabling it or regenerating geometry. Opacity { layer: RenderLayer, value: RenderOpacity }, + /// Change the viewport clear color, or follow the host theme automatically. + Background(RenderBackground), + /// Write the current viewport to an image file. + ExportImage { + /// Optional destination; the default is a timestamped workspace export. + output: Option, + }, } impl RenderCommand { /// Returns the stable command identity. - pub const fn id(self) -> super::CommandId { + pub const fn id(&self) -> super::CommandId { match self { Self::Status => super::CommandId::RenderStatus, Self::AtomStyle(_) => super::CommandId::RenderAtomStyle, @@ -74,6 +83,29 @@ impl RenderCommand { Self::SurfaceBackend(_) => super::CommandId::RenderSurfaceBackend, Self::Color { .. } => super::CommandId::RenderColor, Self::Opacity { .. } => super::CommandId::RenderOpacity, + Self::Background(_) => super::CommandId::RenderBackground, + Self::ExportImage { .. } => super::CommandId::RenderExportImage, + } + } +} + +/// Viewport background chosen by a user or shell command. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum RenderBackground { + /// Follow the host theme: black in dark mode, white in light mode. + Auto, + /// Use an explicit sRGB color. + Custom(RenderRgb), +} + +impl std::str::FromStr for RenderBackground { + type Err = String; + fn from_str(value: &str) -> Result { + match value.to_ascii_lowercase().as_str() { + "auto" => Ok(Self::Auto), + "black" => Ok(Self::Custom(RenderRgb([0, 0, 0]))), + "white" => Ok(Self::Custom(RenderRgb([255, 255, 255]))), + _ => value.parse().map(Self::Custom), } } } diff --git a/crates/chitin-desktop/Cargo.toml b/crates/chitin-desktop/Cargo.toml index 71f43d8b..4497a8aa 100644 --- a/crates/chitin-desktop/Cargo.toml +++ b/crates/chitin-desktop/Cargo.toml @@ -28,6 +28,7 @@ chitin-ui = { path = "../chitin-ui", default-features = false } chitin-wgpu = { path = "../chitin-wgpu" } gpui.workspace = true gpui-kit.workspace = true +png = "0.17" tokio = { version = "1.52", features = ["rt-multi-thread", "sync"] } wgpu = { version = "30", default-features = false, features = ["wgsl"] } thiserror = "2.0" @@ -37,6 +38,7 @@ criterion = "0.5" gpui = { workspace = true, features = ["test-support"] } bytemuck = "1.24" glam = "0.33" +pollster = "0.4" rayon = "1.11" [[bench]] diff --git a/crates/chitin-desktop/src/app.rs b/crates/chitin-desktop/src/app.rs index 1a1cf3c5..d6949d19 100644 --- a/crates/chitin-desktop/src/app.rs +++ b/crates/chitin-desktop/src/app.rs @@ -86,6 +86,8 @@ pub struct ChitinApp { pub(crate) pending_structure_loads: BTreeSet, /// Window-level transient notification queue. pub(crate) toast_viewport: Option>, + /// Subscription that keeps the theme aligned with OS appearance changes. + theme_appearance_subscription: Option, } impl ChitinApp { @@ -170,9 +172,20 @@ impl ChitinApp { sequence_panel: SequencePanelState::default(), pending_structure_loads: BTreeSet::new(), toast_viewport: None, + theme_appearance_subscription: None, } } + /// Keeps the active theme aligned with operating-system appearance changes. + /// + /// Explicit light and dark preferences ignore system changes; the automatic + /// mode follows them. The subscription lives with the app entity. + pub fn follow_system_theme(&mut self, window: &mut Window) { + self.theme_appearance_subscription = Some(window.observe_window_appearance(|window, cx| { + chitin_ui::theme::apply_system_appearance(window.appearance(), cx); + })); + } + /// Creates app state with a preallocated project-sidebar focus handle. /// /// This constructor is used by the GPUI window setup so the project sidebar @@ -553,7 +566,11 @@ impl Render for ChitinApp { }); } }) - .child(render_window_bar(theme, app.clone())) + .child(render_window_bar( + theme, + chitin_ui::theme::effective_mode(cx), + app.clone(), + )) .child( div().flex().flex_1().min_h_0().child( div() diff --git a/crates/chitin-desktop/src/commands/history.rs b/crates/chitin-desktop/src/commands/history.rs index de8518c1..7543797f 100644 --- a/crates/chitin-desktop/src/commands/history.rs +++ b/crates/chitin-desktop/src/commands/history.rs @@ -3,7 +3,7 @@ use crate::{app::ChitinApp, workbench::documents::DocumentPanelState}; use chitin_bio::{structure::selection::AtomSelection, surface::MolecularSurfaceBackend}; use chitin_command::{CommandId, RenderLayer, history::CommandHistory}; -use chitin_molecule_renderer::RepresentationLayers; +use chitin_molecule_renderer::{RepresentationLayers, ViewportBackground}; use gpui::{Context, EntityId}; use std::sync::Arc; @@ -20,6 +20,7 @@ pub(crate) struct ViewSnapshot { view: EntityId, layers: RepresentationLayers, backend: Option, + background: Option, selection: Option>, hidden: Option>, } @@ -30,6 +31,7 @@ impl ViewSnapshot { view: state.rendering_view_id(target)?, layers, backend, + background: state.background(target), selection: state.selection_control(target).map(|control| control.atoms.clone()), hidden: state.selection_control(target).map(|control| control.hidden.clone()), }) @@ -152,6 +154,11 @@ impl ChitinApp { { callback(backend, cx); } + if let Some(background) = snapshot.background + && let Some(callback) = self.document_panels.select_background(change.target, background) + { + callback(background, cx); + } if let Some(callback) = self .document_panels .select_representation_layers(change.target, snapshot.layers) @@ -188,8 +195,10 @@ mod tests { state::{WgpuDocumentView, WgpuDocumentViewFactory}, }; use chitin_bio::structure::{PdbParser, StructureScene}; - use chitin_command::{RenderAtomStyle, RenderCommand, RenderOpacity, SelectionCommand, SelectionMode}; - use chitin_molecule_renderer::AtomStyle; + use chitin_command::{ + RenderAtomStyle, RenderBackground, RenderCommand, RenderOpacity, RenderRgb, SelectionCommand, SelectionMode, + }; + use chitin_molecule_renderer::{AtomStyle, ViewportBackground}; use gpui::{App, AppContext, IntoElement, Render, Window}; struct Probe; @@ -210,6 +219,12 @@ mod tests { |_, _| {}, ) .with_surface_backend(MolecularSurfaceBackend::ImplicitScalarField, |_, _| {}) + .with_background(ViewportBackground::Auto, |_, _| {}) + .with_export(|_, _, _| { + Ok(Box::new(|| { + Ok(std::env::temp_dir().join(format!("chitin-export-{}.png", std::process::id()))) + })) + }) .with_selection(Arc::new(scene), |_, _| {}, |_, _| {}) .with_visibility(|_, _| {}) } @@ -393,6 +408,76 @@ mod tests { }); } + #[gpui::test] + fn export_capability_should_follow_the_rendering_tab(cx: &mut gpui::TestAppContext) { + let (app, cx) = mount(cx); + cx.update(|_, cx| { + app.update(cx, |app, cx| { + assert!(app.document_panels.supports_export(1)); + let path = std::env::temp_dir().join(format!("chitin-export-{}.png", std::process::id())); + assert!(matches!( + app.document_panels.export_image(1, &path, true, cx), + Some(Ok(_)) + )); + assert!(!app.document_panels.supports_export(99)); + }); + }); + } + + #[gpui::test] + fn export_command_should_report_the_destination_path(cx: &mut gpui::TestAppContext) { + let (app, cx) = mount(cx); + cx.update(|_, cx| { + app.update(cx, |app, cx| { + let output = app + .dispatch_render_command(Some(1), RenderCommand::ExportImage { output: None }, cx) + .unwrap_or_else(|error| panic!("export command should succeed: {error}")); + assert!( + output.starts_with("Exporting image to "), + "command output should identify the destination: {output}" + ); + assert!(output.ends_with(".png")); + }); + }); + } + + #[gpui::test] + fn viewport_background_should_be_undoable_and_independent_of_layer_style(cx: &mut gpui::TestAppContext) { + let (app, cx) = mount(cx); + cx.update(|_, cx| { + app.update(cx, |app, cx| { + assert_eq!(app.document_panels.background(1), Some(ViewportBackground::Auto)); + assert!( + app + .dispatch_render_command( + Some(1), + RenderCommand::Background(RenderBackground::Custom(RenderRgb([255, 255, 255]))), + cx, + ) + .is_ok() + ); + assert_eq!( + app.document_panels.background(1), + Some(ViewportBackground::Custom([255, 255, 255])) + ); + assert_eq!( + app + .document_panels + .rendering_settings(1) + .map(|(_, layers, _)| layers.atom_style()), + Some(Some(AtomStyle::Stick)) + ); + assert!(app.dispatch_history_command(false, cx).is_ok()); + assert_eq!(app.document_panels.background(1), Some(ViewportBackground::Auto)); + assert!(app.dispatch_history_command(true, cx).is_ok()); + assert_eq!( + app.document_panels.background(1), + Some(ViewportBackground::Custom([255, 255, 255])) + ); + }) + }); + } + #[gpui::test] fn failed_and_noop_selections_should_preserve_selection_and_redo(cx: &mut gpui::TestAppContext) { let (app, cx) = mount(cx); diff --git a/crates/chitin-desktop/src/commands/render.rs b/crates/chitin-desktop/src/commands/render.rs index 32ee2e85..df7f7b00 100644 --- a/crates/chitin-desktop/src/commands/render.rs +++ b/crates/chitin-desktop/src/commands/render.rs @@ -1,10 +1,12 @@ //! Shared presentation command bus for menus, shell sessions, and typed callers. use chitin_bio::surface::MolecularSurfaceBackend; -use chitin_command::{RenderAtomStyle, RenderCommand, RenderPolymerStyle, RenderSurfaceBackend, RenderSurfaceStyle}; +use chitin_command::{ + RenderAtomStyle, RenderBackground, RenderCommand, RenderPolymerStyle, RenderSurfaceBackend, RenderSurfaceStyle, +}; use chitin_command::{RenderColorScheme, RenderLayer}; use chitin_molecule_renderer::appearance::ColorScheme; -use chitin_molecule_renderer::{AtomStyle, PolymerStyle, SurfaceStyle}; +use chitin_molecule_renderer::{AtomStyle, PolymerStyle, SurfaceStyle, ViewportBackground}; use gpui::Context; use crate::app::ChitinApp; @@ -28,6 +30,10 @@ pub enum RenderCommandError { Unavailable { id: u64 }, #[error("rendering panel #{id} does not support surface backend selection")] UnsupportedBackend { id: u64 }, + #[error("rendering panel #{id} does not support viewport background selection")] + UnsupportedBackground { id: u64 }, + #[error("image export failed: {0}")] + Export(String), } impl ChitinApp { @@ -51,17 +57,15 @@ impl ChitinApp { let id = target.ok_or(RenderCommandError::MissingContext)?; let before = super::history::ViewSnapshot::read(&self.document_panels, id).ok_or(RenderCommandError::Unavailable { id })?; + let command_id = command.id(); + let is_status = command == RenderCommand::Status; + let layer = match &command { + RenderCommand::Color { layer, .. } | RenderCommand::Opacity { layer, .. } => Some(*layer), + _ => None, + }; let output = self.apply_render_command(target, command, cx)?; - if command != RenderCommand::Status - && let Some(after) = super::history::ViewSnapshot::read(&self.document_panels, id) - { - let layer = match command { - RenderCommand::Color { layer, .. } | RenderCommand::Opacity { layer, .. } => Some(layer), - _ => None, - }; - self - .edit_history - .changed(id, (command.id(), layer), before, after, phase); + if !is_status && let Some(after) = super::history::ViewSnapshot::read(&self.document_panels, id) { + self.edit_history.changed(id, (command_id, layer), before, after, phase); } Ok(output) } @@ -135,6 +139,23 @@ impl ChitinApp { cx.notify(); } } + RenderCommand::Background(value) => { + self + .document_panels + .background(id) + .ok_or(RenderCommandError::UnsupportedBackground { id })?; + let value = viewport_background(value); + if let Some(on_change) = self.document_panels.select_background(id, value) { + on_change(value, cx); + cx.notify(); + } + } + RenderCommand::ExportImage { output } => { + let path = self + .export_document_image(id, output.as_deref(), cx) + .map_err(RenderCommandError::Export)?; + return Ok(format!("Exporting image to {}", path.display())); + } } if let Some(on_change) = self.document_panels.select_representation_layers(id, layers) { on_change(layers, cx); @@ -163,8 +184,13 @@ impl ChitinApp { Some(MolecularSurfaceBackend::ImplicitScalarField) => "implicit-scalar-field", Some(MolecularSurfaceBackend::Msms) => "msms", }; + let background = match self.document_panels.background(id) { + None => "unavailable".to_string(), + Some(ViewportBackground::Auto) => "auto (follows theme)".to_string(), + Some(ViewportBackground::Custom([r, g, b])) => format!("#{r:02X}{g:02X}{b:02X}"), + }; let mut output = format!( - "Panel #{id}: {}\nAtom style: {atom}\nPolymer style: {polymer}\nSurface style: {surface}\nSurface backend: {backend}", + "Panel #{id}: {}\nAtom style: {atom}\nPolymer style: {polymer}\nSurface style: {surface}\nSurface backend: {backend}\nBackground: {background}", super::terminal_label(&title) ); for (name, appearance) in ["Atom", "Polymer", "Surface"].into_iter().zip(layers.appearances()) { @@ -191,3 +217,11 @@ fn layer_index(layer: RenderLayer) -> usize { RenderLayer::Surface => 2, } } + +/// Converts a typed command value into the renderer's theme-independent policy. +fn viewport_background(background: RenderBackground) -> ViewportBackground { + match background { + RenderBackground::Auto => ViewportBackground::Auto, + RenderBackground::Custom(color) => ViewportBackground::Custom(color.0), + } +} diff --git a/crates/chitin-desktop/src/commands/shell_host.rs b/crates/chitin-desktop/src/commands/shell_host.rs index 8bd688ba..ae89ed76 100644 --- a/crates/chitin-desktop/src/commands/shell_host.rs +++ b/crates/chitin-desktop/src/commands/shell_host.rs @@ -324,9 +324,11 @@ impl ChitinApp { self.document_panels.activate_tab(leaf, tab); } let result = match command { - FrontendCommand::Render(command) => { - self.dispatch_render_command(submission.rendering_panel().map(|panel| panel.id()), *command, cx) - } + FrontendCommand::Render(command) => self.dispatch_render_command( + submission.rendering_panel().map(|panel| panel.id()), + command.clone(), + cx, + ), FrontendCommand::Selection(command) => self.dispatch_selection_command( submission.rendering_panel().map(|panel| panel.id()), command.clone(), diff --git a/crates/chitin-desktop/src/features/molecule/appearance.rs b/crates/chitin-desktop/src/features/molecule/appearance.rs index 70f17173..69771a12 100644 --- a/crates/chitin-desktop/src/features/molecule/appearance.rs +++ b/crates/chitin-desktop/src/features/molecule/appearance.rs @@ -15,7 +15,10 @@ use gpui_kit::component::{ slider::{Slider, SliderEvent, SliderState, SliderValue}, theme::ThemeColor, }; -use std::{cell::Cell, rc::Rc}; +use std::{ + cell::{Cell, RefCell}, + rc::Rc, +}; /// Shared maximum width for compact inline molecular editors. pub(super) const EDITOR_MAX_WIDTH: gpui::Pixels = px(260.0); @@ -55,7 +58,7 @@ struct LayerControls { /// Opacity editor whose release completes one undoable edit. opacity: Entity, /// Pending command and source view identity, preventing stale frame updates. - pending_opacity: Rc>>, + pending_opacity: Rc>>, } impl LayerControls { @@ -63,7 +66,7 @@ impl LayerControls { fn sync_opacity(&self, appearance: LayerAppearance, window: &mut Window, cx: &mut App) { // A coalesced command may not have reached the model yet. Do not roll the // thumb back to last frame's value while that command is waiting. - if self.pending_opacity.get().is_none() + if self.pending_opacity.borrow().is_none() && (self.opacity.read(cx).value().end() - appearance.opacity()).abs() > f32::EPSILON { self @@ -115,14 +118,14 @@ impl AppearanceControls { }), color: cx.new(|cx| ColorPickerState::new(window, cx)), opacity: cx.new(|_| SliderState::new().min(0.0).max(1.0).step(0.01).default_value(1.0)), - pending_opacity: Rc::new(Cell::new(None)), + pending_opacity: Rc::new(RefCell::new(None)), }), } } /// Discards queued slider previews when the inspector changes its target. pub fn clear_pending(&self) { for layer in &self.layers { - layer.pending_opacity.take(); + layer.pending_opacity.borrow_mut().take(); } } @@ -222,7 +225,7 @@ impl AppearanceControls { }; let command = RenderCommand::Opacity { layer, value }; if matches!(event, SliderEvent::Release(_)) { - pending.take(); + pending.borrow_mut().take(); if let Err(error) = app.dispatch_render_edit(Some(target), command, crate::commands::history::EditPhase::Finish, cx) { @@ -366,14 +369,14 @@ mod tests { let Ok(value) = RenderOpacity::new(0.35) else { panic!("valid opacity should be accepted"); }; - layer.pending_opacity.set(Some(( + *layer.pending_opacity.borrow_mut() = Some(( 1, app.entity_id(), RenderCommand::Opacity { layer: RenderLayer::Atom, value, }, - ))); + )); let appearance = LayerAppearance::new(ColorScheme::Element); layer.sync_opacity(appearance, window, cx); assert_eq!(layer.opacity.read(cx).value(), SliderValue::Single(0.35)); diff --git a/crates/chitin-desktop/src/features/molecule/export.rs b/crates/chitin-desktop/src/features/molecule/export.rs new file mode 100644 index 00000000..40cc1caa --- /dev/null +++ b/crates/chitin-desktop/src/features/molecule/export.rs @@ -0,0 +1,261 @@ +//! Protein viewport image export: destination naming and user feedback. + +use std::{ + path::{Path, PathBuf}, + sync::atomic::{AtomicU64, Ordering}, + time::{SystemTime, UNIX_EPOCH}, +}; + +use chitin_ui::widgets::toast::{Toast, ToastVariant}; +use gpui::{AsyncApp, Context}; + +use crate::app::ChitinApp; + +/// Sequence used to keep default export names unique within one process. +static EXPORT_SEQUENCE: AtomicU64 = AtomicU64::new(0); + +/// Resolved export path and whether it may overwrite an existing file. +struct ExportDestination { + /// Absolute destination path. + path: PathBuf, + /// Reject an existing file instead of replacing it. + create_new: bool, +} + +impl ChitinApp { + /// Starts an asynchronous export of one protein viewport. + /// + /// The file is written to `/.chitin/exports/-<millis>-<sequence>.png`. + /// When no workspace is open, the current working directory is used. GPU + /// submission happens immediately; polling, readback, PNG encoding, and the + /// file write run on the background executor. Toasts report progress and the + /// final result. + /// + /// # Parameters + /// + /// * `panel_id` identifies the stable rendering tab to capture. + /// * `output` optionally supplies a destination file or directory. Relative + /// paths resolve inside the workspace; non-PNG extensions become `.png`. + /// * `cx` schedules the background worker and reports through the toast viewport. + /// + /// # Returns + /// + /// The destination path once GPU work has been submitted. The file may not + /// exist yet when this returns. + /// + /// # Errors + /// + /// Returns a user-facing message when the tab is unavailable, the panel does + /// not support export, or GPU submission fails. + pub(crate) fn export_document_image( + &mut self, + panel_id: u64, + output: Option<&Path>, + cx: &mut Context<Self>, + ) -> Result<PathBuf, String> { + let Some(title) = self.document_panels.tab_title(panel_id).map(str::to_owned) else { + return Err("the requested rendering tab is not open".into()); + }; + let destination = self.export_image_path(&title, output); + let path = destination.path; + let toast_viewport = self.toast_viewport(cx); + let info = toast_viewport.update(cx, |viewport, cx| { + viewport.push( + Toast::new("Exporting protein image") + .description(path.display().to_string()) + .variant(ToastVariant::Info) + .duration(None), + cx, + ) + }); + let task = match self + .document_panels + .export_image(panel_id, &path, destination.create_new, cx) + { + Some(Ok(task)) => task, + Some(Err(error)) => { + toast_viewport.update(cx, |viewport, cx| { + viewport.dismiss(info, cx); + viewport.push( + Toast::new("Failed to export protein image") + .description(error.clone()) + .variant(ToastVariant::Error), + cx, + ); + }); + return Err(error); + } + None => { + let error = "This panel does not support image export".to_string(); + toast_viewport.update(cx, |viewport, cx| { + viewport.dismiss(info, cx); + viewport.push(Toast::new(error.clone()).variant(ToastVariant::Warning), cx); + }); + return Err(error); + } + }; + + let toast_viewport = toast_viewport.clone(); + cx.spawn(async move |_app, async_cx: &mut AsyncApp| { + let result = async_cx.background_executor().spawn(async move { task() }).await; + async_cx.update(|cx| { + toast_viewport.update(cx, |viewport, cx| { + viewport.dismiss(info, cx); + match result { + Ok(path) => { + viewport.push( + Toast::new("Protein image exported") + .description(path.display().to_string()) + .variant(ToastVariant::Success), + cx, + ); + } + Err(error) => { + viewport.push( + Toast::new("Failed to export protein image") + .description(error) + .variant(ToastVariant::Error), + cx, + ); + } + } + }); + }); + }) + .detach(); + + Ok(path) + } + + /// Resolves the export destination for a viewport title. + fn export_image_path(&self, title: &str, output: Option<&Path>) -> ExportDestination { + match output { + Some(output) => { + let mut path = if output.is_absolute() { + output.to_path_buf() + } else { + self.workspace_root().join(output) + }; + if path.is_dir() || output.to_string_lossy().ends_with(['/', '\\']) { + path.push(self.default_export_name(title)); + ExportDestination { path, create_new: true } + } else { + if !path + .extension() + .and_then(|extension| extension.to_str()) + .is_some_and(|extension| extension.eq_ignore_ascii_case("png")) + { + path.set_extension("png"); + } + ExportDestination { + path, + create_new: false, + } + } + } + None => ExportDestination { + path: self.export_directory().join(self.default_export_name(title)), + create_new: true, + }, + } + } + + /// Returns the default directory and filename shown by the save dialog. + pub(crate) fn export_dialog_default(&self, panel_id: u64) -> Option<(PathBuf, String)> { + let title = self.document_panels.tab_title(panel_id)?; + Some((self.export_directory(), self.default_export_name(title))) + } + + /// Returns the default workspace export directory. + fn export_directory(&self) -> PathBuf { + self.workspace_root().join(".chitin").join("exports") + } + + /// Returns a timestamped PNG filename derived from a tab title. + fn default_export_name(&self, title: &str) -> String { + let millis = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map_or(0, |duration| duration.as_millis()); + let sequence = EXPORT_SEQUENCE.fetch_add(1, Ordering::Relaxed); + format!("{}-{millis}-{sequence}.png", export_stem(title)) + } + + /// Returns the workspace root, or the process directory when none is open. + fn workspace_root(&self) -> PathBuf { + self.workspace.as_ref().map_or_else( + || std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")), + |workspace| workspace.root.clone(), + ) + } +} + +/// Converts a tab title into a filesystem-safe filename stem. +fn export_stem(title: &str) -> String { + let mut stem = String::new(); + let mut separator = false; + for character in title.chars() { + if character.is_ascii_alphanumeric() || character == '_' { + stem.push(character); + separator = false; + } else if !separator { + stem.push('-'); + separator = true; + } + } + let stem = stem.trim_matches('-'); + if stem.is_empty() || stem == "png" { + "protein".to_string() + } else { + stem + .strip_suffix(".png") + .unwrap_or(stem) + .trim_end_matches('-') + .to_string() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn export_stem_should_sanitize_titles_and_keep_them_readable() { + assert_eq!(export_stem("1ABC.pdb"), "1ABC-pdb"); + assert_eq!(export_stem("my protein / chain A"), "my-protein-chain-A"); + assert_eq!(export_stem("..."), "protein"); + assert_eq!(export_stem(".png"), "protein"); + } + + #[test] + fn export_paths_should_resolve_relative_destinations_and_force_png() { + let app = ChitinApp::new(None); + let absolute = std::env::temp_dir().join("chitin-export.png"); + let destination = app.export_image_path("1ABC.pdb", Some(&absolute)); + assert_eq!(destination.path, absolute); + assert!(!destination.create_new); + let destination = app.export_image_path("1ABC.pdb", Some(Path::new("images/view.jpg"))); + assert!(destination.path.is_absolute()); + assert!(destination.path.ends_with("images/view.png")); + assert!(!destination.create_new); + let destination = app.export_image_path("1ABC.pdb", Some(Path::new("images/"))); + assert_eq!( + destination.path.parent().and_then(|parent| parent.file_name()), + Some(std::ffi::OsStr::new("images")) + ); + assert_eq!( + destination.path.extension().and_then(|extension| extension.to_str()), + Some("png") + ); + assert!(destination.create_new); + } + + #[test] + fn default_export_names_should_not_repeat_within_a_process() { + let app = ChitinApp::new(None); + let first = app.default_export_name("1ABC.pdb"); + let second = app.default_export_name("1ABC.pdb"); + assert_ne!(first, second); + assert!(first.ends_with(".png")); + assert!(second.ends_with(".png")); + } +} diff --git a/crates/chitin-desktop/src/features/molecule/mod.rs b/crates/chitin-desktop/src/features/molecule/mod.rs index 8df14eae..6cc76c6b 100644 --- a/crates/chitin-desktop/src/features/molecule/mod.rs +++ b/crates/chitin-desktop/src/features/molecule/mod.rs @@ -1,6 +1,7 @@ //! Molecular scene integration, rendering options, and GPU viewport host. mod appearance; +mod export; pub(crate) mod scene; pub(crate) mod settings; pub mod viewport; diff --git a/crates/chitin-desktop/src/features/molecule/scene.rs b/crates/chitin-desktop/src/features/molecule/scene.rs index 70d4eeb4..6a934e7c 100644 --- a/crates/chitin-desktop/src/features/molecule/scene.rs +++ b/crates/chitin-desktop/src/features/molecule/scene.rs @@ -11,13 +11,13 @@ use chitin_bio::{ }; use chitin_molecule_renderer::{ AtomStyle, BallAndStickStyle, MoleculeDebugMode, MoleculeRenderInput, MoleculeRenderer, PolymerStyle, - RepresentationLayers, + RepresentationLayers, ViewportBackground, }; use chitin_ui::widgets::toast::{Toast, ToastVariant, ToastViewport}; use gpui::{AnyWindowHandle, App, AppContext, AsyncApp, Entity, Window}; use super::viewport::{ChitinWgpuDocumentPanel, WgpuPanelFrame, WgpuPanelScene}; -use crate::workbench::documents::state::WgpuDocumentView; +use crate::workbench::documents::state::{ExportTask, WgpuDocumentView}; /// Default representation used when GPUI opens a PDB or mmCIF document. const DEFAULT_STRUCTURE_REPRESENTATION: RepresentationLayers = @@ -72,6 +72,8 @@ pub(crate) struct StructureMoleculeScene { debug_mode: MoleculeDebugMode, /// Representation layers currently rendered by this scene. representation: RepresentationLayers, + /// Resolved linear-RGB viewport clear color. + background_color: [f64; 3], } impl StructureMoleculeScene { @@ -85,6 +87,7 @@ impl StructureMoleculeScene { surface: None, debug_mode: MoleculeDebugMode::Final, representation, + background_color: [0.0, 0.0, 0.0], } } } @@ -184,6 +187,7 @@ impl WgpuPanelScene for StructureMoleculeScene { &BallAndStickStyle::default(), ) }); + renderer.set_background_color(self.background_color); renderer.set_selection(&self.scene, Arc::clone(&self.selected)); renderer.set_hidden(Arc::clone(&self.hidden)); renderer.set_selection_scale(frame.scale_factor); @@ -215,6 +219,21 @@ impl WgpuPanelScene for StructureMoleculeScene { true } + fn set_background_color(&mut self, color: [f64; 3]) -> bool { + if !color.iter().all(|channel| channel.is_finite()) { + return false; + } + let color = color.map(|channel| channel.clamp(0.0, 1.0)); + if self.background_color == color { + return false; + } + self.background_color = color; + if let Some(renderer) = self.renderer.as_mut() { + renderer.set_background_color(color); + } + true + } + fn set_molecular_surface(&mut self, surface: MolecularSurfaceArtifact) -> bool { let is_visible = self.representation.surface_style().is_some(); if is_visible && let Some(renderer) = self.renderer.as_mut() { @@ -297,6 +316,8 @@ pub(crate) fn build_structure_view_from_scene( let selection_panel = panel.clone(); let visibility_panel = panel.clone(); let input_panel = panel.clone(); + let background_panel = panel.clone(); + let export_panel = panel.clone(); let view = view .with_selection( Arc::clone(&scene), @@ -317,6 +338,21 @@ pub(crate) fn build_structure_view_from_scene( cx.notify(); } }); + }) + .with_background(ViewportBackground::Auto, move |background, cx| { + background_panel.update(cx, |panel, cx| { + if panel.set_background(background) { + cx.notify(); + } + }); + }) + .with_export(move |path, create_new, cx| { + export_panel.update(cx, |panel, _| { + panel + .begin_export(path, create_new) + .map(|pending| Box::new(move || pending.finish().map_err(|error| error.to_string())) as ExportTask) + .map_err(|error| error.to_string()) + }) }); let backend_scene = Arc::clone(&scene); let backend_toasts = toast_viewport; diff --git a/crates/chitin-desktop/src/features/molecule/viewport.rs b/crates/chitin-desktop/src/features/molecule/viewport.rs index d1f52e9e..a410022f 100644 --- a/crates/chitin-desktop/src/features/molecule/viewport.rs +++ b/crates/chitin-desktop/src/features/molecule/viewport.rs @@ -1,5 +1,7 @@ //! Experimental WGPU document panel component. +mod export; + use std::{ cell::Cell, rc::Rc, @@ -11,7 +13,7 @@ use chitin_bio::structure::selection::AtomSelection; use chitin_bio::surface::MolecularSurfaceArtifact; use chitin_command::{SelectionCommand, SelectionMode}; use chitin_molecule_renderer::picking::MolecularPick; -use chitin_molecule_renderer::{DragMode, RepresentationLayers, ViewerCamera, ViewportDrag}; +use chitin_molecule_renderer::{DragMode, RepresentationLayers, ViewerCamera, ViewportBackground, ViewportDrag}; use chitin_ui::workbench::{WorkbenchStyle, viewport_container, viewport_position}; use chitin_wgpu::RenderTargetSize; use gpui::{ @@ -93,6 +95,11 @@ pub trait WgpuPanelScene { false } + /// Applies a resolved linear-RGB viewport clear color when supported. + fn set_background_color(&mut self, _color: [f64; 3]) -> bool { + false + } + /// Installs a computed molecular surface when the hosted scene supports it. fn set_molecular_surface(&mut self, _surface: MolecularSurfaceArtifact) -> bool { false @@ -130,6 +137,8 @@ pub struct ChitinWgpuDocumentPanel { started_at: Instant, /// Actual inset viewport bounds, updated during layout rather than rendering. viewport_bounds: Rc<Cell<Bounds<Pixels>>>, + /// User-selected clear-color policy for this viewport. + background: ViewportBackground, } struct SelectionGesture { @@ -170,9 +179,23 @@ impl ChitinWgpuDocumentPanel { active_drag: None, started_at: Instant::now(), viewport_bounds: Rc::new(Cell::new(Bounds::default())), + background: ViewportBackground::Auto, } } + /// Changes the viewport clear-color policy. + /// + /// The next rendered frame resolves automatic colors against the current + /// theme, so callers do not need to know whether the app is in light or dark + /// mode. Returns `true` when the policy changed. + pub(crate) fn set_background(&mut self, background: ViewportBackground) -> bool { + if self.background == background { + return false; + } + self.background = background; + true + } + pub(crate) fn bind_selection_input(&mut self, handler: SelectionInputHandler) { self.selection_input = Some(handler); } @@ -543,7 +566,11 @@ impl Render for ChitinWgpuDocumentPanel { /// /// A GPUI element tree containing the WGPU surface and a small FPS overlay. fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement { - let theme = Theme::global(cx).colors; + let (theme, dark) = { + let theme = Theme::global(cx); + (theme.colors, theme.mode.is_dark()) + }; + self.scene.set_background_color(self.background.resolve(dark)); let style = WorkbenchStyle::new(theme); let viewport_bounds = self.viewport_bounds.clone(); if self.selection_gesture.is_some() { diff --git a/crates/chitin-desktop/src/features/molecule/viewport/export.rs b/crates/chitin-desktop/src/features/molecule/viewport/export.rs new file mode 100644 index 00000000..b7c87e8c --- /dev/null +++ b/crates/chitin-desktop/src/features/molecule/viewport/export.rs @@ -0,0 +1,609 @@ +//! Offscreen PNG capture for one molecular viewport. + +use std::{ + fs::OpenOptions, + io::{BufWriter, ErrorKind}, + path::{Path, PathBuf}, + sync::{ + atomic::{AtomicU64, Ordering}, + mpsc, + }, + time::Duration, +}; + +use chitin_wgpu::RenderTargetSize; + +use super::{ChitinWgpuDocumentPanel, WgpuPanelFrame}; + +/// Sequence used to keep temporary output names unique within one process. +static TEMP_SEQUENCE: AtomicU64 = AtomicU64::new(0); + +/// Failure while rendering or writing a protein image. +#[derive(Debug, thiserror::Error)] +pub(crate) enum ExportError { + /// The panel has no WGPU surface to borrow a device and queue from. + #[error("the protein viewport is not attached to a WGPU surface")] + NoSurface, + /// The native viewport has not received a drawable size yet. + #[error("the protein viewport has no drawable area")] + EmptyTarget, + /// The GPU readback failed or timed out. + #[error("GPU readback failed: {0}")] + Readback(String), + /// The destination could not be created or written. + #[error("failed to write {path}: {source}")] + Io { + /// Destination path. + path: String, + /// Underlying filesystem error. + source: std::io::Error, + }, + /// The caller requested that an existing file not be replaced. + #[error("refusing to overwrite existing image {0}")] + AlreadyExists(String), + /// PNG encoding failed. + #[error("failed to encode PNG: {0}")] + Png(#[from] png::EncodingError), +} + +impl ChitinWgpuDocumentPanel { + /// Starts an offscreen capture of the current camera view. + /// + /// This half runs on the UI thread and only performs GPU submission: it + /// creates the target texture, renders the scene, and queues the readback. + /// Polling, mapping, PNG encoding, and file I/O happen in + /// [`PendingExport::finish`] on a background worker. + /// + /// # Parameters + /// + /// * `path` is the final image path. The target directory is not created + /// until the background write runs. + /// * `create_new` rejects an existing destination instead of overwriting it. + /// + /// # Returns + /// + /// A pending capture that can be finished off the UI thread. + /// + /// # Errors + /// + /// Returns [`ExportError`] when the surface is unavailable, the target is + /// empty, or GPU submission fails. + pub(crate) fn begin_export(&mut self, path: &Path, create_new: bool) -> Result<PendingExport, ExportError> { + let Some(surface) = self.surface.as_ref() else { + return Err(ExportError::NoSurface); + }; + let (width, height) = surface.size(); + if width == 0 || height == 0 { + return Err(ExportError::EmptyTarget); + } + let format = wgpu::TextureFormat::Rgba8UnormSrgb; + let device = surface.device(); + let queue = surface.queue(); + // Prevent a surface resize from reconfiguring the shared queue while the + // offscreen capture is submitted. The guard is released before returning. + let _submit_guard = surface.submit_guard(); + + let texture = device.create_texture(&wgpu::TextureDescriptor { + label: Some("chitin_protein_export_target"), + size: wgpu::Extent3d { + width, + height, + depth_or_array_layers: 1, + }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format, + usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC, + view_formats: &[], + }); + let view = texture.create_view(&Default::default()); + let size = RenderTargetSize::new(width, height); + let elapsed = self.started_at.elapsed(); + let camera = &self.camera; + let _render_submission = self.scene.render_frame(WgpuPanelFrame { + scale_factor: 1.0, + device, + queue, + format, + view: &view, + size, + camera, + elapsed, + }); + + let (readback, submission) = submit_texture_readback(device, queue, &texture, width, height)?; + Ok(PendingExport { + device: device.clone(), + path: path.to_path_buf(), + width, + height, + format, + readback, + submission, + create_new, + }) + } +} + +/// Submitted GPU capture whose readback and file write can run off the UI thread. +pub(crate) struct PendingExport { + /// Device used by the submitted copy. + device: wgpu::Device, + /// Final image path. + path: PathBuf, + /// Capture width in physical pixels. + width: u32, + /// Capture height in physical pixels. + height: u32, + /// Format of the source render target. + format: wgpu::TextureFormat, + /// Buffer receiving the texture copy. + readback: wgpu::Buffer, + /// Queue submission that must complete before mapping. + submission: wgpu::SubmissionIndex, + /// Reject an existing destination instead of overwriting it. + create_new: bool, +} + +impl PendingExport { + /// Waits for the GPU copy, reads it back, and writes the PNG. + /// + /// This blocks the calling worker until the GPU finishes, so callers must not + /// invoke it on the GPUI event thread. + /// + /// # Returns + /// + /// The written image path. + /// + /// # Errors + /// + /// Returns [`ExportError`] when GPU readback fails or the image cannot be + /// encoded or written. + pub(crate) fn finish(self) -> Result<PathBuf, ExportError> { + let mut rgba = read_buffer_rgba( + &self.device, + &self.readback, + self.format, + self.width, + self.height, + Some(self.submission), + )?; + if self.format.is_srgb() { + decode_presentation_rgb(&mut rgba); + } + if let Some(parent) = self.path.parent() { + std::fs::create_dir_all(parent).map_err(|source| ExportError::Io { + path: parent.display().to_string(), + source, + })?; + } + write_atomic_png(&self.path, self.create_new, self.width, self.height, &rgba)?; + Ok(self.path) + } +} + +/// Writes a PNG through a temporary sibling and replaces the destination only +/// after encoding, flushing, and syncing succeed. +fn write_atomic_png(path: &Path, create_new: bool, width: u32, height: u32, rgba: &[u8]) -> Result<(), ExportError> { + let temporary = temporary_export_path(path); + let result = write_png_file(&temporary, width, height, rgba); + if let Err(error) = result { + let _ = std::fs::remove_file(&temporary); + return Err(error); + } + if create_new && path.exists() { + let _ = std::fs::remove_file(&temporary); + return Err(ExportError::AlreadyExists(path.display().to_string())); + } + if let Err(source) = std::fs::rename(&temporary, path) { + let _ = std::fs::remove_file(&temporary); + return Err(ExportError::Io { + path: path.display().to_string(), + source, + }); + } + Ok(()) +} + +/// Encodes a PNG into a fresh temporary file and verifies the final flush. +fn write_png_file(path: &Path, width: u32, height: u32, rgba: &[u8]) -> Result<(), ExportError> { + let file = OpenOptions::new() + .write(true) + .create_new(true) + .open(path) + .map_err(|source| { + if source.kind() == ErrorKind::AlreadyExists { + ExportError::AlreadyExists(path.display().to_string()) + } else { + ExportError::Io { + path: path.display().to_string(), + source, + } + } + })?; + let mut writer = BufWriter::new(file); + encode_png(&mut writer, width, height, rgba)?; + let file = writer.into_inner().map_err(|error| ExportError::Io { + path: path.display().to_string(), + source: error.into_error(), + })?; + file.sync_all().map_err(|source| ExportError::Io { + path: path.display().to_string(), + source, + })?; + Ok(()) +} + +/// Returns a unique sibling path for an in-progress export. +fn temporary_export_path(path: &Path) -> PathBuf { + let name = path.file_name().and_then(|name| name.to_str()).unwrap_or("image.png"); + let sequence = TEMP_SEQUENCE.fetch_add(1, Ordering::Relaxed); + path.with_file_name(format!(".{name}.tmp-{}-{sequence}", std::process::id())) +} + +/// Queues a texture-to-buffer copy and returns the buffer with its submission. +fn submit_texture_readback( + device: &wgpu::Device, + queue: &wgpu::Queue, + texture: &wgpu::Texture, + width: u32, + height: u32, +) -> Result<(wgpu::Buffer, wgpu::SubmissionIndex), ExportError> { + let (readback, padded_bytes_per_row) = create_readback_buffer(device, width, height); + let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { + label: Some("chitin_protein_export_encoder"), + }); + encoder.copy_texture_to_buffer( + wgpu::TexelCopyTextureInfo { + texture, + mip_level: 0, + origin: wgpu::Origin3d::ZERO, + aspect: wgpu::TextureAspect::All, + }, + wgpu::TexelCopyBufferInfo { + buffer: &readback, + layout: wgpu::TexelCopyBufferLayout { + offset: 0, + bytes_per_row: Some(padded_bytes_per_row), + rows_per_image: Some(height), + }, + }, + wgpu::Extent3d { + width, + height, + depth_or_array_layers: 1, + }, + ); + let submission = queue.submit(Some(encoder.finish())); + Ok((readback, submission)) +} + +/// Creates the mappable readback buffer and returns its aligned row stride. +fn create_readback_buffer(device: &wgpu::Device, width: u32, height: u32) -> (wgpu::Buffer, u32) { + let unpadded_bytes_per_row = width * 4; + let padded_bytes_per_row = + unpadded_bytes_per_row.div_ceil(wgpu::COPY_BYTES_PER_ROW_ALIGNMENT) * wgpu::COPY_BYTES_PER_ROW_ALIGNMENT; + let readback = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("chitin_protein_export_readback"), + size: u64::from(padded_bytes_per_row) * u64::from(height), + usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ, + mapped_at_creation: false, + }); + (readback, padded_bytes_per_row) +} + +/// Waits for a submitted copy and returns tightly packed RGBA bytes. +fn read_buffer_rgba( + device: &wgpu::Device, + readback: &wgpu::Buffer, + format: wgpu::TextureFormat, + width: u32, + height: u32, + submission: Option<wgpu::SubmissionIndex>, +) -> Result<Vec<u8>, ExportError> { + device + .poll(wgpu::PollType::Wait { + submission_index: submission.clone(), + timeout: Some(Duration::from_secs(30)), + }) + .map_err(|error| ExportError::Readback(error.to_string()))?; + + let slice = readback.slice(..); + let (sender, receiver) = mpsc::sync_channel(1); + slice.map_async(wgpu::MapMode::Read, move |result| { + let _ = sender.send(result); + }); + device + .poll(wgpu::PollType::Wait { + submission_index: submission, + timeout: Some(Duration::from_secs(30)), + }) + .map_err(|error| ExportError::Readback(error.to_string()))?; + receiver + .recv() + .map_err(|_| ExportError::Readback("map callback was dropped".into()))? + .map_err(|error| ExportError::Readback(error.to_string()))?; + + let mapped = slice + .get_mapped_range() + .map_err(|error| ExportError::Readback(error.to_string()))?; + let unpadded_bytes_per_row = width * 4; + let padded_bytes_per_row = + unpadded_bytes_per_row.div_ceil(wgpu::COPY_BYTES_PER_ROW_ALIGNMENT) * wgpu::COPY_BYTES_PER_ROW_ALIGNMENT; + let mut rgba = Vec::with_capacity((width as usize) * (height as usize) * 4); + for row in 0..height { + let start = (row as usize) * (padded_bytes_per_row as usize); + let end = start + (unpadded_bytes_per_row as usize); + let pixels = &mapped[start..end]; + match format { + wgpu::TextureFormat::Bgra8Unorm | wgpu::TextureFormat::Bgra8UnormSrgb => { + for pixel in pixels.as_chunks::<4>().0 { + rgba.extend_from_slice(&[pixel[2], pixel[1], pixel[0], pixel[3]]); + } + } + _ => rgba.extend_from_slice(pixels), + } + } + drop(mapped); + readback.unmap(); + Ok(rgba) +} + +/// Writes tightly packed RGBA bytes as an 8-bit PNG. +fn encode_png(mut writer: impl std::io::Write, width: u32, height: u32, rgba: &[u8]) -> Result<(), ExportError> { + let mut encoder = png::Encoder::new(&mut writer, width, height); + encoder.set_color(png::ColorType::Rgba); + encoder.set_depth(png::BitDepth::Eight); + let mut png = encoder.write_header()?; + png.write_image_data(rgba)?; + png.finish()?; + Ok(()) +} + +/// Matches the values GPUI currently presents for a WGPU surface. +/// +/// The production viewport uses an sRGB surface that GPUI samples into linear +/// space and writes to a non-sRGB swapchain. Exporting the raw sRGB bytes looks +/// brighter than that viewport, so decode the RGB channels before writing PNG. +fn decode_presentation_rgb(rgba: &mut [u8]) { + for pixel in rgba.as_chunks_mut::<4>().0 { + pixel[0] = srgb_to_linear_channel(pixel[0]); + pixel[1] = srgb_to_linear_channel(pixel[1]); + pixel[2] = srgb_to_linear_channel(pixel[2]); + } +} + +/// Converts one sRGB-encoded channel to the linear value shown by GPUI. +fn srgb_to_linear_channel(value: u8) -> u8 { + let encoded = f32::from(value) / 255.0; + let linear = if encoded <= 0.040_45 { + encoded / 12.92 + } else { + ((encoded + 0.055) / 1.055).powf(2.4) + }; + (linear * 255.0).round().clamp(0.0, 255.0) as u8 +} + +#[cfg(test)] +fn read_texture_rgba( + device: &wgpu::Device, + queue: &wgpu::Queue, + texture: &wgpu::Texture, + format: wgpu::TextureFormat, + width: u32, + height: u32, +) -> Result<Vec<u8>, ExportError> { + let (readback, padded_bytes_per_row) = create_readback_buffer(device, width, height); + let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { + label: Some("chitin_export_test_encoder"), + }); + encoder.copy_texture_to_buffer( + wgpu::TexelCopyTextureInfo { + texture, + mip_level: 0, + origin: wgpu::Origin3d::ZERO, + aspect: wgpu::TextureAspect::All, + }, + wgpu::TexelCopyBufferInfo { + buffer: &readback, + layout: wgpu::TexelCopyBufferLayout { + offset: 0, + bytes_per_row: Some(padded_bytes_per_row), + rows_per_image: Some(height), + }, + }, + wgpu::Extent3d { + width, + height, + depth_or_array_layers: 1, + }, + ); + let submission = queue.submit(Some(encoder.finish())); + read_buffer_rgba(device, &readback, format, width, height, Some(submission)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn png_write_should_preserve_exact_rgba_values() { + let pixels = [ + 0, 0, 0, 255, // black + 255, 255, 255, 255, // white + 128, 128, 128, 255, // mid gray + 255, 0, 0, 255, // red + 0, 255, 0, 255, // green + 0, 0, 255, 255, // blue + ]; + let mut bytes = Vec::new(); + if let Err(error) = encode_png(&mut bytes, 6, 1, &pixels) { + panic!("PNG encoding should succeed: {error}"); + } + let decoder = png::Decoder::new(std::io::Cursor::new(bytes)); + let mut reader = decoder + .read_info() + .unwrap_or_else(|error| panic!("PNG header should decode: {error}")); + let mut output = vec![0; reader.output_buffer_size()]; + let info = reader + .next_frame(&mut output) + .unwrap_or_else(|error| panic!("PNG frame should decode: {error}")); + assert_eq!(info.width, 6); + assert_eq!(info.height, 1); + assert_eq!(&output[..pixels.len()], &pixels); + } + + #[test] + fn presentation_decode_should_keep_endpoints_and_darken_midtones() { + let mut pixels = [0, 0, 0, 255, 255, 255, 255, 255, 226, 226, 226, 255]; + decode_presentation_rgb(&mut pixels); + assert_eq!(&pixels[0..4], &[0, 0, 0, 255]); + assert_eq!(&pixels[4..8], &[255, 255, 255, 255]); + assert!(pixels[8] < 200, "sRGB midtones should decode toward linear"); + assert!(srgb_to_linear_channel(64) < 64); + } + + struct FlushFailWriter; + + impl std::io::Write for FlushFailWriter { + fn write(&mut self, buffer: &[u8]) -> std::io::Result<usize> { + Ok(buffer.len()) + } + + fn flush(&mut self) -> std::io::Result<()> { + Err(std::io::Error::other("intentional flush failure")) + } + } + + #[test] + fn png_encoder_should_report_final_flush_failures() { + assert!( + encode_png(FlushFailWriter, 1, 1, &[255, 0, 0, 255]).is_err(), + "encode_png must surface the final flush error" + ); + } + + #[test] + fn create_new_exports_should_not_replace_an_existing_file() { + let directory = std::env::temp_dir().join(format!( + "chitin-export-overwrite-{}-{}", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |duration| duration.as_nanos()) + )); + if let Err(error) = std::fs::create_dir_all(&directory) { + panic!("test directory should be creatable: {error}"); + } + let path = directory.join("image.png"); + let original = [255, 0, 0, 255]; + if let Err(error) = write_atomic_png(&path, true, 1, 1, &original) { + panic!("initial export should succeed: {error}"); + } + let first = match std::fs::read(&path) { + Ok(bytes) => bytes, + Err(error) => panic!("initial export should be readable: {error}"), + }; + assert!(matches!( + write_atomic_png(&path, true, 1, 1, &[0, 255, 0, 255]), + Err(ExportError::AlreadyExists(_)) + )); + let preserved = match std::fs::read(&path) { + Ok(bytes) => bytes, + Err(error) => panic!("existing export should remain readable: {error}"), + }; + assert_eq!(first, preserved); + if let Err(error) = write_atomic_png(&path, false, 1, 1, &[0, 255, 0, 255]) { + panic!("explicit overwrite should succeed: {error}"); + } + let replaced = match std::fs::read(&path) { + Ok(bytes) => bytes, + Err(error) => panic!("replacement export should be readable: {error}"), + }; + assert_ne!(first, replaced); + if let Ok(entries) = std::fs::read_dir(&directory) { + assert_eq!(entries.count(), 1, "temporary export files must be cleaned up"); + } + let _ = std::fs::remove_dir_all(&directory); + } + + /// Manual GPU check; ignored so CI does not require an adapter. + /// + /// Run with: + /// `cargo test -p chitin-desktop --lib gpu_srgb_readback -- --ignored` + #[test] + #[ignore = "requires a GPU adapter; run manually"] + fn gpu_srgb_readback_should_encode_linear_clear_colors_once() { + let instance = wgpu::Instance::new(wgpu::InstanceDescriptor { + backends: wgpu::Backends::all(), + ..wgpu::InstanceDescriptor::new_without_display_handle() + }); + let adapter = pollster::block_on(instance.request_adapter(&Default::default())) + .unwrap_or_else(|error| panic!("test requires a GPU adapter: {error}")); + let (device, queue) = pollster::block_on(adapter.request_device(&Default::default())) + .unwrap_or_else(|error| panic!("test requires a GPU device: {error}")); + let cases = [ + ([0.0, 0.0, 0.0], [0, 0, 0]), + ([1.0, 1.0, 1.0], [255, 255, 255]), + ([0.5, 0.5, 0.5], [188, 188, 188]), + ([1.0, 0.0, 0.0], [255, 0, 0]), + ([0.0, 1.0, 0.0], [0, 255, 0]), + ([0.0, 0.0, 1.0], [0, 0, 255]), + ]; + for (linear, expected) in cases { + let texture = device.create_texture(&wgpu::TextureDescriptor { + label: Some("chitin_export_color_test"), + size: wgpu::Extent3d { + width: 2, + height: 2, + depth_or_array_layers: 1, + }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: wgpu::TextureFormat::Rgba8UnormSrgb, + usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC, + view_formats: &[], + }); + let view = texture.create_view(&Default::default()); + let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { + label: Some("chitin_export_color_test_encoder"), + }); + { + let _pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { + label: Some("chitin_export_color_test_pass"), + color_attachments: &[Some(wgpu::RenderPassColorAttachment { + view: &view, + resolve_target: None, + depth_slice: None, + ops: wgpu::Operations { + load: wgpu::LoadOp::Clear(wgpu::Color { + r: linear[0], + g: linear[1], + b: linear[2], + a: 1.0, + }), + store: wgpu::StoreOp::Store, + }, + })], + depth_stencil_attachment: None, + timestamp_writes: None, + occlusion_query_set: None, + multiview_mask: None, + }); + } + queue.submit(Some(encoder.finish())); + let rgba = read_texture_rgba(&device, &queue, &texture, wgpu::TextureFormat::Rgba8UnormSrgb, 2, 2) + .unwrap_or_else(|error| panic!("readback should succeed: {error}")); + for pixel in rgba.as_chunks::<4>().0 { + for (channel, expected) in pixel[..3].iter().zip(expected) { + assert!( + i32::from(*channel).abs_diff(expected) <= 1, + "linear {linear:?} should encode to {expected:?}, got {pixel:?}" + ); + } + } + } + } +} diff --git a/crates/chitin-desktop/src/keybindings/dispatch.rs b/crates/chitin-desktop/src/keybindings/dispatch.rs index c7525793..bd091a87 100644 --- a/crates/chitin-desktop/src/keybindings/dispatch.rs +++ b/crates/chitin-desktop/src/keybindings/dispatch.rs @@ -60,8 +60,9 @@ impl ChitinApp { FrontendCommand::Workspace(command) => self.dispatch_workspace_command(command, cx), FrontendCommand::Application(command) => self.dispatch_application_command(command, cx), FrontendCommand::Render(command) => { + let command_id = command.id(); if let Err(error) = self.dispatch_render_command(None, command, cx) { - log::error!("Cannot dispatch {} without an explicit target: {error}", command.id()); + log::error!("Cannot dispatch {command_id} without an explicit target: {error}"); } } FrontendCommand::Selection(command) => { diff --git a/crates/chitin-desktop/src/lib.rs b/crates/chitin-desktop/src/lib.rs index 98ef6f29..95d6a586 100644 --- a/crates/chitin-desktop/src/lib.rs +++ b/crates/chitin-desktop/src/lib.rs @@ -10,6 +10,7 @@ pub(crate) mod features; pub mod fonts; pub mod keybindings; pub mod services; +pub mod settings; pub mod workbench; // Preserve the public application integration entrypoints. diff --git a/crates/chitin-desktop/src/main.rs b/crates/chitin-desktop/src/main.rs index 8ee8ad53..5baf60a6 100644 --- a/crates/chitin-desktop/src/main.rs +++ b/crates/chitin-desktop/src/main.rs @@ -16,6 +16,9 @@ fn main() { // Every layer Chitin draws from, and the theme global each of them reads. // It has to run before anything else is constructed. chitin_ui::init(cx); + // The saved choice may override the system default; no window exists yet, + // so this applies before the first frame is painted. + chitin_ui::theme::set_preference(chitin_desktop::settings::load_theme_preference(), cx); // The compositor owns outer shadows; keep Kit's controls and resize band // without reserving an empty client-side shadow gutter. cx.set_global(gpui_kit::component::WindowBorderOptions::default().with_shadow_size(px(0.0))); @@ -41,7 +44,9 @@ fn main() { let project_sidebar_focus = cx.focus_handle(); window.focus(&project_sidebar_focus, cx); window.activate_window(); - cx.new(|_| ChitinApp::new_with_project_sidebar_focus(project_path, project_sidebar_focus)) + let app = cx.new(|_| ChitinApp::new_with_project_sidebar_focus(project_path, project_sidebar_focus)); + app.update(cx, |app, _| app.follow_system_theme(window)); + app }, ); diff --git a/crates/chitin-desktop/src/settings.rs b/crates/chitin-desktop/src/settings.rs new file mode 100644 index 00000000..e6a0f7b3 --- /dev/null +++ b/crates/chitin-desktop/src/settings.rs @@ -0,0 +1,117 @@ +//! Desktop user settings loaded before the first window is created. + +use std::{ + io::{Error, ErrorKind}, + path::PathBuf, +}; + +use chitin_ui::theme::ThemePreference; +use gpui::Context; + +use crate::app::ChitinApp; + +/// File name used for the persisted theme preference. +const THEME_FILE: &str = "theme"; + +/// Loads the saved theme preference, falling back to following the system. +/// +/// Missing, unreadable, or unrecognized values intentionally fall back to +/// [`ThemePreference::System`] rather than failing application startup. +pub fn load_theme_preference() -> ThemePreference { + theme_path() + .map(|path| load_theme_preference_at(&path)) + .unwrap_or_default() +} + +/// Persists the selected theme preference for the next application launch. +/// +/// # Errors +/// +/// Returns an I/O error when no configuration directory can be resolved or the +/// settings file cannot be written. Callers should log the error without +/// interrupting the current interaction. +pub fn save_theme_preference(preference: ThemePreference) -> std::io::Result<()> { + let path = theme_path().ok_or_else(|| Error::new(ErrorKind::NotFound, "no configuration directory"))?; + save_theme_preference_at(&path, preference) +} + +/// Loads a preference from an explicit path, falling back to following the system. +fn load_theme_preference_at(path: &std::path::Path) -> ThemePreference { + std::fs::read_to_string(path) + .ok() + .and_then(|value| value.trim().parse().ok()) + .unwrap_or_default() +} + +/// Writes a preference atomically to an explicit path. +fn save_theme_preference_at(path: &std::path::Path, preference: ThemePreference) -> std::io::Result<()> { + if let Some(parent) = path.parent() { + std::fs::create_dir_all(parent)?; + } + let temporary = path.with_extension("tmp"); + std::fs::write(&temporary, preference.as_str())?; + std::fs::rename(temporary, path) +} + +impl ChitinApp { + /// Applies and persists a theme selected from the Settings view. + pub(crate) fn set_theme_preference(&mut self, preference: ThemePreference, cx: &mut Context<Self>) { + chitin_ui::theme::set_preference(preference, cx); + if let Err(error) = save_theme_preference(preference) { + log::warn!("failed to persist theme preference: {error}"); + } + cx.notify(); + } +} + +/// Resolves the per-user configuration file that stores the theme preference. +fn theme_path() -> Option<PathBuf> { + config_directory().map(|directory| directory.join(THEME_FILE)) +} + +/// Resolves the per-user configuration directory on supported desktop systems. +fn config_directory() -> Option<PathBuf> { + if let Some(path) = std::env::var_os("XDG_CONFIG_HOME") { + return Some(PathBuf::from(path).join("chitin")); + } + if cfg!(target_os = "windows") + && let Some(path) = std::env::var_os("APPDATA") + { + return Some(PathBuf::from(path).join("chitin")); + } + let home = std::env::var_os("HOME")?; + if cfg!(target_os = "macos") { + Some( + PathBuf::from(home) + .join("Library") + .join("Application Support") + .join("chitin"), + ) + } else { + Some(PathBuf::from(home).join(".config").join("chitin")) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn theme_preference_should_round_trip_through_the_settings_file() { + let unique = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |duration| duration.as_nanos()); + let directory = std::env::temp_dir().join(format!("chitin-theme-{}-{unique}", std::process::id())); + let path = directory.join(THEME_FILE); + assert_eq!(load_theme_preference_at(&path), ThemePreference::System); + if let Err(error) = save_theme_preference_at(&path, ThemePreference::Dark) { + panic!("settings directory should be writable: {error}"); + } + assert_eq!(load_theme_preference_at(&path), ThemePreference::Dark); + if let Err(error) = std::fs::write(&path, "sepia") { + panic!("settings file should be writable: {error}"); + } + assert_eq!(load_theme_preference_at(&path), ThemePreference::System); + let _ = std::fs::remove_dir_all(&directory); + } +} diff --git a/crates/chitin-desktop/src/workbench/documents/dock.rs b/crates/chitin-desktop/src/workbench/documents/dock.rs index a62e7334..ccb74545 100644 --- a/crates/chitin-desktop/src/workbench/documents/dock.rs +++ b/crates/chitin-desktop/src/workbench/documents/dock.rs @@ -125,10 +125,18 @@ impl Panel for DocumentTab { } fn title_suffix(&mut self, _: &mut Window, cx: &mut Context<Self>) -> Option<impl IntoElement> { + let panel_id = self.panel_id; + let tab_id = self.tab.id.value(); + let export_supported = self + .app + .update(cx, |app, _| app.document_panels.supports_export(tab_id)) + .unwrap_or(false); Some(render_panel_tab_strip_actions( - self.panel_id, + panel_id, + tab_id, cx.theme().colors, self.app.clone(), + export_supported, )) } } diff --git a/crates/chitin-desktop/src/workbench/documents/render.rs b/crates/chitin-desktop/src/workbench/documents/render.rs index 2994563a..fe7a927f 100644 --- a/crates/chitin-desktop/src/workbench/documents/render.rs +++ b/crates/chitin-desktop/src/workbench/documents/render.rs @@ -8,7 +8,7 @@ use crate::{ app::ChitinApp, keybindings::{CloseTab, FocusNextPanelTab, FocusPreviousPanelTab, PANEL_CONTAINER_KEY_CONTEXT}, }; -use chitin_command::PanelTabCommand; +use chitin_command::{PanelTabCommand, RenderCommand}; use gpui::{ AnyElement, Context, FocusHandle, FontWeight, InteractiveElement, IntoElement, ParentElement, Pixels, Styled, WeakEntity, div, px, svg, @@ -20,6 +20,7 @@ use gpui_kit::component::{ const SPLIT_HORIZONTAL_ICON_PATH: &str = "icons/panel-split-horizontal.svg"; const SPLIT_VERTICAL_ICON_PATH: &str = "icons/panel-split-vertical.svg"; +const EXPORT_IMAGE_ICON_PATH: &str = "icons/image-export.svg"; const PANEL_ACTION_ICON_SIZE: Pixels = px(16.0); /// Composes the Kit docking view with desktop document commands. @@ -62,23 +63,26 @@ pub fn render_document_area( /// # Parameters /// /// * `panel_id` identifies the panel controlled by the split buttons. +/// * `tab_id` identifies the stable rendering tab targeted by export. /// * `theme` supplies colors for the action buttons. /// * `app` is the weak app entity updated by button clicks. +/// * `export_supported` adds the protein-image export action when true. /// /// # Returns /// -/// A GPUI element containing horizontal and vertical split buttons. +/// A GPUI element containing export and split buttons. pub(super) fn render_panel_tab_strip_actions( panel_id: PanelId, + tab_id: u64, theme: ThemeColor, app: WeakEntity<ChitinApp>, + export_supported: bool, ) -> gpui::Div { - div() - .flex() - .items_center() - .h_full() - .flex_none() - .bg(theme.muted) + let mut actions = div().flex().items_center().h_full().flex_none().bg(theme.muted); + if export_supported { + actions = actions.child(render_panel_export_button(tab_id, theme, app.clone())); + } + actions .child(render_panel_split_button( panel_id, PanelSplitAxis::Horizontal, @@ -95,6 +99,65 @@ pub(super) fn render_panel_tab_strip_actions( )) } +/// Renders the protein-image export button for one document panel. +fn render_panel_export_button(tab_id: u64, theme: ThemeColor, app: WeakEntity<ChitinApp>) -> Button { + Button::new(format!("document-export-{tab_id}")) + .with_variant(ButtonVariant::Ghost) + .size(px(30.0)) + .px(px(0.0)) + .tooltip("Export image") + .accessibility_label("Export protein image") + .on_click(move |_, window, cx| { + let suggested = app + .update(cx, |app, _| app.export_dialog_default(tab_id)) + .ok() + .flatten(); + let Some((directory, suggested_name)) = suggested else { + let _ = app.update(cx, |app, cx| { + if let Err(error) = app.dispatch_render_command(Some(tab_id), RenderCommand::ExportImage { output: None }, cx) + { + log::error!("{error}"); + } + }); + return; + }; + if let Err(error) = std::fs::create_dir_all(&directory) { + log::warn!("failed to create export directory '{}': {error}", directory.display()); + } + let receiver = cx.prompt_for_new_path(&directory, Some(&suggested_name)); + let app = app.clone(); + window + .spawn(cx, async move |cx| { + let path = match receiver.await { + Ok(Ok(Some(path))) => Some(path), + Ok(Ok(None)) => return, + Ok(Err(error)) => { + log::warn!("native export save dialog unavailable ({error}); using the default export path"); + None + } + Err(error) => { + log::warn!("export save dialog channel closed ({error}); using the default export path"); + None + } + }; + let _ = app.update_in(cx, |app, _window, cx| { + if let Err(error) = + app.dispatch_render_command(Some(tab_id), RenderCommand::ExportImage { output: path }, cx) + { + log::error!("{error}"); + } + }); + }) + .detach(); + }) + .child( + svg() + .path(EXPORT_IMAGE_ICON_PATH) + .size(PANEL_ACTION_ICON_SIZE) + .text_color(theme.muted_foreground), + ) +} + /// Renders one split button for a document panel. /// /// # Parameters diff --git a/crates/chitin-desktop/src/workbench/documents/state.rs b/crates/chitin-desktop/src/workbench/documents/state.rs index 2366472a..af3b7a89 100644 --- a/crates/chitin-desktop/src/workbench/documents/state.rs +++ b/crates/chitin-desktop/src/workbench/documents/state.rs @@ -12,7 +12,7 @@ use crate::workbench::documents::layout::{ }; use chitin_bio::structure::{StructureScene, selection::AtomSelection}; use chitin_bio::surface::MolecularSurfaceBackend; -use chitin_molecule_renderer::RepresentationLayers; +use chitin_molecule_renderer::{RepresentationLayers, ViewportBackground}; use gpui::{AnyView, App, Window}; /// Callback that applies molecule representation layers to one WGPU document view. @@ -23,6 +23,12 @@ type SurfaceBackendChangeHandler = dyn Fn(MolecularSurfaceBackend, &mut App); pub(crate) type SelectionInputHandler = Rc<dyn Fn(chitin_command::SelectionCommand, &mut App)>; type SelectionInputBinder = dyn Fn(SelectionInputHandler, &mut App); type SelectionChangeHandler = dyn Fn(Arc<AtomSelection>, &mut App); +/// Callback that applies a viewport background policy to one WGPU document view. +type BackgroundChangeHandler = dyn Fn(ViewportBackground, &mut App); +/// Blocking worker that finishes an already-submitted image capture. +pub(crate) type ExportTask = Box<dyn FnOnce() -> Result<PathBuf, String> + Send>; +/// Callback that submits one WGPU document view capture. +type ExportHandler = dyn Fn(&Path, bool, &mut App) -> Result<ExportTask, String>; /// Result produced when a WGPU document factory creates a fresh view. pub struct WgpuDocumentView { @@ -33,6 +39,10 @@ pub struct WgpuDocumentView { representation_layers: Option<WgpuRepresentationLayersControl>, /// Optional molecule-specific surface backend controller. surface_backend: Option<WgpuSurfaceBackendControl>, + /// Optional viewport background controller. + background: Option<WgpuBackgroundControl>, + /// Optional PNG export controller. + export: Option<WgpuExportControl>, } /// Scientific selection state and its renderer callback, scoped to one view. @@ -87,6 +97,22 @@ pub(crate) struct WgpuSurfaceBackendControl { on_change: Rc<SurfaceBackendChangeHandler>, } +/// Mutable viewport background state and its view update callback. +#[derive(Clone)] +pub(crate) struct WgpuBackgroundControl { + /// Clear-color policy currently selected for this independent panel view. + background: ViewportBackground, + /// Callback that applies the resolved color to the hosted panel. + on_change: Rc<BackgroundChangeHandler>, +} + +/// PNG export callback for one independent panel view. +#[derive(Clone)] +pub(crate) struct WgpuExportControl { + /// Callback that renders and writes the image. + on_export: Rc<ExportHandler>, +} + type FreshWgpuSurfaceCallback = Rc<dyn Fn(&Path, &mut Window, &mut App) -> WgpuDocumentView>; /// Factory used to create independent WGPU document views for split panels. @@ -133,6 +159,10 @@ pub(crate) enum DocumentPanelContent { representation_layers: Option<WgpuRepresentationLayersControl>, /// Surface algorithm state when this view supports molecular rendering. surface_backend: Option<WgpuSurfaceBackendControl>, + /// Viewport background state when this view supports a customized clear color. + background: Option<WgpuBackgroundControl>, + /// PNG export callback when this view supports image capture. + export: Option<WgpuExportControl>, /// Callback that creates an independent view for split-panel clones. clone_view: WgpuDocumentViewFactory, }, @@ -181,6 +211,8 @@ impl WgpuDocumentView { view: view.into(), representation_layers: None, surface_backend: None, + background: None, + export: None, } } @@ -198,6 +230,8 @@ impl WgpuDocumentView { on_change: Rc::new(on_change), }), surface_backend: None, + background: None, + export: None, } } @@ -249,6 +283,49 @@ impl WgpuDocumentView { self } + /// Adds an independently mutable viewport background policy. + /// + /// # Parameters + /// + /// * `background` is the initial clear-color policy for this view. + /// * `on_change` applies later policy changes to the hosted panel. + /// + /// # Returns + /// + /// This document view with its background controller installed. + pub fn with_background( + mut self, + background: ViewportBackground, + on_change: impl Fn(ViewportBackground, &mut App) + 'static, + ) -> Self { + self.background = Some(WgpuBackgroundControl { + background, + on_change: Rc::new(on_change), + }); + self + } + + /// Adds PNG export support for this viewport. + /// + /// # Parameters + /// + /// * `on_export` submits the GPU capture and returns a worker that performs + /// the blocking readback and file write off the UI thread. The second + /// argument rejects an existing destination instead of overwriting it. + /// + /// # Returns + /// + /// This document view with its export controller installed. + pub fn with_export( + mut self, + on_export: impl Fn(&Path, bool, &mut App) -> Result<ExportTask, String> + 'static, + ) -> Self { + self.export = Some(WgpuExportControl { + on_export: Rc::new(on_export), + }); + self + } + /// Applies a copied representation to a newly created independent view. fn select_representation_layers(&mut self, representation: RepresentationLayers, cx: &mut App) { let Some(control) = self.representation_layers.as_mut() else { @@ -268,6 +345,16 @@ impl WgpuDocumentView { on_change(backend, cx); } } + + /// Applies a copied background policy to a newly created independent view. + fn select_background(&mut self, background: ViewportBackground, cx: &mut App) { + let Some(control) = self.background.as_mut() else { + return; + }; + if let Some(on_change) = control.select(background) { + on_change(background, cx); + } + } } impl From<AnyView> for WgpuDocumentView { @@ -332,6 +419,48 @@ impl WgpuSurfaceBackendControl { } } +impl fmt::Debug for WgpuBackgroundControl { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter + .debug_struct("WgpuBackgroundControl") + .field("background", &self.background) + .finish_non_exhaustive() + } +} + +impl PartialEq for WgpuBackgroundControl { + fn eq(&self, other: &Self) -> bool { + self.background == other.background && Rc::ptr_eq(&self.on_change, &other.on_change) + } +} + +impl Eq for WgpuBackgroundControl {} + +impl WgpuBackgroundControl { + /// Selects a new background policy and returns the callback that applies it. + fn select(&mut self, background: ViewportBackground) -> Option<Rc<BackgroundChangeHandler>> { + if self.background == background { + return None; + } + self.background = background; + Some(Rc::clone(&self.on_change)) + } +} + +impl fmt::Debug for WgpuExportControl { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter.debug_struct("WgpuExportControl").finish_non_exhaustive() + } +} + +impl PartialEq for WgpuExportControl { + fn eq(&self, other: &Self) -> bool { + Rc::ptr_eq(&self.on_export, &other.on_export) + } +} + +impl Eq for WgpuExportControl {} + impl WgpuDocumentViewFactory { /// Creates a factory for independent WGPU document views. /// @@ -436,6 +565,8 @@ impl DocumentPanelContent { view: document_view.view, representation_layers: document_view.representation_layers, surface_backend: document_view.surface_backend, + background: document_view.background, + export: document_view.export, clone_view, } } @@ -499,6 +630,33 @@ impl DocumentPanelContent { } } + /// Returns the viewport background policy for molecular content. + pub(super) fn background(&self) -> Option<ViewportBackground> { + match self { + Self::WgpuInteractive { + background: Some(control), + .. + } => Some(control.background), + Self::ProjectDocument(_) | Self::WgpuInteractive { .. } => None, + } + } + + /// Returns whether this view supports PNG image capture. + pub(super) fn supports_export(&self) -> bool { + matches!(self, Self::WgpuInteractive { export: Some(_), .. }) + } + + /// Renders an exported image through this view's capture controller. + pub(super) fn export_image(&self, path: &Path, create_new: bool, cx: &mut App) -> Option<Result<ExportTask, String>> { + let Self::WgpuInteractive { + export: Some(control), .. + } = self + else { + return None; + }; + Some((control.on_export)(path, create_new, cx)) + } + /// Updates molecular selection state and returns its scene callback. fn select_representation_layers( &mut self, @@ -526,6 +684,18 @@ impl DocumentPanelContent { control.select(backend) } + /// Updates background state and returns its panel callback. + fn select_background(&mut self, background: ViewportBackground) -> Option<Rc<BackgroundChangeHandler>> { + let Self::WgpuInteractive { + background: Some(control), + .. + } = self + else { + return None; + }; + control.select(background) + } + /// Creates an independent payload for a split panel. /// /// # Parameters @@ -545,6 +715,7 @@ impl DocumentPanelContent { selection, representation_layers, surface_backend, + background, clone_view, .. } => { @@ -558,6 +729,9 @@ impl DocumentPanelContent { if let Some(control) = representation_layers { document_view.select_representation_layers(control.representation, cx); } + if let Some(control) = background { + document_view.select_background(control.background, cx); + } if let (Some(source), Some(destination)) = (selection, document_view.selection.as_mut()) { destination.atoms = source.atoms.clone(); (destination.on_change)(destination.atoms.clone(), cx); @@ -573,6 +747,8 @@ impl DocumentPanelContent { view: document_view.view, representation_layers: document_view.representation_layers, surface_backend: document_view.surface_backend, + background: document_view.background, + export: document_view.export, clone_view: clone_view.clone(), } } @@ -952,6 +1128,71 @@ impl DocumentPanelState { content.select_surface_backend(backend) } + /// Reads a stable molecular tab's viewport background policy. + pub(crate) fn background(&self, id: u64) -> Option<ViewportBackground> { + let (panel, tab) = self.rendering_panel_location(id)?; + let entry = self.tree.leaf(panel)?.tabs.iter().find(|entry| entry.id == tab)?; + entry.payload.background() + } + + /// Changes a stable molecular tab's background and returns its panel callback. + pub(crate) fn select_background( + &mut self, + id: u64, + background: ViewportBackground, + ) -> Option<Rc<BackgroundChangeHandler>> { + let (panel_id, active_tab_id) = self.rendering_panel_location(id)?; + let leaf = self.tree.leaf_mut(panel_id)?; + let content = leaf + .tabs + .iter_mut() + .find(|tab| tab.id == active_tab_id) + .map(|tab| &mut tab.payload)?; + content.select_background(background) + } + + /// Returns whether a stable rendering tab supports PNG image capture. + pub(crate) fn supports_export(&self, id: u64) -> bool { + self.rendering_panel_location(id).is_some_and(|(panel, tab)| { + self + .tree + .leaf(panel) + .and_then(|leaf| leaf.tabs.iter().find(|entry| entry.id == tab)) + .is_some_and(|entry| entry.payload.supports_export()) + }) + } + + /// Returns the stable display title for one rendering tab. + pub(crate) fn tab_title(&self, id: u64) -> Option<&str> { + let (panel, tab) = self.rendering_panel_location(id)?; + self + .tree + .leaf(panel)? + .tabs + .iter() + .find(|entry| entry.id == tab) + .map(|entry| entry.title.as_str()) + } + + /// Writes a PNG through a stable rendering tab's capture controller. + pub(crate) fn export_image( + &self, + id: u64, + path: &Path, + create_new: bool, + cx: &mut App, + ) -> Option<Result<ExportTask, String>> { + let (panel, tab) = self.rendering_panel_location(id)?; + self + .tree + .leaf(panel)? + .tabs + .iter() + .find(|entry| entry.id == tab)? + .payload + .export_image(path, create_new, cx) + } + /// Splits one document panel and copies its active tab to the new panel. /// /// The new panel receives a fresh panel id and starts with only the source diff --git a/crates/chitin-desktop/src/workbench/sidebar.rs b/crates/chitin-desktop/src/workbench/sidebar.rs index a54596d2..a6b4ae3e 100644 --- a/crates/chitin-desktop/src/workbench/sidebar.rs +++ b/crates/chitin-desktop/src/workbench/sidebar.rs @@ -1,6 +1,7 @@ //! Primary workbench navigation and its project, document, and function views. use chitin_command::CommandId; +use chitin_ui::theme::ThemePreference; use chitin_ui::workbench::{WorkbenchStyle, panel_surface}; use gpui::{ Context, Div, InteractiveElement, IntoElement, ParentElement, StatefulInteractiveElement, Styled, Window, div, px, @@ -9,6 +10,7 @@ use gpui_kit::component::{ Icon, Sizable as _, button::{Button, ButtonVariants as _}, collapsible::Collapsible, + switch::Switch, tab::{Tab, TabBar}, theme::ThemeColor, }; @@ -31,6 +33,8 @@ pub(crate) enum SidebarView { Entries, /// Curated functional commands grouped into collapsible categories. Functions, + /// Application appearance and future user preferences. + Settings, } impl SidebarView { @@ -42,6 +46,7 @@ impl SidebarView { Self::Project => "Project", Self::Entries => "Entries", Self::Functions => "Functions", + Self::Settings => "Settings", } } @@ -51,6 +56,7 @@ impl SidebarView { Self::Project => "icons/folder-closed.svg", Self::Entries => "icons/activity-workspace.svg", Self::Functions => "icons/activity-jobs.svg", + Self::Settings => "icons/activity-settings.svg", } } } @@ -63,16 +69,16 @@ pub(crate) fn render_primary_sidebar( cx: &mut Context<ChitinApp>, ) -> impl IntoElement { let focus = app.project_sidebar_focus(cx); - let selected = SidebarView::ALL - .iter() - .position(|view| *view == app.sidebar_view) - .unwrap_or(0); + let selected = SidebarView::ALL.iter().position(|view| *view == app.sidebar_view); let weak = cx.weak_entity(); - let navigation = TabBar::new("primary-sidebar-navigation") + let mut navigation = TabBar::new("primary-sidebar-navigation") .segmented() .selected_background(WorkbenchStyle::new(theme).raised_background) - .small() - .selected_index(selected) + .small(); + if let Some(selected) = selected { + navigation = navigation.selected_index(selected); + } + let navigation = navigation .children(SidebarView::ALL.map(sidebar_tab)) .on_click(move |index, window, cx| { if let Some(view) = SidebarView::ALL.get(*index) { @@ -90,6 +96,7 @@ pub(crate) fn render_primary_sidebar( .into_any_element(), SidebarView::Entries => super::entries::render_entries(app, theme, window, cx).into_any_element(), SidebarView::Functions => render_functions(app, theme, cx).into_any_element(), + SidebarView::Settings => render_settings(theme, cx).into_any_element(), }; panel_surface(WorkbenchStyle::new(theme)) .border_r_1() @@ -123,6 +130,44 @@ fn sidebar_tab(view: SidebarView) -> Tab { ) } +/// Renders application preferences, currently limited to the color theme. +fn render_settings(theme: ThemeColor, cx: &mut Context<ChitinApp>) -> impl IntoElement { + let preference = chitin_ui::theme::preference(cx); + let mode = chitin_ui::theme::effective_mode(cx); + let weak = cx.weak_entity(); + let follow_system = Switch::new("settings-follow-system") + .small() + .checked(preference == ThemePreference::System) + .label("Follow system theme") + .on_change(move |checked, _, cx| { + let _ = weak.update(cx, |app, cx| { + let preference = if *checked { + ThemePreference::System + } else if chitin_ui::theme::effective_mode(cx).is_dark() { + ThemePreference::Dark + } else { + ThemePreference::Light + }; + app.set_theme_preference(preference, cx); + }); + }); + div() + .id("sidebar-settings") + .flex() + .flex_col() + .flex_1() + .min_h_0() + .overflow_y_scroll() + .gap_2() + .p_2() + .child(div().text_sm().child("Appearance")) + .child(follow_system) + .child(div().text_xs().text_color(theme.muted_foreground).child(format!( + "Current theme: {}. Use the sun/moon button in the title bar to switch light and dark.", + if mode.is_dark() { "Dark" } else { "Light" } + ))) +} + /// Renders curated command categories using retained expansion state. fn render_functions(app: &ChitinApp, theme: ThemeColor, cx: &mut Context<ChitinApp>) -> impl IntoElement { let expanded = app.database_functions_expanded; @@ -378,6 +423,11 @@ mod tests { SidebarView::ALL.map(SidebarView::label), ["Project", "Entries", "Functions"] ); + assert!( + chitin_ui::assets::ChitinAssets + .load(SidebarView::Settings.icon_path())? + .is_some() + ); Ok(()) } diff --git a/crates/chitin-desktop/src/workbench/window_bar.rs b/crates/chitin-desktop/src/workbench/window_bar.rs index bd9fdb7b..974a774b 100644 --- a/crates/chitin-desktop/src/workbench/window_bar.rs +++ b/crates/chitin-desktop/src/workbench/window_bar.rs @@ -1,10 +1,11 @@ //! Desktop content inside GPUI Kit's platform-aware title bar. use crate::app::ChitinApp; +use chitin_ui::theme::ThemePreference; use gpui::prelude::FluentBuilder as _; use gpui::{ParentElement, Styled, WeakEntity, div, px}; use gpui_kit::component::{ - Icon, Sizable as _, TitleBar, + Icon, IconName, Sizable as _, ThemeMode, TitleBar, button::{Button, ButtonVariants as _}, theme::ThemeColor, }; @@ -14,13 +15,22 @@ use gpui_kit::component::{ /// # Parameters /// /// * `theme` supplies Kit's workbench background and text colors. +/// * `mode` selects the icon and target of the light/dark toggle. +/// * `app` owns sidebar, settings, and command-palette routing. /// /// # Returns /// /// A Kit title bar with the same background as the document chrome. -pub fn render_window_bar(theme: ThemeColor, app: WeakEntity<ChitinApp>) -> TitleBar { +pub fn render_window_bar(theme: ThemeColor, mode: ThemeMode, app: WeakEntity<ChitinApp>) -> TitleBar { let search_app = app.clone(); + let settings_app = app.clone(); + let theme_app = app.clone(); let style = chitin_ui::workbench::WorkbenchStyle::new(theme); + let (theme_icon, theme_target, theme_tooltip) = if mode.is_dark() { + (IconName::Sun, ThemePreference::Light, "Switch to light theme") + } else { + (IconName::Moon, ThemePreference::Dark, "Switch to dark theme") + }; TitleBar::new() .bg(style.background) .h(style.header_height) @@ -57,6 +67,25 @@ pub fn render_window_bar(theme: ThemeColor, app: WeakEntity<ChitinApp>) -> Title }); }), ) + .child( + Button::new("window-settings") + .ghost() + .small() + .icon(Icon::default().path("icons/activity-settings.svg")) + .tooltip("Settings") + .accessibility_label("Open settings") + .on_click(move |_, window, cx| { + let _ = settings_app.update(cx, |app, cx| { + let view = if app.project_sidebar_visible && app.sidebar_view == super::sidebar::SidebarView::Settings { + super::sidebar::SidebarView::Project + } else { + super::sidebar::SidebarView::Settings + }; + app.select_sidebar_view(view, window, cx); + cx.notify(); + }); + }), + ) .child( Button::new("window-command-search") .ghost() @@ -70,6 +99,17 @@ pub fn render_window_bar(theme: ThemeColor, app: WeakEntity<ChitinApp>) -> Title }); }), ) - .child(div().flex_1()), + .child(div().flex_1()) + .child( + Button::new("window-theme-toggle") + .ghost() + .small() + .icon(Icon::new(theme_icon)) + .tooltip(theme_tooltip) + .accessibility_label(theme_tooltip) + .on_click(move |_, _, cx| { + let _ = theme_app.update(cx, |app, cx| app.set_theme_preference(theme_target, cx)); + }), + ), ) } diff --git a/crates/chitin-molecule-renderer/src/background.rs b/crates/chitin-molecule-renderer/src/background.rs new file mode 100644 index 00000000..336bf1a1 --- /dev/null +++ b/crates/chitin-molecule-renderer/src/background.rs @@ -0,0 +1,62 @@ +//! Viewport clear-color policy shared by desktop and export paths. + +/// Background policy for a molecular viewport. +/// +/// [`Auto`](Self::Auto) follows the host theme: dark themes clear to black and +/// light themes clear to white. [`Custom`](Self::Custom) keeps an explicit sRGB +/// color independently of the theme. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum ViewportBackground { + /// Follow the host theme. + #[default] + Auto, + /// Use an explicit sRGB color. + Custom([u8; 3]), +} + +impl ViewportBackground { + /// Resolves the linear RGB clear color consumed by the renderer. + /// + /// `dark` selects the automatic branch when this policy is [`Self::Auto`]. + /// Custom colors are converted from sRGB so the drawn result matches the + /// color the user selected rather than appearing washed out. + pub fn resolve(self, dark: bool) -> [f64; 3] { + match self { + Self::Auto if dark => [0.0, 0.0, 0.0], + Self::Auto => [1.0, 1.0, 1.0], + Self::Custom(color) => color.map(srgb_to_linear), + } + } +} + +/// Converts one sRGB channel to linear RGB. +fn srgb_to_linear(value: u8) -> f64 { + let value = f64::from(value) / 255.0; + if value <= 0.040_45 { + value / 12.92 + } else { + ((value + 0.055) / 1.055).powf(2.4) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn automatic_background_should_follow_the_theme() { + assert_eq!(ViewportBackground::Auto.resolve(true), [0.0, 0.0, 0.0]); + assert_eq!(ViewportBackground::Auto.resolve(false), [1.0, 1.0, 1.0]); + } + + #[test] + fn custom_background_should_ignore_the_theme_and_convert_srgb() { + let black = ViewportBackground::Custom([0, 0, 0]); + let white = ViewportBackground::Custom([255, 255, 255]); + let mid = ViewportBackground::Custom([128, 128, 128]); + assert_eq!(black.resolve(false), [0.0, 0.0, 0.0]); + assert_eq!(white.resolve(true), [1.0, 1.0, 1.0]); + assert_eq!(mid.resolve(true), mid.resolve(false)); + assert!((mid.resolve(true)[0] - 0.215_86).abs() < 1.0e-4); + } +} diff --git a/crates/chitin-molecule-renderer/src/lib.rs b/crates/chitin-molecule-renderer/src/lib.rs index f83d38f4..6075a29a 100644 --- a/crates/chitin-molecule-renderer/src/lib.rs +++ b/crates/chitin-molecule-renderer/src/lib.rs @@ -10,6 +10,7 @@ //! [`RepresentationLayers`], and retain ownership of the target surface. pub mod appearance; +pub mod background; mod box_selection; pub mod camera; mod cartoon; @@ -22,6 +23,7 @@ mod surface; mod transparency; mod visibility; +pub use background::ViewportBackground; pub use camera::{DragMode, ViewerCamera, ViewportDrag}; pub use molecule::{ BallAndStickElementStyle, BallAndStickMaterial, BallAndStickPalette, BallAndStickStyle, MoleculeDebugMode, diff --git a/crates/chitin-molecule-renderer/src/molecule.rs b/crates/chitin-molecule-renderer/src/molecule.rs index 4f90211e..2a78276f 100644 --- a/crates/chitin-molecule-renderer/src/molecule.rs +++ b/crates/chitin-molecule-renderer/src/molecule.rs @@ -89,6 +89,8 @@ const OTHER_VDW_RADIUS: f32 = 1.50; const UNIFORM_BUFFER_SIZE: u64 = 288; /// Byte offset at which the lighting and material vectors begin. const MATERIAL_UNIFORM_OFFSET: u64 = 192; +/// Byte offset of the background vector inside the material block. +const BACKGROUND_UNIFORM_OFFSET: u64 = MATERIAL_UNIFORM_OFFSET + 4 * 16; /// Byte offset of the per-frame absolute depth-cue vector. const DEPTH_CUE_UNIFORM_OFFSET: u64 = 240; @@ -298,7 +300,7 @@ impl Default for BallAndStickStyle { }, bond_radius: DEFAULT_STICK_RADIUS, ball_radius_scale: DEFAULT_BALL_RADIUS_SCALE, - background_color: [0.003, 0.003, 0.005], + background_color: [0.0, 0.0, 0.0], depth_cue_start: 0.25, depth_cue_end: 1.0, depth_cue_strength: 0.18, @@ -1169,6 +1171,53 @@ impl MoleculeRenderer { } } + /// Changes the clear color used by the next frame without recreating resources. + /// + /// Colors are linear RGB. Non-finite values are rejected and finite values are + /// clamped to the unit interval, so a host theme or user picker cannot produce + /// an invalid clear operation. + /// + /// # Parameters + /// + /// * `color` supplies linear RGB components. + /// + /// # Returns + /// + /// `true` when the stored clear color changed; otherwise `false`. + pub fn set_background_color(&mut self, color: [f64; 3]) -> bool { + if !color.iter().all(|channel| channel.is_finite()) { + return false; + } + let color = color.map(|channel| channel.clamp(0.0, 1.0)); + let updated = wgpu::Color { + r: color[0], + g: color[1], + b: color[2], + a: 1.0, + }; + if self.background_color == updated { + return false; + } + self.background_color = updated; + // The shader blends distant geometry toward this same color. Keep the + // depth cue and the clear color in sync across theme changes. + self.queue.write_buffer( + &self.uniform_buffer, + BACKGROUND_UNIFORM_OFFSET, + bytemuck::cast_slice(&[color[0] as f32, color[1] as f32, color[2] as f32, 1.0]), + ); + true + } + + /// Returns the clear color used by the next frame as linear RGB. + pub fn background_color(&self) -> [f64; 3] { + [ + self.background_color.r, + self.background_color.g, + self.background_color.b, + ] + } + /// Returns the current render target aspect ratio. pub fn aspect(&self) -> f32 { self.size.aspect() diff --git a/crates/chitin-ui/src/assets.rs b/crates/chitin-ui/src/assets.rs index 7a2a8011..acff5f5a 100644 --- a/crates/chitin-ui/src/assets.rs +++ b/crates/chitin-ui/src/assets.rs @@ -55,6 +55,7 @@ mod tests { fn asset_bundle_should_include_application_and_kit_icons() -> Result<()> { assert!(ChitinAssets.load("icons/terminal-builtin.svg")?.is_some()); assert!(ChitinAssets.load("icons/download.svg")?.is_some()); + assert!(ChitinAssets.load("icons/image-export.svg")?.is_some()); assert!(ChitinAssets.load("icons/chevron-down.svg")?.is_some()); Ok(()) } diff --git a/crates/chitin-ui/src/theme.rs b/crates/chitin-ui/src/theme.rs index 203c9abe..537e133a 100644 --- a/crates/chitin-ui/src/theme.rs +++ b/crates/chitin-ui/src/theme.rs @@ -1,9 +1,68 @@ //! Shared GPUI Kit initialization and Chitin theme policy. -use gpui::App; +use gpui::{App, WindowAppearance}; use gpui_kit::component::{Theme, ThemeMode, theme::ThemeColor}; -/// Initializes Kit controls and selects its built-in dark theme. +/// User-selected theme policy for the desktop. +/// +/// [`System`](Self::System) follows the operating system and is the default. +/// Explicit choices override the system until the user selects `System` again. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum ThemePreference { + /// Follow the window/OS appearance. + #[default] + System, + /// Always use the light theme. + Light, + /// Always use the dark theme. + Dark, +} + +impl ThemePreference { + /// Resolves this preference against the current window appearance. + pub fn resolve(self, appearance: WindowAppearance) -> ThemeMode { + match self { + Self::System => ThemeMode::from(appearance), + Self::Light => ThemeMode::Light, + Self::Dark => ThemeMode::Dark, + } + } + + /// Returns a stable label for tooltips and accessibility text. + pub fn label(self) -> &'static str { + match self { + Self::System => "System", + Self::Light => "Light", + Self::Dark => "Dark", + } + } + + /// Returns the stable lowercase name written to settings files. + pub const fn as_str(self) -> &'static str { + match self { + Self::System => "system", + Self::Light => "light", + Self::Dark => "dark", + } + } +} + +impl std::str::FromStr for ThemePreference { + type Err = (); + + fn from_str(value: &str) -> Result<Self, Self::Err> { + match value.trim().to_ascii_lowercase().as_str() { + "system" | "auto" => Ok(Self::System), + "light" => Ok(Self::Light), + "dark" => Ok(Self::Dark), + _ => Err(()), + } + } +} + +impl gpui::Global for ThemePreference {} + +/// Initializes Kit controls and applies the current system theme. /// /// # Parameters /// @@ -14,7 +73,53 @@ use gpui_kit::component::{Theme, ThemeMode, theme::ThemeColor}; /// Nothing. Kit's global theme and base theme tokens are ready for window creation. pub fn init(cx: &mut App) { gpui_kit::init(cx); - Theme::change(ThemeMode::Dark, None, cx); + cx.set_global(ThemePreference::default()); + let appearance = cx.window_appearance(); + apply_preference(ThemePreference::System, appearance, cx); + reapply_workbench_colors(cx); +} + +/// Returns the current user theme preference. +pub fn preference(cx: &App) -> ThemePreference { + cx.try_global::<ThemePreference>().copied().unwrap_or_default() +} + +/// Returns the theme mode currently painted, after system resolution. +pub fn effective_mode(cx: &App) -> ThemeMode { + Theme::global(cx).mode +} + +/// Stores a theme preference and applies it immediately. +pub fn set_preference(preference: ThemePreference, cx: &mut App) { + cx.set_global(preference); + let appearance = cx.window_appearance(); + apply_preference(preference, appearance, cx); + reapply_workbench_colors(cx); +} + +/// Applies the system theme when the user has not overridden it. +/// +/// Window appearance observers call this when the OS switches between light and +/// dark mode. Explicit light or dark preferences are left unchanged. +pub fn apply_system_appearance(appearance: WindowAppearance, cx: &mut App) { + let preference = preference(cx); + if preference != ThemePreference::System { + return; + } + apply_preference(preference, appearance, cx); + reapply_workbench_colors(cx); +} + +/// Changes Kit's active mode without duplicating work when it is already active. +fn apply_preference(preference: ThemePreference, appearance: WindowAppearance, cx: &mut App) { + let mode = preference.resolve(appearance); + if Theme::global(cx).mode != mode { + Theme::change(mode, None, cx); + } +} + +/// Rebuilds Chitin's surface overrides for the active Kit colors. +fn reapply_workbench_colors(cx: &mut App) { Theme::update(cx, |theme| apply_workbench_colors(&mut theme.colors)); } @@ -36,6 +141,38 @@ fn apply_workbench_colors(colors: &mut ThemeColor) { mod tests { use super::*; + #[test] + fn system_preference_should_resolve_window_appearance() { + assert_eq!(ThemePreference::System.resolve(WindowAppearance::Dark), ThemeMode::Dark); + assert_eq!( + ThemePreference::System.resolve(WindowAppearance::VibrantDark), + ThemeMode::Dark + ); + assert_eq!( + ThemePreference::System.resolve(WindowAppearance::Light), + ThemeMode::Light + ); + assert_eq!( + ThemePreference::System.resolve(WindowAppearance::VibrantLight), + ThemeMode::Light + ); + } + + #[test] + fn explicit_preference_should_ignore_window_appearance() { + assert_eq!(ThemePreference::Light.resolve(WindowAppearance::Dark), ThemeMode::Light); + assert_eq!(ThemePreference::Dark.resolve(WindowAppearance::Light), ThemeMode::Dark); + } + + #[test] + fn theme_preference_should_round_trip_through_its_storage_name() { + for preference in [ThemePreference::System, ThemePreference::Light, ThemePreference::Dark] { + assert_eq!(preference.as_str().parse(), Ok(preference)); + } + assert_eq!("AUTO".parse(), Ok(ThemePreference::System)); + assert!("sepia".parse::<ThemePreference>().is_err()); + } + #[test] fn raised_popups_should_not_change_document_or_viewport_background() { let mut colors = *ThemeColor::dark(); @@ -49,4 +186,20 @@ mod tests { ); assert_eq!(colors.tab_bar_segmented, colors.muted); } + + #[gpui::test] + fn system_appearance_should_not_override_explicit_preferences(cx: &mut gpui::TestAppContext) { + cx.update(|cx| { + init(cx); + assert_eq!(Theme::global(cx).mode, ThemeMode::Light); + set_preference(ThemePreference::Dark, cx); + apply_system_appearance(WindowAppearance::Light, cx); + assert_eq!(Theme::global(cx).mode, ThemeMode::Dark); + set_preference(ThemePreference::System, cx); + apply_system_appearance(WindowAppearance::Dark, cx); + assert_eq!(Theme::global(cx).mode, ThemeMode::Dark); + apply_system_appearance(WindowAppearance::Light, cx); + assert_eq!(Theme::global(cx).mode, ThemeMode::Light); + }); + } } diff --git a/docs/book.typ b/docs/book.typ index cb85b3da..e50094c9 100644 --- a/docs/book.typ +++ b/docs/book.typ @@ -11,6 +11,7 @@ #prefix-chapter("src/cli/completions.typ")[Shell completion] #prefix-chapter("src/cli/database.typ")[Database commands] #prefix-chapter("src/cli/bio.typ")[Bio commands] + #prefix-chapter("src/cli/chemdraw.typ")[Chemical drawing commands] = `chitin-bio` architecture #prefix-chapter("src/architecture/bio/overview.typ")[Overview] diff --git a/docs/commands/chemdraw.md b/docs/src/cli/chemdraw.typ similarity index 74% rename from docs/commands/chemdraw.md rename to docs/src/cli/chemdraw.typ index 69c3c3dc..9d398dc8 100644 --- a/docs/commands/chemdraw.md +++ b/docs/src/cli/chemdraw.typ @@ -1,4 +1,8 @@ -# Chemical drawing commands +#import "/book.typ": book-page +#show: book-page + += 1 Chemical drawing commands +<chemdraw-commands> The CLI and built-in shell share these commands. Omit the initial `chitin` inside the built-in shell. Relative paths use the command's working directory. @@ -21,21 +25,25 @@ Use `-` as the SMILES or diagram input to consume standard input. Shell hosts must supply stdin through their execution context; this is not shell piping. Diagram input accepts JSON or YAML, is limited to 4 MiB, and requires `version: 1`. -## Diagram format +== 1.1 Diagram format +<chemdraw-diagram-format> -See [the complete example](../../crates/chitin-command/examples/reaction.yaml). +See +#link("https://github.com/chitin-dev/chitin/blob/main/crates/chitin-command/examples/reaction.yaml")[the complete example]. Each molecule has a unique `id`, a `smiles` string, an `at: [x, y]` placement, -optional positive `scale`, and optional complete `positions` in SMILES atom order. -Placements use SVG units with y down; authored atom positions use normalized -bond units with y up. Atom indices are zero-based and scoped to their molecule. +optional positive `scale`, and optional complete `positions` in SMILES atom +order. Placements use SVG units with y down; authored atom positions use +normalized bond units with y up. Atom indices are zero-based and scoped to their +molecule. Annotations use `type: highlight|electron-arrow|reaction-arrow|lone-pair`. An atom reference is `{molecule: id, target: {type: atom, index: 0}}`; a bond reference uses `target: {type: bond, atoms: [0, 1]}`. Optional reference offsets are local SVG units and follow molecule scaling. Colors are `[r, g, b, alpha]` -bytes. Electron arrows accept `head: pair|fishhook-left|fishhook-right`; reaction -arrows accept `equilibrium: true`. Arrow `style` accepts `color`, `width`, -`head-length`, `head-width`, and `clearance`. Lone-pair angles use radians. +bytes. Electron arrows accept `head: pair|fishhook-left|fishhook-right`; +reaction arrows accept `equilibrium: true`. Arrow `style` accepts `color`, +`width`, `head-length`, `head-width`, and `clearance`. Lone-pair angles use +radians. Mechanisms are authored, not inferred. Arrow routing is not automatic. Layout warnings are reported without treating every quality diagnostic as a failure. diff --git a/nix/devshell.nix b/nix/devshell.nix index 92cf2272..2d3d6fe3 100644 --- a/nix/devshell.nix +++ b/nix/devshell.nix @@ -13,6 +13,7 @@ pkgs.mkShell { rustfmt typst wasm-pack + zenity z3 ]; buildInputs = platform; diff --git a/nix/platform.nix b/nix/platform.nix index 23a531d7..6f0bcdaa 100644 --- a/nix/platform.nix +++ b/nix/platform.nix @@ -3,6 +3,7 @@ with pkgs; lib.optionals stdenv.hostPlatform.isLinux [ alsa-lib + dbus fontconfig libX11 libXi