Plattformmenüs und Lokalisierung für JavaFX bereitstellen
This commit is contained in:
@@ -2,6 +2,7 @@
|
|||||||
|
|
||||||
## Documentation map
|
## Documentation map
|
||||||
|
|
||||||
|
- [Message catalogs, FXML localization and language changes](docs/i18n.md).
|
||||||
- [FXML support for every public control](docs/fxml-controls.md).
|
- [FXML support for every public control](docs/fxml-controls.md).
|
||||||
|
|
||||||
- [Build a complete application from scratch](docs/quick-start.md).
|
- [Build a complete application from scratch](docs/quick-start.md).
|
||||||
|
|||||||
@@ -98,3 +98,9 @@ required. The launch class is ordinary Java and delegates to the Application.
|
|||||||
The [MVVM docking editor](../../fx-example/docs/docking-mvvm.md) demonstrates
|
The [MVVM docking editor](../../fx-example/docs/docking-mvvm.md) demonstrates
|
||||||
Dockable-owned bars and optional MVVM bindings alongside a plain JavaFX editor.
|
Dockable-owned bars and optional MVVM bindings alongside a plain JavaFX editor.
|
||||||
The standalone controls also support ordinary JavaFX property bindings.
|
The standalone controls also support ordinary JavaFX property bindings.
|
||||||
|
|
||||||
|
## Window menus
|
||||||
|
|
||||||
|
Use `PlatformMenuBar.create(file, quit, view)` from `de.neitzel.fx.control` to build a window's JavaFX menu bar. Supply fresh menus and a localized Quit item with its action already set. Place the result at the top of the scene. On macOS the native menu bar follows the focused stage and supplies the Quit command. On other platforms the file menu includes the supplied Quit item. With docking, route its action to `manager.requestMainWindowClose()`.
|
||||||
|
|
||||||
|
For floating windows, set `FloatingWindowConfiguration.setMenuBarFactory(...)` in the floating window customizer. The factory receives the new window before it is shown. Use that window as the owner for dialogs launched by its menu.
|
||||||
|
|||||||
@@ -0,0 +1,18 @@
|
|||||||
|
# Message catalogs for Java and FXML
|
||||||
|
|
||||||
|
Create one Localizer per application. The initial locale can be null to use the JVM display locale. The second argument specifies the fallback language. Register the service with the same ApplicationContext used by ViewLoader.
|
||||||
|
|
||||||
|
```java
|
||||||
|
var language = new Localizer(initialLocale, Locale.ENGLISH,
|
||||||
|
new Localizer.Catalog(MyApp.class, "MyApp", "org.example.myapp"),
|
||||||
|
LanguageMenu.CATALOG);
|
||||||
|
context.addSingleton(Localizer.class, language);
|
||||||
|
var texts = language.forClass(AccountController.class);
|
||||||
|
label.setText(texts.text("account.saved", accountName));
|
||||||
|
```
|
||||||
|
|
||||||
|
Catalogs are UTF-8 properties files. For each key the search tries the requested locale's variants (for example de-CH before de), then variants of the fallback locale, then files without a language suffix. Each pass visits the view catalog beside its FXML, the controller's class catalog, package Messages catalogs up to the configured root, the named application catalog and the named library catalogs in registration order. For example, use Account_de.properties beside Account.fxml and MyApp_de.properties at the application resource root. Missing keys display as ⟦key⟧ and log once per locale and catalog context. Java calls with arguments use MessageFormat patterns.
|
||||||
|
|
||||||
|
ViewLoader supplies the same Messages bundle to the FXMLLoader and the controller. Use `<Button text="%account.save"/>` in FXML and `@FXML private Messages resources;` in the controller. A plain fx:include inherits the parent's bundle. Load reusable components separately for their own catalog. For an ordinary FXMLLoader, pass `language.forView(location, controllerClass)` as its ResourceBundle.
|
||||||
|
|
||||||
|
Change the language on the FX thread with `language.setLocale(locale)`. Ordinary text lookups return a string immediately. Bind individual live labels with `label.textProperty().bind(texts.observable("account.save"))` or observe `language.localeProperty()` to refresh a view. FXML attributes resolve again when the view is recreated. LanguageMenu.create supplies a selector with an owner for its notice and a callback for saving a user selection. Pass a Messages bundle to DockingOptions.setResourceBundle for localized docking commands.
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
package de.neitzel.fx.control;
|
||||||
|
|
||||||
|
import javafx.scene.control.Menu;
|
||||||
|
import javafx.scene.control.MenuBar;
|
||||||
|
import javafx.scene.control.MenuItem;
|
||||||
|
import javafx.scene.control.SeparatorMenuItem;
|
||||||
|
|
||||||
|
import java.util.Locale;
|
||||||
|
|
||||||
|
/** Builds one window's menu bar, using the native application Quit item on macOS. */
|
||||||
|
public final class PlatformMenuBar {
|
||||||
|
private PlatformMenuBar() {}
|
||||||
|
|
||||||
|
/** Supply fresh menus and a localized quit action for each window. */
|
||||||
|
public static MenuBar create(Menu file, MenuItem quit, Menu... otherMenus) {
|
||||||
|
var bar = new MenuBar(file);
|
||||||
|
bar.getMenus().addAll(otherMenus);
|
||||||
|
if (System.getProperty("os.name").toLowerCase(Locale.ROOT).startsWith("mac")) {
|
||||||
|
bar.setUseSystemMenuBar(true);
|
||||||
|
} else {
|
||||||
|
if (!file.getItems().isEmpty()) file.getItems().add(new SeparatorMenuItem());
|
||||||
|
file.getItems().add(quit);
|
||||||
|
}
|
||||||
|
return bar;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
package de.neitzel.fx.docking;
|
package de.neitzel.fx.docking;
|
||||||
|
|
||||||
|
import de.neitzel.fx.i18n.Messages;
|
||||||
import java.text.MessageFormat;
|
import java.text.MessageFormat;
|
||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
import java.util.Locale;
|
import java.util.Locale;
|
||||||
@@ -12,10 +13,12 @@ final class DockMessages {
|
|||||||
private final ResourceBundle defaults = ResourceBundle.getBundle("de.neitzel.fx.docking.Docking", Locale.ROOT);
|
private final ResourceBundle defaults = ResourceBundle.getBundle("de.neitzel.fx.docking.Docking", Locale.ROOT);
|
||||||
private final Map<String, String> overrides;
|
private final Map<String, String> overrides;
|
||||||
private final Locale locale;
|
private final Locale locale;
|
||||||
|
private final Messages live;
|
||||||
|
|
||||||
DockMessages(ResourceBundle resources) {
|
DockMessages(ResourceBundle resources) {
|
||||||
Map<String, String> captured = new HashMap<>();
|
Map<String, String> captured = new HashMap<>();
|
||||||
if (resources != null) {
|
live = resources instanceof Messages messages ? messages : null;
|
||||||
|
if (resources != null && live == null) {
|
||||||
for (String key : resources.keySet()) {
|
for (String key : resources.keySet()) {
|
||||||
if (resources.getObject(key) instanceof String text) captured.put(key, text);
|
if (resources.getObject(key) instanceof String text) captured.put(key, text);
|
||||||
}
|
}
|
||||||
@@ -24,13 +27,18 @@ final class DockMessages {
|
|||||||
locale = resources == null || resources.getLocale() == null ? Locale.ROOT : resources.getLocale();
|
locale = resources == null || resources.getLocale() == null ? Locale.ROOT : resources.getLocale();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private String override(String key) {
|
||||||
|
return live != null && live.defines(key) ? live.text(key) : overrides.get(key);
|
||||||
|
}
|
||||||
|
|
||||||
String text(String key) {
|
String text(String key) {
|
||||||
if (overrides.containsKey(key)) return overrides.get(key);
|
String wording = override(key);
|
||||||
|
if (wording != null) return wording;
|
||||||
return defaults.containsKey(key) ? defaults.getString(key) : defaults.getString("dock.failure.generic");
|
return defaults.containsKey(key) ? defaults.getString(key) : defaults.getString("dock.failure.generic");
|
||||||
}
|
}
|
||||||
|
|
||||||
String format(String key, Object... values) {
|
String format(String key, Object... values) {
|
||||||
return new MessageFormat(text(key), locale).format(values);
|
return new MessageFormat(text(key), live == null ? locale : live.getLocale()).format(values);
|
||||||
}
|
}
|
||||||
|
|
||||||
String failure(DockFailure failure) {
|
String failure(DockFailure failure) {
|
||||||
@@ -38,9 +46,10 @@ final class DockMessages {
|
|||||||
String codeKey = "dock.failure." + failure.code().name();
|
String codeKey = "dock.failure." + failure.code().name();
|
||||||
String applicationKey = failure.messageKey();
|
String applicationKey = failure.messageKey();
|
||||||
if (applicationKey != null && !applicationKey.isBlank()) {
|
if (applicationKey != null && !applicationKey.isBlank()) {
|
||||||
return overrides.getOrDefault(applicationKey, text(codeKey));
|
return Objects.requireNonNullElseGet(override(applicationKey), () -> text(codeKey));
|
||||||
}
|
}
|
||||||
if (overrides.containsKey(codeKey)) return overrides.get(codeKey);
|
String wording = override(codeKey);
|
||||||
|
if (wording != null) return wording;
|
||||||
// Keep the existing direct-message API useful when no localization key was supplied.
|
// Keep the existing direct-message API useful when no localization key was supplied.
|
||||||
return failure.message() == null || failure.message().isBlank() ? text(codeKey) : failure.message();
|
return failure.message() == null || failure.message().isBlank() ? text(codeKey) : failure.message();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1350,7 +1350,18 @@ public final class DockingManager {
|
|||||||
}
|
}
|
||||||
DockPane floatingPane = new DockPane();
|
DockPane floatingPane = new DockPane();
|
||||||
Stage floatingStage = new Stage();
|
Stage floatingStage = new Stage();
|
||||||
floatingStage.setScene(new javafx.scene.Scene(floatingPane));
|
if (configuration.getMenuBarFactory() == null) {
|
||||||
|
floatingStage.setScene(new javafx.scene.Scene(floatingPane));
|
||||||
|
} else {
|
||||||
|
try {
|
||||||
|
var menu = Objects.requireNonNull(configuration.getMenuBarFactory().apply(floatingStage));
|
||||||
|
var root = new javafx.scene.layout.BorderPane(floatingPane);
|
||||||
|
root.setTop(menu);
|
||||||
|
floatingStage.setScene(new javafx.scene.Scene(root));
|
||||||
|
} catch (RuntimeException failure) {
|
||||||
|
throw new FloatingPreparationFailure(failure);
|
||||||
|
}
|
||||||
|
}
|
||||||
de.neitzel.fx.theme.ThemeManager.link(floatingStage, stage.getScene());
|
de.neitzel.fx.theme.ThemeManager.link(floatingStage, stage.getScene());
|
||||||
javafx.event.EventHandler<javafx.stage.WindowEvent> closeHandler = event -> {
|
javafx.event.EventHandler<javafx.stage.WindowEvent> closeHandler = event -> {
|
||||||
event.consume();
|
event.consume();
|
||||||
|
|||||||
@@ -1,14 +1,19 @@
|
|||||||
package de.neitzel.fx.docking;
|
package de.neitzel.fx.docking;
|
||||||
|
|
||||||
|
import javafx.scene.control.MenuBar;
|
||||||
import javafx.scene.image.Image;
|
import javafx.scene.image.Image;
|
||||||
|
import javafx.stage.Window;
|
||||||
import lombok.Getter;
|
import lombok.Getter;
|
||||||
import lombok.Setter;
|
import lombok.Setter;
|
||||||
|
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.function.Function;
|
||||||
|
|
||||||
/** Appearance supplied before a managed window appears; its Stage and Scene remain manager-owned. */
|
/** Appearance supplied before a managed window appears; its Stage and Scene remain manager-owned. */
|
||||||
public final class FloatingWindowConfiguration {
|
public final class FloatingWindowConfiguration {
|
||||||
|
/** Optional factory for a fresh menu bar. The window provides context for actions and dialogs. */
|
||||||
|
@Getter @Setter private Function<Window, MenuBar> menuBarFactory;
|
||||||
@Getter @Setter private String title = "Docking";
|
@Getter @Setter private String title = "Docking";
|
||||||
@Getter private final List<Image> icons = new ArrayList<>();
|
@Getter private final List<Image> icons = new ArrayList<>();
|
||||||
@Getter private final List<String> stylesheets = new ArrayList<>();
|
@Getter private final List<String> stylesheets = new ArrayList<>();
|
||||||
|
|||||||
@@ -0,0 +1,48 @@
|
|||||||
|
package de.neitzel.fx.i18n;
|
||||||
|
|
||||||
|
import javafx.scene.control.Alert;
|
||||||
|
import javafx.scene.control.Menu;
|
||||||
|
import javafx.scene.control.RadioMenuItem;
|
||||||
|
import javafx.scene.control.ToggleGroup;
|
||||||
|
import javafx.stage.Window;
|
||||||
|
import java.util.Locale;
|
||||||
|
import java.util.function.Consumer;
|
||||||
|
import java.util.function.Supplier;
|
||||||
|
|
||||||
|
/** Language selection shared by desktop windows. Only a changed user selection shows a notice. */
|
||||||
|
public final class LanguageMenu {
|
||||||
|
public static final Localizer.Catalog CATALOG = new Localizer.Catalog(LanguageMenu.class, "NeitzelLib-fx", "de.neitzel.fx");
|
||||||
|
|
||||||
|
private LanguageMenu() {}
|
||||||
|
|
||||||
|
public static Menu create(Localizer languages, Supplier<Window> owner, Consumer<Locale> remember,
|
||||||
|
Locale... choices) {
|
||||||
|
var texts = languages.forClass(LanguageMenu.class);
|
||||||
|
var menu = new Menu();
|
||||||
|
menu.textProperty().bind(languages.localeProperty().map(locale -> texts.text("language.menu")));
|
||||||
|
var group = new ToggleGroup();
|
||||||
|
for (Locale choice : choices) {
|
||||||
|
var item = new RadioMenuItem(choice.getDisplayName(choice));
|
||||||
|
item.setToggleGroup(group);
|
||||||
|
item.setUserData(choice);
|
||||||
|
item.setOnAction(event -> {
|
||||||
|
if (choice.equals(languages.getLocale())) return;
|
||||||
|
languages.setLocale(choice);
|
||||||
|
remember.accept(choice);
|
||||||
|
var notice = new Alert(Alert.AlertType.INFORMATION, texts.text("language.reopen"));
|
||||||
|
notice.initOwner(owner.get());
|
||||||
|
notice.setTitle(texts.text("language.menu"));
|
||||||
|
notice.setHeaderText(null);
|
||||||
|
notice.show();
|
||||||
|
});
|
||||||
|
menu.getItems().add(item);
|
||||||
|
}
|
||||||
|
menu.setOnShowing(event -> {
|
||||||
|
for (var toggle : group.getToggles()) {
|
||||||
|
Locale choice = (Locale) toggle.getUserData();
|
||||||
|
toggle.setSelected(choice.getLanguage().equals(languages.getLocale().getLanguage()));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
return menu;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,99 @@
|
|||||||
|
package de.neitzel.fx.i18n;
|
||||||
|
|
||||||
|
import javafx.beans.property.ReadOnlyObjectProperty;
|
||||||
|
import javafx.beans.property.ReadOnlyObjectWrapper;
|
||||||
|
|
||||||
|
import java.net.URL;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.LinkedHashSet;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Locale;
|
||||||
|
import java.util.Objects;
|
||||||
|
import java.util.Set;
|
||||||
|
import java.util.concurrent.ConcurrentHashMap;
|
||||||
|
|
||||||
|
/** Application-wide language selection and ordered property catalog sources. */
|
||||||
|
public final class Localizer {
|
||||||
|
public record Catalog(Class<?> anchor, String name, String packageRoot) {
|
||||||
|
public Catalog {
|
||||||
|
Objects.requireNonNull(anchor);
|
||||||
|
Objects.requireNonNull(packageRoot);
|
||||||
|
if (!name.matches("[\\w.-]+")) throw new IllegalArgumentException("Invalid catalog name: " + name);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Catalog(Class<?> anchor, String name) {
|
||||||
|
this(anchor, name, anchor.getPackageName());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
record Family(Class<?> anchor, String path, URL siblingOf) {}
|
||||||
|
private record Missing(List<Family> context, Locale locale, String key) {}
|
||||||
|
private final Set<Missing> missing = ConcurrentHashMap.newKeySet();
|
||||||
|
private final ReadOnlyObjectWrapper<Locale> locale;
|
||||||
|
final Locale fallback;
|
||||||
|
private final List<Catalog> catalogs;
|
||||||
|
|
||||||
|
public Localizer(Locale initial, Locale fallback, Catalog application, Catalog... libraries) {
|
||||||
|
this.locale = new ReadOnlyObjectWrapper<>(initial == null ? Locale.getDefault(Locale.Category.DISPLAY) : initial);
|
||||||
|
this.fallback = Objects.requireNonNull(fallback);
|
||||||
|
var sources = new ArrayList<Catalog>();
|
||||||
|
sources.add(Objects.requireNonNull(application));
|
||||||
|
sources.addAll(List.of(libraries));
|
||||||
|
this.catalogs = List.copyOf(sources);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Locale getLocale() { return locale.get(); }
|
||||||
|
public ReadOnlyObjectProperty<Locale> localeProperty() { return locale.getReadOnlyProperty(); }
|
||||||
|
|
||||||
|
/** Set on the JavaFX thread when controls observe this property. */
|
||||||
|
public void setLocale(Locale value) {
|
||||||
|
if (!getLocale().equals(Objects.requireNonNull(value))) locale.set(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Messages forClass(Class<?> type) { return forView(null, type); }
|
||||||
|
|
||||||
|
public Messages forView(URL fxml, Class<?> controller) {
|
||||||
|
var families = new LinkedHashSet<Family>();
|
||||||
|
Class<?> anchor = controller == null ? catalogs.getFirst().anchor() : controller;
|
||||||
|
if (fxml != null) {
|
||||||
|
String path = fxml.getPath();
|
||||||
|
String file = path.substring(path.lastIndexOf('/') + 1);
|
||||||
|
families.add(new Family(anchor, file.replaceFirst("\\.fxml$", ""), fxml));
|
||||||
|
}
|
||||||
|
if (controller != null) families.add(new Family(controller, controller.getSimpleName(), null));
|
||||||
|
String pkg = anchor.getPackageName();
|
||||||
|
String root = catalogs.stream().map(Catalog::packageRoot)
|
||||||
|
.filter(p -> pkg.equals(p) || pkg.startsWith(p + "."))
|
||||||
|
.max(java.util.Comparator.comparingInt(String::length)).orElse(pkg);
|
||||||
|
if (fxml != null) {
|
||||||
|
String directory = fxml.getPath().substring(0, fxml.getPath().lastIndexOf('/') + 1);
|
||||||
|
catalogs.stream().filter(c -> !c.packageRoot().isEmpty()
|
||||||
|
&& directory.contains("/" + c.packageRoot().replace('.', '/') + "/"))
|
||||||
|
.max(java.util.Comparator.comparingInt(c -> c.packageRoot().length()))
|
||||||
|
.ifPresent(source -> {
|
||||||
|
String prefix = "/" + source.packageRoot().replace('.', '/') + "/";
|
||||||
|
String path = directory.substring(directory.lastIndexOf(prefix), directory.length() - 1);
|
||||||
|
addPackages(families, source.anchor(), path, source.packageRoot());
|
||||||
|
});
|
||||||
|
}
|
||||||
|
addPackages(families, anchor, "/" + pkg.replace('.', '/'), root);
|
||||||
|
for (Catalog catalog : catalogs) families.add(new Family(catalog.anchor(), "/" + catalog.name(), null));
|
||||||
|
return new Messages(this, List.copyOf(families));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void addPackages(Set<Family> result, Class<?> anchor, String path, String root) {
|
||||||
|
String boundary = "/" + root.replace('.', '/');
|
||||||
|
while (path.length() > 1) {
|
||||||
|
result.add(new Family(anchor, path + "/Messages", null));
|
||||||
|
if (path.equals(boundary)) break;
|
||||||
|
path = path.substring(0, path.lastIndexOf('/'));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void reportMissing(List<Family> context, Locale language, String key) {
|
||||||
|
if (missing.add(new Missing(context, language, key))) {
|
||||||
|
System.getLogger(Localizer.class.getName()).log(System.Logger.Level.WARNING,
|
||||||
|
"Missing translation {0} for {1} in {2}", key, language, context);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,93 @@
|
|||||||
|
package de.neitzel.fx.i18n;
|
||||||
|
|
||||||
|
import java.io.FileNotFoundException;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.InputStreamReader;
|
||||||
|
import java.io.UncheckedIOException;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.text.MessageFormat;
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.Enumeration;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.LinkedHashSet;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Locale;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Objects;
|
||||||
|
import java.util.Properties;
|
||||||
|
import java.util.ResourceBundle;
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
|
/** A live ResourceBundle for FXML, controller injection and immediate Java lookups. */
|
||||||
|
public final class Messages extends ResourceBundle {
|
||||||
|
private static final Control RULES = Control.getControl(Control.FORMAT_PROPERTIES);
|
||||||
|
private final Localizer localizer;
|
||||||
|
private final List<Localizer.Family> families;
|
||||||
|
private Locale loaded;
|
||||||
|
private Map<String,String> entries;
|
||||||
|
|
||||||
|
Messages(Localizer localizer, List<Localizer.Family> families) {
|
||||||
|
this.localizer = localizer;
|
||||||
|
this.families = families;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Opt-in live label for JavaFX property binding. */
|
||||||
|
public javafx.beans.value.ObservableValue<String> observable(String key) {
|
||||||
|
return localizer.localeProperty().map(locale -> text(key));
|
||||||
|
}
|
||||||
|
|
||||||
|
public String text(String key, Object... arguments) {
|
||||||
|
String pattern = getString(key);
|
||||||
|
return arguments.length == 0 ? pattern : new MessageFormat(pattern, getLocale()).format(arguments);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Localizer localizer() { return localizer; }
|
||||||
|
@Override public Locale getLocale() { return localizer.getLocale(); }
|
||||||
|
|
||||||
|
@Override protected Object handleGetObject(String key) {
|
||||||
|
String value = values().get(Objects.requireNonNull(key));
|
||||||
|
if (value != null) return value;
|
||||||
|
localizer.reportMissing(families, getLocale(), key);
|
||||||
|
return "⟦" + key + "⟧";
|
||||||
|
}
|
||||||
|
|
||||||
|
/** FXMLLoader checks containsKey before getString. Every key has a visible fallback. */
|
||||||
|
@Override public boolean containsKey(String key) { Objects.requireNonNull(key); return true; }
|
||||||
|
public boolean defines(String key) { return values().containsKey(key); }
|
||||||
|
@Override public Enumeration<String> getKeys() { return Collections.enumeration(values().keySet()); }
|
||||||
|
@Override protected Set<String> handleKeySet() { return values().keySet(); }
|
||||||
|
|
||||||
|
private synchronized Map<String,String> values() {
|
||||||
|
Locale current = getLocale();
|
||||||
|
if (current.equals(loaded)) return entries;
|
||||||
|
var languages = new LinkedHashSet<>(RULES.getCandidateLocales("", current));
|
||||||
|
languages.addAll(RULES.getCandidateLocales("", localizer.fallback));
|
||||||
|
languages.remove(Locale.ROOT);
|
||||||
|
languages.add(Locale.ROOT);
|
||||||
|
var result = new HashMap<String,String>();
|
||||||
|
for (Locale language : languages) {
|
||||||
|
for (var family : families) read(family, language, result);
|
||||||
|
}
|
||||||
|
entries = Map.copyOf(result);
|
||||||
|
loaded = current;
|
||||||
|
return entries;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void read(Localizer.Family family, Locale locale, Map<String,String> result) {
|
||||||
|
String file = RULES.toBundleName(family.path(), locale) + ".properties";
|
||||||
|
try {
|
||||||
|
var url = family.siblingOf() == null ? family.anchor().getResource(file)
|
||||||
|
: new java.net.URL(family.siblingOf(), file);
|
||||||
|
if (url == null) return;
|
||||||
|
try (var reader = new InputStreamReader(url.openStream(), StandardCharsets.UTF_8)) {
|
||||||
|
var properties = new Properties();
|
||||||
|
properties.load(reader);
|
||||||
|
for (var key : properties.stringPropertyNames()) result.putIfAbsent(key, properties.getProperty(key));
|
||||||
|
}
|
||||||
|
} catch (FileNotFoundException missingSibling) {
|
||||||
|
// A locale or layer may have no properties file.
|
||||||
|
} catch (IOException problem) {
|
||||||
|
throw new UncheckedIOException("Cannot read catalog " + file, problem);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -178,7 +178,7 @@ final class Components {
|
|||||||
}
|
}
|
||||||
LoadSession nested = LoadSession.nest();
|
LoadSession nested = LoadSession.nest();
|
||||||
try {
|
try {
|
||||||
FXMLLoader loader = new FXMLLoader(fxml);
|
FXMLLoader loader = new FXMLLoader(fxml, ViewLoader.resources(context, fxml, type));
|
||||||
loader.setRoot(component);
|
loader.setRoot(component);
|
||||||
loader.setController(component);
|
loader.setController(component);
|
||||||
loader.setBuilderFactory(nestedType -> builder(nestedType, context));
|
loader.setBuilderFactory(nestedType -> builder(nestedType, context));
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
package de.neitzel.fx.view;
|
package de.neitzel.fx.view;
|
||||||
|
|
||||||
|
import de.neitzel.fx.i18n.Localizer;
|
||||||
|
import de.neitzel.fx.i18n.Messages;
|
||||||
import de.neitzel.injection.ApplicationContext;
|
import de.neitzel.injection.ApplicationContext;
|
||||||
import javafx.fxml.FXMLLoader;
|
import javafx.fxml.FXMLLoader;
|
||||||
import javafx.scene.Parent;
|
import javafx.scene.Parent;
|
||||||
@@ -75,11 +77,12 @@ public final class ViewLoader {
|
|||||||
* @throws IllegalArgumentException when a Direct binding names a path that is not a read-write Attribute
|
* @throws IllegalArgumentException when a Direct binding names a path that is not a read-write Attribute
|
||||||
*/
|
*/
|
||||||
public static LoadedView load(URL fxml, Object model, ApplicationContext context) {
|
public static LoadedView load(URL fxml, Object model, ApplicationContext context) {
|
||||||
Class<?> viewModelClass = ViewModels.namedOn(FxmlControllers.controllerClass(fxml));
|
Class<?> controllerType = FxmlControllers.controllerClass(fxml);
|
||||||
|
Class<?> viewModelClass = ViewModels.namedOn(controllerType);
|
||||||
Object viewModel = ViewModels.of(model, viewModelClass);
|
Object viewModel = ViewModels.of(model, viewModelClass);
|
||||||
LoadSession session = LoadSession.open();
|
LoadSession session = LoadSession.open();
|
||||||
try {
|
try {
|
||||||
FXMLLoader loader = new FXMLLoader(fxml);
|
FXMLLoader loader = new FXMLLoader(fxml, resources(context, fxml, controllerType));
|
||||||
loader.setControllerFactory(type -> controller(context, type));
|
loader.setControllerFactory(type -> controller(context, type));
|
||||||
loader.setBuilderFactory(type -> Components.builder(type, context));
|
loader.setBuilderFactory(type -> Components.builder(type, context));
|
||||||
Object loaded = loader.load();
|
Object loaded = loader.load();
|
||||||
@@ -105,6 +108,16 @@ public final class ViewLoader {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
static Messages resources(ApplicationContext context, URL fxml, Class<?> type) {
|
||||||
|
Localizer languages;
|
||||||
|
try {
|
||||||
|
languages = context.getComponent(Localizer.class);
|
||||||
|
} catch (IllegalArgumentException unregistered) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return languages.forView(fxml, type);
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Asks the container for the Controller class named by the document.
|
* Asks the container for the Controller class named by the document.
|
||||||
*
|
*
|
||||||
|
|||||||
@@ -0,0 +1,44 @@
|
|||||||
|
language.menu=Language
|
||||||
|
language.reopen=The language has changed. Some texts update when you reopen the window.
|
||||||
|
|
||||||
|
dock.action.move=Move to
|
||||||
|
dock.action.split=Split
|
||||||
|
dock.action.close=Close
|
||||||
|
dock.action.float=Float
|
||||||
|
dock.action.return=Return to main
|
||||||
|
dock.action.pin=Pin group
|
||||||
|
dock.side.TOP=Above
|
||||||
|
dock.side.RIGHT=Right
|
||||||
|
dock.side.BOTTOM=Below
|
||||||
|
dock.side.LEFT=Left
|
||||||
|
dock.action.unavailable={0} ({1})
|
||||||
|
dock.action.noChange={0} (Already here)
|
||||||
|
dock.failure.generic=The operation cannot be completed
|
||||||
|
dock.failure.LAYOUT_CHANGE_IN_PROGRESS=A layout change is in progress
|
||||||
|
dock.failure.RESTORE_REQUIRES_EMPTY_MANAGER=Restore requires an empty manager
|
||||||
|
dock.failure.UNSUPPORTED_SNAPSHOT_VERSION=This snapshot version is not supported
|
||||||
|
dock.failure.INVALID_SNAPSHOT=The snapshot is invalid
|
||||||
|
dock.failure.UNSUPPORTED_SNAPSHOT_FEATURE=This snapshot feature is not supported
|
||||||
|
dock.failure.DOCKABLE_LOAD_FAILED=The content could not be loaded
|
||||||
|
dock.failure.MISSING_DOCKABLE=The requested content is unavailable
|
||||||
|
dock.failure.INVALID_GROUP_CONFIGURATION=The group settings are incompatible
|
||||||
|
dock.failure.COLLAPSE_DISABLED=This group cannot collapse
|
||||||
|
dock.failure.SPLIT_DISABLED=This group cannot split in that direction
|
||||||
|
dock.failure.SPLIT_TOO_SMALL=There is not enough space to split this group
|
||||||
|
dock.failure.TARGET_NOT_FOUND=The destination is unavailable
|
||||||
|
dock.failure.REFERENCE_TAB_NOT_FOUND=The reference tab is unavailable
|
||||||
|
dock.failure.DOCKABLE_NOT_FOUND=The content is not open
|
||||||
|
dock.failure.CONTENT_ALREADY_ATTACHED=The content already belongs to a view
|
||||||
|
dock.failure.PLACEMENT_REJECTED=This placement is not allowed
|
||||||
|
dock.failure.PLACEMENT_CHECK_FAILED=The placement check failed
|
||||||
|
dock.failure.ID_MISMATCH=The created content has a different identity
|
||||||
|
dock.failure.FACTORY_FAILED=The content could not be created
|
||||||
|
dock.failure.MAIN_WINDOW_ONLY=This content must remain in the main window
|
||||||
|
dock.failure.CLOSE_IN_PROGRESS=A close decision is pending
|
||||||
|
dock.failure.CLOSE_CHECK_FAILED=The close check failed
|
||||||
|
dock.failure.CLEANUP_FAILED=Resource release failed
|
||||||
|
dock.failure.INVALID_WINDOW_BOUNDS=The window bounds are invalid
|
||||||
|
dock.failure.WINDOW_CREATION_FAILED=The floating window could not be prepared
|
||||||
|
|
||||||
|
dock.failure.SHUTDOWN_CALLBACK_FAILED=The shutdown preparation failed
|
||||||
|
dock.failure.MANAGER_CLOSED=The docking manager has ended
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
language.menu=Sprache
|
||||||
|
language.reopen=Die Sprache wurde geändert. Einige Texte werden beim erneuten Öffnen des Fensters aktualisiert.
|
||||||
|
|
||||||
|
dock.action.move=Verschieben nach
|
||||||
|
dock.action.split=Teilen
|
||||||
|
dock.action.close=Schließen
|
||||||
|
dock.action.float=Abdocken
|
||||||
|
dock.action.return=Ins Hauptfenster zurückholen
|
||||||
|
dock.action.pin=Gruppe anheften
|
||||||
|
dock.side.TOP=Oben
|
||||||
|
dock.side.RIGHT=Rechts
|
||||||
|
dock.side.BOTTOM=Unten
|
||||||
|
dock.side.LEFT=Links
|
||||||
|
dock.action.unavailable={0} ({1})
|
||||||
|
dock.action.noChange={0} (bereits hier)
|
||||||
|
dock.failure.generic=Der Vorgang konnte nicht abgeschlossen werden.
|
||||||
|
dock.failure.LAYOUT_CHANGE_IN_PROGRESS=Eine Layoutänderung läuft.
|
||||||
|
dock.failure.RESTORE_REQUIRES_EMPTY_MANAGER=Zum Wiederherstellen muss der Arbeitsbereich leer sein.
|
||||||
|
dock.failure.UNSUPPORTED_SNAPSHOT_VERSION=Diese Layoutversion wird nicht unterstützt.
|
||||||
|
dock.failure.INVALID_SNAPSHOT=Das gespeicherte Layout ist ungültig.
|
||||||
|
dock.failure.UNSUPPORTED_SNAPSHOT_FEATURE=Dieses Layoutmerkmal wird nicht unterstützt.
|
||||||
|
dock.failure.DOCKABLE_LOAD_FAILED=Der Inhalt konnte nicht geladen werden.
|
||||||
|
dock.failure.MISSING_DOCKABLE=Der angeforderte Inhalt ist nicht verfügbar.
|
||||||
|
dock.failure.INVALID_GROUP_CONFIGURATION=Die Gruppeneinstellungen sind inkompatibel.
|
||||||
|
dock.failure.COLLAPSE_DISABLED=Diese Gruppe kann nicht eingeklappt werden.
|
||||||
|
dock.failure.SPLIT_DISABLED=Die Gruppe kann in dieser Richtung nicht geteilt werden.
|
||||||
|
dock.failure.SPLIT_TOO_SMALL=Zum Teilen der Gruppe fehlt Platz.
|
||||||
|
dock.failure.TARGET_NOT_FOUND=Das Ziel ist nicht verfügbar.
|
||||||
|
dock.failure.REFERENCE_TAB_NOT_FOUND=Der Referenzreiter ist nicht verfügbar.
|
||||||
|
dock.failure.DOCKABLE_NOT_FOUND=Der Inhalt ist nicht geöffnet.
|
||||||
|
dock.failure.CONTENT_ALREADY_ATTACHED=Der Inhalt gehört bereits zu einer Ansicht.
|
||||||
|
dock.failure.PLACEMENT_REJECTED=Diese Platzierung ist nicht zulässig.
|
||||||
|
dock.failure.PLACEMENT_CHECK_FAILED=Die Platzierung konnte nicht geprüft werden.
|
||||||
|
dock.failure.ID_MISMATCH=Der erzeugte Inhalt hat eine andere Identität.
|
||||||
|
dock.failure.FACTORY_FAILED=Der Inhalt konnte nicht erzeugt werden.
|
||||||
|
dock.failure.MAIN_WINDOW_ONLY=Dieser Inhalt muss im Hauptfenster bleiben.
|
||||||
|
dock.failure.CLOSE_IN_PROGRESS=Eine Schließanfrage ist bereits offen.
|
||||||
|
dock.failure.CLOSE_CHECK_FAILED=Die Schließanfrage konnte nicht geprüft werden.
|
||||||
|
dock.failure.CLEANUP_FAILED=Ressourcen konnten nicht freigegeben werden.
|
||||||
|
dock.failure.INVALID_WINDOW_BOUNDS=Die Fensterabmessungen sind ungültig.
|
||||||
|
dock.failure.WINDOW_CREATION_FAILED=Das abgedockte Fenster konnte nicht vorbereitet werden.
|
||||||
|
dock.failure.SHUTDOWN_CALLBACK_FAILED=Das Beenden konnte nicht vorbereitet werden.
|
||||||
|
dock.failure.MANAGER_CLOSED=Der Arbeitsbereich wurde bereits geschlossen.
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
language.menu=Language
|
||||||
|
language.reopen=The language has changed. Some texts update when you reopen the window.
|
||||||
|
|
||||||
|
dock.action.move=Move to
|
||||||
|
dock.action.split=Split
|
||||||
|
dock.action.close=Close
|
||||||
|
dock.action.float=Float
|
||||||
|
dock.action.return=Return to main
|
||||||
|
dock.action.pin=Pin group
|
||||||
|
dock.side.TOP=Above
|
||||||
|
dock.side.RIGHT=Right
|
||||||
|
dock.side.BOTTOM=Below
|
||||||
|
dock.side.LEFT=Left
|
||||||
|
dock.action.unavailable={0} ({1})
|
||||||
|
dock.action.noChange={0} (Already here)
|
||||||
|
dock.failure.generic=The operation cannot be completed
|
||||||
|
dock.failure.LAYOUT_CHANGE_IN_PROGRESS=A layout change is in progress
|
||||||
|
dock.failure.RESTORE_REQUIRES_EMPTY_MANAGER=Restore requires an empty manager
|
||||||
|
dock.failure.UNSUPPORTED_SNAPSHOT_VERSION=This snapshot version is not supported
|
||||||
|
dock.failure.INVALID_SNAPSHOT=The snapshot is invalid
|
||||||
|
dock.failure.UNSUPPORTED_SNAPSHOT_FEATURE=This snapshot feature is not supported
|
||||||
|
dock.failure.DOCKABLE_LOAD_FAILED=The content could not be loaded
|
||||||
|
dock.failure.MISSING_DOCKABLE=The requested content is unavailable
|
||||||
|
dock.failure.INVALID_GROUP_CONFIGURATION=The group settings are incompatible
|
||||||
|
dock.failure.COLLAPSE_DISABLED=This group cannot collapse
|
||||||
|
dock.failure.SPLIT_DISABLED=This group cannot split in that direction
|
||||||
|
dock.failure.SPLIT_TOO_SMALL=There is not enough space to split this group
|
||||||
|
dock.failure.TARGET_NOT_FOUND=The destination is unavailable
|
||||||
|
dock.failure.REFERENCE_TAB_NOT_FOUND=The reference tab is unavailable
|
||||||
|
dock.failure.DOCKABLE_NOT_FOUND=The content is not open
|
||||||
|
dock.failure.CONTENT_ALREADY_ATTACHED=The content already belongs to a view
|
||||||
|
dock.failure.PLACEMENT_REJECTED=This placement is not allowed
|
||||||
|
dock.failure.PLACEMENT_CHECK_FAILED=The placement check failed
|
||||||
|
dock.failure.ID_MISMATCH=The created content has a different identity
|
||||||
|
dock.failure.FACTORY_FAILED=The content could not be created
|
||||||
|
dock.failure.MAIN_WINDOW_ONLY=This content must remain in the main window
|
||||||
|
dock.failure.CLOSE_IN_PROGRESS=A close decision is pending
|
||||||
|
dock.failure.CLOSE_CHECK_FAILED=The close check failed
|
||||||
|
dock.failure.CLEANUP_FAILED=Resource release failed
|
||||||
|
dock.failure.INVALID_WINDOW_BOUNDS=The window bounds are invalid
|
||||||
|
dock.failure.WINDOW_CREATION_FAILED=The floating window could not be prepared
|
||||||
|
|
||||||
|
dock.failure.SHUTDOWN_CALLBACK_FAILED=The shutdown preparation failed
|
||||||
|
dock.failure.MANAGER_CLOSED=The docking manager has ended
|
||||||
@@ -13,6 +13,7 @@ import javafx.application.Platform;
|
|||||||
import javafx.geometry.Rectangle2D;
|
import javafx.geometry.Rectangle2D;
|
||||||
import javafx.scene.Scene;
|
import javafx.scene.Scene;
|
||||||
import javafx.scene.control.IndexRange;
|
import javafx.scene.control.IndexRange;
|
||||||
|
import javafx.scene.control.MenuBar;
|
||||||
import javafx.scene.control.TextArea;
|
import javafx.scene.control.TextArea;
|
||||||
import javafx.stage.Stage;
|
import javafx.stage.Stage;
|
||||||
import javafx.stage.Window;
|
import javafx.stage.Window;
|
||||||
@@ -142,7 +143,13 @@ class FloatDockablesTest {
|
|||||||
pane.getInitialLayout().setCenter(new DockGroupDefinition("editors"));
|
pane.getInitialLayout().setCenter(new DockGroupDefinition("editors"));
|
||||||
Stage main = new Stage();
|
Stage main = new Stage();
|
||||||
main.setScene(new Scene(pane, 800, 500));
|
main.setScene(new Scene(pane, 800, 500));
|
||||||
DockingManager manager = DockingManager.attach(main, pane, new DockingOptions());
|
DockingOptions options = new DockingOptions();
|
||||||
|
options.setFloatingWindowCustomizer(config -> config.setMenuBarFactory(owner -> {
|
||||||
|
MenuBar menu = new MenuBar();
|
||||||
|
menu.setUserData(owner);
|
||||||
|
return menu;
|
||||||
|
}));
|
||||||
|
DockingManager manager = DockingManager.attach(main, pane, options);
|
||||||
TextArea notes = new TextArea("Edited without saving");
|
TextArea notes = new TextArea("Edited without saving");
|
||||||
Dockable editor = new Dockable(new DockableId("notes"), notes);
|
Dockable editor = new Dockable(new DockableId("notes"), notes);
|
||||||
editor.setTitle("Notes");
|
editor.setTitle("Notes");
|
||||||
@@ -160,6 +167,8 @@ class FloatDockablesTest {
|
|||||||
Window detached = notes.getScene().getWindow();
|
Window detached = notes.getScene().getWindow();
|
||||||
assertNotSame(main, detached);
|
assertNotSame(main, detached);
|
||||||
assertTrue(detached.isShowing());
|
assertTrue(detached.isShowing());
|
||||||
|
MenuBar menu = (MenuBar) detached.getScene().lookup(".menu-bar");
|
||||||
|
assertSame(detached, menu.getUserData());
|
||||||
assertEquals(2, manager.layout().windows().size());
|
assertEquals(2, manager.layout().windows().size());
|
||||||
assertEquals("Edited without saving", notes.getText());
|
assertEquals("Edited without saving", notes.getText());
|
||||||
assertEquals(new IndexRange(2, 8), notes.getSelection());
|
assertEquals(new IndexRange(2, 8), notes.getSelection());
|
||||||
|
|||||||
@@ -0,0 +1,52 @@
|
|||||||
|
package de.neitzel.fx.view;
|
||||||
|
|
||||||
|
import de.neitzel.fx.i18n.Localizer;
|
||||||
|
import javafx.fxml.FXMLLoader;
|
||||||
|
import javafx.scene.layout.VBox;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.junit.jupiter.api.io.TempDir;
|
||||||
|
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.util.Locale;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
|
class LocalizerTest {
|
||||||
|
@TempDir Path folder;
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void localePrecedesCatalogAndMissingKeysSurviveAnFxmlLoad() throws Exception {
|
||||||
|
var app = new Localizer.Catalog(getClass(), "LocalizerTestApp");
|
||||||
|
var library = new Localizer.Catalog(getClass(), "LocalizerTestLib");
|
||||||
|
var languages = new Localizer(Locale.forLanguageTag("de-CH"), Locale.ENGLISH, app, library);
|
||||||
|
Files.writeString(folder.resolve("Part.fxml"), """
|
||||||
|
<?import javafx.scene.layout.Pane?>
|
||||||
|
<Pane xmlns:fx="http://javafx.com/fxml/1" accessibleText="%part"/>
|
||||||
|
""");
|
||||||
|
var view = folder.resolve("Main.fxml");
|
||||||
|
Files.writeString(view, """
|
||||||
|
<?import javafx.scene.layout.VBox?>
|
||||||
|
<VBox xmlns:fx="http://javafx.com/fxml/1" accessibleText="%absent"><fx:include source="Part.fxml"/></VBox>
|
||||||
|
""");
|
||||||
|
Files.writeString(folder.resolve("Main_de.properties"), "close=Schließen\npart=Outer\n");
|
||||||
|
Files.writeString(folder.resolve("Part_de.properties"), "part=Inner\n");
|
||||||
|
Files.writeString(folder.resolve("Main.properties"), "fallback=Root\n");
|
||||||
|
var url = view.toUri().toURL();
|
||||||
|
var texts = languages.forView(url, getClass());
|
||||||
|
assertEquals("Schliessen", texts.text("close"));
|
||||||
|
assertEquals("Application", texts.text("shared"));
|
||||||
|
assertEquals("Fallback 2", texts.text("fallback", 2));
|
||||||
|
assertEquals("Library", texts.text("library"));
|
||||||
|
var root = (VBox) new FXMLLoader(url, texts).load();
|
||||||
|
assertEquals("⟦absent⟧", root.getAccessibleText());
|
||||||
|
assertEquals("Outer", root.getChildren().getFirst().getAccessibleText());
|
||||||
|
assertEquals("Inner", languages.forView(folder.resolve("Part.fxml").toUri().toURL(), getClass()).text("part"));
|
||||||
|
var label = texts.observable("close");
|
||||||
|
languages.setLocale(Locale.GERMAN);
|
||||||
|
assertEquals("Schließen", label.getValue());
|
||||||
|
assertEquals("⟦absent⟧", texts.text("absent"));
|
||||||
|
assertFalse(texts.defines("absent"));
|
||||||
|
assertEquals(Locale.getDefault(Locale.Category.DISPLAY), new Localizer(null, Locale.ENGLISH, app).getLocale());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
shared=Application
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
close=Schliessen
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
fallback=Fallback {0}
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
shared=Overridden
|
||||||
|
library=Library
|
||||||
Reference in New Issue
Block a user