feat(studio): add JavaFX 2 foundation and minimal shell
Test / Tests and coverage
Intrepid/Prometeu/Studio/pipeline/head This commit looks good

This commit is contained in:
2026-11-18 09:39:42 +00:00
parent fa37d0d0c7
commit 1e17fc4d67
41 changed files with 1417 additions and 0 deletions
@@ -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(); }
}
@@ -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); }
}
@@ -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<PresentationSettings> settings;
private final Messages messages;
private final FontResources fonts;
private final Consumer<PresentationSettings> persistence;
private final List<Runnable> cleanup = new ArrayList<>();
private boolean closed;
public AppearanceContext(PresentationSettings initial, Messages messages, FontResources fonts, Consumer<PresentationSettings> persistence) {
this.settings = new SimpleObjectProperty<>(initial); this.messages = messages; this.fonts = fonts; this.persistence = persistence;
}
public PresentationSettings settings() { return settings.get(); }
public ReadOnlyObjectProperty<PresentationSettings> 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<PresentationSettings> 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; }
}
@@ -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<Typeface,String> families;
private FontResources(Map<Typeface,String> families) { this.families = Map.copyOf(families); }
public static FontResources load(Consumer<String> diagnostics) {
Map<Typeface,String> 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); }
}
@@ -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); }
}
@@ -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"; }
}
@@ -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; }
}
@@ -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();
}
}
@@ -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);
}
}
@@ -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(); }
}
@@ -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);
}
}
}
@@ -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);
}
}
@@ -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<T> extends ComboBox<T> {
private final AppearanceContext context;
private final Function<T,String> label;
@SafeVarargs public StudioSelect(AppearanceContext context, String accessibleKey, Function<T,String> 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<T> localizedCell() {
ListCell<T> 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<T> current, Consumer<T> update) {
context.observe(() -> setValue(current.get()));
setOnAction(event -> { T value = getValue(); if (value != null && !value.equals(current.get())) update.accept(value); });
}
}
@@ -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; }
}
@@ -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); }
}
@@ -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);
}
}
@@ -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; }
}
@@ -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<StudioLanguage, Map<String, String>> bundles;
private final Consumer<String> diagnostics;
public Messages(Map<StudioLanguage, Map<String, String>> bundles, Consumer<String> diagnostics) {
this.bundles = Map.copyOf(bundles); this.diagnostics = diagnostics;
}
public static Messages load(Consumer<String> diagnostics) {
Map<StudioLanguage, Map<String, String>> 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<String,String> 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<String> keys(StudioLanguage language) { return bundles.getOrDefault(language, Map.of()).keySet(); }
}
@@ -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;
}
}
@@ -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();
}
}
@@ -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);
}
@@ -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<String> diagnostics;
public UserSettingsStore(Preferences node, Locale systemLocale, Consumer<String> 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<String> 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 extends Enum<T>> T read(Class<T> type, String value, T fallback, Consumer<String> 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; }
}
}
@@ -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> theme;
private final StudioSelect<StudioLanguage> 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<Theme> themeSelector() { return theme; }
public StudioSelect<StudioLanguage> languageSelector() { return language; }
}
@@ -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);
}
}
@@ -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.
@@ -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.
@@ -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.
@@ -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.
@@ -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; }
@@ -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;
}
@@ -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;
}
@@ -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> T fx(Callable<T> task) throws Exception {
FutureTask<T> future=new FutureTask<>(task);Platform.runLater(future);return future.get(30,TimeUnit.SECONDS);
}
}
@@ -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<String,String> dark=tokens(Theme.DARK),light=tokens(Theme.LIGHT);
assertEquals(dark.keySet(),light.keySet());
for (Map<String,String> 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<String,String> 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<String,String> 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;
}
}
@@ -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<String> 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<String> 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<PresentationSettings> 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());
}
}