diff --git a/docs/specs/studio/13. JavaFX 2 Foundation Specification.md b/docs/specs/studio/13. JavaFX 2 Foundation Specification.md new file mode 100644 index 00000000..1af5c27c --- /dev/null +++ b/docs/specs/studio/13. JavaFX 2 Foundation Specification.md @@ -0,0 +1,49 @@ +# JavaFX 2 Foundation Specification + +Status: Implemented foundation. Owner: `studio`. + +## Scope and precedence + +This document governs `prometeu-studio-ui-javafx-2`, an independent replacement frontend foundation. It defines the minimal shell, presentation components, themes, localization and typography. It does not redefine Studio API/Core, MCP, asset banks or runtime contracts. + +The existing frontend and its launcher remain available. Specifications 1–4 continue to describe that frontend's current shell/components/workspaces; they are not a visual or architectural template for JavaFX 2. Later capabilities must extend the new foundation through their own explicit contracts. + +## Shell + +The default launch MUST show a native-decorated window with Studio identity, theme/language selectors and an empty central working area. Minimum outer window size is 680×480; the initial scene is 1200×800. Toolbar content MUST wrap/reflow instead of requiring horizontal scrolling at the supported minimum width. + +The shell MUST NOT initialize a game project, backend service graph, runtime or agent. It MUST NOT contain fictitious editor tabs, operations or domain panels. The component gallery is a separate developer launch, not a product workspace. + +## Presentation ownership + +An `AppearanceContext` owns presentation state and subscriptions for one window and MUST be closed when that window is hidden. A closed context MUST NOT accept updates. Reopening MUST construct a new context. Components MUST retain normal JavaFX semantics for keyboard, focus, editing and accessibility, while exposing Studio appearance and small APIs. + +Reusable families are text/title, decorative pixel icon, button, toggle, text field, non-editable selector, panel and message/progress feedback. Error appearance MUST have explanatory text. Text meaning MUST NOT depend on color alone. Custom geometry MUST NOT replace native interaction with a rasterized whole-window surface. + +## Themes and geometry + +The dark and light themes MUST provide matching semantic color tokens for background/workspace/surface/field, text/muted text, border, highlight/shadow, accent/on-accent, focus and error. Shared state styles MUST use those tokens. Theme changes MUST update active controls and selector popups in place without losing entered text. + +Stepped corners and layered relief are the foundation's visual direction. Region outlines MUST be recomputed at actual layout dimensions so corner steps do not grow with panel width. Main text MUST remain vector-rendered and independently scalable. Palette and geometry refinements MUST preserve legibility, interaction and the agreed identity. + +Normal text contrast targets are at least 4.5:1, large text 3:1, and necessary control/focus indicators 3:1. These are design/verification references, not an accessibility certification. + +## Fonts and configuration + +Departure Mono MUST be the default interior family; Roboto Mono MUST be available locally as an alternative. Both MUST ship with full SIL OFL 1.1 copyright and license notices. Loading MUST NOT require network access or preinstalled fonts. Font failure MUST diagnose and use a readable fallback. + +Family and text scale MUST be configurable through presentation settings, not hardcoded in consumers. Supported text scale is 75–200%, default 100%. The developer gallery exposes these choices and comparable editable text. This contract does not require a full preferences window or system-font manager. Native window decoration remains platform-owned. + +## Localization and persistence + +The UI MUST support pt-BR and English, including runtime labels, accessible names and feedback. English is the fallback bundle. A missing translation MUST diagnose and fall back; an unknown key MUST remain identifiable as `[key]`. Bundles MUST have matching key sets in verification. Formatting MUST use the active locale. Changing locale MUST preserve user-authored text. + +First launch MUST select dark, Departure Mono and 100% scale. A supported system locale selects pt-BR; otherwise English. Explicit choices MUST restore without a game project. Invalid individual preference values MUST fall back independently. Persistence MUST remain local presentation state, execute outside the FX thread and flush the latest selection on orderly close. It MUST NOT migrate or mutate the previous frontend's project-local state. + +## Verification and non-goals + +The foundation MUST have display-free tests of its own locale/preferences/resources/contracts and opt-in real desktop qualification. Desktop checks MUST identify environment/output scale, include normal/minimum sizes and inspect both themes, locales and fonts. Tests MUST exercise active popup appearance, focus/Tab, clipboard, state retention and close/reopen. Performance evidence MUST identify the measured operation; a CSS/layout measurement MUST NOT be presented as total frame latency. + +Initial qualification is on available macOS. Windows/Linux, assistive-technology walkthroughs and native IME composition require their own evidence. Logical scene snapshots MUST NOT be presented as proof of physical pixel alignment at every HiDPI scale. + +Project navigation, document host, free docking, ACP, asset workflows, code/LSP editor, scene/entity authoring, pixels/audio editing and Shipper are outside this foundation contract. Backend integrations MUST use existing application services when those features are introduced; domain logic MUST NOT be duplicated here. diff --git a/docs/specs/studio/README.md b/docs/specs/studio/README.md index 8e408d9e..423b4021 100644 --- a/docs/specs/studio/README.md +++ b/docs/specs/studio/README.md @@ -4,6 +4,16 @@ Owner: `studio`. Canonical source: `docs/specs/studio`. This directory contains the normative Studio specification set. +## JavaFX 2 foundation + +[`13. JavaFX 2 Foundation Specification.md`](13.%20JavaFX%202%20Foundation%20Specification.md) +defines the independent `prometeu-studio-ui-javafx-2` foundation and minimal shell. +Its [module guide](../../../prometeu-studio-ui-javafx-2/README.md) documents execution, +component ownership, themes, locales, bundled fonts and verification. The previous +frontend remains available; specifications 1–4 describe its existing behavior and +do not impose its visual structure on the new implementation. Backend contracts +remain shared and unchanged. + ## Purpose Specs define the official Studio contract. diff --git a/prometeu-studio-ui-javafx-2/README.md b/prometeu-studio-ui-javafx-2/README.md new file mode 100644 index 00000000..c48cc491 --- /dev/null +++ b/prometeu-studio-ui-javafx-2/README.md @@ -0,0 +1,68 @@ +# Studio JavaFX 2 foundation + +This independent frontend contains the Studio presentation foundation and a minimal native-decorated shell. It has no dependency on the previous frontend, Studio services, MCP, a game project or the runtime. The previous application's launcher remains unchanged. + +Requires Java 21 or later; Gradle selects Java 21 and JavaFX 23.0.2 for the module. + +From the Studio repository: + +```sh +./gradlew :prometeu-studio-ui-javafx-2:run +./gradlew :prometeu-studio-ui-javafx-2:gallery +``` + +The default shell contains identity, theme and language selectors and an empty central area. The **separate development gallery** demonstrates components, validation, progress, both fonts and configurable text scale. Its actions operate on sample text only. + +```sh +./gradlew :prometeu-studio-ui-javafx-2:test +./gradlew :prometeu-studio-ui-javafx-2:desktopTest +./gradlew :prometeu-studio-ui-javafx-2:installDist +``` + +`desktopTest` requires a desktop session and opens temporary windows. It exercises actual JavaFX behavior and writes PNG captures with environment metadata under `build/desktop-captures`. Normal unit tests do not require a display. Clipboard testing replaces clipboard content with a test string. Preference tests use an isolated disposable node rather than application preferences. + +The generated launcher is `build/install/prometeu-studio-ui-javafx-2/bin/prometeu-studio-ui-javafx-2`; pass `--gallery` to open the gallery. This development distribution uses an available Java installation, unlike the existing product installation's bundled runtime. + +## Components and ownership + +`AppearanceContext` belongs to one window. Construct it with initial `PresentationSettings`, loaded `Messages` and `FontResources`, and a persistence consumer. Attach it to the window root. Views own their children; the context owns their presentation subscriptions and removes them on `close()`. Do not reuse a closed context. Settings updates and composition run on the FX thread. + +| Component | Contract | +| --- | --- | +| `StudioText` | Localized label with wrapping and optional title role in the visual hierarchy. `setLabelFor` associates input labels. | +| `StudioIcon` | Decorative vector pixel mark; put meaningful names on the action or container that uses it. | +| `StudioButton` | Native Button actions, focus/default-button APIs and enabled/armed behavior; optional primary appearance. | +| `StudioToggle` | Native ToggleButton selection and accessibility. | +| `StudioTextField` | Native editing, clipboard and IME path; `setError` controls appearance and must accompany explanatory feedback. | +| `StudioSelect` | Native, non-editable ComboBox with localized cells, context-owned selection connection and themed popup. | +| `StudioPanel` | Resizable content frame with stepped vector geometry and layered bevel colors. | +| `StudioFeedback` | Localized parameterized message/error and optional determinate progress. | + +Fields retain their contents when theme, locale, typeface or scale changes. Geometry follows each Region's actual layout size, rather than stretching a low-resolution image. JavaFX native controls and skins retain interaction semantics; there is no all-Canvas widget toolkit. + +Semantic theme colors are in `styles/dark.css` and `styles/light.css`. Component geometry/state styles are in `styles/components.css`. `AppearanceContext` sets inherited family and size from the centralized presentation settings. There is no third-party control library in this slice. + +## Preferences and localization + +`UserSettingsStore` uses the Java Preferences node `p/studio/ui/javafx2` for theme, language, bundled typeface and text scale (75–200%). Startup uses dark, Departure Mono and 100%; a supported system locale chooses pt-BR, otherwise English. Invalid individual values fall back independently with diagnostics. + +Load preferences and font/bundle resources before composing views. `SettingsPersistence` debounces writes on its worker, flushes the last choice asynchronously on close, and shuts the worker down. It never writes from the FX thread. No project state or previous frontend preferences are migrated. + +All interface messages live in UTF-8 `messages_en.properties` and `messages_pt_BR.properties`. Missing translations diagnose and fall back to English; an absent English key displays `[key]`. Bundle parity is checked by unit tests. Dynamic feedback retains its key/arguments and is reformatted on locale changes; user-authored text retains its value. + +## Fonts and licenses + +- **Departure Mono 1.500**: default, monospaced pixel design. Source: `rektdeckard/departure-mono`, revision `75152a3f1e6dacdd248a6c397c97dbf27e33eea0`. +- **Roboto Mono Regular**: bundled alternative. Source: `googlefonts/RobotoMono`, revision `7bf0b33178844cc7d0c9915b746ece1be7f46bea`. + +Both font files load from local classpath resources. Their full copyright/SIL OFL 1.1 notices are under `src/main/resources/p/studio/ui/javafx2/fonts/*-LICENSE.txt`, inside the application jar and in the installed distribution's `licenses/` directory. No system font installation or network request is required. A failed font load diagnoses and uses Monospaced; JavaFX supplies fallback glyph rendering. + +The default 16.5 logical pixel size was checked on a macOS display reporting 2× output scale. Departure's 11 px grid does not guarantee pixel-perfect rendering at every fractional output/text scale. Alternative family/scale are presentation choices rather than fixed assumptions inside views. Future editors may choose their own documented text roles. + +## Validation boundaries + +Unit tests verify preference codecs/storage, asynchronous final persistence, locale fallback and bundle parity, font/license packaging and semantic contrast pairs. Desktop qualification exercises actual selectors/popups, dynamic feedback, clipboard, Tab traversal, input retention, both themes/locales/fonts, minimum width, repeated appearance changes and reopening with new contexts. + +The initial desktop target is macOS. Snapshot PNGs are logical scene captures; metadata records actual output scale, but these captures do not themselves prove physical-pixel sharpness at every scale. Windows/Linux, a screen-reader walkthrough and native multi-step IME input remain environment-specific manual qualification. Preserving JavaFX semantics is not a claim that those checks were completed. + +No project navigation, editor host, ACP, domain workspace, asset authoring, build/run/debug or shipping feature is implemented here. diff --git a/prometeu-studio-ui-javafx-2/build.gradle.kts b/prometeu-studio-ui-javafx-2/build.gradle.kts new file mode 100644 index 00000000..e802d887 --- /dev/null +++ b/prometeu-studio-ui-javafx-2/build.gradle.kts @@ -0,0 +1,46 @@ +plugins { + id("gradle.java-application-conventions") + alias(libs.plugins.javafx) +} + +javafx { + version = libs.versions.javafx.get() + modules("javafx.controls", "javafx.swing") +} + +application { + mainClass = "p.studio.ui.javafx2.StudioLauncher" +} + +distributions { + main { + contents { + from("src/main/resources/p/studio/ui/javafx2/fonts") { + include("*-LICENSE.txt") + into("licenses") + } + } + } +} + +tasks.register("gallery") { + group = "application" + description = "Opens the independent Studio component gallery, without a project or backend." + classpath = sourceSets["main"].runtimeClasspath + mainClass = application.mainClass + args("--gallery") +} + +tasks.named("test") { exclude("**/FoundationDesktopTest.class") } +tasks.register("desktopTest") { + group = "verification" + description = "Qualifies actual JavaFX windows and captures the foundation (requires a macOS desktop)." + testClassesDirs = sourceSets["test"].output.classesDirs + classpath = sourceSets["test"].runtimeClasspath + useJUnitPlatform() + include("**/FoundationDesktopTest.class") + systemProperty("java.awt.headless", "false") + systemProperty("studio.ui2.captureDir", layout.buildDirectory.dir("desktop-captures").get().asFile.absolutePath) + outputs.upToDateWhen { false } + testLogging.showStandardStreams = true +} diff --git a/prometeu-studio-ui-javafx-2/src/main/java/p/studio/ui/javafx2/StudioApplication.java b/prometeu-studio-ui-javafx-2/src/main/java/p/studio/ui/javafx2/StudioApplication.java new file mode 100644 index 00000000..ca56d984 --- /dev/null +++ b/prometeu-studio-ui-javafx-2/src/main/java/p/studio/ui/javafx2/StudioApplication.java @@ -0,0 +1,42 @@ +package p.studio.ui.javafx2; + +import javafx.application.Application; +import javafx.scene.Scene; +import javafx.scene.control.ScrollPane; +import javafx.scene.layout.VBox; +import javafx.stage.Stage; +import p.studio.ui.javafx2.appearance.*; +import p.studio.ui.javafx2.demo.ComponentGallery; +import p.studio.ui.javafx2.i18n.Messages; +import p.studio.ui.javafx2.preferences.*; +import p.studio.ui.javafx2.shell.MinimalShell; +import java.util.Locale; +import java.util.prefs.Preferences; + +public final class StudioApplication extends Application { + private PresentationSettings initial; + private FontResources fonts; + private Messages messages; + private SettingsPersistence persistence; + private AppearanceContext context; + @Override public void init() { + var store = new UserSettingsStore(Preferences.userRoot().node("p/studio/ui/javafx2"),Locale.getDefault(),System.err::println); + initial = store.load(); persistence = new SettingsPersistence(store); + fonts = FontResources.load(System.err::println); messages = Messages.load(System.err::println); + } + @Override public void start(Stage stage) { + context = new AppearanceContext(initial,messages,fonts,persistence::changed); + MinimalShell shell = new MinimalShell(context); + if (getParameters().getRaw().contains("--gallery")) { + shell.workspace().setMinHeight(160); shell.setMinHeight(340); + VBox content = new VBox(shell,new ComponentGallery(context)); context.attach(content); + content.setMinWidth(0); + ScrollPane scroll = new ScrollPane(content); scroll.setFitToWidth(true); context.attach(scroll); + stage.setScene(new Scene(scroll,1200,800)); + } else stage.setScene(new Scene(shell,1200,800)); + stage.setTitle("Prometeu Studio"); stage.setMinWidth(680); stage.setMinHeight(480); + stage.setOnHidden(event -> { context.close(); persistence.close(); }); + stage.show(); + } + @Override public void stop() { if (context != null) context.close(); if (persistence != null) persistence.close(); } +} diff --git a/prometeu-studio-ui-javafx-2/src/main/java/p/studio/ui/javafx2/StudioLauncher.java b/prometeu-studio-ui-javafx-2/src/main/java/p/studio/ui/javafx2/StudioLauncher.java new file mode 100644 index 00000000..e3b0e41a --- /dev/null +++ b/prometeu-studio-ui-javafx-2/src/main/java/p/studio/ui/javafx2/StudioLauncher.java @@ -0,0 +1,7 @@ +package p.studio.ui.javafx2; + +/** Plain launcher avoids the JDK's special JavaFX Application classpath launch path. */ +public final class StudioLauncher { + private StudioLauncher() { } + public static void main(String[] args) { javafx.application.Application.launch(StudioApplication.class,args); } +} diff --git a/prometeu-studio-ui-javafx-2/src/main/java/p/studio/ui/javafx2/appearance/AppearanceContext.java b/prometeu-studio-ui-javafx-2/src/main/java/p/studio/ui/javafx2/appearance/AppearanceContext.java new file mode 100644 index 00000000..c0e199da --- /dev/null +++ b/prometeu-studio-ui-javafx-2/src/main/java/p/studio/ui/javafx2/appearance/AppearanceContext.java @@ -0,0 +1,56 @@ +package p.studio.ui.javafx2.appearance; + +import javafx.beans.binding.Bindings; +import javafx.beans.value.ChangeListener; +import javafx.beans.property.*; +import javafx.scene.Parent; +import javafx.scene.control.Labeled; +import p.studio.ui.javafx2.i18n.Messages; +import java.util.*; +import java.util.function.Consumer; + +/** One window's presentation state. Must be accessed on the FX thread after construction. */ +public final class AppearanceContext implements AutoCloseable { + private final ObjectProperty settings; + private final Messages messages; + private final FontResources fonts; + private final Consumer persistence; + private final List cleanup = new ArrayList<>(); + private boolean closed; + public AppearanceContext(PresentationSettings initial, Messages messages, FontResources fonts, Consumer persistence) { + this.settings = new SimpleObjectProperty<>(initial); this.messages = messages; this.fonts = fonts; this.persistence = persistence; + } + public PresentationSettings settings() { return settings.get(); } + public ReadOnlyObjectProperty settingsProperty() { return settings; } + public void update(PresentationSettings value) { + if (closed) throw new IllegalStateException("Presentation context is closed"); + if (!settings.get().equals(value)) { settings.set(value); persistence.accept(value); } + } + public String text(String key, Object... arguments) { return messages.text(settings().language(), key, arguments); } + public String family(Typeface typeface) { return fonts.family(typeface); } + public void bindText(Labeled control, String key, Object... arguments) { + var binding = Bindings.createStringBinding(() -> text(key, arguments), settings); + control.textProperty().bind(binding); + onClose(() -> { control.textProperty().unbind(); binding.dispose(); }); + } + public void onClose(Runnable action) { if (closed) throw new IllegalStateException("Context closed"); cleanup.add(action); } + public void observe(Runnable action) { + ChangeListener listener = (observable, before, after) -> action.run(); + settings.addListener(listener); onClose(() -> settings.removeListener(listener)); action.run(); + } + public void attach(Parent root) { + if (!root.getStyleClass().contains("studio-root")) root.getStyleClass().add("studio-root"); + String common = resource("/p/studio/ui/javafx2/styles/components.css"); + observe(() -> { + root.getStylesheets().setAll(common, resource(settings().theme().stylesheet())); + root.setStyle("-fx-font-family: '" + family(settings().typeface()) + "'; -fx-font-size: " + (16.5 * settings().scale()) + "px;"); + }); + } + private static String resource(String path) { return Objects.requireNonNull(AppearanceContext.class.getResource(path), path).toExternalForm(); } + @Override public void close() { + if (closed) return; closed = true; + for (int i = cleanup.size() - 1; i >= 0; i--) cleanup.get(i).run(); + cleanup.clear(); + } + public boolean isClosed() { return closed; } +} diff --git a/prometeu-studio-ui-javafx-2/src/main/java/p/studio/ui/javafx2/appearance/FontResources.java b/prometeu-studio-ui-javafx-2/src/main/java/p/studio/ui/javafx2/appearance/FontResources.java new file mode 100644 index 00000000..925b219b --- /dev/null +++ b/prometeu-studio-ui-javafx-2/src/main/java/p/studio/ui/javafx2/appearance/FontResources.java @@ -0,0 +1,23 @@ +package p.studio.ui.javafx2.appearance; + +import javafx.scene.text.Font; +import java.util.*; +import java.util.function.Consumer; + +/** Load once before composing controls; the standard JavaFX text renderer retains glyph fallback. */ +public final class FontResources { + private final Map families; + private FontResources(Map families) { this.families = Map.copyOf(families); } + public static FontResources load(Consumer diagnostics) { + Map result = new EnumMap<>(Typeface.class); + for (Typeface typeface : Typeface.values()) { + try (var stream = FontResources.class.getResourceAsStream(typeface.resource())) { + Font font = stream == null ? null : Font.loadFont(stream, 16.5); + if (font == null) { diagnostics.accept("Cannot load " + typeface.family() + "; using Monospaced"); result.put(typeface, "Monospaced"); } + else result.put(typeface, font.getFamily()); + } catch (java.io.IOException ex) { diagnostics.accept("Font load failed: " + typeface.family()); result.put(typeface, "Monospaced"); } + } + return new FontResources(result); + } + public String family(Typeface typeface) { return families.get(typeface); } +} diff --git a/prometeu-studio-ui-javafx-2/src/main/java/p/studio/ui/javafx2/appearance/PresentationSettings.java b/prometeu-studio-ui-javafx-2/src/main/java/p/studio/ui/javafx2/appearance/PresentationSettings.java new file mode 100644 index 00000000..71836d21 --- /dev/null +++ b/prometeu-studio-ui-javafx-2/src/main/java/p/studio/ui/javafx2/appearance/PresentationSettings.java @@ -0,0 +1,19 @@ +package p.studio.ui.javafx2.appearance; + +import p.studio.ui.javafx2.i18n.StudioLanguage; +import java.util.Locale; +import java.util.Objects; + +public record PresentationSettings(Theme theme, StudioLanguage language, Typeface typeface, double scale) { + public PresentationSettings { + Objects.requireNonNull(theme); Objects.requireNonNull(language); Objects.requireNonNull(typeface); + if (!Double.isFinite(scale) || scale < 0.75 || scale > 2.0) throw new IllegalArgumentException("Scale must be between 0.75 and 2.0"); + } + public static PresentationSettings defaults(Locale locale) { + return new PresentationSettings(Theme.DARK, StudioLanguage.system(locale), Typeface.DEPARTURE, 1.0); + } + public PresentationSettings withTheme(Theme value) { return new PresentationSettings(value, language, typeface, scale); } + public PresentationSettings withLanguage(StudioLanguage value) { return new PresentationSettings(theme, value, typeface, scale); } + public PresentationSettings withTypeface(Typeface value) { return new PresentationSettings(theme, language, value, scale); } + public PresentationSettings withScale(double value) { return new PresentationSettings(theme, language, typeface, value); } +} diff --git a/prometeu-studio-ui-javafx-2/src/main/java/p/studio/ui/javafx2/appearance/Theme.java b/prometeu-studio-ui-javafx-2/src/main/java/p/studio/ui/javafx2/appearance/Theme.java new file mode 100644 index 00000000..a067e31e --- /dev/null +++ b/prometeu-studio-ui-javafx-2/src/main/java/p/studio/ui/javafx2/appearance/Theme.java @@ -0,0 +1,9 @@ +package p.studio.ui.javafx2.appearance; + +public enum Theme { + DARK("theme.dark"), LIGHT("theme.light"); + private final String label; + Theme(String label) { this.label = label; } + public String labelKey() { return label; } + public String stylesheet() { return "/p/studio/ui/javafx2/styles/" + name().toLowerCase(java.util.Locale.ROOT) + ".css"; } +} diff --git a/prometeu-studio-ui-javafx-2/src/main/java/p/studio/ui/javafx2/appearance/Typeface.java b/prometeu-studio-ui-javafx-2/src/main/java/p/studio/ui/javafx2/appearance/Typeface.java new file mode 100644 index 00000000..95176254 --- /dev/null +++ b/prometeu-studio-ui-javafx-2/src/main/java/p/studio/ui/javafx2/appearance/Typeface.java @@ -0,0 +1,11 @@ +package p.studio.ui.javafx2.appearance; + +public enum Typeface { + DEPARTURE("Departure Mono", "DepartureMono-1.500.otf"), + ROBOTO("Roboto Mono", "RobotoMono-Regular.otf"); + private final String family; + private final String resource; + Typeface(String family, String resource) { this.family = family; this.resource = resource; } + public String family() { return family; } + public String resource() { return "/p/studio/ui/javafx2/fonts/" + resource; } +} diff --git a/prometeu-studio-ui-javafx-2/src/main/java/p/studio/ui/javafx2/components/PixelGeometry.java b/prometeu-studio-ui-javafx-2/src/main/java/p/studio/ui/javafx2/components/PixelGeometry.java new file mode 100644 index 00000000..9fb33039 --- /dev/null +++ b/prometeu-studio-ui-javafx-2/src/main/java/p/studio/ui/javafx2/components/PixelGeometry.java @@ -0,0 +1,22 @@ +package p.studio.ui.javafx2.components; + +import javafx.scene.layout.Region; +import javafx.scene.shape.Polygon; + +/** Recomputes a vector outline at the actual layout size; corners do not stretch with panel width. */ +final class PixelGeometry { + private PixelGeometry() { } + static void apply(Region region) { + Polygon outline = new Polygon(); + region.setShape(outline); region.setScaleShape(false); region.setCenterShape(false); region.setPickOnBounds(true); + Runnable update = () -> { + double w = region.getWidth(), h = region.getHeight(), s = Math.min(4, Math.min(w,h)/6); + outline.getPoints().setAll(2*s,0., w-2*s,0., w-2*s,s, w-s,s, w-s,2*s, w,2*s, + w,h-2*s, w-s,h-2*s, w-s,h-s, w-2*s,h-s, w-2*s,h, 2*s,h, 2*s,h-s, + s,h-s, s,h-2*s, 0.,h-2*s, 0.,2*s, s,2*s, s,s, 2*s,s); + }; + region.widthProperty().addListener((o,b,a) -> update.run()); + region.heightProperty().addListener((o,b,a) -> update.run()); + update.run(); + } +} diff --git a/prometeu-studio-ui-javafx-2/src/main/java/p/studio/ui/javafx2/components/StudioButton.java b/prometeu-studio-ui-javafx-2/src/main/java/p/studio/ui/javafx2/components/StudioButton.java new file mode 100644 index 00000000..ffbad058 --- /dev/null +++ b/prometeu-studio-ui-javafx-2/src/main/java/p/studio/ui/javafx2/components/StudioButton.java @@ -0,0 +1,11 @@ +package p.studio.ui.javafx2.components; + +import javafx.scene.control.Button; +import p.studio.ui.javafx2.appearance.AppearanceContext; + +public final class StudioButton extends Button { + public StudioButton(AppearanceContext context, String key, boolean primary) { + getStyleClass().add("studio-button"); if (primary) getStyleClass().add("primary"); + context.bindText(this, key); PixelGeometry.apply(this); + } +} diff --git a/prometeu-studio-ui-javafx-2/src/main/java/p/studio/ui/javafx2/components/StudioFeedback.java b/prometeu-studio-ui-javafx-2/src/main/java/p/studio/ui/javafx2/components/StudioFeedback.java new file mode 100644 index 00000000..be550b86 --- /dev/null +++ b/prometeu-studio-ui-javafx-2/src/main/java/p/studio/ui/javafx2/components/StudioFeedback.java @@ -0,0 +1,44 @@ +package p.studio.ui.javafx2.components; + +import javafx.css.PseudoClass; +import javafx.scene.AccessibleRole; +import javafx.scene.AccessibleAttribute; +import javafx.scene.control.Label; +import javafx.scene.control.ProgressBar; +import javafx.scene.layout.VBox; +import javafx.scene.layout.HBox; +import javafx.scene.layout.Priority; +import p.studio.ui.javafx2.appearance.AppearanceContext; + +public final class StudioFeedback extends VBox { + private final Label message = new Label(); + private final ProgressBar progress = new ProgressBar(); + private final Label progressLabel = new Label(); + private final HBox progressRow = new HBox(12,progress,progressLabel); + private final AppearanceContext context; + private String key; + private Object[] arguments = new Object[0]; + public StudioFeedback(AppearanceContext context) { + this.context = context; getStyleClass().add("studio-feedback"); + message.getStyleClass().add("feedback-message"); + setSpacing(10); message.setWrapText(true); message.setAccessibleRole(AccessibleRole.TEXT); + progress.setMaxWidth(Double.MAX_VALUE); HBox.setHgrow(progress,Priority.ALWAYS); + progressRow.setAlignment(javafx.geometry.Pos.CENTER_LEFT); progressRow.setVisible(false); progressRow.setManaged(false); + getChildren().addAll(message,progressRow); + context.observe(() -> { if (key != null) message.setText(context.text(key,arguments)); updateProgressLabel(); }); + } + public void show(String key, boolean error, Object... arguments) { + this.key = key; this.arguments = arguments.clone(); + message.setText(context.text(key,arguments)); + pseudoClassStateChanged(PseudoClass.getPseudoClass("error"),error); + message.notifyAccessibleAttributeChanged(AccessibleAttribute.TEXT); + } + public void setProgress(double value) { + progress.setProgress(value); progressRow.setManaged(true); progressRow.setVisible(true); updateProgressLabel(); + } + private void updateProgressLabel() { + String label=progress.getProgress()<0?context.text("feedback.busy"):context.text("feedback.progress",progress.getProgress()); + progressLabel.setText(label);progress.setAccessibleText(label); + } + public String message() { return message.getText(); } +} diff --git a/prometeu-studio-ui-javafx-2/src/main/java/p/studio/ui/javafx2/components/StudioIcon.java b/prometeu-studio-ui-javafx-2/src/main/java/p/studio/ui/javafx2/components/StudioIcon.java new file mode 100644 index 00000000..17267991 --- /dev/null +++ b/prometeu-studio-ui-javafx-2/src/main/java/p/studio/ui/javafx2/components/StudioIcon.java @@ -0,0 +1,16 @@ +package p.studio.ui.javafx2.components; + +import javafx.scene.layout.Region; +import javafx.scene.shape.Rectangle; + +/** Decorative nine-cell Studio mark, rendered as vectors at the active output scale. */ +public final class StudioIcon extends Region { + public StudioIcon() { + getStyleClass().add("studio-icon"); setMouseTransparent(true); + setMinSize(24,24); setPrefSize(24,24); setMaxSize(24,24); + for (int i=0;i<9;i++) if (i!=4) { + Rectangle pixel = new Rectangle((i%3)*8, (i/3)*8, 6,6); + pixel.getStyleClass().add("studio-icon-pixel"); getChildren().add(pixel); + } + } +} diff --git a/prometeu-studio-ui-javafx-2/src/main/java/p/studio/ui/javafx2/components/StudioPanel.java b/prometeu-studio-ui-javafx-2/src/main/java/p/studio/ui/javafx2/components/StudioPanel.java new file mode 100644 index 00000000..66e1e325 --- /dev/null +++ b/prometeu-studio-ui-javafx-2/src/main/java/p/studio/ui/javafx2/components/StudioPanel.java @@ -0,0 +1,10 @@ +package p.studio.ui.javafx2.components; + +import javafx.scene.Node; +import javafx.scene.layout.StackPane; + +public final class StudioPanel extends StackPane { + public StudioPanel(Node... contents) { + super(contents); getStyleClass().add("studio-panel"); PixelGeometry.apply(this); + } +} diff --git a/prometeu-studio-ui-javafx-2/src/main/java/p/studio/ui/javafx2/components/StudioSelect.java b/prometeu-studio-ui-javafx-2/src/main/java/p/studio/ui/javafx2/components/StudioSelect.java new file mode 100644 index 00000000..ce703c1c --- /dev/null +++ b/prometeu-studio-ui-javafx-2/src/main/java/p/studio/ui/javafx2/components/StudioSelect.java @@ -0,0 +1,52 @@ +package p.studio.ui.javafx2.components; + +import javafx.scene.Parent; +import javafx.scene.control.*; +import javafx.scene.control.skin.ComboBoxListViewSkin; +import javafx.util.StringConverter; +import javafx.beans.binding.Bindings; +import p.studio.ui.javafx2.appearance.AppearanceContext; +import java.util.function.*; + +/** Native selection and keyboard behavior, with locale-aware cells and explicitly themed popup. */ +public final class StudioSelect extends ComboBox { + private final AppearanceContext context; + private final Function label; + @SafeVarargs public StudioSelect(AppearanceContext context, String accessibleKey, Function label, T... items) { + this.context = context; this.label = label; + getStyleClass().add("studio-select"); getItems().setAll(items); setMaxWidth(Double.MAX_VALUE); + setConverter(new StringConverter<>() { + @Override public String toString(T item) { return item == null ? "" : label.apply(item); } + @Override public T fromString(String value) { throw new UnsupportedOperationException("Read-only selector"); } + }); + setCellFactory(view -> localizedCell()); setButtonCell(localizedCell()); + PixelGeometry.apply(this); + context.observe(() -> { + setAccessibleText(context.text(accessibleKey)); + stylePopup(); + }); + setOnShowing(event -> stylePopup()); + context.onClose(() -> { hide(); setOnShowing(null); setOnAction(null); }); + } + private ListCell localizedCell() { + ListCell cell = new ListCell<>(); + // JavaFX bindings use weak dependency listeners, so discarded virtual cells are not retained by the context. + cell.textProperty().bind(Bindings.createStringBinding(() -> cell.isEmpty() || cell.getItem() == null ? "" : label.apply(cell.getItem()), + cell.itemProperty(),cell.emptyProperty(),context.settingsProperty())); + return cell; + } + private void stylePopup() { + if (getSkin() instanceof ComboBoxListViewSkin skin && skin.getPopupContent() instanceof Parent popup) { + // attach() installs a context listener, so attach once per actual skin popup. + if (!Boolean.TRUE.equals(popup.getProperties().get("studio.ui2.themed"))) { + popup.getProperties().put("studio.ui2.themed", true); context.attach(popup); + } + popup.applyCss(); + } + } + /** Connect selection to a presentation value; the owning context removes its subscription on close. */ + public void connect(Supplier current, Consumer update) { + context.observe(() -> setValue(current.get())); + setOnAction(event -> { T value = getValue(); if (value != null && !value.equals(current.get())) update.accept(value); }); + } +} diff --git a/prometeu-studio-ui-javafx-2/src/main/java/p/studio/ui/javafx2/components/StudioText.java b/prometeu-studio-ui-javafx-2/src/main/java/p/studio/ui/javafx2/components/StudioText.java new file mode 100644 index 00000000..1797d6a5 --- /dev/null +++ b/prometeu-studio-ui-javafx-2/src/main/java/p/studio/ui/javafx2/components/StudioText.java @@ -0,0 +1,11 @@ +package p.studio.ui.javafx2.components; + +import javafx.scene.control.Label; +import p.studio.ui.javafx2.appearance.AppearanceContext; + +public final class StudioText extends Label { + public StudioText(AppearanceContext context, String key) { + getStyleClass().add("studio-text"); context.bindText(this, key); setWrapText(true); + } + public StudioText title() { getStyleClass().add("studio-title"); return this; } +} diff --git a/prometeu-studio-ui-javafx-2/src/main/java/p/studio/ui/javafx2/components/StudioTextField.java b/prometeu-studio-ui-javafx-2/src/main/java/p/studio/ui/javafx2/components/StudioTextField.java new file mode 100644 index 00000000..60931dfa --- /dev/null +++ b/prometeu-studio-ui-javafx-2/src/main/java/p/studio/ui/javafx2/components/StudioTextField.java @@ -0,0 +1,10 @@ +package p.studio.ui.javafx2.components; + +import javafx.css.PseudoClass; +import javafx.scene.control.TextField; + +public final class StudioTextField extends TextField { + private static final PseudoClass ERROR = PseudoClass.getPseudoClass("error"); + public StudioTextField() { getStyleClass().add("studio-field"); PixelGeometry.apply(this); } + public void setError(boolean error) { pseudoClassStateChanged(ERROR, error); } +} diff --git a/prometeu-studio-ui-javafx-2/src/main/java/p/studio/ui/javafx2/components/StudioToggle.java b/prometeu-studio-ui-javafx-2/src/main/java/p/studio/ui/javafx2/components/StudioToggle.java new file mode 100644 index 00000000..539e34cc --- /dev/null +++ b/prometeu-studio-ui-javafx-2/src/main/java/p/studio/ui/javafx2/components/StudioToggle.java @@ -0,0 +1,10 @@ +package p.studio.ui.javafx2.components; + +import javafx.scene.control.ToggleButton; +import p.studio.ui.javafx2.appearance.AppearanceContext; + +public final class StudioToggle extends ToggleButton { + public StudioToggle(AppearanceContext context, String key) { + getStyleClass().add("studio-toggle"); context.bindText(this, key); PixelGeometry.apply(this); + } +} diff --git a/prometeu-studio-ui-javafx-2/src/main/java/p/studio/ui/javafx2/demo/ComponentGallery.java b/prometeu-studio-ui-javafx-2/src/main/java/p/studio/ui/javafx2/demo/ComponentGallery.java new file mode 100644 index 00000000..3d3e794a --- /dev/null +++ b/prometeu-studio-ui-javafx-2/src/main/java/p/studio/ui/javafx2/demo/ComponentGallery.java @@ -0,0 +1,58 @@ +package p.studio.ui.javafx2.demo; + +import javafx.scene.control.*; +import javafx.scene.layout.*; +import p.studio.ui.javafx2.appearance.*; +import p.studio.ui.javafx2.components.*; +import p.studio.ui.javafx2.shell.MinimalShell; + +/** Development-only specimens. This is a separate launch, never a product workspace. */ +public final class ComponentGallery extends VBox { + private final StudioTextField name = new StudioTextField(); + private final StudioFeedback feedback; + public ComponentGallery(AppearanceContext context) { + super(22); setMinWidth(0); getStyleClass().add("studio-gallery"); context.attach(this); + var typeface = new StudioSelect<>(context,"font.label",Typeface::family,Typeface.values()); + typeface.setId("font-select"); typeface.connect(() -> context.settings().typeface(), value -> context.update(context.settings().withTypeface(value))); + var scale = new StudioSelect<>(context,"scale.label",value -> context.text("scale.value",value),.75,1.,1.25,1.5,2.); + scale.setId("scale-select"); scale.connect(() -> context.settings().scale(), value -> context.update(context.settings().withScale(value))); + getChildren().add(new FlowPane(20,16,MinimalShell.labeled(context,"font.label",typeface),MinimalShell.labeled(context,"scale.label",scale))); + StudioButton apply = new StudioButton(context,"action.apply",true); apply.setId("apply"); + StudioButton reset = new StudioButton(context,"action.reset",false); reset.setId("reset"); + StudioButton disabled = new StudioButton(context,"action.unavailable",false); disabled.setDisable(true); + StudioToggle toggle = new StudioToggle(context,"toggle.enabled"); toggle.setSelected(true); + FlowPane buttons = new FlowPane(12,14,apply,reset,disabled,toggle); + name.setId("sample-name"); name.setText("Prometeu"); + context.observe(() -> name.setAccessibleText(context.text("field.name"))); + feedback = new StudioFeedback(context); feedback.setId("feedback"); feedback.setProgress(.6); + apply.setOnAction(event -> { boolean invalid = name.getText().isBlank(); name.setError(invalid); + feedback.show(invalid ? "feedback.required" : "feedback.applied",invalid,name.getText()); }); + reset.setOnAction(event -> { name.setText("Prometeu"); name.setError(false); feedback.show("feedback.reset",false); }); + VBox samples = new VBox(18,new StudioText(context,"components.title").title(),buttons,MinimalShell.labeled(context,"field.name",name),feedback); + StudioPanel panel = new StudioPanel(samples); panel.getStyleClass().add("specimen-panel"); getChildren().add(panel); + getChildren().add(new StudioText(context,"fonts.title").title()); + TextArea text = new TextArea(); text.setId("comparison-input"); text.setWrapText(true); text.setPrefRowCount(3); text.setMinWidth(0); + boolean[] updating = {false}; + context.observe(() -> { + updating[0] = true; + if (!Boolean.TRUE.equals(text.getProperties().get("edited"))) text.setText(context.text("fonts.sample")); + text.setAccessibleText(context.text("fonts.input")); updating[0] = false; + }); + text.textProperty().addListener((o,b,a) -> { if (!updating[0]) text.getProperties().put("edited",true); }); + getChildren().add(MinimalShell.labeled(context,"fonts.input",text)); + for (Typeface face : Typeface.values()) { + Label specimen = new Label(); specimen.setWrapText(true); specimen.textProperty().bind(text.textProperty()); + Label glyphs = new Label("Aa Bb · á à â ã é ê í ó ô õ ú ç\nIl1 O0 · 0123456789 · {} [] () <> != == + - * /"); glyphs.setWrapText(true); + context.observe(() -> { + String style = "-fx-font-family: '" + context.family(face) + "'; -fx-font-size: " + 16.5*context.settings().scale() + "px;"; + specimen.setStyle(style); glyphs.setStyle(style); + }); + context.onClose(() -> specimen.textProperty().unbind()); + VBox fontSample = new VBox(10,new Label(face.family()),specimen,glyphs); fontSample.getStyleClass().add("font-sample"); + getChildren().add(fontSample); + } + getChildren().add(new StudioText(context,"fonts.licenses")); + } + public StudioTextField nameField() { return name; } + public StudioFeedback feedback() { return feedback; } +} diff --git a/prometeu-studio-ui-javafx-2/src/main/java/p/studio/ui/javafx2/i18n/Messages.java b/prometeu-studio-ui-javafx-2/src/main/java/p/studio/ui/javafx2/i18n/Messages.java new file mode 100644 index 00000000..5e0303c8 --- /dev/null +++ b/prometeu-studio-ui-javafx-2/src/main/java/p/studio/ui/javafx2/i18n/Messages.java @@ -0,0 +1,36 @@ +package p.studio.ui.javafx2.i18n; + +import java.text.MessageFormat; +import java.util.*; +import java.util.function.Consumer; +import java.io.InputStreamReader; +import java.nio.charset.StandardCharsets; + +/** UTF-8 classpath bundles with explicit English fallback and observable missing keys. */ +public final class Messages { + private final Map> bundles; + private final Consumer diagnostics; + public Messages(Map> bundles, Consumer diagnostics) { + this.bundles = Map.copyOf(bundles); this.diagnostics = diagnostics; + } + public static Messages load(Consumer diagnostics) { + Map> bundles = new EnumMap<>(StudioLanguage.class); + for (StudioLanguage language : StudioLanguage.values()) { + String suffix = language == StudioLanguage.ENGLISH ? "en" : "pt_BR"; + String path = "/p/studio/ui/javafx2/i18n/messages_" + suffix + ".properties"; + Properties bundle = new Properties(); + try (var input = Objects.requireNonNull(Messages.class.getResourceAsStream(path), path); + var reader = new InputStreamReader(input, StandardCharsets.UTF_8)) { bundle.load(reader); } + catch (java.io.IOException ex) { throw new IllegalStateException("Cannot load " + path, ex); } + Map values = new HashMap<>(); bundle.forEach((key,value) -> values.put((String) key, (String) value)); + bundles.put(language, Map.copyOf(values)); + } + return new Messages(bundles, diagnostics); + } + public String text(StudioLanguage language, String key, Object... arguments) { + String pattern = bundles.getOrDefault(language, Map.of()).get(key); + if (pattern == null) { diagnostics.accept("Missing UI key " + language + ": " + key); pattern = bundles.getOrDefault(StudioLanguage.ENGLISH, Map.of()).get(key); } + return pattern == null ? "[" + key + "]" : new MessageFormat(pattern, language.locale()).format(arguments); + } + public Set keys(StudioLanguage language) { return bundles.getOrDefault(language, Map.of()).keySet(); } +} diff --git a/prometeu-studio-ui-javafx-2/src/main/java/p/studio/ui/javafx2/i18n/StudioLanguage.java b/prometeu-studio-ui-javafx-2/src/main/java/p/studio/ui/javafx2/i18n/StudioLanguage.java new file mode 100644 index 00000000..a8bf56a3 --- /dev/null +++ b/prometeu-studio-ui-javafx-2/src/main/java/p/studio/ui/javafx2/i18n/StudioLanguage.java @@ -0,0 +1,16 @@ +package p.studio.ui.javafx2.i18n; + +import java.util.Locale; + +public enum StudioLanguage { + PORTUGUESE("pt-BR", "Português (Brasil)"), ENGLISH("en", "English"); + private final String tag; + private final String label; + StudioLanguage(String tag, String label) { this.tag = tag; this.label = label; } + public Locale locale() { return Locale.forLanguageTag(tag); } + public String label() { return label; } + public static StudioLanguage system(Locale locale) { + return "pt".equals(locale.getLanguage()) && (locale.getCountry().isEmpty() || "BR".equals(locale.getCountry())) + ? PORTUGUESE : ENGLISH; + } +} diff --git a/prometeu-studio-ui-javafx-2/src/main/java/p/studio/ui/javafx2/preferences/SettingsPersistence.java b/prometeu-studio-ui-javafx-2/src/main/java/p/studio/ui/javafx2/preferences/SettingsPersistence.java new file mode 100644 index 00000000..2bd324fb --- /dev/null +++ b/prometeu-studio-ui-javafx-2/src/main/java/p/studio/ui/javafx2/preferences/SettingsPersistence.java @@ -0,0 +1,27 @@ +package p.studio.ui.javafx2.preferences; + +import p.studio.ui.javafx2.appearance.PresentationSettings; +import java.util.concurrent.*; + +/** Coalesces changes and flushes the latest value on close, always outside the FX thread. */ +public final class SettingsPersistence implements AutoCloseable { + private final ScheduledExecutorService worker = Executors.newSingleThreadScheduledExecutor(r -> new Thread(r, "studio-ui2-preferences")); + private final SettingsStore store; + private ScheduledFuture pending; + private PresentationSettings latest; + private boolean closed; + public SettingsPersistence(SettingsStore store) { this.store = store; } + public synchronized void changed(PresentationSettings settings) { + if (closed) return; + latest = settings; + if (pending != null) pending.cancel(false); + pending = worker.schedule(() -> store.save(settings), 180, TimeUnit.MILLISECONDS); + } + @Override public synchronized void close() { + if (closed) return; + closed = true; + if (pending != null) pending.cancel(false); + if (latest != null) { var snapshot = latest; worker.execute(() -> store.save(snapshot)); } + worker.shutdown(); + } +} diff --git a/prometeu-studio-ui-javafx-2/src/main/java/p/studio/ui/javafx2/preferences/SettingsStore.java b/prometeu-studio-ui-javafx-2/src/main/java/p/studio/ui/javafx2/preferences/SettingsStore.java new file mode 100644 index 00000000..a6af29ac --- /dev/null +++ b/prometeu-studio-ui-javafx-2/src/main/java/p/studio/ui/javafx2/preferences/SettingsStore.java @@ -0,0 +1,9 @@ +package p.studio.ui.javafx2.preferences; + +import p.studio.ui.javafx2.appearance.PresentationSettings; + +/** Called off the FX thread. Stores presentation preferences only, never project state. */ +public interface SettingsStore { + PresentationSettings load(); + void save(PresentationSettings settings); +} diff --git a/prometeu-studio-ui-javafx-2/src/main/java/p/studio/ui/javafx2/preferences/UserSettingsStore.java b/prometeu-studio-ui-javafx-2/src/main/java/p/studio/ui/javafx2/preferences/UserSettingsStore.java new file mode 100644 index 00000000..2afff106 --- /dev/null +++ b/prometeu-studio-ui-javafx-2/src/main/java/p/studio/ui/javafx2/preferences/UserSettingsStore.java @@ -0,0 +1,56 @@ +package p.studio.ui.javafx2.preferences; + +import p.studio.ui.javafx2.appearance.*; +import p.studio.ui.javafx2.i18n.StudioLanguage; +import java.util.Locale; +import java.util.Properties; +import java.util.prefs.Preferences; +import java.util.function.Consumer; + +/** The only preferences adapter. Its codec is independent of OS storage and JavaFX. */ +public final class UserSettingsStore implements SettingsStore { + private final Preferences node; + private final Locale systemLocale; + private final Consumer diagnostics; + public UserSettingsStore(Preferences node, Locale systemLocale, Consumer diagnostics) { + this.node = node; this.systemLocale = systemLocale; this.diagnostics = diagnostics; + } + @Override public PresentationSettings load() { + Properties values = new Properties(); + try { for (String key : new String[]{"theme", "language", "typeface", "scale"}) { + String value = node.get(key, null); if (value != null) values.setProperty(key, value); + }} catch (RuntimeException ex) { diagnostics.accept("Cannot read UI preferences: " + ex.getMessage()); } + return decode(values, systemLocale, diagnostics); + } + @Override public void save(PresentationSettings settings) { + try { + Properties values = encode(settings); + values.forEach((key, value) -> node.put((String) key, (String) value)); + node.flush(); + } catch (Exception ex) { diagnostics.accept("Cannot save UI preferences: " + ex.getMessage()); } + } + public static PresentationSettings decode(Properties values, Locale locale, Consumer diagnostics) { + PresentationSettings fallback = PresentationSettings.defaults(locale); + Theme theme = read(Theme.class, values.getProperty("theme"), fallback.theme(), diagnostics); + StudioLanguage language = read(StudioLanguage.class, values.getProperty("language"), fallback.language(), diagnostics); + Typeface typeface = read(Typeface.class, values.getProperty("typeface"), fallback.typeface(), diagnostics); + double scale = fallback.scale(); + if (values.containsKey("scale")) try { + double value = Double.parseDouble(values.getProperty("scale")); + if (!Double.isFinite(value) || value < .75 || value > 2) throw new IllegalArgumentException(); + scale = value; + } catch (RuntimeException ex) { diagnostics.accept("Invalid UI scale; using default"); } + return new PresentationSettings(theme, language, typeface, scale); + } + public static Properties encode(PresentationSettings settings) { + Properties values = new Properties(); + values.setProperty("theme", settings.theme().name()); values.setProperty("language", settings.language().name()); + values.setProperty("typeface", settings.typeface().name()); values.setProperty("scale", Double.toString(settings.scale())); + return values; + } + private static > T read(Class type, String value, T fallback, Consumer diagnostics) { + if (value == null) return fallback; + try { return Enum.valueOf(type, value); } + catch (IllegalArgumentException ex) { diagnostics.accept("Invalid preference " + type.getSimpleName() + "; using default"); return fallback; } + } +} diff --git a/prometeu-studio-ui-javafx-2/src/main/java/p/studio/ui/javafx2/shell/MinimalShell.java b/prometeu-studio-ui-javafx-2/src/main/java/p/studio/ui/javafx2/shell/MinimalShell.java new file mode 100644 index 00000000..b8fccff5 --- /dev/null +++ b/prometeu-studio-ui-javafx-2/src/main/java/p/studio/ui/javafx2/shell/MinimalShell.java @@ -0,0 +1,38 @@ +package p.studio.ui.javafx2.shell; + +import javafx.geometry.Pos; +import javafx.geometry.Insets; +import javafx.scene.Node; +import javafx.scene.control.Label; +import javafx.scene.layout.*; +import p.studio.ui.javafx2.appearance.*; +import p.studio.ui.javafx2.components.*; +import p.studio.ui.javafx2.i18n.StudioLanguage; + +/** The product shell deliberately contains only identity, presentation selectors and empty working space. */ +public final class MinimalShell extends BorderPane { + private final StudioPanel workspace = new StudioPanel(); + private final StudioSelect theme; + private final StudioSelect language; + public MinimalShell(AppearanceContext context) { + setId("studio-shell"); getStyleClass().add("studio-shell"); context.attach(this); + theme = new StudioSelect<>(context,"theme.label",item -> context.text(item.labelKey()),Theme.values()); + theme.setId("theme-select"); theme.connect(() -> context.settings().theme(), value -> context.update(context.settings().withTheme(value))); + language = new StudioSelect<>(context,"language.label",StudioLanguage::label,StudioLanguage.values()); + language.setId("language-select"); language.connect(() -> context.settings().language(), value -> context.update(context.settings().withLanguage(value))); + HBox identity = new HBox(12,new StudioIcon(),new StudioText(context,"brand").title()); identity.setAlignment(Pos.CENTER_LEFT); + FlowPane selectors = new FlowPane(18,14,labeled(context,"theme.label",theme),labeled(context,"language.label",language)); + selectors.setPrefWrapLength(680); + PresentationToolbar toolbar = new PresentationToolbar(identity,selectors); + setTop(toolbar); workspace.setId("empty-workspace"); workspace.getStyleClass().add("workspace"); + context.observe(() -> workspace.setAccessibleText(context.text("workspace.empty"))); + setMargin(workspace,new Insets(18,18,0,18)); setCenter(workspace); + } + public static VBox labeled(AppearanceContext context, String key, Node input) { + Label label = new StudioText(context,key); label.setLabelFor(input); + VBox box = new VBox(6,label,input); box.setFillWidth(true); return box; + } + public StudioPanel workspace() { return workspace; } + public StudioSelect themeSelector() { return theme; } + public StudioSelect languageSelector() { return language; } +} diff --git a/prometeu-studio-ui-javafx-2/src/main/java/p/studio/ui/javafx2/shell/PresentationToolbar.java b/prometeu-studio-ui-javafx-2/src/main/java/p/studio/ui/javafx2/shell/PresentationToolbar.java new file mode 100644 index 00000000..add6d6e2 --- /dev/null +++ b/prometeu-studio-ui-javafx-2/src/main/java/p/studio/ui/javafx2/shell/PresentationToolbar.java @@ -0,0 +1,40 @@ +package p.studio.ui.javafx2.shell; + +import javafx.scene.layout.Region; +import javafx.scene.layout.HBox; +import javafx.scene.layout.FlowPane; + +/** Places identity beside selectors when space permits, or above them at narrow widths. */ +final class PresentationToolbar extends Region { + private final HBox identity; + private final FlowPane selectors; + private static final double GAP=28, ROW_GAP=16; + PresentationToolbar(HBox identity,FlowPane selectors) { + this.identity=identity;this.selectors=selectors;getChildren().addAll(identity,selectors); + getStyleClass().add("studio-toolbar"); + } + @Override public javafx.geometry.Orientation getContentBias() { return javafx.geometry.Orientation.HORIZONTAL; } + @Override protected double computeMinWidth(double height) { + return snappedLeftInset()+snappedRightInset()+Math.max(identity.minWidth(-1),selectors.minWidth(-1)); + } + @Override protected double computePrefWidth(double height) { + return snappedLeftInset()+snappedRightInset()+identity.prefWidth(-1)+GAP+selectors.prefWidth(-1); + } + @Override protected double computePrefHeight(double width) { + double inner=width<0?computePrefWidth(-1):Math.max(0,width-snappedLeftInset()-snappedRightInset()); + double idWidth=identity.prefWidth(-1),idHeight=identity.prefHeight(idWidth); + boolean beside=inner>=idWidth+GAP+selectors.minWidth(-1); + double selectorHeight=selectors.prefHeight(beside?inner-idWidth-GAP:inner); + return snappedTopInset()+snappedBottomInset()+(beside?Math.max(idHeight,selectorHeight):idHeight+ROW_GAP+selectorHeight); + } + @Override protected void layoutChildren() { + double x=snappedLeftInset(),y=snappedTopInset(); + double inner=Math.max(0,getWidth()-x-snappedRightInset()); + double idWidth=identity.prefWidth(-1),idHeight=identity.prefHeight(idWidth); + boolean beside=inner>=idWidth+GAP+selectors.minWidth(-1); + double selectorWidth=beside?inner-idWidth-GAP:inner; + double selectorHeight=selectors.prefHeight(selectorWidth); + identity.resizeRelocate(x,y+(beside?Math.max(0,(selectorHeight-idHeight)/2):0),idWidth,idHeight); + selectors.resizeRelocate(beside?x+idWidth+GAP:x,beside?y:y+idHeight+ROW_GAP,selectorWidth,selectorHeight); + } +} diff --git a/prometeu-studio-ui-javafx-2/src/main/resources/p/studio/ui/javafx2/fonts/DepartureMono-1.500.otf b/prometeu-studio-ui-javafx-2/src/main/resources/p/studio/ui/javafx2/fonts/DepartureMono-1.500.otf new file mode 100644 index 00000000..e0b25021 Binary files /dev/null and b/prometeu-studio-ui-javafx-2/src/main/resources/p/studio/ui/javafx2/fonts/DepartureMono-1.500.otf differ diff --git a/prometeu-studio-ui-javafx-2/src/main/resources/p/studio/ui/javafx2/fonts/RobotoMono-Regular.otf b/prometeu-studio-ui-javafx-2/src/main/resources/p/studio/ui/javafx2/fonts/RobotoMono-Regular.otf new file mode 100644 index 00000000..f96054a8 Binary files /dev/null and b/prometeu-studio-ui-javafx-2/src/main/resources/p/studio/ui/javafx2/fonts/RobotoMono-Regular.otf differ diff --git a/prometeu-studio-ui-javafx-2/src/main/resources/p/studio/ui/javafx2/fonts/departure-mono-LICENSE.txt b/prometeu-studio-ui-javafx-2/src/main/resources/p/studio/ui/javafx2/fonts/departure-mono-LICENSE.txt new file mode 100644 index 00000000..de524761 --- /dev/null +++ b/prometeu-studio-ui-javafx-2/src/main/resources/p/studio/ui/javafx2/fonts/departure-mono-LICENSE.txt @@ -0,0 +1,93 @@ +Copyright 2022–2024 Helena Zhang (helenazhang.com). + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +https://openfontlicense.org + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/prometeu-studio-ui-javafx-2/src/main/resources/p/studio/ui/javafx2/fonts/roboto-mono-LICENSE.txt b/prometeu-studio-ui-javafx-2/src/main/resources/p/studio/ui/javafx2/fonts/roboto-mono-LICENSE.txt new file mode 100644 index 00000000..8e7df338 --- /dev/null +++ b/prometeu-studio-ui-javafx-2/src/main/resources/p/studio/ui/javafx2/fonts/roboto-mono-LICENSE.txt @@ -0,0 +1,93 @@ +Copyright 2015 The Roboto Mono Project Authors (https://github.com/googlefonts/robotomono) + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +https://openfontlicense.org + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/prometeu-studio-ui-javafx-2/src/main/resources/p/studio/ui/javafx2/i18n/messages_en.properties b/prometeu-studio-ui-javafx-2/src/main/resources/p/studio/ui/javafx2/i18n/messages_en.properties new file mode 100644 index 00000000..9feeacb8 --- /dev/null +++ b/prometeu-studio-ui-javafx-2/src/main/resources/p/studio/ui/javafx2/i18n/messages_en.properties @@ -0,0 +1,24 @@ +brand=prometeu studio +theme.label=Theme +theme.dark=Bananodore · dark +theme.light=Bananodore · light +language.label=Language +workspace.empty=Empty workspace +font.label=Typeface +scale.label=Text scale +scale.value={0,number,percent} +components.title=COMPONENTS · SPECIMENS +action.apply=Apply +action.reset=Reset +action.unavailable=Unavailable +toggle.enabled=Enabled +field.name=Name +feedback.required=Enter a name to test the action. +feedback.applied=Action demonstrated for: {0} +feedback.reset=Sample restored. +feedback.progress={0,number,percent} +feedback.busy=Working… +fonts.title=TEXT COMPARISON +fonts.input=Text to compare +fonts.sample=Creation starts with an idea. Organize your scenes, adjust the characters and bring the adventure to life. Action, music and imagination: you choose the next step. +fonts.licenses=Departure Mono and Roboto Mono · SIL Open Font License 1.1 · Full notices are bundled in the fonts resource directory. diff --git a/prometeu-studio-ui-javafx-2/src/main/resources/p/studio/ui/javafx2/i18n/messages_pt_BR.properties b/prometeu-studio-ui-javafx-2/src/main/resources/p/studio/ui/javafx2/i18n/messages_pt_BR.properties new file mode 100644 index 00000000..28311f82 --- /dev/null +++ b/prometeu-studio-ui-javafx-2/src/main/resources/p/studio/ui/javafx2/i18n/messages_pt_BR.properties @@ -0,0 +1,24 @@ +brand=prometeu studio +theme.label=Tema +theme.dark=Bananodore · escuro +theme.light=Bananodore · claro +language.label=Idioma +workspace.empty=Área central vazia +font.label=Tipografia +scale.label=Escala do texto +scale.value={0,number,percent} +components.title=COMPONENTES · AMOSTRAS +action.apply=Aplicar +action.reset=Restaurar +action.unavailable=Indisponível +toggle.enabled=Ativo +field.name=Nome +feedback.required=Informe um nome para testar a ação. +feedback.applied=Ação demonstrada para: {0} +feedback.reset=Amostra restaurada. +feedback.progress={0,number,percent} +feedback.busy=Em andamento… +fonts.title=COMPARAÇÃO DE TEXTO +fonts.input=Texto para comparar +fonts.sample=A criação começa com uma ideia. Organize suas cenas, ajuste os personagens e dê vida à aventura. Ação, música e imaginação: você escolhe o próximo passo. +fonts.licenses=Departure Mono e Roboto Mono · SIL Open Font License 1.1 · Avisos completos incluídos no diretório de recursos de fontes. diff --git a/prometeu-studio-ui-javafx-2/src/main/resources/p/studio/ui/javafx2/styles/components.css b/prometeu-studio-ui-javafx-2/src/main/resources/p/studio/ui/javafx2/styles/components.css new file mode 100644 index 00000000..1cfe4a42 --- /dev/null +++ b/prometeu-studio-ui-javafx-2/src/main/resources/p/studio/ui/javafx2/styles/components.css @@ -0,0 +1,76 @@ +/* Semantic colors are supplied by exactly one theme sheet. Typography is inherited from the window context. */ +.studio-root { + -fx-base: -studio-surface; + -fx-background: -studio-background; + -fx-control-inner-background: -studio-field; + -fx-accent: -studio-accent; + -fx-focus-color: -studio-focus; + -fx-faint-focus-color: transparent; + -fx-background-color: -studio-background; + -fx-text-background-color: -studio-text; + -fx-text-fill: -studio-text; +} +.studio-root .label { -fx-text-fill: -studio-text; } +.studio-title { -fx-font-size: 1.333em; } +.studio-toolbar { -fx-background-color: -studio-surface; -fx-padding: 22 24; -fx-border-color: -studio-border; -fx-border-width: 0 0 3 0; } +.studio-icon-pixel { -fx-fill: -studio-accent; } +.studio-panel { + -fx-background-color: -studio-border, -studio-shadow, -studio-highlight, -studio-surface; + -fx-background-insets: 0, 3, 3 6 6 3, 6; + -fx-padding: 20; +} +.studio-panel.workspace { + -fx-background-color: -studio-border, -studio-highlight, -studio-shadow, -studio-workspace; + -fx-background-insets: 0, 3, 3 6 6 3, 6; +} +.studio-shell { -fx-padding: 0 0 18 0; } +.studio-shell > .workspace { -fx-border-insets: 18; } +.studio-button, .studio-toggle { + -fx-background-color: -studio-border, -studio-shadow, -studio-highlight, -studio-surface; + -fx-background-insets: 0, 3, 3 6 6 3, 6; + -fx-text-fill: -studio-text; + -fx-padding: .75em 1.1em; + -fx-min-height: 44; + -fx-cursor: hand; +} +.studio-button:hover, .studio-toggle:hover { -fx-background-color: -studio-border, -studio-shadow, -studio-highlight, derive(-studio-surface, 15%); } +.studio-button.primary, .studio-toggle:selected { + -fx-background-color: -studio-border, -studio-on-accent, derive(-studio-accent, 30%), -studio-accent; + -fx-text-fill: -studio-on-accent; +} +.studio-button.primary:hover { -fx-background-color: -studio-border, -studio-on-accent, derive(-studio-accent, 40%), derive(-studio-accent, 8%); } +.studio-button:armed, .studio-toggle:armed { -fx-background-insets: 0, 3, 6 3 3 6, 6; } +.studio-button:disabled, .studio-toggle:disabled { -fx-opacity: .45; -fx-cursor: default; } +.studio-button:focused, .studio-toggle:focused { -fx-border-color: -studio-focus; -fx-border-width: 2; -fx-border-insets: -4; } +.studio-field, .studio-select { + -fx-background-color: -studio-border, -studio-shadow, -studio-field; + -fx-background-insets: 0, 3, 5; + -fx-text-fill: -studio-text; + -fx-prompt-text-fill: -studio-muted; + -fx-padding: .65em .8em; + -fx-min-height: 44; + -fx-highlight-fill: -studio-accent; + -fx-highlight-text-fill: -studio-on-accent; +} +.studio-field:focused, .studio-select:focused { -fx-border-color: -studio-focus; -fx-border-width: 2; -fx-border-insets: -4; } +.studio-field:error { -fx-background-color: -studio-error, -studio-shadow, -studio-field; } +.studio-select .list-cell { -fx-background-color: transparent; -fx-text-fill: -studio-text; -fx-padding: 0; } +.studio-select .arrow-button { -fx-background-color: transparent; -fx-padding: 0 0 0 12; } +.studio-select .arrow { -fx-background-color: -studio-text; } +.combo-box-popup .list-view, .list-view.studio-root { -fx-background-color: -studio-border, -studio-field; -fx-background-insets: 0, 2; -fx-padding: 4; } +.list-view.studio-root .list-cell { -fx-background-color: -studio-field; -fx-text-fill: -studio-text; -fx-padding: .7em .8em; } +.list-view.studio-root .list-cell:filled:hover { -fx-background-color: -studio-surface; } +.list-view.studio-root .list-cell:filled:selected { -fx-background-color: -studio-accent; -fx-text-fill: -studio-on-accent; } +.studio-gallery { -fx-padding: 24; } +.studio-gallery .studio-title { -fx-text-fill: -studio-heading; -fx-font-size: 1em; } +.studio-feedback .label { -fx-text-fill: -studio-muted; } +.studio-feedback:error .feedback-message { -fx-text-fill: -studio-error; } +.studio-feedback .progress-bar { -fx-accent: -studio-progress; -fx-min-height: 6; -fx-pref-height: 6; -fx-max-height: 6; } +.studio-feedback .progress-bar .bar { -fx-background-color: -studio-progress; -fx-background-radius: 0; -fx-background-insets: 0; } +.studio-feedback .progress-bar .track { -fx-background-color: -studio-field; -fx-background-radius: 0; -fx-background-insets: 0; } +.font-sample { -fx-padding: 18 0; -fx-border-color: -studio-border; -fx-border-width: 1 0 0 0; } +.studio-root .text-area { -fx-text-fill: -studio-text; -fx-background-color: -studio-border; -fx-background-radius: 0; -fx-padding: 2; } +.studio-root .text-area .content { -fx-background-color: -studio-field; -fx-background-radius: 0; } +.studio-root .scroll-pane, .studio-root .scroll-pane > .viewport { -fx-background-color: -studio-background; } +.studio-root .scroll-bar { -fx-background-color: -studio-background; } +.studio-root .scroll-bar .thumb { -fx-background-color: -studio-border; -fx-background-radius: 0; } diff --git a/prometeu-studio-ui-javafx-2/src/main/resources/p/studio/ui/javafx2/styles/dark.css b/prometeu-studio-ui-javafx-2/src/main/resources/p/studio/ui/javafx2/styles/dark.css new file mode 100644 index 00000000..8f60e86b --- /dev/null +++ b/prometeu-studio-ui-javafx-2/src/main/resources/p/studio/ui/javafx2/styles/dark.css @@ -0,0 +1,17 @@ +.root, .studio-root { + -studio-background: #1b1829; + -studio-workspace: #201c2e; + -studio-surface: #2d263e; + -studio-field: #221d30; + -studio-text: #f5efdf; + -studio-muted: #c0b4d0; + -studio-border: #8b7aab; + -studio-highlight: #a998c9; + -studio-shadow: #100e19; + -studio-accent: #edce62; + -studio-on-accent: #2c2315; + -studio-focus: #a9c8ff; + -studio-error: #ffa6a1; + -studio-heading: #edce62; + -studio-progress: #edce62; +} diff --git a/prometeu-studio-ui-javafx-2/src/main/resources/p/studio/ui/javafx2/styles/light.css b/prometeu-studio-ui-javafx-2/src/main/resources/p/studio/ui/javafx2/styles/light.css new file mode 100644 index 00000000..5ebe3ef6 --- /dev/null +++ b/prometeu-studio-ui-javafx-2/src/main/resources/p/studio/ui/javafx2/styles/light.css @@ -0,0 +1,17 @@ +.root, .studio-root { + -studio-background: #e5dfcf; + -studio-workspace: #faf6eb; + -studio-surface: #f1ebdc; + -studio-field: #fffaf0; + -studio-text: #302a3b; + -studio-muted: #5e536c; + -studio-border: #807057; + -studio-highlight: #fffdf4; + -studio-shadow: #81715b; + -studio-accent: #d5b24b; + -studio-on-accent: #261e11; + -studio-focus: #4942a6; + -studio-error: #9c2925; + -studio-heading: #4942a6; + -studio-progress: #4942a6; +} diff --git a/prometeu-studio-ui-javafx-2/src/test/java/p/studio/ui/javafx2/FoundationDesktopTest.java b/prometeu-studio-ui-javafx-2/src/test/java/p/studio/ui/javafx2/FoundationDesktopTest.java new file mode 100644 index 00000000..82ebd2e1 --- /dev/null +++ b/prometeu-studio-ui-javafx-2/src/test/java/p/studio/ui/javafx2/FoundationDesktopTest.java @@ -0,0 +1,149 @@ +package p.studio.ui.javafx2; + +import javafx.application.Platform; +import javafx.animation.AnimationTimer; +import javafx.embed.swing.SwingFXUtils; +import javafx.event.Event; +import javafx.scene.*; +import javafx.scene.control.*; +import javafx.scene.control.skin.ComboBoxListViewSkin; +import javafx.scene.image.WritableImage; +import javafx.scene.input.KeyCode; +import javafx.scene.input.KeyEvent; +import javafx.scene.layout.VBox; +import javafx.scene.paint.Color; +import javafx.stage.Stage; +import org.junit.jupiter.api.*; +import p.studio.ui.javafx2.appearance.*; +import p.studio.ui.javafx2.components.*; +import p.studio.ui.javafx2.demo.ComponentGallery; +import p.studio.ui.javafx2.i18n.*; +import p.studio.ui.javafx2.shell.MinimalShell; +import javax.imageio.ImageIO; +import java.nio.file.*; +import java.util.*; +import java.util.concurrent.*; +import static org.junit.jupiter.api.Assertions.*; + +/** Opt-in real toolkit contract tests. No backend, game project, or personal preference writes. */ +class FoundationDesktopTest { + private static FontResources fonts; + private static Messages messages; + private static Path captures; + private record Window(Stage stage,AppearanceContext context,MinimalShell shell,ComponentGallery gallery) { } + @BeforeAll static void startToolkit() throws Exception { + CountDownLatch ready=new CountDownLatch(1); + Platform.startup(ready::countDown); assertTrue(ready.await(15,TimeUnit.SECONDS)); + Platform.setImplicitExit(false); + fonts=fx(() -> FontResources.load(s -> fail(s))); messages=Messages.load(s -> fail(s)); + captures=Path.of(System.getProperty("studio.ui2.captureDir")); Files.createDirectories(captures); + } + @AfterAll static void stopToolkit() { Platform.exit(); } + @Test void shellGalleryStateThemesLocalesFontsAndLifecycle() throws Exception { + Window window=fx(() -> open(true)); + try { + fx(() -> { + assertTrue(window.shell.workspace().getChildren().isEmpty()); + assertEquals("Departure Mono",fonts.family(Typeface.DEPARTURE)); + assertEquals("Roboto Mono",fonts.family(Typeface.ROBOTO)); + assertEquals("São João · 0123",typeAndCopy(window.gallery.nameField(),"São João · 0123")); + ((Button)window.stage.getScene().lookup("#apply")).fire(); + assertTrue(window.gallery.feedback().message().contains("São João")); + window.context.update(window.context.settings().withLanguage(StudioLanguage.PORTUGUESE)); + assertTrue(window.gallery.feedback().message().startsWith("Ação")); + assertEquals("São João · 0123",window.gallery.nameField().getText()); + window.gallery.nameField().setText(""); ((Button)window.stage.getScene().lookup("#apply")).fire(); + assertTrue(window.gallery.feedback().message().startsWith("Informe")); + assertTrue(window.gallery.nameField().getPseudoClassStates().stream().anyMatch(p -> p.getPseudoClassName().equals("error"))); + return null; + }); + for(Theme theme:Theme.values()) for(StudioLanguage language:StudioLanguage.values()) for(Typeface face:Typeface.values()) { + fx(() -> {window.context.update(new PresentationSettings(theme,language,face,1));window.stage.getScene().getRoot().applyCss();window.stage.getScene().getRoot().layout();return null;}); + capture(window,theme+"-"+language+"-"+face); + } + fx(() -> { + window.shell.themeSelector().show(); + var popup=(Parent)((ComboBoxListViewSkin)window.shell.themeSelector().getSkin()).getPopupContent(); + popup.applyCss(); + assertTrue(popup.getStyleClass().contains("studio-root")); + assertTrue(popup.getStylesheets().stream().anyMatch(value -> value.endsWith("light.css"))); + window.context.update(window.context.settings().withLanguage(StudioLanguage.ENGLISH)); popup.applyCss();popup.layout(); + assertTrue(popup.lookupAll(".list-cell").stream().filter(node -> node instanceof ListCell).map(node -> ((ListCell)node).getText()).anyMatch("Bananodore · dark"::equals),"An already open popup must translate"); + window.shell.themeSelector().hide(); + window.shell.themeSelector().requestFocus(); + Event.fireEvent(window.shell.themeSelector(),new KeyEvent(KeyEvent.KEY_PRESSED,"","",KeyCode.TAB,false,false,false,false)); + assertSame(window.shell.languageSelector(),window.stage.getScene().getFocusOwner(),"Tab must move from theme to language selector"); + window.context.update(window.context.settings().withScale(1.5)); + assertEquals("Roboto Mono",window.gallery.nameField().getFont().getFamily()); + return null; + }); + long duration=fx(() -> { + long begin=System.nanoTime(); + for(int i=0;i<20;i++) { + window.context.update(new PresentationSettings(i%2==0?Theme.DARK:Theme.LIGHT,i%2==0?StudioLanguage.ENGLISH:StudioLanguage.PORTUGUESE,i%2==0?Typeface.DEPARTURE:Typeface.ROBOTO,1)); + window.stage.getScene().getRoot().applyCss();window.stage.getScene().getRoot().layout(); + } + return System.nanoTime()-begin; + }); + double averageMillis=duration/20_000_000.; + System.out.println("20 appearance changes, average FX CSS/layout ms="+averageMillis); + assertTrue(averageMillis<250,"Appearance update exceeds 250ms average budget"); + fx(() -> {window.stage.setWidth(680);window.stage.setHeight(480);return null;}); + capture(window,"minimum-680x480"); + fx(() -> { + var scroll=(ScrollPane)window.stage.getScene().getRoot(); + assertTrue(scroll.getContent().getLayoutBounds().getWidth() <= scroll.getViewportBounds().getWidth()+1,"Minimum width must not cause horizontal overflow"); + return null; + }); + fx(() -> {((ScrollPane)window.stage.getScene().getRoot()).setVvalue(1);return null;}); + capture(window,"fonts-and-licenses"); + } finally { fx(() -> {window.stage.close();assertTrue(window.context.isClosed());return null;}); } + for(int i=0;i<3;i++) { + Window reopened=fx(() -> open(false)); + if(i==0){ + capture(reopened,"shell-dark-default"); + fx(() -> {reopened.stage.setWidth(680);reopened.stage.setHeight(480);return null;}); + capture(reopened,"shell-minimum-680x480"); + fx(() -> {assertTrue(reopened.shell.workspace().getHeight()>80);return null;}); + } + fx(() -> {assertTrue(reopened.shell.workspace().getChildren().isEmpty());reopened.stage.close();assertTrue(reopened.context.isClosed());assertThrows(IllegalStateException.class,() -> reopened.context.update(reopened.context.settings().withTheme(Theme.LIGHT)));return null;}); + } + } + private static Window open(boolean gallery) { + var context=new AppearanceContext(PresentationSettings.defaults(Locale.ENGLISH),messages,fonts,value -> { }); + var shell=new MinimalShell(context); ComponentGallery specimens=gallery?new ComponentGallery(context):null; + Stage stage=new Stage(); Parent root=shell; + if(gallery) { + shell.setMinHeight(340); shell.workspace().setMinHeight(160); + VBox content=new VBox(shell,specimens); content.setMinWidth(0); context.attach(content); + ScrollPane scroll=new ScrollPane(content);scroll.setFitToWidth(true);context.attach(scroll);root=scroll; + } + stage.setScene(new Scene(root,1200,800));stage.setMinWidth(680);stage.setMinHeight(480);stage.setTitle("Prometeu Studio — desktop qualification"); + stage.setOnHidden(event -> context.close());stage.show();root.applyCss();root.layout(); + return new Window(stage,context,shell,specimens); + } + private static String typeAndCopy(TextField field,String text) { + field.requestFocus();field.setText(text);field.selectAll();field.copy();field.clear();field.paste();return field.getText(); + } + private static void capture(Window window,String name) throws Exception { + settleFrames(); + record Capture(WritableImage image,String metadata) { } + Capture captured=fx(() -> { + window.stage.getScene().getRoot().applyCss();window.stage.getScene().getRoot().layout(); + WritableImage image=window.stage.getScene().snapshot(null); + String metadata="os="+System.getProperty("os.name")+" "+System.getProperty("os.version")+"\njava="+System.getProperty("java.version")+"\noutputScale="+window.stage.getOutputScaleX()+"x"+window.stage.getOutputScaleY()+"\nsettings="+window.context.settings()+"\nscene="+window.stage.getScene().getWidth()+"x"+window.stage.getScene().getHeight()+"\nimage="+image.getWidth()+"x"+image.getHeight()+"\n"; + assertEquals(window.stage.getScene().getWidth(),image.getWidth(),1); + return new Capture(image,metadata); + }); + ImageIO.write(SwingFXUtils.fromFXImage(captured.image(),null),"png",captures.resolve(name+".png").toFile()); + Files.writeString(captures.resolve(name+".txt"),captured.metadata()); + } + private static void settleFrames() throws Exception { + CountDownLatch settled=new CountDownLatch(1); + fx(() -> {new AnimationTimer(){int count;@Override public void handle(long now){if(++count==3){stop();settled.countDown();}}}.start();return null;}); + assertTrue(settled.await(5,TimeUnit.SECONDS),"JavaFX pulses did not settle"); + } + private static T fx(Callable task) throws Exception { + FutureTask future=new FutureTask<>(task);Platform.runLater(future);return future.get(30,TimeUnit.SECONDS); + } +} diff --git a/prometeu-studio-ui-javafx-2/src/test/java/p/studio/ui/javafx2/FoundationResourcesTest.java b/prometeu-studio-ui-javafx-2/src/test/java/p/studio/ui/javafx2/FoundationResourcesTest.java new file mode 100644 index 00000000..2a8d7595 --- /dev/null +++ b/prometeu-studio-ui-javafx-2/src/test/java/p/studio/ui/javafx2/FoundationResourcesTest.java @@ -0,0 +1,49 @@ +package p.studio.ui.javafx2; + +import org.junit.jupiter.api.Test; +import p.studio.ui.javafx2.appearance.*; +import java.nio.charset.StandardCharsets; +import java.util.*; +import java.util.regex.*; +import static org.junit.jupiter.api.Assertions.*; + +class FoundationResourcesTest { + @Test void fontsAndFullNoticesAreAvailableWithoutNetwork() throws Exception { + for (Typeface face:Typeface.values()) try (var input=getClass().getResourceAsStream(face.resource())) { + assertNotNull(input,face.resource()); assertEquals("OTTO",new String(input.readNBytes(4),StandardCharsets.US_ASCII)); + } + for (String license:List.of("departure-mono-LICENSE.txt","roboto-mono-LICENSE.txt")) try (var input=getClass().getResourceAsStream("/p/studio/ui/javafx2/fonts/"+license)) { + assertNotNull(input); String text=new String(input.readAllBytes(),StandardCharsets.UTF_8); + assertTrue(text.contains("Copyright")); assertTrue(text.contains("SIL OPEN FONT LICENSE Version 1.1")); + } + } + @Test void bothThemeTokenSetsMatchAndMeetRequiredContrastPairs() throws Exception { + Map dark=tokens(Theme.DARK),light=tokens(Theme.LIGHT); + assertEquals(dark.keySet(),light.keySet()); + for (Map theme:List.of(dark,light)) { + for (String background:List.of("background","workspace","surface","field")) { + assertTrue(contrast(theme.get("text"),theme.get(background))>=4.5,background+" text contrast"); + assertTrue(contrast(theme.get("focus"),theme.get(background))>=3,background+" focus contrast"); + assertTrue(contrast(theme.get("border"),theme.get(background))>=3,background+" border contrast"); + } + assertTrue(contrast(theme.get("on-accent"),theme.get("accent"))>=4.5); + assertTrue(contrast(theme.get("error"),theme.get("surface"))>=4.5); + assertTrue(contrast(theme.get("heading"),theme.get("surface"))>=4.5); + assertTrue(contrast(theme.get("progress"),theme.get("field"))>=3); + } + } + private Map tokens(Theme theme) throws Exception { + try(var stream=getClass().getResourceAsStream(theme.stylesheet())) { + assertNotNull(stream); String css=new String(stream.readAllBytes(),StandardCharsets.UTF_8); + Matcher matcher=Pattern.compile("-studio-([a-z-]+):\\s*(#[0-9a-fA-F]{6})").matcher(css); + Map values=new HashMap<>(); while(matcher.find())values.put(matcher.group(1),matcher.group(2)); return values; + } + } + private double contrast(String first,String second) { double a=luminance(first),b=luminance(second); return (Math.max(a,b)+.05)/(Math.min(a,b)+.05); } + private double luminance(String hex) { + int color=Integer.parseInt(hex.substring(1),16); double result=0; + double[] weights={.2126,.7152,.0722}; + for(int i=0;i<3;i++){double channel=((color>>(16-8*i))&255)/255.;result+=weights[i]*(channel<=.04045?channel/12.92:Math.pow((channel+.055)/1.055,2.4));} + return result; + } +} diff --git a/prometeu-studio-ui-javafx-2/src/test/java/p/studio/ui/javafx2/PresentationContractTest.java b/prometeu-studio-ui-javafx-2/src/test/java/p/studio/ui/javafx2/PresentationContractTest.java new file mode 100644 index 00000000..eab2aec3 --- /dev/null +++ b/prometeu-studio-ui-javafx-2/src/test/java/p/studio/ui/javafx2/PresentationContractTest.java @@ -0,0 +1,68 @@ +package p.studio.ui.javafx2; + +import org.junit.jupiter.api.Test; +import p.studio.ui.javafx2.appearance.*; +import p.studio.ui.javafx2.i18n.*; +import p.studio.ui.javafx2.preferences.*; +import java.util.*; +import java.util.concurrent.*; +import static org.junit.jupiter.api.Assertions.*; + +class PresentationContractTest { + @Test void preferencesRoundTripAndInvalidValuesRetainOtherChoices() { + var chosen = new PresentationSettings(Theme.LIGHT,StudioLanguage.PORTUGUESE,Typeface.ROBOTO,1.5); + assertEquals(chosen,UserSettingsStore.decode(UserSettingsStore.encode(chosen),Locale.ENGLISH,s -> fail(s))); + Properties values = UserSettingsStore.encode(chosen); + values.setProperty("theme","missing"); values.setProperty("scale","NaN"); + List diagnostics = new ArrayList<>(); + var restored = UserSettingsStore.decode(values,Locale.ENGLISH,diagnostics::add); + assertEquals(Theme.DARK,restored.theme()); assertEquals(1.,restored.scale()); + assertEquals(Typeface.ROBOTO,restored.typeface()); assertEquals(StudioLanguage.PORTUGUESE,restored.language()); + assertEquals(2,diagnostics.size()); + assertThrows(IllegalArgumentException.class,() -> chosen.withScale(Double.POSITIVE_INFINITY)); + } + @Test void firstLaunchHasDeterministicDefaults() { + assertEquals(StudioLanguage.PORTUGUESE,PresentationSettings.defaults(Locale.forLanguageTag("pt-BR")).language()); + assertEquals(StudioLanguage.ENGLISH,PresentationSettings.defaults(Locale.JAPAN).language()); + assertEquals(Typeface.DEPARTURE,PresentationSettings.defaults(Locale.ENGLISH).typeface()); + } + @Test void realPreferenceAdapterRestoresANewInstanceWithoutTouchingUserChoices() throws Exception { + var node=java.util.prefs.Preferences.userRoot().node("p/studio/ui/javafx2-tests/"+UUID.randomUUID()); + try { + var chosen=new PresentationSettings(Theme.LIGHT,StudioLanguage.PORTUGUESE,Typeface.ROBOTO,1.25); + new UserSettingsStore(node,Locale.ENGLISH,s -> fail(s)).save(chosen); + assertEquals(chosen,new UserSettingsStore(node,Locale.JAPAN,s -> fail(s)).load()); + node.put("scale","corrupt"); + assertEquals(1.,new UserSettingsStore(node,Locale.ENGLISH,s -> {}).load().scale()); + } finally { node.removeNode(); java.util.prefs.Preferences.userRoot().flush(); } + } + @Test void bundlesHaveParityAndDynamicMessagesUseTheirLocale() { + var messages = Messages.load(s -> fail(s)); + assertFalse(messages.keys(StudioLanguage.ENGLISH).isEmpty()); + assertEquals(messages.keys(StudioLanguage.ENGLISH),messages.keys(StudioLanguage.PORTUGUESE)); + assertEquals("Ação demonstrada para: São João",messages.text(StudioLanguage.PORTUGUESE,"feedback.applied","São João")); + assertTrue(messages.text(StudioLanguage.PORTUGUESE,"scale.value",1.25).contains("125")); + assertEquals("Apply",messages.text(StudioLanguage.ENGLISH,"action.apply")); + } + @Test void absentTranslationFallsBackButReportsTheMissingKey() { + List diagnostics = new ArrayList<>(); + var messages = new Messages(Map.of(StudioLanguage.ENGLISH,Map.of("present","Value {0}"),StudioLanguage.PORTUGUESE,Map.of()),diagnostics::add); + assertEquals("Value 7",messages.text(StudioLanguage.PORTUGUESE,"present",7)); + assertEquals("[absent]",messages.text(StudioLanguage.PORTUGUESE,"absent")); + assertEquals(2,diagnostics.size()); + } + @Test void persistenceCoalescesAndFlushesTheLatestChoiceOffTheCallerThread() throws Exception { + CountDownLatch saved = new CountDownLatch(1); + List writes = new CopyOnWriteArrayList<>(); + Thread caller = Thread.currentThread(); + var settings = PresentationSettings.defaults(Locale.ENGLISH); + SettingsStore store = new SettingsStore() { + public PresentationSettings load() { return settings; } + public void save(PresentationSettings value) { assertNotSame(caller,Thread.currentThread()); writes.add(value); saved.countDown(); } + }; + var persistence = new SettingsPersistence(store); + persistence.changed(settings); persistence.changed(settings.withTheme(Theme.LIGHT)); persistence.close(); persistence.close(); + assertTrue(saved.await(5,TimeUnit.SECONDS)); + assertEquals(settings.withTheme(Theme.LIGHT),writes.getLast()); + } +} diff --git a/settings.gradle.kts b/settings.gradle.kts index dfa9a555..2485eaba 100644 --- a/settings.gradle.kts +++ b/settings.gradle.kts @@ -23,6 +23,7 @@ include("prometeu-compiler:prometeu-frontend-registry") include("prometeu-studio-api") include("prometeu-studio-core") include("prometeu-studio-ui-javafx") +include("prometeu-studio-ui-javafx-2") include("prometeu-app")