From ea9c44e003ff1b1a48a8acb847846becdf403eef Mon Sep 17 00:00:00 2001 From: Keavon Chambers Date: Sat, 7 Nov 2026 05:18:23 -0800 Subject: [PATCH] Add typed length and angle values with a per-document resolution --- Cargo.lock | 1 + document/graph-storage/src/attributes/attr.rs | 4 + document/graph-storage/src/from_runtime.rs | 6 + document/graph-storage/src/metadata_source.rs | 7 + document/graph-storage/src/to_runtime.rs | 1 + .../nodes/src/vector_nodes/circle_v1.rs | 65 +++ .../migrations/nodes/src/vector_nodes/mod.rs | 1 + editor/src/messages/dialog/dialog_message.rs | 3 + .../messages/dialog/dialog_message_handler.rs | 11 + .../document_setup_dialog_message.rs | 9 + .../document_setup_dialog_message_handler.rs | 158 ++++++ .../dialog/document_setup_dialog/mod.rs | 7 + editor/src/messages/dialog/mod.rs | 1 + .../messages/layout/layout_message_handler.rs | 59 ++- .../utility_types/widgets/input_widgets.rs | 8 + .../menu_bar/menu_bar_message_handler.rs | 7 + .../data_panel/data_panel_message_handler.rs | 29 ++ .../portfolio/document/document_message.rs | 5 + .../document/document_message_handler.rs | 16 +- .../document/node_graph/node_inspector.rs | 97 +++- .../document/node_graph/utility_types.rs | 2 +- .../document/storage_tests/metadata_tests.rs | 23 + .../utility_types/network_interface/apply.rs | 1 + .../network_interface/editor_delta.rs | 7 + .../network_interface/mutations.rs | 13 + .../network_interface/queries.rs | 10 +- .../network_interface/reconcile.rs | 3 + .../network_interface/storage_metadata.rs | 5 + .../network_interface/store/cursor.rs | 10 + .../network_interface/store/mod.rs | 1 + .../network_interface/template.rs | 1 + .../utility_types/network_interface/types.rs | 3 + editor/src/messages/prelude.rs | 1 + .../shape_gizmos/circle_arc_radius_handle.rs | 10 +- .../shapes/circle_shape.rs | 3 +- .../shapes/shape_utility.rs | 6 +- editor/src/node_graph_executor.rs | 4 + editor/src/node_graph_executor/runtime.rs | 9 +- .../widgets/inputs/NumberInput.svelte | 35 +- node-graph/graph-craft/src/document/value.rs | 72 +++ node-graph/graph-craft/src/proto.rs | 2 +- node-graph/graphene-cli/src/lib.rs | 2 +- .../benches/benchmark_util.rs | 7 +- .../benches/brush_stroke_gungraun.rs | 2 +- .../src/dynamic_executor/test.rs | 4 +- .../interpreted-executor/src/node_registry.rs | 13 + node-graph/interpreted-executor/src/util.rs | 10 +- node-graph/libraries/core-types/Cargo.toml | 1 + node-graph/libraries/core-types/src/lib.rs | 1 + .../libraries/core-types/src/registry.rs | 1 + node-graph/libraries/core-types/src/units.rs | 465 ++++++++++++++++++ node-graph/nodes/math/src/lib.rs | 2 + node-graph/nodes/math/src/units.rs | 81 +++ .../nodes/vector/src/generator_nodes.rs | 13 +- node-graph/preprocessor/src/lib.rs | 15 + node-graph/preprocessor/src/value_types.rs | 2 + tools/node-docs/src/utility.rs | 1 + 57 files changed, 1286 insertions(+), 50 deletions(-) create mode 100644 document/migrations/nodes/src/vector_nodes/circle_v1.rs create mode 100644 editor/src/messages/dialog/document_setup_dialog/document_setup_dialog_message.rs create mode 100644 editor/src/messages/dialog/document_setup_dialog/document_setup_dialog_message_handler.rs create mode 100644 editor/src/messages/dialog/document_setup_dialog/mod.rs create mode 100644 node-graph/libraries/core-types/src/units.rs create mode 100644 node-graph/nodes/math/src/units.rs diff --git a/Cargo.lock b/Cargo.lock index 9348287d17..ec50b14345 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1226,6 +1226,7 @@ dependencies = [ "kurbo", "log", "lyon_geom", + "math-parser", "node-macro", "num-derive", "num-traits", diff --git a/document/graph-storage/src/attributes/attr.rs b/document/graph-storage/src/attributes/attr.rs index bb61630d49..b1abab6b57 100644 --- a/document/graph-storage/src/attributes/attr.rs +++ b/document/graph-storage/src/attributes/attr.rs @@ -57,6 +57,10 @@ pub mod network { pub const IMPORT_METADATA: &str = "ui::import_metadata"; pub const EXPORT_NAMES: &str = "ui::export_names"; pub const EXPORT_DESCRIPTIONS: &str = "ui::export_descriptions"; + + /// How many pixels make an inch in the network's document, which sizes lengths typed in a physical unit. Absent where it + /// is the default, CSS's 96. Only the root network's applies. + pub const PIXELS_PER_INCH: &str = "pixels_per_inch"; } pub mod delta { diff --git a/document/graph-storage/src/from_runtime.rs b/document/graph-storage/src/from_runtime.rs index 18b2b6961a..027c41653e 100644 --- a/document/graph-storage/src/from_runtime.rs +++ b/document/graph-storage/src/from_runtime.rs @@ -473,6 +473,12 @@ fn write_ui_network_attributes( .map_err(map_serialization_error(network::PINNED_ORDER))?; } + if let Some(pixels_per_inch) = metadata.pixels_per_inch(location) { + attributes + .set_serialized(network::PIXELS_PER_INCH, &pixels_per_inch, timestamp) + .map_err(map_serialization_error(network::PIXELS_PER_INCH))?; + } + Ok(()) } diff --git a/document/graph-storage/src/metadata_source.rs b/document/graph-storage/src/metadata_source.rs index df1a8d0434..2ea7fc2997 100644 --- a/document/graph-storage/src/metadata_source.rs +++ b/document/graph-storage/src/metadata_source.rs @@ -38,6 +38,8 @@ pub struct NetworkMetadataEntry { pub import_metadata: Vec, pub export_names: Vec, pub export_descriptions: Vec, + /// The document's pixels per inch, where it differs from the default. + pub pixels_per_inch: Option, } /// Editor metadata for one import of a subgraph. Mirrors `InputPersistentMetadata` but wraps strings in `Option` so @@ -78,6 +80,11 @@ pub trait NodeMetadataSource { Vec::new() } + /// The network's pixels per inch, where it differs from the default. + fn pixels_per_inch(&self, _network: NetworkLocation) -> Option { + None + } + fn import_metadata(&self, _network: NetworkLocation) -> Vec { Vec::new() } diff --git a/document/graph-storage/src/to_runtime.rs b/document/graph-storage/src/to_runtime.rs index fcdcf889c6..95ccc25c95 100644 --- a/document/graph-storage/src/to_runtime.rs +++ b/document/graph-storage/src/to_runtime.rs @@ -417,6 +417,7 @@ fn extract_network_metadata(registry: &Registry, attributes: &crate::Attributes, import_metadata: attributes.get_or_default(network::IMPORT_METADATA), export_names: attributes.get_or_default(network::EXPORT_NAMES), export_descriptions: attributes.get_or_default(network::EXPORT_DESCRIPTIONS), + pixels_per_inch: attributes.get_typed(network::PIXELS_PER_INCH), } } diff --git a/document/migrations/nodes/src/vector_nodes/circle_v1.rs b/document/migrations/nodes/src/vector_nodes/circle_v1.rs new file mode 100644 index 0000000000..0c70d0b34d --- /dev/null +++ b/document/migrations/nodes/src/vector_nodes/circle_v1.rs @@ -0,0 +1,65 @@ +use migration_core::{Inputs, Node, literal, literal_of, migration}; +use serde::{Deserialize, Serialize}; + +const RADIUS: usize = 1; + +/// Frozen mirror of the `TaggedValue` variants this migration reads and writes. +#[derive(Serialize, Deserialize)] +enum Tagged { + None, + Number(f64), + Length(TypedLength), +} + +#[derive(Serialize, Deserialize)] +struct TypedLength { + value: f64, + unit: LengthUnit, +} + +#[derive(Serialize, Deserialize)] +enum LengthUnit { + Pixel, +} + +/// The radius is a length, which keeps the number of pixels it held. A wired number still feeds it, read as pixels. +#[migration("vector_nodes::generator_nodes::CircleNode"@1 => @2)] +pub fn circle_v1(node: &Node, inputs: &mut Inputs) { + let Some(slot) = node.inputs().get(RADIUS) else { return }; + let Some(Tagged::Number(pixels)) = literal_of::(&slot.input) else { return }; + + inputs.set( + RADIUS as u32, + literal(Tagged::Length(TypedLength { + value: pixels, + unit: LengthUnit::Pixel, + })), + ); +} + +#[cfg(test)] +mod tests { + use super::*; + use migration_core::decl; + use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo}; + + fn contract() -> SourceContract { + SourceContract::new(2, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) }) + } + + #[test] + fn rewrites_history() { + check_commutation(&CircleV1, &contract()); + check_undo(&CircleV1, &contract()); + } + + #[test] + fn a_number_of_pixels_becomes_a_length_in_pixels() { + let mut fixture = Fixture::new(&CircleV1); + let circle = fixture.add(decl!("vector_nodes::generator_nodes::CircleNode"@1), vec![literal(Tagged::None), literal(Tagged::Number(50.))]); + let migrated = fixture.migrate(&CircleV1).unwrap(); + + let radius = literal(Tagged::Length(TypedLength { value: 50., unit: LengthUnit::Pixel })); + assert_eq!(fixture.inputs(&migrated, circle), [literal(Tagged::None), radius]); + } +} diff --git a/document/migrations/nodes/src/vector_nodes/mod.rs b/document/migrations/nodes/src/vector_nodes/mod.rs index d3785a3985..fb5812477a 100644 --- a/document/migrations/nodes/src/vector_nodes/mod.rs +++ b/document/migrations/nodes/src/vector_nodes/mod.rs @@ -1,4 +1,5 @@ //! Migrations of the nodes in `vector_nodes`. +mod circle_v1; mod path_from_path_network; mod renames; diff --git a/editor/src/messages/dialog/dialog_message.rs b/editor/src/messages/dialog/dialog_message.rs index 14fa9d3ddb..3623c26f55 100644 --- a/editor/src/messages/dialog/dialog_message.rs +++ b/editor/src/messages/dialog/dialog_message.rs @@ -6,6 +6,8 @@ use crate::messages::prelude::*; pub enum DialogMessage { // Sub-messages #[child] + DocumentSetupDialog(DocumentSetupDialogMessage), + #[child] ExportDialog(ExportDialogMessage), #[child] NewDocumentDialog(NewDocumentDialogMessage), @@ -34,6 +36,7 @@ pub enum DialogMessage { localized_commit_year: String, }, RequestDemoArtworkDialog, + RequestDocumentSetupDialog, RequestExportDialog, RequestLicensesDialogWithLocalizedCommitDate { localized_commit_year: String, diff --git a/editor/src/messages/dialog/dialog_message_handler.rs b/editor/src/messages/dialog/dialog_message_handler.rs index de7a1fd92d..c0ee542651 100644 --- a/editor/src/messages/dialog/dialog_message_handler.rs +++ b/editor/src/messages/dialog/dialog_message_handler.rs @@ -16,6 +16,7 @@ pub struct DialogMessageContext<'a> { pub struct DialogMessageHandler { on_dismiss: Option, redisplay: Option, + document_setup_dialog: DocumentSetupDialogMessageHandler, export_dialog: ExportDialogMessageHandler, new_document_dialog: NewDocumentDialogMessageHandler, preferences_dialog: PreferencesDialogMessageHandler, @@ -27,6 +28,7 @@ impl MessageHandler> for DialogMessageHa let DialogMessageContext { portfolio, preferences } = context; match message { + DialogMessage::DocumentSetupDialog(message) => self.document_setup_dialog.process_message(message, responses, ()), DialogMessage::ExportDialog(message) => self.export_dialog.process_message(message, responses, ExportDialogMessageContext { portfolio }), DialogMessage::NewDocumentDialog(message) => self.new_document_dialog.process_message(message, responses, ()), DialogMessage::PreferencesDialog(message) => self.preferences_dialog.process_message(message, responses, PreferencesDialogMessageContext { preferences }), @@ -100,6 +102,15 @@ impl MessageHandler> for DialogMessageHa let dialog = DemoArtworkDialog; dialog.send_dialog_to_frontend(responses); } + DialogMessage::RequestDocumentSetupDialog => { + self.on_dismiss = Some(DialogMessage::Close.into()); + if let Some(document) = portfolio.active_document() { + self.document_setup_dialog = DocumentSetupDialogMessageHandler { + pixels_per_inch: document.network_interface.pixels_per_inch(), + }; + self.document_setup_dialog.send_dialog_to_frontend(responses); + } + } DialogMessage::RequestExportDialog => { self.on_dismiss = Some(DialogMessage::Close.into()); if let Some(document) = portfolio.active_document() { diff --git a/editor/src/messages/dialog/document_setup_dialog/document_setup_dialog_message.rs b/editor/src/messages/dialog/document_setup_dialog/document_setup_dialog_message.rs new file mode 100644 index 0000000000..819612aaa8 --- /dev/null +++ b/editor/src/messages/dialog/document_setup_dialog/document_setup_dialog_message.rs @@ -0,0 +1,9 @@ +use crate::messages::prelude::*; + +#[impl_message(Message, DialogMessage, DocumentSetupDialog)] +#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)] +pub enum DocumentSetupDialogMessage { + Resolution { pixels_per_inch: f64 }, + + Submit, +} diff --git a/editor/src/messages/dialog/document_setup_dialog/document_setup_dialog_message_handler.rs b/editor/src/messages/dialog/document_setup_dialog/document_setup_dialog_message_handler.rs new file mode 100644 index 0000000000..6eb326739b --- /dev/null +++ b/editor/src/messages/dialog/document_setup_dialog/document_setup_dialog_message_handler.rs @@ -0,0 +1,158 @@ +use crate::messages::layout::utility_types::widget_prelude::*; +use crate::messages::prelude::*; +use graphene_std::units::DEFAULT_PIXELS_PER_INCH; + +/// A dialog to allow users to change the settings of the active document. +#[derive(Debug, Clone, ExtractField)] +pub struct DocumentSetupDialogMessageHandler { + pub pixels_per_inch: f64, +} + +impl Default for DocumentSetupDialogMessageHandler { + fn default() -> Self { + Self { + pixels_per_inch: DEFAULT_PIXELS_PER_INCH, + } + } +} + +#[message_handler_data] +impl MessageHandler for DocumentSetupDialogMessageHandler { + fn process_message(&mut self, message: DocumentSetupDialogMessage, responses: &mut VecDeque, _: ()) { + match message { + DocumentSetupDialogMessage::Resolution { pixels_per_inch } => self.pixels_per_inch = pixels_per_inch, + + DocumentSetupDialogMessage::Submit => { + // The settings apply as one undo step, which ending the transaction drops if nothing changed + responses.add(DocumentMessage::StartTransaction); + responses.add(DocumentMessage::SetPixelsPerInch { + pixels_per_inch: self.pixels_per_inch, + }); + responses.add(DocumentMessage::EndTransaction); + } + } + + self.send_dialog_to_frontend(responses); + } + + advertise_actions!(DocumentSetupDialogUpdate; + ); +} + +impl DialogLayoutHolder for DocumentSetupDialogMessageHandler { + const ICON: &'static str = "File"; + const TITLE: &'static str = "Document Setup"; + + fn layout_buttons(&self) -> Layout { + let widgets = vec![ + TextButton::new("OK") + .emphasized(true) + .on_update(|_| { + DialogMessage::CloseAndThen { + followups: vec![DocumentSetupDialogMessage::Submit.into()], + } + .into() + }) + .widget_instance(), + TextButton::new("Cancel").on_update(|_| DialogMessage::Close.into()).widget_instance(), + ]; + + Layout(vec![LayoutGroup::row(widgets)]) + } +} + +impl LayoutHolder for DocumentSetupDialogMessageHandler { + fn layout(&self) -> Layout { + let resolution = resolution_row(self.pixels_per_inch, |pixels_per_inch| DocumentSetupDialogMessage::Resolution { pixels_per_inch }.into()); + + Layout(vec![LayoutGroup::row(resolution)]) + } +} + +/// The labeled field for a document's resolution in pixels per inch, shared by the dialogs that set it. +pub fn resolution_row(pixels_per_inch: f64, on_update: impl Fn(f64) -> Message + Send + Sync + 'static) -> Vec { + let description = "How many pixels make an inch, which sizes the lengths typed in physical units like millimeters and inches, and the physical size of exported files."; + + vec![ + TextLabel::new("Resolution") + .table_align(true) + .sizing(WidgetSizing::fixed(90)) + .tooltip_label("Resolution") + .tooltip_description(description) + .widget_instance(), + Separator::new(SeparatorStyle::Unrelated).widget_instance(), + NumberInput::new(Some(pixels_per_inch)) + .unit(" PPI") + .min(1.) + .max(100_000.) + .tooltip_label("Resolution") + .tooltip_description(description) + // Matches the width of the New Document dialog's Name field + .sizing(WidgetSizing::default().min_width(204)) + .on_update(move |number_input: &NumberInput| on_update(number_input.value.unwrap_or(DEFAULT_PIXELS_PER_INCH))) + .widget_instance(), + ] +} + +#[cfg(test)] +mod tests { + use crate::test_utils::test_prelude::*; + + fn pixels_per_inch(editor: &EditorTestUtils) -> f64 { + editor.active_document().network_interface.pixels_per_inch() + } + + async fn open_and_set_resolution(editor: &mut EditorTestUtils, pixels_per_inch: f64) { + editor.handle_message(DialogMessage::RequestDocumentSetupDialog).await; + editor.handle_message(DocumentSetupDialogMessage::Resolution { pixels_per_inch }).await; + } + + async fn confirm(editor: &mut EditorTestUtils) { + editor + .handle_message(DialogMessage::CloseAndThen { + followups: vec![DocumentSetupDialogMessage::Submit.into()], + }) + .await; + } + + #[tokio::test] + async fn confirming_a_resolution_applies_it_as_one_undo_step() { + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + editor.draw_rect(0., 0., 100., 100.).await; + let layer_count = editor.active_document().metadata().all_layers().count(); + + open_and_set_resolution(&mut editor, 300.).await; + assert_eq!(pixels_per_inch(&editor), 96., "the dialog applies nothing before it is confirmed"); + confirm(&mut editor).await; + assert_eq!(pixels_per_inch(&editor), 300.); + + // Undoing reverts only the resolution, leaving the rectangle drawn before it + editor.handle_message(DocumentMessage::Undo).await; + assert_eq!(pixels_per_inch(&editor), 96.); + assert_eq!(editor.active_document().metadata().all_layers().count(), layer_count); + + editor.handle_message(DocumentMessage::Redo).await; + assert_eq!(pixels_per_inch(&editor), 300.); + } + + #[tokio::test] + async fn canceling_or_confirming_an_unchanged_resolution_adds_no_undo_step() { + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + open_and_set_resolution(&mut editor, 300.).await; + confirm(&mut editor).await; + + open_and_set_resolution(&mut editor, 150.).await; + editor.handle_message(DialogMessage::Close).await; + assert_eq!(pixels_per_inch(&editor), 300., "canceling discards the dialog's resolution"); + + // Reopening starts from the document's resolution, so confirming it unchanged has nothing to apply + editor.handle_message(DialogMessage::RequestDocumentSetupDialog).await; + confirm(&mut editor).await; + assert_eq!(pixels_per_inch(&editor), 300.); + + editor.handle_message(DocumentMessage::Undo).await; + assert_eq!(pixels_per_inch(&editor), 96., "the one undo step is the resolution's first change"); + } +} diff --git a/editor/src/messages/dialog/document_setup_dialog/mod.rs b/editor/src/messages/dialog/document_setup_dialog/mod.rs new file mode 100644 index 0000000000..93aac69a74 --- /dev/null +++ b/editor/src/messages/dialog/document_setup_dialog/mod.rs @@ -0,0 +1,7 @@ +mod document_setup_dialog_message; +mod document_setup_dialog_message_handler; + +#[doc(inline)] +pub use document_setup_dialog_message::{DocumentSetupDialogMessage, DocumentSetupDialogMessageDiscriminant}; +#[doc(inline)] +pub use document_setup_dialog_message_handler::{DocumentSetupDialogMessageHandler, resolution_row}; diff --git a/editor/src/messages/dialog/mod.rs b/editor/src/messages/dialog/mod.rs index 4fa605ca29..944a324a14 100644 --- a/editor/src/messages/dialog/mod.rs +++ b/editor/src/messages/dialog/mod.rs @@ -8,6 +8,7 @@ mod dialog_message; mod dialog_message_handler; +pub mod document_setup_dialog; pub mod export_dialog; pub mod new_document_dialog; pub mod preferences_dialog; diff --git a/editor/src/messages/layout/layout_message_handler.rs b/editor/src/messages/layout/layout_message_handler.rs index a860b4b051..3b59b59a24 100644 --- a/editor/src/messages/layout/layout_message_handler.rs +++ b/editor/src/messages/layout/layout_message_handler.rs @@ -417,16 +417,20 @@ impl LayoutMessageHandler { } // A text-field commit sends the user's raw entry as a math expression to evaluate and validate. Value::String(expression) => { - let Some(evaluated) = evaluate_and_validate_number_input(&expression, number_input) else { return }; + let Some((evaluated, kept_unit)) = evaluate_and_validate_number_input(&expression, number_input) else { + return; + }; + let unit = kept_unit.map_or_else(|| number_input.unit.clone(), |symbol| unit_suffix(&symbol)); // Skip the update (and its history transaction) when the value is unchanged, since the network interface would short-circuit it anyway. - if number_input.value == Some(evaluated) { + if number_input.value == Some(evaluated) && number_input.unit == unit { return; } // Snapshot the pre-change state for undo via `on_commit`, then apply the new value via `on_update`. responses.add((number_input.on_commit.callback)(&())); number_input.value = Some(evaluated); + number_input.unit = unit; responses.add((number_input.on_update.callback)(number_input)); } // The increment arrows send `{ "increment": "Increase" | "Decrease" }` to invoke the backend's directional step callback. @@ -704,30 +708,41 @@ fn populate_computed_display_fields(layout: &mut Layout) { } } -/// Evaluates a math expression committed in a `NumberInput`'s text field, then clamps and rounds it to the widget's constraints. -/// Returns `None` if the expression fails to parse, fails to evaluate, or yields a non-real number (such as `sqrt(-1)`). -fn evaluate_and_validate_number_input(expression: &str, number_input: &NumberInput) -> Option { - let value = math_parser::evaluate(expression) +/// The suffix a field shows after a number in this unit: a space before a word like `mm`, and none before a symbol like `°` or `%`. +pub fn unit_suffix(symbol: &str) -> String { + if symbol.starts_with(char::is_alphabetic) { format!(" {symbol}") } else { symbol.to_string() } +} + +/// Evaluates a math expression committed in a `NumberInput`'s text field, then clamps and rounds it to the widget's constraints, giving +/// the unit it keeps where the field keeps the unit a value is typed in. Returns `None` if the expression fails to parse, fails to +/// evaluate, yields a non-real number (such as `sqrt(-1)`), or measures something the field doesn't (such as `5s` in a length field). +fn evaluate_and_validate_number_input(expression: &str, number_input: &NumberInput) -> Option<(f64, Option)> { + let context = math_parser::context::EvalContext::default().with_pixels_per_inch(number_input.pixels_per_inch); + let value = math_parser::ast::Node::try_parse_from_str(expression) .inspect_err(|err| error!("Math parser error on \"{expression}\": {err}")) .ok()? + .eval(&context) .inspect_err(|err| error!("Math evaluate error on \"{expression}\": {err}")) .ok()?; // The result reads in the field's unit, where a plain number is already in it and a unit like `mm` converts into it let field_unit = math_parser::units::Unit::named(number_input.unit.trim()); - let real = match (value.as_quantity(), field_unit) { - (Some(quantity), Some(unit)) => quantity - .read_in(unit, math_parser::units::DEFAULT_PIXELS_PER_INCH) - .inspect_err(|_| error!("\"{expression}\" is {}, which a field in `{unit}` can't hold", quantity.dimension().description())) - .ok()? - .as_real()?, - _ => value.as_real()?, + let (in_field_unit, quantity) = match (value.as_quantity(), field_unit) { + (Some(quantity), Some(unit)) => { + let read = quantity + .read_in(unit, number_input.pixels_per_inch) + .inspect_err(|_| error!("\"{expression}\" is {}, which a field in `{unit}` can't hold", quantity.dimension().description())) + .ok()? + .as_real()?; + (read, Some(*quantity)) + } + _ => (value.as_real()?, None), }; - if real.is_nan() { + if in_field_unit.is_nan() { return None; } - let mut validated = real; + let mut validated = in_field_unit; if let Some(min) = number_input.min { validated = validated.max(min); } @@ -738,5 +753,17 @@ fn evaluate_and_validate_number_input(expression: &str, number_input: &NumberInp validated = validated.round(); } - Some(validated) + // A value typed in a unit the field keeps stays in it, unless the field's limits moved it + let kept_unit = quantity.and_then(|quantity| { + let symbol = quantity.unit.single()?.definition().symbol; + number_input.kept_units.iter().any(|kept| kept == symbol).then_some((quantity, symbol)) + }); + if let Some((quantity, symbol)) = kept_unit + && validated == in_field_unit + && let Some(kept_value) = quantity.value.as_real() + { + return Some((kept_value, Some(symbol.to_string()))); + } + + Some((validated, None)) } diff --git a/editor/src/messages/layout/utility_types/widgets/input_widgets.rs b/editor/src/messages/layout/utility_types/widgets/input_widgets.rs index 3b81d255f1..d76e38e9da 100644 --- a/editor/src/messages/layout/utility_types/widgets/input_widgets.rs +++ b/editor/src/messages/layout/utility_types/widgets/input_widgets.rs @@ -247,6 +247,14 @@ pub struct NumberInput { #[serde(rename = "unitIsHiddenWhenEditing")] #[derivative(Default(value = "true"))] pub unit_is_hidden_when_editing: bool, + /// The units, by symbol, that a typed value keeps rather than converting into the field's `unit`, like `mm` in a length field + /// that remembers the unit a length was typed in. A kept unit becomes the field's `unit`. + #[serde(skip)] + pub kept_units: Vec, + /// The size of a pixel against an inch for converting a typed physical length, the document's resolution. + #[serde(skip)] + #[derivative(Default(value = "96."))] + pub pixels_per_inch: f64, // Tooltips #[serde(rename = "tooltipLabel")] diff --git a/editor/src/messages/menu_bar/menu_bar_message_handler.rs b/editor/src/messages/menu_bar/menu_bar_message_handler.rs index 56d0ef6268..cb9e0aba95 100644 --- a/editor/src/messages/menu_bar/menu_bar_message_handler.rs +++ b/editor/src/messages/menu_bar/menu_bar_message_handler.rs @@ -181,6 +181,13 @@ impl LayoutHolder for MenuBarMessageHandler { .on_commit(|_| DialogMessage::RequestExportDialog.into()) .disabled(no_active_document), ], + vec![ + MenuListEntry::new("Document Setup…") + .label("Document Setup…") + .icon("Settings") + .on_commit(|_| DialogMessage::RequestDocumentSetupDialog.into()) + .disabled(no_active_document), + ], #[cfg(not(target_os = "macos"))] vec![preferences], ]) diff --git a/editor/src/messages/portfolio/document/data_panel/data_panel_message_handler.rs b/editor/src/messages/portfolio/document/data_panel/data_panel_message_handler.rs index 6e1c98110b..595d322cdd 100644 --- a/editor/src/messages/portfolio/document/data_panel/data_panel_message_handler.rs +++ b/editor/src/messages/portfolio/document/data_panel/data_panel_message_handler.rs @@ -25,6 +25,7 @@ use graphene_std::text_nodes::{StringCapitalization, TextDenomination}; use graphene_std::transfer_curve::TransferCurve; use graphene_std::transform::Footprint; use graphene_std::transform::{ReferencePoint, ScaleType}; +use graphene_std::units::{Angle, Length}; use graphene_std::vector::misc::{ ArcType, BooleanOperation, BoxCorners, CentroidType, ExtrudeJoiningAlgorithm, GridTopology, GridType, InterpolationDistribution, PointSpacingType, RowsOrColumns, SpiralType, UnweldMethod, WeldMethod, @@ -401,6 +402,8 @@ macro_rules! inspectable_types { List, List, List, + List, + List, List, List, List, @@ -461,6 +464,8 @@ macro_rules! inspectable_types { Item, Item, Item, + Item, + Item, Item, Item, Item, @@ -1100,6 +1105,30 @@ impl TableItemLayout for f64 { } } +impl TableItemLayout for Length { + fn type_name() -> &'static str { + "Length" + } + fn identifier(&self) -> String { + format!("{} px", format_f64(round_away_float_noise(self.pixels()))) + } + fn value_widgets(&self, _target: PathStep, _data: &LayoutData) -> Vec { + vec![TextLabel::new(self.identifier()).selectable(true).narrow(true).widget_instance()] + } +} + +impl TableItemLayout for Angle { + fn type_name() -> &'static str { + "Angle" + } + fn identifier(&self) -> String { + format!("{}°", format_f64(round_away_float_noise(self.degrees()))) + } + fn value_widgets(&self, _target: PathStep, _data: &LayoutData) -> Vec { + vec![TextLabel::new(self.identifier()).selectable(true).narrow(true).widget_instance()] + } +} + impl TableItemLayout for u8 { fn type_name() -> &'static str { "Byte" diff --git a/editor/src/messages/portfolio/document/document_message.rs b/editor/src/messages/portfolio/document/document_message.rs index a081081a9c..5d1e247607 100644 --- a/editor/src/messages/portfolio/document/document_message.rs +++ b/editor/src/messages/portfolio/document/document_message.rs @@ -266,6 +266,11 @@ pub enum DocumentMessage { SetRenderMode { render_mode: RenderMode, }, + /// Sets how many pixels make an inch, which sizes the lengths typed in a physical unit and the physical size of exports. + /// The caller wraps it in a transaction to make it one undo step. + SetPixelsPerInch { + pixels_per_inch: f64, + }, ShowNodeInGraph { node_id: NodeId, }, diff --git a/editor/src/messages/portfolio/document/document_message_handler.rs b/editor/src/messages/portfolio/document/document_message_handler.rs index 68a161caf4..0c4d9a102a 100644 --- a/editor/src/messages/portfolio/document/document_message_handler.rs +++ b/editor/src/messages/portfolio/document/document_message_handler.rs @@ -53,6 +53,7 @@ use graphene_std::vector::misc::dvec2_to_point; use graphene_std::vector::style::{GradientStops, RenderMode}; use kurbo::{Affine, BezPath, Line, PathSeg, Shape}; use std::collections::HashSet; +use std::hash::{Hash, Hasher}; use std::path::PathBuf; use std::sync::Arc; use std::time::Duration; @@ -1694,6 +1695,16 @@ impl MessageHandler> for DocumentMes self.render_mode = render_mode; responses.add_front(NodeGraphMessage::RunDocumentGraph); } + DocumentMessage::SetPixelsPerInch { pixels_per_inch } => { + if !pixels_per_inch.is_finite() || pixels_per_inch <= 0. || pixels_per_inch == self.network_interface.pixels_per_inch() { + return; + } + self.network_interface.set_pixels_per_inch(pixels_per_inch); + + // Lengths typed in a physical unit change their size in pixels, so the graph runs again + responses.add(NodeGraphMessage::RunDocumentGraph); + responses.add(InspectorMessage::Refresh); + } DocumentMessage::ShowNodeInGraph { node_id } => { // The node is in the document network, so the graph first leaves any nested network it's showing if !self.breadcrumb_network_path.is_empty() { @@ -3230,7 +3241,10 @@ impl DocumentMessageHandler { } pub fn current_hash(&self) -> u64 { - self.network_interface.document_network().current_hash() + // The resolution lives in the network's metadata rather than the network, but changing it changes the document + let mut hasher = std::collections::hash_map::DefaultHasher::new(); + (self.network_interface.document_network().current_hash(), self.network_interface.pixels_per_inch().to_bits()).hash(&mut hasher); + hasher.finish() } pub fn is_auto_saved(&self) -> bool { diff --git a/editor/src/messages/portfolio/document/node_graph/node_inspector.rs b/editor/src/messages/portfolio/document/node_graph/node_inspector.rs index 6c8338c654..a86660cdf0 100644 --- a/editor/src/messages/portfolio/document/node_graph/node_inspector.rs +++ b/editor/src/messages/portfolio/document/node_graph/node_inspector.rs @@ -2,6 +2,7 @@ use super::document_node_definitions::{NODE_OVERRIDES, NodeInspectorContext}; use super::utility_types::FrontendGraphDataType; +use crate::messages::layout::layout_message_handler::unit_suffix; use crate::messages::layout::utility_types::math_expression::{MathExpressionTokens, math_expression_error, math_expression_error_ranges, math_expression_tokens}; use crate::messages::layout::utility_types::tooltip_markdown::{escape_markdown, markdown_code_span}; use crate::messages::layout::utility_types::widget_prelude::*; @@ -31,6 +32,7 @@ use graphene_std::text::{Font, TextAlign}; use graphene_std::text_nodes::{StringCapitalization, TextDenomination}; use graphene_std::transfer_curve::TransferCurve; use graphene_std::transform::{Footprint, ReferencePoint, ScaleType, Transform}; +use graphene_std::units::{Angle, AngleUnit, Length, LengthUnit, TypedAngle, TypedLength}; use graphene_std::vector::misc::BooleanOperation; use graphene_std::vector::misc::{ ArcType, BoxCorners, CentroidType, ExtrudeJoiningAlgorithm, GridTopology, GridType, InterpolationDistribution, PointSpacingType, RowsOrColumns, SpiralType, UnweldMethod, WeldMethod, @@ -305,7 +307,7 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type, step, } = options; - let mut number_input = NumberInput::default(); + let mut number_input = NumberInput::default().pixels_per_inch(context.network_interface.pixels_per_inch()); if slider { number_input = number_input.mode_range(); } @@ -387,6 +389,8 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type, false => number_or_slider(default_info, bounded(number_input, f64::NEG_INFINITY, f64::INFINITY)), }, Some(x) if id_is::(x) => number_widget(default_info, bounded(number_input.int(), f64::NEG_INFINITY, f64::INFINITY)).into(), + Some(x) if id_is::(x) => length_widget(default_info, bounded(number_input, f64::NEG_INFINITY, f64::INFINITY)).into(), + Some(x) if id_is::(x) => angle_widget(default_info, bounded(number_input, f64::NEG_INFINITY, f64::INFINITY)).into(), Some(x) if id_is::(x) => bool_widget(default_info, CheckboxInput::default()).into(), Some(x) if id_is::(x) => match multiline { true => text_area_widget(default_info).into(), @@ -896,6 +900,7 @@ pub fn transform_widget(parameter_widgets_info: ParameterWidgetsInfo, extra_widg pub fn vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &str, unit: &str, min: Option, is_integer: bool, disabled: bool) -> LayoutGroup { let mut widgets = start_widgets(¶meter_widgets_info); + let pixels_per_inch = parameter_widgets_info.network_interface.pixels_per_inch(); let Some(input) = parameter_widgets_info.input() else { log::warn!("A widget failed to be built because its node's input index is invalid."); @@ -912,6 +917,7 @@ pub fn vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &st .max((1_u64 << f64::MANTISSA_DIGITS) as f64) .is_integer(is_integer) .disabled(disabled) + .pixels_per_inch(pixels_per_inch) .on_update(parameter_widgets_info.update_value(move |input: &NumberInput| TaggedValue::DVec2(DVec2::new(input.value.unwrap(), dvec2.y)))) .on_commit(commit_value) .widget_instance(), @@ -923,6 +929,7 @@ pub fn vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &st .max((1_u64 << f64::MANTISSA_DIGITS) as f64) .is_integer(is_integer) .disabled(disabled) + .pixels_per_inch(pixels_per_inch) .on_update(parameter_widgets_info.update_value(move |input: &NumberInput| TaggedValue::DVec2(DVec2::new(dvec2.x, input.value.unwrap())))) .on_commit(commit_value) .widget_instance(), @@ -938,6 +945,7 @@ pub fn vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &st .max((1_u64 << f64::MANTISSA_DIGITS) as f64) .is_integer(is_integer) .disabled(disabled) + .pixels_per_inch(pixels_per_inch) .on_update(parameter_widgets_info.update_value(move |input: &NumberInput| TaggedValue::DVec2(DVec2::new(input.value.unwrap(), value)))) .on_commit(commit_value) .widget_instance(), @@ -949,6 +957,7 @@ pub fn vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &st .max((1_u64 << f64::MANTISSA_DIGITS) as f64) .is_integer(is_integer) .disabled(disabled) + .pixels_per_inch(pixels_per_inch) .on_update(parameter_widgets_info.update_value(move |input: &NumberInput| TaggedValue::DVec2(DVec2::new(value, input.value.unwrap())))) .on_commit(commit_value) .widget_instance(), @@ -1317,6 +1326,92 @@ pub fn number_widget(parameter_widgets_info: ParameterWidgetsInfo, number_props: widgets } +/// Converts a field's bounds from the unit they're given in into the unit its value is shown in. +fn bounds_in_unit(number_input: NumberInput, convert: impl Fn(f64) -> f64) -> NumberInput { + let convert = |bound: Option| bound.map(|bound| if bound.is_finite() { convert(bound) } else { bound }); + NumberInput { + min: convert(number_input.min), + max: convert(number_input.max), + range_min: convert(number_input.range_min), + range_max: convert(number_input.range_max), + ..number_input + } +} + +/// A length's number field, which shows the length in the unit it was typed in and keeps any length unit typed into it, with the +/// field's bounds given in pixels. +pub fn length_widget(parameter_widgets_info: ParameterWidgetsInfo, number_props: NumberInput) -> Vec { + let mut widgets = start_widgets(¶meter_widgets_info); + + let Some(input) = parameter_widgets_info.input() else { + log::warn!("A widget failed to be built because its node's input index is invalid."); + return vec![]; + }; + let length = match input.as_non_exposed_value() { + Some(&TaggedValue::Length(length)) => length, + Some(&TaggedValue::Number(pixels)) => TypedLength::pixels(pixels), + _ => return widgets, + }; + + let pixels_per_inch = parameter_widgets_info.network_interface.pixels_per_inch(); + let number_props = bounds_in_unit(number_props, |pixels| LengthUnit::Pixel.convert(pixels, length.unit, pixels_per_inch)); + widgets.extend_from_slice(&[ + Separator::new(SeparatorStyle::Unrelated).widget_instance(), + number_props + .value(Some(length.value)) + .unit(unit_suffix(length.unit.symbol())) + .kept_units(LengthUnit::ALL.iter().map(|unit| unit.symbol().to_string()).collect()) + .pixels_per_inch(pixels_per_inch) + .on_update(parameter_widgets_info.update_value(|input: &NumberInput| { + let unit = math_parser::units::Unit::named(input.unit.trim()).and_then(LengthUnit::from_unit).unwrap_or_default(); + TaggedValue::Length(TypedLength { + value: input.value.unwrap_or_default(), + unit, + }) + })) + .on_commit(commit_value) + .widget_instance(), + ]); + + widgets +} + +/// An angle's number field, which shows the angle in the unit it was typed in and keeps any angle unit typed into it, with the +/// field's bounds given in degrees. +pub fn angle_widget(parameter_widgets_info: ParameterWidgetsInfo, number_props: NumberInput) -> Vec { + let mut widgets = start_widgets(¶meter_widgets_info); + + let Some(input) = parameter_widgets_info.input() else { + log::warn!("A widget failed to be built because its node's input index is invalid."); + return vec![]; + }; + let angle = match input.as_non_exposed_value() { + Some(&TaggedValue::Angle(angle)) => angle, + Some(&TaggedValue::Number(degrees)) => TypedAngle::degrees(degrees), + _ => return widgets, + }; + + let number_props = bounds_in_unit(number_props, |degrees| angle.unit.from_angle(Angle::from_degrees(degrees))); + widgets.extend_from_slice(&[ + Separator::new(SeparatorStyle::Unrelated).widget_instance(), + number_props + .value(Some(angle.value)) + .unit(unit_suffix(angle.unit.symbol())) + .kept_units(AngleUnit::ALL.iter().map(|unit| unit.symbol().to_string()).collect()) + .on_update(parameter_widgets_info.update_value(|input: &NumberInput| { + let unit = math_parser::units::Unit::named(input.unit.trim()).and_then(AngleUnit::from_unit).unwrap_or_default(); + TaggedValue::Angle(TypedAngle { + value: input.value.unwrap_or_default(), + unit, + }) + })) + .on_commit(commit_value) + .widget_instance(), + ]); + + widgets +} + // TODO: Auto-generate this enum dropdown menu widget pub fn blend_mode_widget(parameter_widgets_info: ParameterWidgetsInfo) -> LayoutGroup { let mut widgets = start_widgets(¶meter_widgets_info); diff --git a/editor/src/messages/portfolio/document/node_graph/utility_types.rs b/editor/src/messages/portfolio/document/node_graph/utility_types.rs index d16046525a..c4e8fa0099 100644 --- a/editor/src/messages/portfolio/document/node_graph/utility_types.rs +++ b/editor/src/messages/portfolio/document/node_graph/utility_types.rs @@ -34,7 +34,7 @@ impl FrontendGraphDataType { "Color" => Self::Color, "Gradient" => Self::Gradient, "String" => Self::Typography, - "f64" | "i64" | "bool" | "DVec2" | "DAffine2" => Self::Number, + "f64" | "i64" | "bool" | "DVec2" | "DAffine2" | "Length" | "Angle" => Self::Number, // A generator draws pixels like an image, at whatever resolution is needed "Generator" => Self::Raster, raster if raster.starts_with("Raster") => Self::Raster, diff --git a/editor/src/messages/portfolio/document/storage_tests/metadata_tests.rs b/editor/src/messages/portfolio/document/storage_tests/metadata_tests.rs index f9c6ab674d..bc897373d2 100644 --- a/editor/src/messages/portfolio/document/storage_tests/metadata_tests.rs +++ b/editor/src/messages/portfolio/document/storage_tests/metadata_tests.rs @@ -296,6 +296,29 @@ fn pinned_order_round_trips_through_the_registry() { ); } +/// The document's resolution is shared document state, so it survives a registry round trip, and the default is stored as its absence. +#[test] +fn pixels_per_inch_round_trips_through_the_registry() { + let round_trip = |pixels_per_inch: f64| { + let mut document = open_demo("changing-seasons.graphite"); + document.network_interface.set_pixels_per_inch(pixels_per_inch); + + let network = document.network_interface.document_network().clone(); + let view = StorageMetadataView::new(&document.network_interface); + let conversion = Registry::convert_from_runtime(&network, &view, &Default::default(), PeerId(0)).expect("convert_from_runtime failed"); + let declarations = conversion.declarations; + let (rebuilt_network, node_entries, network_entries) = conversion.registry.to_runtime_with_full_metadata(&declarations, &conversion.blob_bytes).expect("to_runtime failed"); + let rebuilt = build_interface_from_storage(rebuilt_network, node_entries, network_entries); + ( + rebuilt.pixels_per_inch(), + rebuilt.network_metadata(&[]).expect("the rebuilt document network should resolve").persistent_metadata.pixels_per_inch, + ) + }; + + assert_eq!(round_trip(300.), (300., Some(300.))); + assert_eq!(round_trip(96.), (96., None)); +} + /// Per-peer view settings (`ui::doc::*`) survive the `session.json` round-trip: serialize them into /// the view map, then apply it onto a fresh handler and confirm each field matches. #[test] diff --git a/editor/src/messages/portfolio/document/utility_types/network_interface/apply.rs b/editor/src/messages/portfolio/document/utility_types/network_interface/apply.rs index 309c3f80cf..27c8a76b64 100644 --- a/editor/src/messages/portfolio/document/utility_types/network_interface/apply.rs +++ b/editor/src/messages/portfolio/document/utility_types/network_interface/apply.rs @@ -105,6 +105,7 @@ impl NodeNetworkInterface { match change { NetworkMetadataChange::Reference(reference) => network.set_reference(reference.clone()), NetworkMetadataChange::PinnedOrder(order) => network.set_pinned_order(order.clone()), + NetworkMetadataChange::PixelsPerInch(pixels_per_inch) => network.set_pixels_per_inch(*pixels_per_inch), NetworkMetadataChange::ImportMetadata(import_metadata) => network.set_import_metadata(import_metadata.clone()), NetworkMetadataChange::ExportNames(export_names) => network.set_export_names(export_names.clone()), NetworkMetadataChange::ExportDescriptions(export_descriptions) => network.set_export_descriptions(export_descriptions.clone()), diff --git a/editor/src/messages/portfolio/document/utility_types/network_interface/editor_delta.rs b/editor/src/messages/portfolio/document/utility_types/network_interface/editor_delta.rs index dd752c0cfa..fb806bfb1f 100644 --- a/editor/src/messages/portfolio/document/utility_types/network_interface/editor_delta.rs +++ b/editor/src/messages/portfolio/document/utility_types/network_interface/editor_delta.rs @@ -75,6 +75,7 @@ pub enum NetworkMetadataChange { Reference(Option), /// The whole order, since the encoding is one array-valued attribute rather than a slot each. PinnedOrder(Vec), + PixelsPerInch(Option), ImportMetadata(Vec), ExportNames(Vec), ExportDescriptions(Vec), @@ -256,6 +257,12 @@ impl EditorDelta { value: (!stored.is_empty()).then(|| serialize_attribute(network_attr::PINNED_ORDER, &stored)).transpose()?, } } + NetworkMetadataChange::PixelsPerInch(pixels_per_inch) => AttributeDelta { + key: network_attr::PIXELS_PER_INCH.to_string(), + value: pixels_per_inch + .map(|pixels_per_inch| serialize_attribute(network_attr::PIXELS_PER_INCH, &pixels_per_inch)) + .transpose()?, + }, NetworkMetadataChange::ImportMetadata(import_metadata) => import_metadata_delta(import_metadata)?, NetworkMetadataChange::ExportNames(export_names) => export_names_delta(export_names)?, NetworkMetadataChange::ExportDescriptions(export_descriptions) => export_descriptions_delta(export_descriptions)?, diff --git a/editor/src/messages/portfolio/document/utility_types/network_interface/mutations.rs b/editor/src/messages/portfolio/document/utility_types/network_interface/mutations.rs index 66ddf616a6..5d6d39acd8 100644 --- a/editor/src/messages/portfolio/document/utility_types/network_interface/mutations.rs +++ b/editor/src/messages/portfolio/document/utility_types/network_interface/mutations.rs @@ -1254,6 +1254,19 @@ impl NodeNetworkInterface { self.transaction_modified(); } + /// Sets how many pixels make an inch in the document, stored only where it differs from the default. + pub fn set_pixels_per_inch(&mut self, pixels_per_inch: f64) { + let stored = (pixels_per_inch != graphene_std::units::DEFAULT_PIXELS_PER_INCH).then_some(pixels_per_inch); + + let Some(mut network) = self.network_mut(&[]) else { + log::error!("Could not get the root network in set_pixels_per_inch"); + return; + }; + network.set_pixels_per_inch(stored); + + self.transaction_modified(); + } + pub fn set_visibility(&mut self, node_id: &NodeId, network_path: &[NodeId], is_visible: bool) { let Some(mut node) = self.node_mut(NodeLocator::new(*node_id, network_path)) else { log::error!("Could not get node {node_id} in set_visibility"); diff --git a/editor/src/messages/portfolio/document/utility_types/network_interface/queries.rs b/editor/src/messages/portfolio/document/utility_types/network_interface/queries.rs index d7c3fa89d0..0f69ac8d1d 100644 --- a/editor/src/messages/portfolio/document/utility_types/network_interface/queries.rs +++ b/editor/src/messages/portfolio/document/utility_types/network_interface/queries.rs @@ -128,10 +128,18 @@ impl NodeNetworkInterface { }); let mut hasher = std::hash::DefaultHasher::new(); - (self.network.current_hash(), self.previewed_nodes(), layers_hash).hash(&mut hasher); + (self.network.current_hash(), self.previewed_nodes(), layers_hash, self.pixels_per_inch().to_bits()).hash(&mut hasher); hasher.finish() } + /// How many pixels make an inch in the document, which sizes the lengths typed in a physical unit. + pub fn pixels_per_inch(&self) -> f64 { + self.network_metadata(&[]) + .and_then(|metadata| metadata.persistent_metadata.pixels_per_inch) + .filter(|pixels_per_inch| pixels_per_inch.is_finite() && *pixels_per_inch > 0.) + .unwrap_or(graphene_std::units::DEFAULT_PIXELS_PER_INCH) + } + /// Get the specified document node in the nested network based on node_id and network_path pub fn document_node(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<&DocumentNode> { self.query(network_path, "document_node", |view| view.node(node_id)) diff --git a/editor/src/messages/portfolio/document/utility_types/network_interface/reconcile.rs b/editor/src/messages/portfolio/document/utility_types/network_interface/reconcile.rs index 6537695329..ec0d0673c6 100644 --- a/editor/src/messages/portfolio/document/utility_types/network_interface/reconcile.rs +++ b/editor/src/messages/portfolio/document/utility_types/network_interface/reconcile.rs @@ -143,6 +143,9 @@ impl NodeNetworkInterface { if current_metadata.pinned_node_order != target.metadata.pinned_order { deltas.push(change(NetworkMetadataChange::PinnedOrder(target.metadata.pinned_order.clone()))); } + if current_metadata.pixels_per_inch != target.metadata.pixels_per_inch { + deltas.push(change(NetworkMetadataChange::PixelsPerInch(target.metadata.pixels_per_inch))); + } // An empty list states nothing, since a catalog entry's interface comes from the catalog rather than storage let import_metadata: Vec<_> = target.metadata.import_metadata.iter().cloned().map(input_metadata_entry_to_runtime).collect(); if !import_metadata.is_empty() && current_metadata.import_metadata != import_metadata { diff --git a/editor/src/messages/portfolio/document/utility_types/network_interface/storage_metadata.rs b/editor/src/messages/portfolio/document/utility_types/network_interface/storage_metadata.rs index f24aa2feca..3d8e9d4c50 100644 --- a/editor/src/messages/portfolio/document/utility_types/network_interface/storage_metadata.rs +++ b/editor/src/messages/portfolio/document/utility_types/network_interface/storage_metadata.rs @@ -111,6 +111,10 @@ impl NodeMetadataSource for StorageMetadataView<'_> { fn pinned_order(&self, network: NetworkLocation) -> Vec { self.network_persistent(network).map(|persistent| persistent.pinned_node_order.clone()).unwrap_or_default() } + + fn pixels_per_inch(&self, network: NetworkLocation) -> Option { + self.network_persistent(network)?.pixels_per_inch + } } impl DocumentSettings<'_> { @@ -307,6 +311,7 @@ fn apply_network_entries_into_tree(metadata: &mut NodeNetworkMetadata, entries: network_metadata.persistent_metadata.reference = Some(reference); } network_metadata.persistent_metadata.pinned_node_order = entry.pinned_order; + network_metadata.persistent_metadata.pixels_per_inch = entry.pixels_per_inch; network_metadata.persistent_metadata.import_metadata = entry.import_metadata.into_iter().map(input_metadata_entry_to_runtime).collect(); network_metadata.persistent_metadata.export_names = entry.export_names; network_metadata.persistent_metadata.export_descriptions = entry.export_descriptions; diff --git a/editor/src/messages/portfolio/document/utility_types/network_interface/store/cursor.rs b/editor/src/messages/portfolio/document/utility_types/network_interface/store/cursor.rs index 3df77c7f01..51c20038ce 100644 --- a/editor/src/messages/portfolio/document/utility_types/network_interface/store/cursor.rs +++ b/editor/src/messages/portfolio/document/utility_types/network_interface/store/cursor.rs @@ -538,6 +538,16 @@ impl NetworkMut<'_> { changed } + /// How many pixels make an inch in the document, or `None` for the default. + pub(crate) fn set_pixels_per_inch(&mut self, pixels_per_inch: Option) -> bool { + let changed = self.metadata.pixels_per_inch != pixels_per_inch; + self.metadata.pixels_per_inch = pixels_per_inch; + if changed { + self.emit(NetworkMetadataChange::PixelsPerInch(pixels_per_inch)); + } + changed + } + /// The display order of pinned nodes in the Inspector. pub(crate) fn set_pinned_order(&mut self, pinned_node_order: Vec) -> bool { let changed = self.metadata.pinned_node_order != pinned_node_order; diff --git a/editor/src/messages/portfolio/document/utility_types/network_interface/store/mod.rs b/editor/src/messages/portfolio/document/utility_types/network_interface/store/mod.rs index 48c50c0460..f62abfdeee 100644 --- a/editor/src/messages/portfolio/document/utility_types/network_interface/store/mod.rs +++ b/editor/src/messages/portfolio/document/utility_types/network_interface/store/mod.rs @@ -511,6 +511,7 @@ impl NodeNetworkInterface { .into_iter() .chain([ NetworkMetadataChange::PinnedOrder(persistent_metadata.pinned_node_order.clone()), + NetworkMetadataChange::PixelsPerInch(persistent_metadata.pixels_per_inch), NetworkMetadataChange::ImportMetadata(persistent_metadata.import_metadata.clone()), NetworkMetadataChange::ExportNames(persistent_metadata.export_names.clone()), NetworkMetadataChange::ExportDescriptions(persistent_metadata.export_descriptions.clone()), diff --git a/editor/src/messages/portfolio/document/utility_types/network_interface/template.rs b/editor/src/messages/portfolio/document/utility_types/network_interface/template.rs index efcdbba810..347e0fd643 100644 --- a/editor/src/messages/portfolio/document/utility_types/network_interface/template.rs +++ b/editor/src/messages/portfolio/document/utility_types/network_interface/template.rs @@ -291,6 +291,7 @@ impl NodeTemplateImplementation { reference, node_metadata, pinned_node_order, + pixels_per_inch: None, previewing, navigation_metadata, selection_undo_history: Default::default(), diff --git a/editor/src/messages/portfolio/document/utility_types/network_interface/types.rs b/editor/src/messages/portfolio/document/utility_types/network_interface/types.rs index 54dedc3a3b..712b3fcc81 100644 --- a/editor/src/messages/portfolio/document/utility_types/network_interface/types.rs +++ b/editor/src/messages/portfolio/document/utility_types/network_interface/types.rs @@ -674,6 +674,9 @@ pub struct NodeNetworkPersistentMetadata { /// The display order of pinned nodes in the Inspector (shown when nothing is selected in this network), keyed by node ID. #[serde(default)] pub pinned_node_order: Vec, + /// How many pixels make an inch, which sizes lengths typed in a physical unit, or `None` for the default of 96. Only the root network's applies. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub pixels_per_inch: Option, /// Cached metadata for each node, which is calculated when adding a node to node_metadata /// Indicates whether the network is currently rendered with a particular node that is previewed, and if so, which connection should be restored when the preview ends. pub previewing: Previewing, diff --git a/editor/src/messages/prelude.rs b/editor/src/messages/prelude.rs index 9af94c9078..ea77b5ef71 100644 --- a/editor/src/messages/prelude.rs +++ b/editor/src/messages/prelude.rs @@ -11,6 +11,7 @@ pub use crate::messages::clipboard::{ClipboardMessage, ClipboardMessageContext, pub use crate::messages::color_picker::{ColorPickerMessage, ColorPickerMessageDiscriminant, ColorPickerMessageHandler}; pub use crate::messages::debug::{DebugMessage, DebugMessageDiscriminant, DebugMessageHandler}; pub use crate::messages::defer::{DeferMessage, DeferMessageDiscriminant, DeferMessageHandler}; +pub use crate::messages::dialog::document_setup_dialog::{DocumentSetupDialogMessage, DocumentSetupDialogMessageDiscriminant, DocumentSetupDialogMessageHandler}; pub use crate::messages::dialog::export_dialog::{ExportDialogMessage, ExportDialogMessageContext, ExportDialogMessageDiscriminant, ExportDialogMessageHandler}; pub use crate::messages::dialog::new_document_dialog::{NewDocumentDialogMessage, NewDocumentDialogMessageDiscriminant, NewDocumentDialogMessageHandler}; pub use crate::messages::dialog::preferences_dialog::{PreferencesDialogMessage, PreferencesDialogMessageContext, PreferencesDialogMessageDiscriminant, PreferencesDialogMessageHandler}; diff --git a/editor/src/messages/tool/common_functionality/gizmos/shape_gizmos/circle_arc_radius_handle.rs b/editor/src/messages/tool/common_functionality/gizmos/shape_gizmos/circle_arc_radius_handle.rs index 5aad44524a..c8202881b3 100644 --- a/editor/src/messages/tool/common_functionality/gizmos/shape_gizmos/circle_arc_radius_handle.rs +++ b/editor/src/messages/tool/common_functionality/gizmos/shape_gizmos/circle_arc_radius_handle.rs @@ -194,9 +194,15 @@ impl RadiusHandle { // The size is snapped, which keeps whichever sign the radius has come to let snapped_radius = snap_session.snap_value(view, position_of, self.free_radius.abs(), on_screen_per_unit, equal_radii) * self.free_radius.signum(); + // A radius typed in a unit like millimeters stays in it + let input_connector = InputConnector::node(node_id, radius_parameter); + let radius = match document.network_interface.input_from_connector(&input_connector, &[]).and_then(|input| input.as_value()) { + Some(existing @ TaggedValue::Length(_)) => existing.length_in_same_unit(snapped_radius, document.network_interface.pixels_per_inch()), + _ => TaggedValue::Number(snapped_radius), + }; responses.add(NodeGraphMessage::SetInput { - input_connector: InputConnector::node(node_id, radius_parameter), - input: NodeInput::value(TaggedValue::Number(snapped_radius), false), + input_connector, + input: NodeInput::value(radius, false), }); responses.add(NodeGraphMessage::RunDocumentGraph); } diff --git a/editor/src/messages/tool/common_functionality/shapes/circle_shape.rs b/editor/src/messages/tool/common_functionality/shapes/circle_shape.rs index 95e0525c77..981b54ab88 100644 --- a/editor/src/messages/tool/common_functionality/shapes/circle_shape.rs +++ b/editor/src/messages/tool/common_functionality/shapes/circle_shape.rs @@ -12,6 +12,7 @@ use crate::messages::tool::tool_messages::shape_tool::ShapeToolData; use crate::messages::tool::tool_messages::tool_prelude::*; use graph_craft::document::NodeInput; use graph_craft::document::value::TaggedValue; +use graphene_std::units::TypedLength; #[derive(Clone, Debug, Default)] pub struct CircleGizmoHandler { @@ -108,7 +109,7 @@ impl Circle { responses.add(NodeGraphMessage::SetInput { input_connector: InputConnector::node(node_id, graphene_std::vector::generator_nodes::circle::RadiusInput), - input: NodeInput::value(TaggedValue::Number(radius), false), + input: NodeInput::value(TaggedValue::Length(TypedLength::pixels(radius)), false), }); responses.add(window_aligned_transform_set(document, layer, start.midpoint(end), DVec2::ONE)); diff --git a/editor/src/messages/tool/common_functionality/shapes/shape_utility.rs b/editor/src/messages/tool/common_functionality/shapes/shape_utility.rs index b79b089848..f20e9f1713 100644 --- a/editor/src/messages/tool/common_functionality/shapes/shape_utility.rs +++ b/editor/src/messages/tool/common_functionality/shapes/shape_utility.rs @@ -421,11 +421,7 @@ pub fn pointer_travel_per_radian(layer_to_viewport: DAffine2, pointer: DVec2) -> pub fn extract_circle_radius(layer: LayerNodeIdentifier, document: &DocumentMessageHandler) -> Option { let node_inputs = NodeGraphLayer::new(layer, &document.network_interface).find_node_inputs(&DefinitionIdentifier::ProtoNode(graphene_std::vector::generator_nodes::circle::IDENTIFIER))?; - let Some(&TaggedValue::Number(radius)) = node_inputs.get(1)?.as_value() else { - return None; - }; - - Some(radius) + node_inputs.get(1)?.as_value()?.as_length_pixels(document.network_interface.pixels_per_inch()) } /// Calculate the viewport position of as a star vertex given its index diff --git a/editor/src/node_graph_executor.rs b/editor/src/node_graph_executor.rs index fa8b3fe1b1..2d99548619 100644 --- a/editor/src/node_graph_executor.rs +++ b/editor/src/node_graph_executor.rs @@ -271,6 +271,7 @@ impl NodeGraphExecutor { previewed: Vec::new(), layers: document.network_interface.layer_paths(), observations: self.observations(&document.network_interface), + pixels_per_inch: document.network_interface.pixels_per_inch(), })) .map_err(|e| e.to_string())?; Ok(instrumented) @@ -301,6 +302,7 @@ impl NodeGraphExecutor { previewed, layers, observations: self.observations(&document.network_interface), + pixels_per_inch: document.network_interface.pixels_per_inch(), })) .map_err(|e| e.to_string())?; } else if inspected_node_changed { @@ -492,6 +494,7 @@ impl NodeGraphExecutor { previewed, layers: document.network_interface.layer_paths(), observations: self.observations(&document.network_interface), + pixels_per_inch: document.network_interface.pixels_per_inch(), })) .map_err(|e| e.to_string())?; let execution_id = self.queue_execution(render_config); @@ -891,6 +894,7 @@ impl NodeGraphExecutor { previewed: Vec::new(), layers: document.network_interface.layer_paths(), observations: HashMap::from([(ObservationKey::FillMeasurement, fill_measurement)]), + pixels_per_inch: document.network_interface.pixels_per_inch(), })) .is_err() { diff --git a/editor/src/node_graph_executor/runtime.rs b/editor/src/node_graph_executor/runtime.rs index f7f4e63400..902b84ba3a 100644 --- a/editor/src/node_graph_executor/runtime.rs +++ b/editor/src/node_graph_executor/runtime.rs @@ -124,6 +124,8 @@ pub struct GraphUpdate { pub(super) layers: Vec>, /// The connectors whose values are sent back after each evaluation, replacing those observed before. pub(super) observations: HashMap, + /// The document's pixels per inch, which sizes lengths typed in a physical unit. + pub(super) pixels_per_inch: f64, } /// Replaces each network's primary export with its previewed node. @@ -240,6 +242,7 @@ impl NodeRuntime { previewed, layers, observations, + pixels_per_inch, }) = graph else { return; @@ -252,7 +255,7 @@ impl NodeRuntime { self.node_graph_errors.clear(); self.node_graph_warnings.clear(); - let result = self.update_network(network.clone()); + let result = self.update_network(network.clone(), pixels_per_inch); self.compile_failed = result.is_err(); if result.is_ok() { self.thumbnails.update_sources(&layers, &network, &self.executor); @@ -521,8 +524,8 @@ impl NodeRuntime { Raster::new_gpu(texture).convert(Footprint::BOUNDLESS, executor.clone()).await } - fn update_network(&mut self, graph: NodeNetwork) -> Result { - let mut scoped_network = wrap_network_in_scope(graph, self.editor_api.clone(), self.async_runtime().handle()); + fn update_network(&mut self, graph: NodeNetwork, pixels_per_inch: f64) -> Result { + let mut scoped_network = wrap_network_in_scope(graph, self.editor_api.clone(), self.async_runtime().handle(), pixels_per_inch); if let Err(e) = self.preprocessor.preprocess(&mut scoped_network, &|resource_id| self.resources.hash(&resource_id)) { return Err((ResolvedDocumentNodeTypesDelta::default(), e.to_string())); diff --git a/frontend/src/components/widgets/inputs/NumberInput.svelte b/frontend/src/components/widgets/inputs/NumberInput.svelte index 93f818c856..0025db1458 100644 --- a/frontend/src/components/widgets/inputs/NumberInput.svelte +++ b/frontend/src/components/widgets/inputs/NumberInput.svelte @@ -75,6 +75,9 @@ let inputRangeElement: HTMLInputElement | undefined; let text = exact ?? displayText(value, unit); let editing = false; + + // While editing, the unit a number typed without one is read in shows faintly after the text + $: ghostUnit = editing && exact === undefined && unit.trim() !== "" && !endsInUnit(text) ? unit : ""; let isDragging = false; let pressingArrow = false; let repeatTimeout: ReturnType | undefined = undefined; @@ -118,7 +121,7 @@ let sliderAbortTimeout1: ReturnType | undefined; let sliderAbortTimeout2: ReturnType | undefined; - $: watchValue(value, unit); + $: watchValue(value, unit, min, max); $: if (exact !== undefined && !editing) text = exact; $: present = exact !== undefined || value !== undefined; // A number of only one digit, like `0` or `-1`, has no other digit to move the underline to, so it isn't shown @@ -176,8 +179,8 @@ // TRACKING AND UPDATING THE VALUE // =============================== - // Called only when `value` is changed from outside this component. - function watchValue(value: number | undefined, unit: string) { + // Called only when `value`, its unit, or its bounds are changed from outside this component. + function watchValue(value: number | undefined, unit: string, min: number | undefined, max: number | undefined) { // Don't update if the slider is currently being dragged (we don't want the backend fighting with the user's drag) if (rangeSliderClickDragState === "Dragging") return; @@ -381,6 +384,11 @@ return `${number}`; } + // Whether typed text ends in a unit (or a name), so no unit is assumed after it + function endsInUnit(typed: string): boolean { + return /[\p{L}%°'"]\s*$/u.test(typed); + } + // Removes the trailing "s" from a unit if the quantity is 1. function unPluralize(unit: string, quantity: number): string { if (quantity !== 1 || !unit.endsWith("s")) return unit; @@ -1002,6 +1010,9 @@ >{text.slice(markedDigit + 1)} {/if} + {#if ghostUnit} + {text}{ghostUnit} + {/if} {#if present} {#if mode === "Increment" && incrementBehavior !== "None"}