feat(studio): restore project selection and loading flow
Restore the project launcher, creation wizard and loading shield with UI2 components. Coordinate real opening phases, a one-second minimum, pending session cleanup and per-project window geometry while retaining the Play slice. Keep global presentation controls in the project window, make the launcher frame resize with its window and prevent root run from chaining the foundation demo after the product exits. Update desktop/installed probes and documentation. Register the existing native bundle after capacity qualification, without changing native binaries or bypassing the execution guard. Validated with unit, desktop, native Play, headless, save, MCP and installed connector gates. Human-tested and accepted under WRK-0018.
This commit is contained in:
@@ -19,6 +19,14 @@ Run these commands from the Studio repository root:
|
||||
./gradlew :prometeu-app:run
|
||||
```
|
||||
|
||||
`./gradlew run` from this repository root also starts only the product. The
|
||||
standalone foundation shell is an explicit developer command,
|
||||
`./gradlew :prometeu-studio-ui-javafx-2:run`; it does not open after Studio exits.
|
||||
|
||||
The project chooser contains project commands and inherits your presentation
|
||||
preferences. Language, theme, typeface and scale controls belong to the project
|
||||
window. Closing the chooser exits Studio without opening a shell.
|
||||
|
||||
Open an existing project from the project chooser and select a qualified runtime
|
||||
installation. Use Play, Pause, Resume and Stop to run the game inside Studio.
|
||||
Games with saves require an existing development save image or an explicitly
|
||||
|
||||
@@ -10,6 +10,13 @@ repositories {
|
||||
dependencies {
|
||||
}
|
||||
|
||||
// An unqualified `run` must launch the product, not every application subproject.
|
||||
tasks.register("run") {
|
||||
group = "application"
|
||||
description = "Starts Prometeu Studio. Foundation demos have explicit module tasks."
|
||||
dependsOn(":prometeu-app:run")
|
||||
}
|
||||
|
||||
val jacocoTestReport = tasks.register<JacocoReport>("jacocoTestReport") {
|
||||
group = "Verification"
|
||||
description = "Generates consolidated unit-test coverage for all subprojects."
|
||||
|
||||
@@ -169,6 +169,31 @@ environment, scaffolding/preparation and JavaFX startup.
|
||||
|
||||
### Integrated Play
|
||||
|
||||
The product starts with a separate project launcher. Add selects a `prometeu.json`
|
||||
and remembers the project without opening it; Forget removes only the reference.
|
||||
New Project opens a five-step wizard using the language catalogue. Successful
|
||||
creation opens the project through the same shield as an existing project. The
|
||||
shield follows actual opening steps and remains visible for at least one second,
|
||||
counted in parallel with preparation. Opening a project does not compile or start
|
||||
the game. Closing its window stops execution and returns to the launcher.
|
||||
|
||||
The launcher inherits presentation preferences and has no language, theme,
|
||||
typeface or scale controls. Closing it exits Studio. `./gradlew run` at the root
|
||||
launches only the product; the independent shell/gallery require their explicit
|
||||
module commands and do not run after the product closes.
|
||||
|
||||
Qualify these windows without a native runtime using disposable projects and
|
||||
isolated presentation storage:
|
||||
|
||||
```bash
|
||||
./gradlew :prometeu-app:studioProjectsDesktopTest
|
||||
```
|
||||
|
||||
Scene captures and environment metadata are written to
|
||||
`prometeu-app/build/projects-desktop-captures`. This gate covers the catalogue,
|
||||
wizard, appearance, geometry, failure feedback and late-session cleanup; the
|
||||
separate Play gates below exercise the native process and game lifecycle.
|
||||
|
||||
Requires a desktop environment and an installed native runtime:
|
||||
|
||||
```bash
|
||||
|
||||
@@ -9,9 +9,14 @@ The normal `prometeu-app` launcher and managed installation MUST use
|
||||
development entry points. The previous frontend is retained for existing adapter
|
||||
qualification; its workspaces are not mounted in the new product.
|
||||
|
||||
Startup MUST show known projects and an action to open an existing project
|
||||
directory. A project MUST be closed before another can open. Closing returns to
|
||||
the chooser. Startup MUST NOT automatically restore the previous project.
|
||||
Startup MUST show a separate compact project launcher with known projects and
|
||||
actions to add an existing `prometeu.json`, open, forget and create a project.
|
||||
Opening MUST hide the launcher and present a separate loading shield; the project
|
||||
window MUST appear only after preparation and the minimum shield duration.
|
||||
A project MUST be closed before another can open. Closing returns to the
|
||||
launcher after execution and session cleanup. Startup MUST NOT automatically
|
||||
restore the previous project. Project-window geometry MUST be restored per
|
||||
project through the neutral window-state port.
|
||||
|
||||
This slice exposes Play, Pause, Resume, Stop, a game viewport, and bounded logs.
|
||||
It MUST NOT initialize an AI client or editor/LSP infrastructure when opening for
|
||||
@@ -19,11 +24,70 @@ Play. Existing headless, MCP, evidence, tests and agent contracts remain availab
|
||||
through their existing entry points and services. Their preservation takes
|
||||
precedence over interactive convenience.
|
||||
|
||||
Project creation UI, editors, workspaces, AI prompts, tuning during Play,
|
||||
Editors, workspaces, AI prompts, tuning during Play,
|
||||
breakpoints, hot reload, PMC builds and distribution/export are outside this
|
||||
slice. Future packaging belongs in Studio as a separate action; Play MUST NOT
|
||||
implicitly package a PMC or a distributable runtime.
|
||||
|
||||
## Project selection, creation and loading
|
||||
|
||||
The launcher MUST reuse the persisted known-project catalogue, ordered by name,
|
||||
and display name, version, language, stdlib and path. Open and Forget MUST require
|
||||
a selection; Open MUST also work by double click or Enter. Adding a manifest MUST
|
||||
validate, remember and select it without automatically opening. Forget MUST remove
|
||||
only the catalogue reference, never files. Cancelled file selection MUST leave the
|
||||
catalogue unchanged. Empty and failed states MUST provide visible feedback.
|
||||
The launcher MUST contain project selection/management and identity only, without
|
||||
global language, theme, typeface or scale controls. It MUST inherit the existing
|
||||
presentation settings; those controls belong to the project window. Closing the
|
||||
launcher MUST exit Studio without presenting an empty project/foundation shell.
|
||||
The internal project frame MUST grow and shrink with the available launcher width
|
||||
and height, allocating additional height to the project list. Smaller viewports or
|
||||
larger text scales MUST retain scrolling so project commands remain accessible.
|
||||
|
||||
The creation wizard MUST use UI2 components and preserve five steps: name,
|
||||
language/stdlib/source root, indentation/runtime details, parent location and
|
||||
confirmation. Options MUST come from `ProjectLanguageCatalog`, with Game as the
|
||||
target. Back MUST preserve input. Cancel MUST return to selection; creation and
|
||||
persistence MUST execute off the FX thread. Successful creation MUST remember and
|
||||
open the project through the common loading flow. A failed opening after creation
|
||||
MUST explain that the project exists and can be opened again. Partial creation
|
||||
MUST retain diagnostics and identify its location without deleting files as an
|
||||
automatic rollback. The catalogue's existing machine-local MCP configuration
|
||||
preparation remains available; it does not start an AI client or LSP.
|
||||
|
||||
The opening coordinator MUST expose real steps for catalogue validation,
|
||||
`openForPlay()` session acquisition, known-project persistence and FX view
|
||||
composition. The sequence MUST accommodate future steps without enabling them in
|
||||
this slice. It MUST NOT initialize the previous workspace initializer merely to
|
||||
provide the loading mechanism. Unmeasurable work MUST use indeterminate progress;
|
||||
time-driven percentages MUST NOT stand in for actual progress.
|
||||
|
||||
The shield MUST identify Studio, its version, the project and current phase. It
|
||||
MUST remain visible for at least one second, measured with a monotonic clock from
|
||||
presentation, in parallel with preparation. The project is ready when validation,
|
||||
session acquisition, required persistence and view composition succeed. If ready
|
||||
before the minimum, show completion while awaiting the remainder; if slower,
|
||||
there MUST be no additional full-second delay. This is independent of native
|
||||
runtime READY and first-frame delivery, which belong to Play.
|
||||
|
||||
Each opening attempt MUST own its pending session, timer and callbacks until
|
||||
handoff or cleanup. Failures at every step, including executor admission and FX
|
||||
composition, MUST release acquired resources before enabling another opening and
|
||||
return to selection with a visible error after the minimum. Cleanup failure MUST
|
||||
retain recovery feedback and block new openings until explicitly retried cleanup
|
||||
succeeds. There MUST be no automatic opening retry. Application exit MUST cancel
|
||||
the cosmetic delay, prevent late presentation and still release late-arriving
|
||||
sessions; cancelling a future is not proof of resource release.
|
||||
|
||||
IO, session teardown and operation waits MUST stay off the FX thread. Window
|
||||
transitions MUST NOT accidentally exit JavaFX while all stages are hidden.
|
||||
Launcher, wizard, shield and project MUST share UI2 theme, locale, typeface and
|
||||
scale, with scrolling as needed to keep commands accessible. The launcher MUST
|
||||
request application exit when closed; closing the project window MUST request
|
||||
project closure and return to selection under the existing Stop/save rules.
|
||||
Timers, views and appearance subscriptions MUST be disposed with their owners.
|
||||
|
||||
## Preparation, process and authority
|
||||
|
||||
Play MUST reuse the compiler/Packer/Shipper preparation pipeline to produce the
|
||||
@@ -143,6 +207,12 @@ called end-to-end input latency or physical scanout latency. CPU/heap observatio
|
||||
and hardware/OS/build flavor MUST accompany performance claims. A heap-used sample
|
||||
does not prove retained-memory bounds; ownership and resource tests do.
|
||||
|
||||
`studioProjectsDesktopTest` qualifies real launcher/wizard/shield/project window
|
||||
transitions with isolated projects/preferences and filesystem catalogue services.
|
||||
It does not require or qualify native execution. Its snapshots include environment
|
||||
metadata under `prometeu-app/build/projects-desktop-captures`. Unit tests with a
|
||||
controlled clock cover fast/slow loading, failure, cleanup retry and late results.
|
||||
|
||||
Executed functional qualification includes macOS ARM64 with Java 25 and the release
|
||||
umbrella distribution produced by `runtime/scripts/local-dist.sh`, including real
|
||||
Pong Play and the deterministic headless process. Capacity qualification identifies
|
||||
|
||||
@@ -167,6 +167,19 @@ tasks.withType<Test>().configureEach {
|
||||
|
||||
tasks.named<Test>("test") { exclude("**/StudioPlayProcessTest.class") }
|
||||
tasks.named<Test>("test") { exclude("**/StudioPlayDesktopTest.class") }
|
||||
tasks.named<Test>("test") { exclude("**/StudioProjectsDesktopTest.class") }
|
||||
tasks.register<Test>("studioProjectsDesktopTest") {
|
||||
group = "verification"
|
||||
description = "Qualifies launcher, new-project wizard, loading shield and window lifecycle on a desktop."
|
||||
testClassesDirs = sourceSets["test"].output.classesDirs
|
||||
classpath = sourceSets["test"].runtimeClasspath
|
||||
useJUnitPlatform()
|
||||
include("**/StudioProjectsDesktopTest.class")
|
||||
systemProperty("java.awt.headless", "false")
|
||||
systemProperty("studio.test.projectsCaptures", layout.buildDirectory.dir("projects-desktop-captures").get().asFile.absolutePath)
|
||||
outputs.upToDateWhen { false }
|
||||
testLogging.showStandardStreams = true
|
||||
}
|
||||
tasks.register<Test>("studioPlayDesktopTest") {
|
||||
group = "verification"
|
||||
description = "Qualifies the default Play frontend with an installed native runtime and a desktop."
|
||||
|
||||
@@ -42,7 +42,7 @@ public final class StudioUiFactory {
|
||||
public p.studio.ui.javafx2.window.StudioWindowCoordinator2 createInteractive(Stage stage){
|
||||
if(interactiveResources==null)throw new IllegalStateException("Interactive resources were not initialized");
|
||||
return new p.studio.ui.javafx2.window.StudioWindowCoordinator2(stage,projectCatalog,knownProjects,projectSessionFactory,
|
||||
Objects.requireNonNull(interactiveExecutions),setupSaver,executor,interactiveResources);
|
||||
Objects.requireNonNull(interactiveExecutions),setupSaver,executor,interactiveResources,languageCatalog,windowStateStore);
|
||||
}
|
||||
private final ProjectCatalog projectCatalog;
|
||||
private final KnownProjects knownProjects;
|
||||
|
||||
@@ -231,6 +231,39 @@
|
||||
"prometeu-headless": "16aa375c2f79884f45d4a54f62bcaa25d62949ff96295422bc4a8e41d10e66a0",
|
||||
"prometeu-runtime": "2ba89830c9588e2854ee9feed0dea92506f22b08224523cea66d5701f66e0046"
|
||||
}
|
||||
},
|
||||
{
|
||||
"profile": {
|
||||
"contractVersion": 1,
|
||||
"profileId": "native-bundle-70741fd42462f538ab02c15999e5eed0c9347cb0983848e30202cd71d6434aed",
|
||||
"runtimeVersion": "0.1.0",
|
||||
"executableSha256": "a6870f026926d45135e5ee31910fb0291648620bae290a1120d2ca2579ea5f94",
|
||||
"limits": {
|
||||
"glyph": 16,
|
||||
"scene": 16
|
||||
},
|
||||
"evidence": [
|
||||
{
|
||||
"bankType": "glyph",
|
||||
"acceptedPreloads": 16,
|
||||
"rejectedPreloads": 17,
|
||||
"evidencePath": "asset-capacity/evidence/native-bundle-70741fd42462f538ab02c15999e5eed0c9347cb0983848e30202cd71d6434aed.json",
|
||||
"evidenceSha256": "09070c30416bcd12e20a18cb23fabe26a720e49b480f8395f873e2111aaf74e5"
|
||||
},
|
||||
{
|
||||
"bankType": "scene",
|
||||
"acceptedPreloads": 16,
|
||||
"rejectedPreloads": 17,
|
||||
"evidencePath": "asset-capacity/evidence/native-bundle-70741fd42462f538ab02c15999e5eed0c9347cb0983848e30202cd71d6434aed.json",
|
||||
"evidenceSha256": "09070c30416bcd12e20a18cb23fabe26a720e49b480f8395f873e2111aaf74e5"
|
||||
}
|
||||
]
|
||||
},
|
||||
"executables": {
|
||||
"prometeu": "a6870f026926d45135e5ee31910fb0291648620bae290a1120d2ca2579ea5f94",
|
||||
"prometeu-headless": "5107d2d0fc30149cb2ece3124b0622654bd991871d6a3c2b26f22e97dd2645f9",
|
||||
"prometeu-runtime": "a29e75597ffb7110854452c9ce4802167a78e62f6b19526bc12b83584a52996f"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
+1675
File diff suppressed because it is too large
Load Diff
@@ -163,9 +163,9 @@ class StudioPlayDesktopTest {
|
||||
fire(stage,"play");running(window,stage,facts);
|
||||
fx(()->{window.requestCloseProject();return null;});
|
||||
await(()->{try{return fx(()->window.projectSession()==null);}catch(Exception e){throw new RuntimeException(e);}},facts);
|
||||
fx(()->{assertNotNull(stage.getScene().lookup("#open-project"));return null;});capture(stage,"projects.png");
|
||||
fx(()->{assertTrue(window.launcherStage().isShowing());assertFalse(stage.isShowing());assertNotNull(window.launcherStage().getScene().lookup("#open-project"));return null;});capture(window.launcherStage(),"projects.png");
|
||||
assertEquals(0,runtimeCount());assertEquals(0,heartbeatThreads());
|
||||
}finally{fx(()->{window.close();stage.hide();return null;});}
|
||||
}finally{fx(window::closeAsync).toCompletableFuture().get(15,TimeUnit.SECONDS);}
|
||||
}
|
||||
}
|
||||
static void fire(Stage stage,String id)throws Exception{fx(()->{Button button=(Button)stage.getScene().lookup("#"+id);assertFalse(button.isDisabled(),id+" disabled");button.fire();return null;});}
|
||||
|
||||
@@ -0,0 +1,179 @@
|
||||
package p.studio.app;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import javafx.application.Platform;
|
||||
import javafx.scene.Node;
|
||||
import javafx.scene.control.*;
|
||||
import javafx.scene.input.*;
|
||||
import javafx.stage.Stage;
|
||||
import javafx.stage.Window;
|
||||
import org.junit.jupiter.api.*;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import p.studio.api.execution.*;
|
||||
import p.studio.api.preferences.*;
|
||||
import p.studio.api.project.*;
|
||||
import p.studio.api.session.*;
|
||||
import p.studio.core.execution.DefaultExecutionSession;
|
||||
import p.studio.core.project.*;
|
||||
import p.studio.ui.javafx2.appearance.*;
|
||||
import p.studio.ui.javafx2.i18n.StudioLanguage;
|
||||
import p.studio.ui.javafx2.preferences.SettingsStore;
|
||||
import p.studio.ui.javafx2.window.*;
|
||||
|
||||
import java.lang.reflect.Proxy;
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.*;
|
||||
import java.util.concurrent.atomic.*;
|
||||
import java.util.function.*;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
/** Real stages and filesystem catalogue, isolated preferences/projects, no native execution. */
|
||||
@Tag("integration")
|
||||
class StudioProjectsDesktopTest {
|
||||
@TempDir Path temporary;
|
||||
static <T>T fx(Callable<T> action)throws Exception {
|
||||
var task=new FutureTask<>(action);Platform.runLater(task);return task.get(15,TimeUnit.SECONDS);
|
||||
}
|
||||
static void await(Callable<Boolean> condition)throws Exception {
|
||||
long end=System.nanoTime()+TimeUnit.SECONDS.toNanos(15);
|
||||
while(System.nanoTime()<end){if(condition.call())return;Thread.sleep(20);}fail("Desktop condition timed out");
|
||||
}
|
||||
@BeforeAll static void start()throws Exception {var ready=new CompletableFuture<Void>();Platform.startup(()->{Platform.setImplicitExit(false);ready.complete(null);});ready.get(15,TimeUnit.SECONDS);}
|
||||
@AfterAll static void end(){Platform.exit();}
|
||||
static void fire(Stage stage,String id)throws Exception {fx(()->{var b=(Button)stage.getScene().lookup("#"+id);assertNotNull(b,id);assertFalse(b.isDisabled(),id);b.fire();return null;});}
|
||||
static Stage wizard()throws Exception {return fx(()->(Stage)Window.getWindows().stream().filter(w->w.isShowing()&&w.getScene().lookup("#wizard-name")!=null).findFirst().orElseThrow());}
|
||||
static Stage shield()throws Exception {return fx(()->(Stage)Window.getWindows().stream().filter(w->w.isShowing()&&w.getScene().lookup("#loading-phase")!=null).findFirst().orElseThrow());}
|
||||
|
||||
@Test void completeProjectFlowWindowsAppearanceWizardAndRecovery()throws Exception {
|
||||
var mapper=new ObjectMapper();Path projects=Files.createDirectories(temporary.resolve("projects"));
|
||||
var setups=new ProjectLocalStudioSetupStore(mapper);var catalog=new ProjectCatalogService(projects,mapper,setups);
|
||||
var known=new KnownProjectsService(temporary.resolve("known-projects.txt"),catalog);
|
||||
var template=new ProjectLanguageTemplate("pbs",List.of(new ProjectLanguageTemplate.StdlibOption(1,ProjectLanguageTemplate.Stability.DEFAULT)),
|
||||
new ProjectLanguageTemplate.StdlibOption(1,ProjectLanguageTemplate.Stability.DEFAULT),List.of("src"),"src");
|
||||
var seed=catalog.createProject(new ProjectCreationRequest("Existing Game",projects,"pbs",1,ProjectTarget.Game,"src",4,null));
|
||||
var initial=PresentationSettings.defaults(Locale.ENGLISH);
|
||||
var resources=new WindowResources(initial,new SettingsStore(){public PresentationSettings load(){return initial;}public void save(PresentationSettings value){assertFalse(Platform.isFxApplicationThread());}});
|
||||
var worker=Executors.newFixedThreadPool(3);var sessionsOpened=new AtomicInteger();var sessionsClosed=new AtomicInteger();
|
||||
var failOpen=new AtomicBoolean();var hold=new AtomicReference<CountDownLatch>();
|
||||
ProjectSessionFactory sessions=new ProjectSessionFactory(){
|
||||
public ProjectSession open(ProjectReference ref){throw new AssertionError("editor session must not start");}
|
||||
public ProjectSession openForPlay(ProjectReference ref){
|
||||
assertFalse(Platform.isFxApplicationThread());var latch=hold.getAndSet(null);
|
||||
if(latch!=null)try{assertTrue(latch.await(10,TimeUnit.SECONDS));}catch(InterruptedException e){throw new RuntimeException(e);}
|
||||
if(failOpen.get())throw new IllegalStateException("session-fixture-failure");
|
||||
sessionsOpened.incrementAndGet();var execution=new DefaultExecutionSession();var setup=setups.load(ref);
|
||||
return (ProjectSession)Proxy.newProxyInstance(getClass().getClassLoader(),new Class[]{ProjectSession.class},(proxy,method,args)->switch(method.getName()){
|
||||
case "projectReference"->ref;
|
||||
case "projectLocalStudioSetup"->setup;
|
||||
case "executionSession"->execution;
|
||||
case "close"->{assertFalse(Platform.isFxApplicationThread());execution.close();sessionsClosed.incrementAndGet();yield null;}
|
||||
default->throw new AssertionError(method.getName());
|
||||
});
|
||||
}
|
||||
};
|
||||
var geometries=new ConcurrentHashMap<Path,WindowGeometry>();
|
||||
WindowStateStore windows=new WindowStateStore(){
|
||||
public Optional<WindowGeometry> load(ProjectReference ref){assertFalse(Platform.isFxApplicationThread());return Optional.ofNullable(geometries.get(ref.rootPath()));}
|
||||
public void save(ProjectReference ref,WindowGeometry geometry){assertFalse(Platform.isFxApplicationThread());geometries.put(ref.rootPath(),geometry);}
|
||||
};
|
||||
Stage stage=fx(Stage::new);
|
||||
var window=fx(()->new StudioWindowCoordinator2(stage,catalog,known,sessions,null,(p,s)->{},worker,resources,()->List.of(template),windows));
|
||||
try {
|
||||
fx(()->{window.showLauncher();return null;});Stage launcher=fx(window::launcherStage);
|
||||
fx(()->{for(String id:List.of("studio-shell","theme-select","language-select","typeface-select","scale-select"))
|
||||
assertNull(launcher.getScene().lookup("#"+id),"Project selection must not contain "+id);return null;});
|
||||
await(()->fx(()->!launcher.getScene().lookup("#open-project").isDisabled()));
|
||||
assertFalse(fx(stage::isShowing));capture(launcher,"launcher-dark");
|
||||
double[] before=launcherLayout(launcher);
|
||||
assertTrue(before[0]>=900,"The default chooser should provide a wider project list");
|
||||
fx(()->{launcher.setWidth(launcher.getWidth()+140);launcher.setHeight(launcher.getHeight()+80);return null;});
|
||||
capture(launcher,"launcher-expanded");double[] expanded=launcherLayout(launcher);
|
||||
assertEquals(expanded[0]-before[0],expanded[2]-before[2],3,"Frame must follow viewport width");
|
||||
assertEquals(expanded[1]-before[1],expanded[3]-before[3],3,"Frame must follow viewport height");
|
||||
assertTrue(expanded[4]>before[4]+40,"Additional window height must reach the project list");
|
||||
fx(()->{launcher.setWidth(launcher.getWidth()-140);launcher.setHeight(launcher.getHeight()-80);return null;});
|
||||
capture(launcher,"launcher-restored");double[] restored=launcherLayout(launcher);
|
||||
assertEquals(before[2],restored[2],3,"Frame must shrink with the window");
|
||||
assertEquals(before[3],restored[3],3,"Frame must shrink with the window");
|
||||
System.out.println("launcher layout [viewportW, viewportH, frameW, frameH, listH]: default="+Arrays.toString(before)+", expanded="+Arrays.toString(expanded)+", restored="+Arrays.toString(restored));
|
||||
double[] normalWindow=fx(()->new double[]{launcher.getWidth(),launcher.getHeight()});
|
||||
fx(()->{launcher.setWidth(600);launcher.setHeight(440);return null;});capture(launcher,"launcher-minimum");
|
||||
fx(()->{((ScrollPane)launcher.getScene().lookup("#launcher-scroll")).setVvalue(1);return null;});capture(launcher,"launcher-minimum-actions");
|
||||
fx(()->{
|
||||
var page=(ScrollPane)launcher.getScene().lookup("#launcher-scroll");var viewport=page.lookup(".viewport");
|
||||
var bounds=viewport.localToScene(viewport.getBoundsInLocal());
|
||||
for(String id:List.of("open-project","add-project","new-project","forget-project")){
|
||||
var button=launcher.getScene().lookup("#"+id);var area=button.localToScene(button.getBoundsInLocal());
|
||||
assertTrue(bounds.contains(area.getCenterX(),area.getCenterY()),id+" must remain reachable in a small window");
|
||||
}
|
||||
launcher.setWidth(normalWindow[0]);launcher.setHeight(normalWindow[1]);page.setVvalue(0);return null;
|
||||
});
|
||||
// Add remembers and selects without opening. Forget removes only the persisted reference.
|
||||
fx(()->{window.addProjectManifest(seed.rootPath().resolve("prometeu.json"));return null;});
|
||||
await(()->fx(()->!launcher.getScene().lookup("#forget-project").isDisabled()));
|
||||
assertEquals(0,sessionsOpened.get());fire(launcher,"forget-project");
|
||||
await(()->fx(()->launcher.getScene().lookup("#open-project").isDisabled()&&!launcher.getScene().lookup("#add-project").isDisabled()));
|
||||
assertTrue(Files.isRegularFile(seed.rootPath().resolve("prometeu.json")));assertTrue(known.listKnownProjects().isEmpty());
|
||||
fx(()->{window.addProjectManifest(seed.rootPath().resolve("prometeu.json"));return null;});
|
||||
await(()->fx(()->!launcher.getScene().lookup("#open-project").isDisabled()));
|
||||
long started=System.nanoTime();fire(launcher,"open-project");capture(shield(),"shield-ready");
|
||||
assertFalse(fx(stage::isShowing));assertFalse(fx(launcher::isShowing));
|
||||
await(()->fx(()->window.projectSession()!=null));assertTrue(System.nanoTime()-started>=TimeUnit.SECONDS.toNanos(1));
|
||||
assertTrue(fx(stage::isShowing));capture(stage,"project-ready");
|
||||
fx(()->{stage.setWidth(1040);stage.setHeight(730);window.requestCloseProject();return null;});
|
||||
await(()->fx(()->launcher.isShowing()&&!launcher.getScene().lookup("#open-project").isDisabled()));
|
||||
// Keyboard opening uses the selected project and restores its geometry.
|
||||
fx(()->{Node list=launcher.getScene().lookup("#known-projects");list.fireEvent(new KeyEvent(KeyEvent.KEY_PRESSED,"","",KeyCode.ENTER,false,false,false,false));return null;});
|
||||
await(()->fx(()->window.projectSession()!=null));assertEquals(1040,fx(stage::getWidth),3);assertEquals(730,fx(stage::getHeight),3);
|
||||
fx(()->{((ComboBox<Theme>)stage.getScene().lookup("#theme-select")).setValue(Theme.LIGHT);
|
||||
((ComboBox<StudioLanguage>)stage.getScene().lookup("#language-select")).setValue(StudioLanguage.PORTUGUESE);
|
||||
window.requestCloseProject();return null;});await(()->fx(()->launcher.isShowing()&&!launcher.getScene().lookup("#new-project").isDisabled()));
|
||||
// A wizard cancellation does not leave a stale wizard owner behind.
|
||||
fire(launcher,"new-project");await(()->fx(()->Window.getWindows().stream().anyMatch(w->w.isShowing()&&w.getScene().lookup("#wizard-name")!=null)));
|
||||
fire(wizard(),"wizard-cancel");fire(launcher,"new-project");
|
||||
await(()->fx(()->Window.getWindows().stream().anyMatch(w->w.isShowing()&&w.getScene().lookup("#wizard-name")!=null)));
|
||||
Stage wizard=wizard();fire(wizard,"wizard-next");
|
||||
assertFalse(fx(()->((Label)wizard.getScene().lookup("#wizard-feedback")).getText().isBlank()));
|
||||
fx(()->{((TextField)wizard.getScene().lookup("#wizard-name")).setText("New Adventure");return null;});
|
||||
fire(wizard,"wizard-next");fire(wizard,"wizard-back");
|
||||
assertEquals("New Adventure",fx(()->((TextField)wizard.getScene().lookup("#wizard-name")).getText()));
|
||||
fire(wizard,"wizard-next");fire(wizard,"wizard-next");fire(wizard,"wizard-next");fire(wizard,"wizard-next");
|
||||
// The selector and wizard inherit presentation chosen in the project window.
|
||||
assertTrue(fx(()->((Label)wizard.getScene().lookup("#wizard-summary")).getText().contains("Nome: New Adventure")));
|
||||
capture(wizard,"wizard-confirm-light-pt");fire(wizard,"wizard-create");
|
||||
await(()->fx(()->window.projectSession()!=null));assertEquals("New Adventure",fx(()->window.projectSession().projectReference().name()));
|
||||
Path created=projects.resolve("new-adventure");assertTrue(Files.isRegularFile(created.resolve("prometeu.json")));assertTrue(Files.isDirectory(created.resolve("src")));
|
||||
fx(()->{((ComboBox<Double>)stage.getScene().lookup("#scale-select")).setValue(1.5);window.requestCloseProject();return null;});
|
||||
await(()->fx(()->launcher.isShowing()&&!launcher.getScene().lookup("#open-project").isDisabled()));capture(launcher,"launcher-light-pt-150");
|
||||
fx(()->{((ScrollPane)launcher.getScene().lookup("#launcher-scroll")).setVvalue(1);return null;});capture(launcher,"launcher-light-pt-150-actions");
|
||||
failOpen.set(true);fire(launcher,"open-project");
|
||||
await(()->fx(()->launcher.isShowing()&&((Label)launcher.getScene().lookup("#launcher-notice")).getText().contains("session-fixture-failure")));
|
||||
assertNull(fx(window::projectSession));assertTrue(fx(()->!launcher.getScene().lookup("#open-project").isDisabled()));capture(launcher,"open-failure");
|
||||
failOpen.set(false);var latch=new CountDownLatch(1);hold.set(latch);fire(launcher,"open-project");
|
||||
await(()->hold.get()==null);var stopped=fx(window::closeAsync).toCompletableFuture();assertFalse(stopped.isDone());
|
||||
latch.countDown();stopped.get(15,TimeUnit.SECONDS);Thread.sleep(1100);
|
||||
assertFalse(fx(stage::isShowing));assertFalse(fx(launcher::isShowing));assertEquals(sessionsOpened.get(),sessionsClosed.get());
|
||||
assertTrue(fx(()->Window.getWindows().stream().noneMatch(Window::isShowing)));
|
||||
System.out.println("project desktop: sessions="+sessionsOpened.get()+", closed="+sessionsClosed.get()+", os="+System.getProperty("os.name")+", java="+System.getProperty("java.version"));
|
||||
} finally {fx(window::closeAsync).toCompletableFuture().get(15,TimeUnit.SECONDS);worker.shutdown();assertTrue(worker.awaitTermination(15,TimeUnit.SECONDS));}
|
||||
}
|
||||
static double[] launcherLayout(Stage launcher)throws Exception {
|
||||
return fx(()->{
|
||||
var page=(ScrollPane)launcher.getScene().lookup("#launcher-scroll");
|
||||
var frame=(javafx.scene.layout.Region)launcher.getScene().lookup("#projects-frame");
|
||||
var list=(ListView<?>)launcher.getScene().lookup("#known-projects");
|
||||
return new double[]{page.getViewportBounds().getWidth(),page.getViewportBounds().getHeight(),frame.getWidth(),frame.getHeight(),list.getHeight()};
|
||||
});
|
||||
}
|
||||
static void capture(Stage stage,String name)throws Exception {
|
||||
Thread.sleep(120);
|
||||
fx(()->{stage.getScene().getRoot().applyCss();stage.getScene().getRoot().layout();var image=stage.getScene().snapshot(null);
|
||||
var output=new java.awt.image.BufferedImage((int)image.getWidth(),(int)image.getHeight(),java.awt.image.BufferedImage.TYPE_INT_ARGB);
|
||||
for(int y=0;y<output.getHeight();y++)for(int x=0;x<output.getWidth();x++)output.setRGB(x,y,image.getPixelReader().getArgb(x,y));
|
||||
Path directory=Path.of(System.getProperty("studio.test.projectsCaptures"));Files.createDirectories(directory);
|
||||
javax.imageio.ImageIO.write(output,"png",directory.resolve(name+".png").toFile());
|
||||
Files.writeString(directory.resolve(name+".txt"),"os="+System.getProperty("os.name")+"\njava="+System.getProperty("java.version")+"\noutputScale="+stage.getOutputScaleX()+"x"+stage.getOutputScaleY()+"\nscene="+image.getWidth()+"x"+image.getHeight()+"\n");return null;});
|
||||
}
|
||||
}
|
||||
@@ -67,15 +67,52 @@ class InstalledConnectorTest {
|
||||
builder.environment().clear(); builder.environment().put("PATH", "/usr/bin:/bin"); builder.environment().put("HOME", System.getProperty("user.home"));
|
||||
return builder;
|
||||
}
|
||||
@Test void closingInstalledLauncherEndsApplicationWithoutPresentingShell() throws Exception {
|
||||
Path base=temporary.resolve("Studio close test");
|
||||
ManagedStudioInstallation.install(Path.of(System.getProperty("studio.test.distribution")),base);
|
||||
String fixtures=Path.of(LauncherCloseMain.class.getProtectionDomain().getCodeSource().getLocation().toURI()).toString();
|
||||
Path log=temporary.resolve("launcher-close.log");
|
||||
var process=minimal(base.resolve("current/runtime/bin/java").toString(),"-cp",
|
||||
base.resolve("current/lib/*")+java.io.File.pathSeparator+fixtures,LauncherCloseMain.class.getName())
|
||||
.redirectErrorStream(true).redirectOutput(log.toFile()).start();
|
||||
try {
|
||||
assertTrue(process.waitFor(20,TimeUnit.SECONDS),"Closing selection must terminate the installed application");
|
||||
assertEquals(0,process.exitValue(),Files.readString(log));
|
||||
} finally {process.destroyForcibly();}
|
||||
}
|
||||
public static class LauncherCloseMain {
|
||||
public static void main(String[] args) {
|
||||
javafx.application.Application.launch(LauncherCloseProbe.class,args);
|
||||
if(!LauncherCloseProbe.stopped)throw new AssertionError("Application.stop was not called");
|
||||
if(LauncherCloseProbe.failure!=null)throw new AssertionError("Unexpected shell presentation",LauncherCloseProbe.failure);
|
||||
}
|
||||
}
|
||||
public static class LauncherCloseProbe extends p.studio.app.App {
|
||||
static boolean stopped;
|
||||
static Throwable failure;
|
||||
@Override public void start(javafx.stage.Stage stage) {
|
||||
super.start(stage);
|
||||
if(stage.isShowing())throw new AssertionError("Project shell must stay hidden before a project is opened");
|
||||
stage.showingProperty().addListener((o,a,b)->{if(b){failure=new AssertionError("Closing selection showed the project shell");javafx.application.Platform.exit();}});
|
||||
var launcher=(javafx.stage.Stage)javafx.stage.Window.getWindows().stream().filter(window->window.isShowing()
|
||||
&&window.getScene()!=null&&window.getScene().lookup("#project-chooser")!=null).findFirst().orElseThrow();
|
||||
for(String id:List.of("studio-shell","theme-select","language-select","typeface-select","scale-select"))
|
||||
if(launcher.getScene().lookup("#"+id)!=null)throw new AssertionError("Selection contains global control "+id);
|
||||
javafx.application.Platform.runLater(()->launcher.fireEvent(new javafx.stage.WindowEvent(launcher,javafx.stage.WindowEvent.WINDOW_CLOSE_REQUEST)));
|
||||
}
|
||||
@Override public void stop() throws Exception {super.stop();stopped=true;}
|
||||
}
|
||||
public static class DesktopProbe {
|
||||
public static void main(String[] args) throws Exception {
|
||||
var application=new p.studio.app.App();application.init();
|
||||
javafx.application.Platform.startup(() -> {
|
||||
try {
|
||||
var stage = new javafx.stage.Stage();application.start(stage);
|
||||
if(stage.getScene().lookup("#studio-shell")==null||stage.getScene().lookup("#open-project")==null)
|
||||
var launcher=javafx.stage.Window.getWindows().stream().filter(window->window.isShowing()
|
||||
&&window.getScene()!=null&&window.getScene().lookup("#project-chooser")!=null).findFirst().orElseThrow();
|
||||
if(stage.isShowing()||launcher.getScene().lookup("#studio-shell")!=null||launcher.getScene().lookup("#open-project")==null)
|
||||
throw new AssertionError("Installed app did not open the new project chooser");
|
||||
application.stop();stage.hide();System.exit(0);
|
||||
application.stop();stage.hide();launcher.hide();System.exit(0);
|
||||
} catch (Throwable failure) { failure.printStackTrace();System.exit(2); }
|
||||
});
|
||||
}
|
||||
|
||||
@@ -16,14 +16,22 @@ From the Studio repository:
|
||||
```
|
||||
|
||||
The standalone shell contains identity, presentation selectors and an empty central
|
||||
area. The application mounts its chooser/Play view in that shell. The **separate
|
||||
area. The product uses a separate project launcher, creation wizard and loading
|
||||
shield, then mounts Play in its project shell. The **separate
|
||||
development gallery** demonstrates components, validation, progress, both fonts and
|
||||
configurable text scale. Gallery actions operate on sample text only.
|
||||
|
||||
The product project chooser contains identity, the project list and project
|
||||
commands only. It inherits presentation settings; language, theme, typeface and
|
||||
scale selectors remain in the project window. From the repository root, an
|
||||
unqualified `run` starts the product and skips the foundation demo. Launch the
|
||||
foundation with the explicit module command above (or from that module directory).
|
||||
|
||||
```sh
|
||||
./gradlew :prometeu-studio-ui-javafx-2:test
|
||||
./gradlew :prometeu-studio-ui-javafx-2:desktopTest
|
||||
./gradlew :prometeu-studio-ui-javafx-2:installDist
|
||||
./gradlew :prometeu-app:studioProjectsDesktopTest
|
||||
```
|
||||
|
||||
`desktopTest` requires a desktop session and opens temporary windows. It exercises actual JavaFX behavior and writes PNG captures with environment metadata under `build/desktop-captures`. Normal unit tests do not require a display. Clipboard testing replaces clipboard content with a test string. Preference tests use an isolated disposable node rather than application preferences.
|
||||
@@ -53,7 +61,7 @@ Semantic theme colors are in `styles/dark.css` and `styles/light.css`. Component
|
||||
|
||||
`UserSettingsStore` uses the Java Preferences node `p/studio/ui/javafx2` for theme, language, bundled typeface and text scale (75–200%). Startup uses dark, Departure Mono and 100%; a supported system locale chooses pt-BR, otherwise English. Invalid individual values fall back independently with diagnostics.
|
||||
|
||||
Load preferences and font/bundle resources before composing views. `SettingsPersistence` debounces writes on its worker, flushes the last choice asynchronously on close, and shuts the worker down. It never writes from the FX thread. No project state or previous frontend preferences are migrated.
|
||||
Load preferences and font/bundle resources before composing views. `SettingsPersistence` debounces writes on its worker, flushes the last choice asynchronously on close, and shuts the worker down. It never writes from the FX thread. Project-window geometry is restored per project through `WindowStateStore`, with IO off the FX thread. Previous frontend presentation preferences are not migrated.
|
||||
|
||||
All interface messages live in UTF-8 `messages_en.properties` and `messages_pt_BR.properties`. Missing translations diagnose and fall back to English; an absent English key displays `[key]`. Bundle parity is checked by unit tests. Dynamic feedback retains its key/arguments and is reformatted on locale changes; user-authored text retains its value.
|
||||
|
||||
@@ -72,4 +80,13 @@ Unit tests verify preference codecs/storage, asynchronous final persistence, loc
|
||||
|
||||
The initial desktop target is macOS. Snapshot PNGs are logical scene captures; metadata records actual output scale, but these captures do not themselves prove physical-pixel sharpness at every scale. Windows/Linux, a screen-reader walkthrough and native multi-step IME input remain environment-specific manual qualification. Preserving JavaFX semantics is not a claim that those checks were completed.
|
||||
|
||||
No project navigation, editor host, ACP, domain workspace, asset authoring, build/run/debug or shipping feature is implemented here.
|
||||
The launcher supports known-project selection, manifest addition, opening,
|
||||
forgetting and a five-step new-project wizard through neutral API ports. Loading
|
||||
uses observable real steps and a one-second minimum counted in parallel; pending
|
||||
sessions and late results remain owned until presentation or cleanup. A failed
|
||||
cleanup blocks a replacement opening and offers an explicit cleanup retry.
|
||||
`closeAsync()` completes after coordinated session and presentation teardown;
|
||||
callers must await it off the FX thread before shutting down their worker pool.
|
||||
|
||||
No editor host, ACP, domain workspace, asset authoring, debug or shipping view is
|
||||
mounted in this product. Native Play remains behind the execution API.
|
||||
|
||||
@@ -12,6 +12,15 @@ application {
|
||||
mainClass = "p.studio.ui.javafx2.StudioLauncher"
|
||||
}
|
||||
|
||||
// Gradle's unqualified task selector also finds this application's `run` after
|
||||
// the product's run. Keep the foundation demo opt-in when invoked at the root.
|
||||
tasks.named<JavaExec>("run") {
|
||||
onlyIf("the foundation demo was explicitly selected") {
|
||||
gradle.startParameter.currentDir.toPath().normalize().startsWith(projectDir.toPath().normalize()) ||
|
||||
gradle.startParameter.taskNames.any { it.removePrefix(":") == "prometeu-studio-ui-javafx-2:run" }
|
||||
}
|
||||
}
|
||||
|
||||
dependencies { implementation(project(":prometeu-studio-api")) }
|
||||
|
||||
distributions {
|
||||
|
||||
+147
@@ -0,0 +1,147 @@
|
||||
package p.studio.ui.javafx2.window;
|
||||
|
||||
import javafx.geometry.Insets;
|
||||
import javafx.scene.Node;
|
||||
import javafx.scene.Scene;
|
||||
import javafx.scene.control.*;
|
||||
import javafx.scene.layout.*;
|
||||
import javafx.stage.*;
|
||||
import p.studio.api.project.*;
|
||||
import p.studio.ui.javafx2.appearance.AppearanceContext;
|
||||
import p.studio.ui.javafx2.components.*;
|
||||
import p.studio.ui.javafx2.shell.MinimalShell;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.*;
|
||||
import java.util.function.*;
|
||||
|
||||
/** Five persistent input pages. Domain creation runs on the operation executor. */
|
||||
final class NewProjectWizard2 {
|
||||
private final Stage stage=new Stage();
|
||||
private final AppearanceContext context;
|
||||
private final Executor executor;
|
||||
private final Function<ProjectCreationRequest,ProjectReference> create;
|
||||
private final BiConsumer<ProjectReference,Boolean> completed;
|
||||
private final StudioTextField name=new StudioTextField(),location=new StudioTextField(),runtime=new StudioTextField();
|
||||
private final StudioSelect<ProjectLanguageTemplate> language;
|
||||
private final StudioSelect<ProjectLanguageTemplate.StdlibOption> stdlib;
|
||||
private final StudioSelect<String> source;
|
||||
private final StudioSelect<Integer> indentation;
|
||||
private final Label heading=new Label(),description=new Label(),summary=new Label(),feedback=new Label();
|
||||
private final VBox body=new VBox(14);
|
||||
private final List<Node> pages;
|
||||
private final Button back,next,finish,cancel;
|
||||
private final CompletableFuture<Void> dismissed=new CompletableFuture<>();
|
||||
private int step;
|
||||
private boolean busy,closeRequested;
|
||||
private String feedbackKey;
|
||||
private Object[] feedbackArguments=new Object[0];
|
||||
|
||||
NewProjectWizard2(Window owner, AppearanceContext context, Path projectsRoot,
|
||||
List<ProjectLanguageTemplate> templates, String defaultLanguage, Executor executor,
|
||||
Function<ProjectCreationRequest,ProjectReference> create, BiConsumer<ProjectReference,Boolean> completed) {
|
||||
this.context=context;this.executor=executor;this.create=create;this.completed=completed;
|
||||
stage.initOwner(owner);stage.initModality(Modality.WINDOW_MODAL);
|
||||
name.setId("wizard-name");location.setId("wizard-location");runtime.setId("wizard-runtime");
|
||||
location.setText(projectsRoot.toString());
|
||||
language=new StudioSelect<>(context,"wizard.language",ProjectLanguageTemplate::languageId);
|
||||
language.setId("wizard-language");language.getItems().setAll(templates);
|
||||
stdlib=new StudioSelect<>(context,"wizard.stdlib",option->context.text("wizard.stdlibOption",option.version(),
|
||||
context.text("wizard.stability."+option.stability().name())));stdlib.setId("wizard-stdlib");
|
||||
source=new StudioSelect<>(context,"wizard.source",Function.identity());source.setId("wizard-source");
|
||||
indentation=new StudioSelect<>(context,"wizard.indentation",String::valueOf,2,4,8);indentation.setValue(4);indentation.setId("wizard-indentation");
|
||||
language.setOnAction(e->applyLanguage());
|
||||
language.setValue(templates.stream().filter(t->t.languageId().equals(defaultLanguage)).findFirst().orElse(templates.isEmpty()?null:templates.getFirst()));
|
||||
applyLanguage();
|
||||
summary.setWrapText(true);summary.setId("wizard-summary");
|
||||
pages=List.of(MinimalShell.labeled(context,"wizard.name",name),
|
||||
new VBox(14,MinimalShell.labeled(context,"wizard.language",language),MinimalShell.labeled(context,"wizard.stdlib",stdlib),MinimalShell.labeled(context,"wizard.source",source)),
|
||||
new VBox(14,MinimalShell.labeled(context,"wizard.indentation",indentation),browseRow(runtime,"wizard.runtime")),
|
||||
browseRow(location,"wizard.location"),summary);
|
||||
back=button("wizard.back","wizard-back",()->{if(step>0){step--;render();}});
|
||||
next=button("wizard.next","wizard-next",()->{if(valid(step)){step++;render();}});
|
||||
finish=button("wizard.create","wizard-create",this::finish);
|
||||
cancel=button("wizard.cancel","wizard-cancel",this::requestClose);
|
||||
next.setDefaultButton(true);cancel.setCancelButton(true);
|
||||
heading.getStyleClass().add("studio-title");heading.setWrapText(true);description.setWrapText(true);
|
||||
feedback.setWrapText(true);feedback.setId("wizard-feedback");feedback.getStyleClass().add("project-error");
|
||||
FlowPane actions=new FlowPane(12,10,back,next,finish,cancel);
|
||||
VBox content=new VBox(18,heading,description,body,feedback,actions);content.setPadding(new Insets(24));
|
||||
ScrollPane scroll=new ScrollPane(content);scroll.setFitToWidth(true);context.attach(scroll);
|
||||
stage.setScene(new Scene(scroll,760,600));stage.setMinWidth(580);stage.setMinHeight(400);
|
||||
stage.setOnCloseRequest(e->{e.consume();requestClose();});
|
||||
stage.setOnHidden(e->{context.close();dismissed.complete(null);});
|
||||
context.observe(this::strings);render();
|
||||
}
|
||||
void show() { stage.show();stage.centerOnScreen();stage.toFront();name.requestFocus(); }
|
||||
CompletionStage<Void> dismissed() { return dismissed; }
|
||||
CompletionStage<Void> requestClose() {
|
||||
closeRequested=true;
|
||||
if(!busy)stage.hide();
|
||||
return dismissed;
|
||||
}
|
||||
private Button button(String key,String id,Runnable action) {
|
||||
Button result=new StudioButton(context,key,false);result.setId(id);result.setOnAction(e->action.run());return result;
|
||||
}
|
||||
private Node browseRow(StudioTextField field,String label) {
|
||||
Button browse=button("play.browse",field.getId()+"-browse",()->{
|
||||
DirectoryChooser chooser=new DirectoryChooser();chooser.setTitle(context.text(label));
|
||||
var selected=chooser.showDialog(stage);if(selected!=null)field.setText(selected.getAbsolutePath());
|
||||
});
|
||||
HBox row=new HBox(12,field,browse);HBox.setHgrow(field,Priority.ALWAYS);
|
||||
return MinimalShell.labeled(context,label,row);
|
||||
}
|
||||
private void applyLanguage() {
|
||||
var template=language.getValue();
|
||||
stdlib.getItems().setAll(template==null?List.of():template.stdlibOptions());
|
||||
source.getItems().setAll(template==null?List.of():template.sourceRoots());
|
||||
stdlib.setValue(template==null?null:template.defaultStdlib());source.setValue(template==null?null:template.defaultSourceRoot());
|
||||
}
|
||||
private void render() {
|
||||
body.getChildren().setAll(pages.get(step));feedbackKey=null;feedback.setText("");
|
||||
back.setDisable(step==0||busy);next.setVisible(step<4);next.setManaged(step<4);
|
||||
finish.setVisible(step==4);finish.setManaged(step==4);finish.setDefaultButton(step==4);next.setDefaultButton(step<4);
|
||||
strings();
|
||||
}
|
||||
private void strings() {
|
||||
stage.setTitle(context.text("projects.new"));heading.setText(context.text("wizard.step."+step));
|
||||
description.setText(context.text("wizard.description."+step));
|
||||
if(feedbackKey!=null)feedback.setText(context.text(feedbackKey,feedbackArguments));
|
||||
if(step==4)summary.setText(context.text("wizard.summary",name.getText().trim(),language.getValue().languageId(),
|
||||
stdlib.getValue().version(),source.getValue(),indentation.getValue(),runtime.getText().isBlank()?"—":runtime.getText().trim(),location.getText().trim()));
|
||||
}
|
||||
private boolean valid(int page) {
|
||||
String key=null;
|
||||
if(page==0&&name.getText().isBlank())key="wizard.name.required";
|
||||
if(page==1&&(language.getValue()==null||stdlib.getValue()==null||source.getValue()==null))key="wizard.language.required";
|
||||
if(page==2&&(indentation.getValue()==null||indentation.getValue()<=0))key="wizard.indentation.required";
|
||||
if(page==3){
|
||||
if(location.getText().isBlank())key="wizard.location.required";
|
||||
else try{Path.of(location.getText().trim());}catch(RuntimeException error){key="wizard.location.required";}
|
||||
}
|
||||
if(key!=null){showFeedback(key);return false;}return true;
|
||||
}
|
||||
private void showFeedback(String key,Object...arguments){feedbackKey=key;feedbackArguments=arguments.clone();feedback.setText(context.text(key,arguments));}
|
||||
private void finish() {
|
||||
for(int page=0;page<4;page++)if(!valid(page))return;
|
||||
var request=new ProjectCreationRequest(name.getText().trim(),Path.of(location.getText().trim()),language.getValue().languageId(),
|
||||
stdlib.getValue().version(),ProjectTarget.Game,source.getValue(),indentation.getValue(),runtime.getText().isBlank()?null:runtime.getText().trim());
|
||||
busy=true;body.setDisable(true);back.setDisable(true);finish.setDisable(true);cancel.setDisable(true);
|
||||
showFeedback("wizard.creating");
|
||||
try {
|
||||
CompletableFuture.supplyAsync(()->create.apply(request),executor).whenComplete((project,failure)->javafx.application.Platform.runLater(()->{
|
||||
busy=false;
|
||||
if(failure==null){stage.hide();completed.accept(project,!closeRequested);}
|
||||
else {
|
||||
body.setDisable(false);finish.setDisable(false);back.setDisable(false);cancel.setDisable(false);
|
||||
showFeedback("wizard.failed",location.getText().trim(),ProjectOpening.unwrap(failure).getMessage());
|
||||
if(closeRequested)stage.hide();
|
||||
}
|
||||
}));
|
||||
} catch(RuntimeException failure) {
|
||||
busy=false;body.setDisable(false);finish.setDisable(false);back.setDisable(false);cancel.setDisable(false);
|
||||
showFeedback("wizard.failed",location.getText().trim(),failure.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
+88
@@ -0,0 +1,88 @@
|
||||
package p.studio.ui.javafx2.window;
|
||||
|
||||
import javafx.geometry.Insets;
|
||||
import javafx.scene.control.*;
|
||||
import javafx.scene.input.KeyCode;
|
||||
import javafx.scene.layout.*;
|
||||
import p.studio.api.project.ProjectReference;
|
||||
import p.studio.ui.javafx2.appearance.AppearanceContext;
|
||||
import p.studio.ui.javafx2.components.*;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
/** Project selection only; services and asynchronous ownership belong to the coordinator. */
|
||||
final class ProjectChooser extends BorderPane {
|
||||
private final ListView<ProjectReference> list = new ListView<>();
|
||||
private final Button open, forget, add, create, retry;
|
||||
private final Label message = new Label();
|
||||
private final AppearanceContext context;
|
||||
private boolean busy;
|
||||
private String messageKey;
|
||||
private Object[] messageArguments=new Object[0];
|
||||
|
||||
ProjectChooser(AppearanceContext context, Consumer<Path> opening, Runnable adding,
|
||||
Runnable creating, Consumer<ProjectReference> forgetting, Runnable retryCleanup) {
|
||||
this.context=context;
|
||||
context.attach(this);
|
||||
setId("project-chooser");
|
||||
list.setId("known-projects");list.setPrefHeight(280);list.setMinHeight(220);context.attach(list);
|
||||
list.setPlaceholder(new StudioText(context,"projects.empty"));
|
||||
list.setCellFactory(ignored -> new ListCell<>() {
|
||||
@Override protected void updateItem(ProjectReference item, boolean empty) {
|
||||
super.updateItem(item,empty);setText(null);setGraphic(null);
|
||||
if (empty || item==null) return;
|
||||
Label name=new Label(item.name());name.getStyleClass().add("studio-title");name.setWrapText(true);
|
||||
Label details=new Label(context.text("projects.details",item.version(),item.languageId(),item.stdlibVersion()));
|
||||
details.setWrapText(true);Label path=new Label(item.rootPath().toString());path.setWrapText(true);
|
||||
VBox row=new VBox(6,name,details,path);row.setMinWidth(0);row.prefWidthProperty().bind(list.widthProperty().subtract(64));setGraphic(row);
|
||||
setAccessibleText(item.name()+" · "+details.getText()+" · "+path.getText());
|
||||
}
|
||||
});
|
||||
context.observe(list::refresh);
|
||||
Runnable selected=()->{var ref=list.getSelectionModel().getSelectedItem();if(!busy&&ref!=null)opening.accept(ref.rootPath());};
|
||||
open=action(context,"projects.open","open-project",selected);
|
||||
forget=action(context,"projects.forget","forget-project",()->{
|
||||
var ref=list.getSelectionModel().getSelectedItem();if(ref!=null)forgetting.accept(ref);
|
||||
});
|
||||
add=action(context,"projects.add","add-project",adding);
|
||||
create=action(context,"projects.new","new-project",creating);
|
||||
retry=action(context,"projects.retryCleanup","retry-cleanup",retryCleanup);retry.setVisible(false);retry.setManaged(false);
|
||||
list.getSelectionModel().selectedItemProperty().addListener((o,a,b)->refresh());
|
||||
list.setOnMouseClicked(event->{if(event.getClickCount()==2)selected.run();});
|
||||
list.setOnKeyPressed(event->{if(event.getCode()==KeyCode.ENTER){selected.run();event.consume();}});
|
||||
FlowPane actions=new FlowPane(12,10,open,add,create,forget,retry);
|
||||
VBox content=new VBox(14,new StudioText(context,"projects.title").title(),list,actions);
|
||||
content.setPadding(new Insets(12));VBox.setVgrow(list,Priority.ALWAYS);
|
||||
HBox identity=new HBox(12,new StudioIcon(),new StudioText(context,"brand").title());
|
||||
identity.setAlignment(javafx.geometry.Pos.CENTER_LEFT);
|
||||
StudioPanel frame=new StudioPanel(content);frame.setId("projects-frame");
|
||||
VBox layout=new VBox(20,identity,frame);layout.setPadding(new Insets(24));VBox.setVgrow(frame,Priority.ALWAYS);
|
||||
layout.setMinHeight(Region.USE_PREF_SIZE);
|
||||
ScrollPane page=new ScrollPane(layout);page.setFitToWidth(true);page.setFitToHeight(true);page.setId("launcher-scroll");setCenter(page);
|
||||
message.setId("launcher-notice");message.setWrapText(true);setBottom(message);BorderPane.setMargin(message,new Insets(12,24,12,24));
|
||||
context.observe(()->{if(messageKey!=null)message.setText(context.text(messageKey,messageArguments));});refresh();
|
||||
}
|
||||
private Button action(AppearanceContext context,String key,String id,Runnable action) {
|
||||
Button button=new StudioButton(context,key,false);button.setId(id);button.setOnAction(e->action.run());return button;
|
||||
}
|
||||
void projects(List<ProjectReference> projects,Path selection) {
|
||||
list.getItems().setAll(projects);
|
||||
var selected=projects.stream().filter(p->p.rootPath().equals(selection)).findFirst().orElse(null);
|
||||
if(selected!=null)list.getSelectionModel().select(selected);else if(!projects.isEmpty())list.getSelectionModel().selectFirst();
|
||||
refresh();
|
||||
}
|
||||
void busy(boolean busy) { this.busy=busy;refresh(); }
|
||||
private void refresh() {
|
||||
boolean empty=list.getSelectionModel().getSelectedItem()==null;
|
||||
open.setDisable(busy||empty);forget.setDisable(busy||empty);add.setDisable(busy);create.setDisable(busy);list.setDisable(busy);
|
||||
}
|
||||
void message(String text,boolean cleanupRequired) {
|
||||
messageKey=null;
|
||||
message.setText(text);retry.setVisible(cleanupRequired);retry.setManaged(cleanupRequired);
|
||||
}
|
||||
void feedback(String key,boolean cleanupRequired,Object...arguments) {
|
||||
message(context.text(key,arguments),cleanupRequired);messageKey=key;messageArguments=arguments.clone();
|
||||
}
|
||||
}
|
||||
+160
@@ -0,0 +1,160 @@
|
||||
package p.studio.ui.javafx2.window;
|
||||
|
||||
import p.studio.api.preferences.WindowGeometry;
|
||||
import p.studio.api.preferences.WindowStateStore;
|
||||
import p.studio.api.project.*;
|
||||
import p.studio.api.session.*;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.util.concurrent.*;
|
||||
import java.util.function.*;
|
||||
|
||||
/** One owned opening attempt. All state and listeners run on the supplied UI executor. */
|
||||
final class ProjectOpening {
|
||||
enum Phase { VALIDATING, SESSION, CATALOG, VIEW, READY, CLEANUP }
|
||||
interface Timer { Runnable after(long nanos, Runnable action); }
|
||||
interface View {
|
||||
void phase(Phase phase);
|
||||
default void resolved(ProjectReference reference) { }
|
||||
void prepare(ProjectSession session, WindowGeometry geometry);
|
||||
void present();
|
||||
void discard();
|
||||
void failed(Throwable failure, boolean cleanupRequired);
|
||||
}
|
||||
private static final long MINIMUM_NANOS = 1_000_000_000L;
|
||||
private final ProjectCatalog catalog;
|
||||
private final KnownProjects known;
|
||||
private final ProjectSessionFactory sessions;
|
||||
private final WindowStateStore windows;
|
||||
private final Executor worker, ui;
|
||||
private final LongSupplier clock;
|
||||
private final Timer timer;
|
||||
private final View view;
|
||||
private Attempt active;
|
||||
private boolean closed;
|
||||
|
||||
private static final class Attempt {
|
||||
final long started;
|
||||
final CompletableFuture<Void> settled = new CompletableFuture<>();
|
||||
ProjectSession pending;
|
||||
Throwable failure;
|
||||
boolean cancelled, cleaning, cleanupRequired, inFlight;
|
||||
Runnable cancelTimer = () -> { };
|
||||
Attempt(long started) { this.started = started; }
|
||||
}
|
||||
ProjectOpening(ProjectCatalog catalog, KnownProjects known, ProjectSessionFactory sessions,
|
||||
WindowStateStore windows, Executor worker, Executor ui, LongSupplier clock, Timer timer, View view) {
|
||||
this.catalog=catalog; this.known=known; this.sessions=sessions; this.windows=windows;
|
||||
this.worker=worker; this.ui=ui; this.clock=clock; this.timer=timer; this.view=view;
|
||||
}
|
||||
boolean busy() { return active != null; }
|
||||
boolean cleanupRequired() { return active != null && active.cleanupRequired; }
|
||||
|
||||
void start(Path path) {
|
||||
if (closed || active != null) throw new IllegalStateException("A project opening is already active or closing");
|
||||
var attempt = new Attempt(clock.getAsLong()); active = attempt;
|
||||
step(attempt, Phase.VALIDATING, () -> catalog.openProject(path), reference -> {
|
||||
view.resolved(reference);
|
||||
step(attempt, Phase.SESSION, () -> sessions.openForPlay(reference), session -> {
|
||||
attempt.pending = session;
|
||||
if (attempt.cancelled) { cleanup(attempt); return; }
|
||||
step(attempt, Phase.CATALOG, () -> {
|
||||
known.remember(reference);
|
||||
return windows.load(reference).orElse(null);
|
||||
}, geometry -> {
|
||||
try {
|
||||
view.phase(Phase.VIEW);
|
||||
view.prepare(session, geometry);
|
||||
view.phase(Phase.READY);
|
||||
afterMinimum(attempt, () -> {
|
||||
if (attempt.cancelled) { cleanup(attempt); return; }
|
||||
try {
|
||||
view.present();
|
||||
attempt.pending = null; active = null;
|
||||
attempt.settled.complete(null);
|
||||
} catch (RuntimeException failure) { fail(attempt, failure); }
|
||||
});
|
||||
} catch (RuntimeException failure) { fail(attempt, failure); }
|
||||
});
|
||||
});});
|
||||
}
|
||||
private <T> void step(Attempt attempt, Phase phase, Supplier<T> work, Consumer<T> next) {
|
||||
if (attempt.cancelled) { cleanup(attempt); return; }
|
||||
try {
|
||||
view.phase(phase);
|
||||
attempt.inFlight = true;
|
||||
CompletableFuture.supplyAsync(work, worker).whenComplete((value, failure) -> ui.execute(() -> {
|
||||
attempt.inFlight = false;
|
||||
// In particular, a late session result must become owned before checking cancellation.
|
||||
if (value instanceof ProjectSession session) attempt.pending = session;
|
||||
if (failure != null) { fail(attempt, unwrap(failure)); return; }
|
||||
if (attempt.cancelled) { cleanup(attempt); return; }
|
||||
try { next.accept(value); } catch (RuntimeException error) { fail(attempt, error); }
|
||||
}));
|
||||
} catch (RuntimeException failure) { attempt.inFlight = false; fail(attempt, failure); }
|
||||
}
|
||||
private void afterMinimum(Attempt attempt, Runnable action) {
|
||||
long remaining = MINIMUM_NANOS - (clock.getAsLong() - attempt.started);
|
||||
if (remaining <= 0) action.run();
|
||||
else attempt.cancelTimer = timer.after(remaining, () -> {
|
||||
attempt.cancelTimer = () -> { };
|
||||
if (active == attempt) action.run();
|
||||
});
|
||||
}
|
||||
private void fail(Attempt attempt, Throwable failure) {
|
||||
if (attempt.failure == null) attempt.failure = failure;
|
||||
else if (attempt.failure != failure) attempt.failure.addSuppressed(failure);
|
||||
attempt.cancelTimer.run();
|
||||
cleanup(attempt);
|
||||
}
|
||||
private void cleanup(Attempt attempt) {
|
||||
if (attempt.cleaning) return;
|
||||
attempt.cleaning = true;
|
||||
try { view.discard(); } catch (RuntimeException failure) {
|
||||
if (attempt.failure == null) attempt.failure = failure; else attempt.failure.addSuppressed(failure);
|
||||
}
|
||||
ProjectSession pending = attempt.pending;
|
||||
if (pending == null) { cleanupDone(attempt); return; }
|
||||
try {
|
||||
CompletableFuture.runAsync(pending::close, worker)
|
||||
.whenComplete((ignored, failure) -> ui.execute(() -> {
|
||||
attempt.cleaning = false;
|
||||
if (failure != null) { cleanupFailed(attempt, unwrap(failure)); return; }
|
||||
cleanupDone(attempt);
|
||||
}));
|
||||
} catch (RuntimeException failure) { attempt.cleaning = false; cleanupFailed(attempt, failure); }
|
||||
}
|
||||
private void cleanupDone(Attempt attempt) {
|
||||
attempt.cleaning = false; attempt.pending = null; attempt.cleanupRequired = false;
|
||||
Runnable finish = () -> {
|
||||
active = null;
|
||||
if (!attempt.cancelled) view.failed(attempt.failure, false);
|
||||
attempt.settled.complete(null);
|
||||
};
|
||||
if (attempt.cancelled) finish.run(); else afterMinimum(attempt, finish);
|
||||
}
|
||||
private void cleanupFailed(Attempt attempt, Throwable failure) {
|
||||
attempt.cleanupRequired = true;
|
||||
if (attempt.failure == null) attempt.failure = failure; else if (attempt.failure != failure) attempt.failure.addSuppressed(failure);
|
||||
Runnable report=()->view.failed(attempt.failure, true);
|
||||
if(attempt.cancelled)report.run();else afterMinimum(attempt,report);
|
||||
}
|
||||
/** A failed cleanup retains ownership. The human can retry cleanup without starting another open. */
|
||||
void retryCleanup() { if (cleanupRequired()) cleanup(active); }
|
||||
|
||||
CompletionStage<Void> cancel() {
|
||||
closed = true;return abort();
|
||||
}
|
||||
CompletionStage<Void> abort() {
|
||||
if (active == null) return CompletableFuture.completedFuture(null);
|
||||
Attempt attempt = active; attempt.cancelled = true; attempt.cancelTimer.run();
|
||||
// If waiting for the minimum, all worker steps have already finished.
|
||||
if (!attempt.inFlight && !attempt.cleaning) cleanup(attempt);
|
||||
return attempt.settled;
|
||||
}
|
||||
static Throwable unwrap(Throwable failure) {
|
||||
while ((failure instanceof CompletionException || failure instanceof ExecutionException) && failure.getCause()!=null)
|
||||
failure=failure.getCause();
|
||||
return failure;
|
||||
}
|
||||
}
|
||||
+170
-40
@@ -1,7 +1,9 @@
|
||||
package p.studio.ui.javafx2.window;
|
||||
|
||||
import javafx.animation.AnimationTimer;
|
||||
import javafx.animation.PauseTransition;
|
||||
import javafx.application.Platform;
|
||||
import javafx.util.Duration;
|
||||
import javafx.geometry.Insets;
|
||||
import javafx.scene.Scene;
|
||||
import javafx.scene.control.*;
|
||||
@@ -10,17 +12,37 @@ import javafx.stage.*;
|
||||
import p.studio.api.execution.*;
|
||||
import p.studio.api.project.*;
|
||||
import p.studio.api.session.*;
|
||||
import p.studio.api.preferences.*;
|
||||
import p.studio.ui.javafx2.appearance.AppearanceContext;
|
||||
import p.studio.ui.javafx2.components.*;
|
||||
import p.studio.ui.javafx2.play.PlaybackViewport;
|
||||
import p.studio.ui.javafx2.shell.MinimalShell;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Files;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.*;
|
||||
import java.util.function.*;
|
||||
|
||||
/** The normal Studio product: one project and one owned interactive execution. */
|
||||
public final class StudioWindowCoordinator2 implements AutoCloseable {
|
||||
private final Stage stage;
|
||||
private final Stage launcherStage=new Stage();
|
||||
private Stage loadingStage;
|
||||
private final ProjectLanguageCatalog languages;
|
||||
private final WindowStateStore windows;
|
||||
private final AppearanceContext launcherContext;
|
||||
private AppearanceContext loadingContext;
|
||||
private final ProjectChooser chooser;
|
||||
private final ProjectOpening opening;
|
||||
private ProjectOpening.Phase loadingPhase;
|
||||
private Label loadingStatus;
|
||||
private Label loadingProject;
|
||||
private StudioFeedback loadingFeedback;
|
||||
private Path initialDirectory;
|
||||
private Path createdProject;
|
||||
private NewProjectWizard2 wizard;
|
||||
private final CompletableFuture<Void> shutdown=new CompletableFuture<>();
|
||||
private boolean exitPlatform;
|
||||
private final ProjectCatalog catalog;
|
||||
private final KnownProjects known;
|
||||
private final ProjectSessionFactory sessions;
|
||||
@@ -50,13 +72,41 @@ public final class StudioWindowCoordinator2 implements AutoCloseable {
|
||||
public StudioWindowCoordinator2(Stage stage,ProjectCatalog catalog,KnownProjects known,ProjectSessionFactory sessions,
|
||||
ExecutionControllerFactory executions,BiConsumer<ProjectReference,ProjectLocalStudioSetup> saveSetup,
|
||||
Executor executor,WindowResources resources) {
|
||||
this(stage,catalog,known,sessions,executions,saveSetup,executor,resources,()->List.of(),new WindowStateStore(){
|
||||
public Optional<WindowGeometry> load(ProjectReference project){return Optional.empty();}
|
||||
public void save(ProjectReference project,WindowGeometry geometry){} });
|
||||
}
|
||||
public StudioWindowCoordinator2(Stage stage,ProjectCatalog catalog,KnownProjects known,ProjectSessionFactory sessions,
|
||||
ExecutionControllerFactory executions,BiConsumer<ProjectReference,ProjectLocalStudioSetup> saveSetup,
|
||||
Executor executor,WindowResources resources,ProjectLanguageCatalog languages,WindowStateStore windows) {
|
||||
this.stage=stage;this.catalog=catalog;this.known=known;this.sessions=sessions;this.executions=executions;
|
||||
this.languages=languages;this.windows=windows;
|
||||
this.saveSetup=saveSetup;this.executor=executor;this.resources=resources;
|
||||
context=resources.context();shell=new MinimalShell(context);notice.setWrapText(true);notice.setId("studio-notice");
|
||||
context.observe(()->shell.workspace().setAccessibleText(project==null?context.text("projects.title"):project.projectReference().name()));
|
||||
shell.setBottom(notice);BorderPane.setMargin(notice,new Insets(10,18,12,18));
|
||||
stage.setScene(new Scene(shell,1200,850));stage.setTitle("Prometeu Studio");stage.setMinWidth(680);stage.setMinHeight(480);
|
||||
stage.setOnCloseRequest(e->{e.consume();exitRequested=true;requestCloseProject();});
|
||||
Platform.setImplicitExit(false);
|
||||
stage.setOnCloseRequest(e->{e.consume();requestCloseProject();});
|
||||
launcherContext=resources.child(context);
|
||||
chooser=new ProjectChooser(launcherContext,p->safe(()->openProject(p)),()->safe(this::addExisting),
|
||||
()->safe(this::newProject),ref->safe(()->forget(ref)),()->openingRetry());
|
||||
launcherStage.setScene(new Scene(chooser,960,720));launcherStage.setMinWidth(600);launcherStage.setMinHeight(440);
|
||||
context.observe(()->{launcherStage.setTitle(context.text("brand"));stage.setTitle(project==null?context.text("brand"):project.projectReference().name()+" · "+context.text("brand"));});
|
||||
launcherStage.setOnCloseRequest(e->{e.consume();exitPlatform=true;exitRequested=true;requestCloseProject();});
|
||||
opening=new ProjectOpening(catalog,known,sessions,windows,executor,Platform::runLater,System::nanoTime,(nanos,action)->{
|
||||
PauseTransition delay=new PauseTransition(Duration.millis(nanos/1_000_000.));delay.setOnFinished(e->action.run());delay.play();return delay::stop;
|
||||
},new ProjectOpening.View(){
|
||||
public void phase(ProjectOpening.Phase phase){loadingPhase=phase;updateLoadingText();}
|
||||
public void resolved(ProjectReference reference){loadingProject.setText(reference.name());}
|
||||
public void prepare(ProjectSession session,WindowGeometry geometry){project=session;showProject();restoreGeometry(geometry);}
|
||||
public void present(){stage.setTitle(project.projectReference().name()+" · "+context.text("brand"));stage.show();stage.toFront();hideLoading();createdProject=null;refresh();}
|
||||
public void discard(){stage.hide();project=null;play=null;if(viewport!=null){viewport.close();viewport=null;}if(viewContext!=null){viewContext.close();viewContext=null;}shell.workspace().getChildren().clear();}
|
||||
public void failed(Throwable failure,boolean cleanupRequired){hideLoading();showChooser();
|
||||
String detail=diagnostic(failure);
|
||||
chooser.feedback(cleanupRequired?"projects.cleanupFailed":createdProject==null?"projects.openFailed":"projects.createdOpenFailed",cleanupRequired,detail);
|
||||
chooser.busy(cleanupRequired);}
|
||||
});
|
||||
stage.iconifiedProperty().addListener((o,a,b)->{if(b)pauseForFocus();});
|
||||
lifecycle=new AnimationTimer(){long previous;@Override public void handle(long now){
|
||||
if(now-previous<100_000_000)return;previous=now;
|
||||
@@ -65,9 +115,9 @@ public final class StudioWindowCoordinator2 implements AutoCloseable {
|
||||
refresh();
|
||||
}};lifecycle.start();
|
||||
}
|
||||
public void showLauncher(){showChooser();stage.show();}
|
||||
public void showLauncher(){showChooser();}
|
||||
private boolean belongsToStudio(Window window){
|
||||
if(window==stage)return true;
|
||||
if(window==stage||window==launcherStage||window==loadingStage)return true;
|
||||
if(window instanceof Stage s&&s.getOwner()!=null)return belongsToStudio(s.getOwner());
|
||||
return window instanceof PopupWindow p&&p.getOwnerWindow()!=null&&belongsToStudio(p.getOwnerWindow());
|
||||
}
|
||||
@@ -79,40 +129,93 @@ public final class StudioWindowCoordinator2 implements AutoCloseable {
|
||||
Button b=new StudioButton(c,key,false);b.setId(id);b.setOnAction(e->safe(action));return b;
|
||||
}
|
||||
private void safe(Runnable action){try{action.run();}catch(RuntimeException failure){error(failure);}}
|
||||
private void error(Throwable failure){while(failure instanceof CompletionException&&failure.getCause()!=null)failure=failure.getCause();
|
||||
notice.setText(failure.getMessage()==null?failure.getClass().getSimpleName():failure.getMessage());}
|
||||
private String diagnostic(Throwable failure){failure=ProjectOpening.unwrap(failure);return failure.getMessage()==null?failure.getClass().getSimpleName():failure.getMessage();}
|
||||
private void error(Throwable failure){String text=context.text("feedback.error",diagnostic(failure));notice.setText(text);if(launcherStage.isShowing())chooser.feedback("feedback.error",false,diagnostic(failure));}
|
||||
private <T> void background(Supplier<T> work,BiConsumer<T,Throwable> result){
|
||||
CompletableFuture.supplyAsync(work,executor).whenComplete((value,failure)->Platform.runLater(()->{if(!closed)result.accept(value,failure);}));
|
||||
try{CompletableFuture.supplyAsync(work,executor).whenComplete((value,failure)->Platform.runLater(()->{if(!closed)result.accept(value,failure);}));}
|
||||
catch(RuntimeException failure){if(!closed)result.accept(null,failure);}
|
||||
}
|
||||
private void showChooser(){
|
||||
var c=beginView();shell.workspace().setAccessibleText(c.text("projects.title"));
|
||||
VBox content=new VBox(14,new StudioText(c,"projects.title").title());content.setPadding(new Insets(20));
|
||||
content.getChildren().add(button(c,"projects.open","open-project",()->{
|
||||
DirectoryChooser chooser=new DirectoryChooser();chooser.setTitle(c.text("projects.open"));
|
||||
var selected=chooser.showDialog(stage);if(selected!=null)openProject(selected.toPath());
|
||||
}));
|
||||
VBox rows=new VBox(12);content.getChildren().add(rows);
|
||||
ScrollPane scroll=new ScrollPane(content);scroll.setFitToWidth(true);shell.workspace().getChildren().setAll(scroll);
|
||||
background(known::listKnownProjects,(list,failure)->{
|
||||
if(viewContext!=c||project!=null)return;if(failure!=null){error(failure);return;}
|
||||
for(ProjectReference ref:list){
|
||||
Label title=new Label(ref.name()+"\n"+ref.rootPath());title.setWrapText(true);HBox.setHgrow(title,Priority.ALWAYS);
|
||||
var row=new HBox(16,title,button(c,"projects.open","known-open",()->openProject(ref.rootPath())),
|
||||
button(c,"projects.forget","known-forget",()->{
|
||||
if(busy)return;busy=true;background(()->{known.forget(ref);return true;},(v,f)->{
|
||||
busy=false;if(exitRequested)finishExit();else if(f!=null)error(f);else showChooser();});
|
||||
}));row.setPadding(new Insets(14));rows.getChildren().add(new StudioPanel(row));
|
||||
}
|
||||
stage.hide();launcherStage.show();launcherStage.centerOnScreen();launcherStage.toFront();
|
||||
reloadProjects(null);
|
||||
}
|
||||
private void reloadProjects(Path selection){
|
||||
chooser.busy(true);
|
||||
background(()->{var root=catalog.projectsRoot();return new ProjectList(known.listKnownProjects(),Files.isDirectory(root)?root:null);},(result,failure)->{
|
||||
if(project!=null)return;
|
||||
chooser.busy(busy||opening.busy());if(failure!=null){error(failure);return;}
|
||||
initialDirectory=result.root();chooser.projects(result.projects(),selection);
|
||||
});
|
||||
}
|
||||
public void openProject(Path path){
|
||||
if(busy||project!=null||closing)return;busy=true;notice.setText(context.text("feedback.busy"));
|
||||
background(()->{var ref=catalog.openProject(path);var opened=sessions.openForPlay(ref);
|
||||
try{known.remember(ref);return opened;}catch(RuntimeException f){opened.close();throw f;}},(opened,failure)->{
|
||||
busy=false;if(failure!=null){error(failure);projectCloseRequested=false;if(exitRequested)finishExit();return;}
|
||||
project=opened;notice.setText("");showProject();if(exitRequested||projectCloseRequested)requestCloseProject();
|
||||
private record ProjectList(List<ProjectReference> projects,Path root){}
|
||||
private void addExisting(){
|
||||
if(busy||opening.busy())return;
|
||||
FileChooser picker=new FileChooser();picker.setTitle(context.text("projects.add"));
|
||||
picker.getExtensionFilters().add(new FileChooser.ExtensionFilter(context.text("projects.manifest"),"prometeu.json"));
|
||||
if(initialDirectory!=null)picker.setInitialDirectory(initialDirectory.toFile());
|
||||
var file=picker.showOpenDialog(launcherStage);if(file!=null)addProjectManifest(file.toPath());
|
||||
}
|
||||
public void addProjectManifest(Path path){
|
||||
if(closed||exitRequested||busy||opening.busy()||project!=null)return;busy=true;chooser.busy(true);chooser.message("",false);
|
||||
background(()->{var ref=catalog.openProjectManifest(path);known.remember(ref);return ref;},(ref,failure)->{
|
||||
busy=false;if(exitRequested){finishExit();return;}if(failure!=null){chooser.busy(false);error(failure);}else reloadProjects(ref.rootPath());
|
||||
});
|
||||
}
|
||||
private void forget(ProjectReference reference){
|
||||
if(busy||opening.busy())return;busy=true;chooser.busy(true);chooser.message("",false);
|
||||
background(()->{known.forget(reference);return true;},(v,failure)->{
|
||||
busy=false;if(exitRequested){finishExit();return;}if(failure!=null){chooser.busy(false);error(failure);}else reloadProjects(null);
|
||||
});
|
||||
}
|
||||
private void newProject(){
|
||||
if(busy||opening.busy()||wizard!=null)return;busy=true;chooser.busy(true);
|
||||
background(()->new LanguageOptions(catalog.projectsRoot(),languages.listLanguageTemplates(),languages.defaultTemplate().languageId()),(options,failure)->{
|
||||
busy=false;if(exitRequested){finishExit();return;}chooser.busy(false);if(failure!=null){error(failure);return;}
|
||||
wizard=new NewProjectWizard2(launcherStage,resources.child(context),options.root(),options.templates(),options.defaultId(),executor,
|
||||
request->{var ref=catalog.createProject(request);known.remember(ref);return ref;},(ref,open)->{
|
||||
wizard=null;if(exitRequested){finishExit();return;}reloadProjects(ref.rootPath());
|
||||
if(open){createdProject=ref.rootPath();openProject(ref.rootPath());}
|
||||
});
|
||||
wizard.dismissed().whenComplete((v,f)->{wizard=null;});wizard.show();
|
||||
});
|
||||
}
|
||||
private record LanguageOptions(Path root,List<ProjectLanguageTemplate> templates,String defaultId){}
|
||||
private void openingRetry(){opening.retryCleanup();}
|
||||
private void showLoading(Path path){
|
||||
loadingContext=resources.child(context);loadingStage=new Stage(StageStyle.UNDECORATED);
|
||||
loadingStatus=new Label();loadingStatus.setWrapText(true);loadingStatus.setId("loading-phase");
|
||||
loadingFeedback=new StudioFeedback(loadingContext);loadingFeedback.setProgress(-1);
|
||||
String versionText=System.getProperty("prometeu.studio.version",Optional.ofNullable(getClass().getPackage().getImplementationVersion()).orElse("dev"));
|
||||
Label version=new Label();loadingContext.observe(()->version.setText(context.text("projects.version",versionText)));
|
||||
loadingProject=new Label(path.getFileName()==null?path.toString():path.getFileName().toString());loadingProject.setWrapText(true);
|
||||
VBox body=new VBox(16,new HBox(12,new StudioIcon(),new StudioText(loadingContext,"brand").title()),version,loadingProject,loadingStatus,loadingFeedback);
|
||||
body.setPadding(new Insets(28));StudioPanel frame=new StudioPanel(body);loadingContext.attach(frame);
|
||||
ScrollPane page=new ScrollPane(frame);page.setFitToWidth(true);loadingContext.attach(page);
|
||||
double scale=context.settings().scale();var bounds=Screen.getPrimary().getVisualBounds();
|
||||
loadingStage.setScene(new Scene(page,Math.min(bounds.getWidth()*.9,560*scale),Math.min(bounds.getHeight()*.85,340*scale)));loadingStage.setResizable(false);
|
||||
loadingStage.setOnCloseRequest(e->{e.consume();exitPlatform=true;exitRequested=true;requestCloseProject();});
|
||||
loadingContext.observe(this::updateLoadingText);loadingStage.show();loadingStage.centerOnScreen();loadingStage.toFront();launcherStage.hide();
|
||||
}
|
||||
private void updateLoadingText(){if(loadingStatus!=null&&loadingPhase!=null){loadingStatus.setText(context.text("loading."+loadingPhase.name()));
|
||||
loadingFeedback.setProgress(loadingPhase==ProjectOpening.Phase.READY?1:-1);}}
|
||||
private void hideLoading(){if(loadingStage!=null){loadingStage.hide();loadingStage.setOnCloseRequest(null);loadingStage=null;}
|
||||
if(loadingContext!=null){loadingContext.close();loadingContext=null;}loadingStatus=null;loadingProject=null;loadingFeedback=null;}
|
||||
private void restoreGeometry(WindowGeometry geometry){
|
||||
stage.setMaximized(false);stage.setWidth(1200);stage.setHeight(850);
|
||||
if(geometry==null){stage.centerOnScreen();return;}
|
||||
var bounds=Screen.getPrimary().getVisualBounds();
|
||||
double width=Double.isFinite(geometry.width())?Math.max(680,Math.min(geometry.width(),bounds.getWidth())):1200;
|
||||
double height=Double.isFinite(geometry.height())?Math.max(480,Math.min(geometry.height(),bounds.getHeight())):850;
|
||||
stage.setWidth(width);stage.setHeight(height);
|
||||
boolean visible=Screen.getScreens().stream().anyMatch(screen->screen.getVisualBounds().intersects(geometry.x(),geometry.y(),width,height));
|
||||
if(visible&&Double.isFinite(geometry.x())&&Double.isFinite(geometry.y())){stage.setX(geometry.x());stage.setY(geometry.y());}else stage.centerOnScreen();
|
||||
stage.setMaximized(geometry.maximized());
|
||||
}
|
||||
public void openProject(Path path){
|
||||
if(closed||exitRequested||busy||project!=null||closing||opening.busy())return;
|
||||
if(!path.equals(createdProject))createdProject=null;
|
||||
chooser.message("",false);chooser.busy(true);showLoading(path);opening.start(path);
|
||||
}
|
||||
private void showProject(){
|
||||
var c=beginView();var ref=project.projectReference();var setup=project.projectLocalStudioSetup();
|
||||
shell.workspace().setAccessibleText(ref.name());
|
||||
@@ -201,26 +304,53 @@ public final class StudioWindowCoordinator2 implements AutoCloseable {
|
||||
public void requestCloseProject(){
|
||||
if(closed||closing)return;
|
||||
projectCloseRequested=true;
|
||||
if(wizard!=null){wizard.requestClose().whenComplete((v,f)->{if(exitRequested)finishExit();});return;}
|
||||
if(opening.busy()){
|
||||
closing=true;
|
||||
(exitRequested?opening.cancel():opening.abort()).whenComplete((v,f)->Platform.runLater(()->{
|
||||
closing=false;projectCloseRequested=false;hideLoading();
|
||||
if(exitRequested)finishExit();else showChooser();
|
||||
}));return;
|
||||
}
|
||||
if(busy){if(exitRequested)notice.setText(context.text("feedback.busy"));return;}
|
||||
if(project==null){projectCloseRequested=false;if(exitRequested)finishExit();return;}
|
||||
closing=true;refresh();if(viewport!=null)viewport.neutralize();
|
||||
CompletionStage<Void> stopping=controller==null?CompletableFuture.completedFuture(null):controller.stopAsync();
|
||||
CompletionStage<Void> stopping;
|
||||
try{stopping=controller==null?CompletableFuture.completedFuture(null):controller.stopAsync();}
|
||||
catch(RuntimeException failure){closing=false;exitRequested=false;projectCloseRequested=false;error(failure);refresh();return;}
|
||||
stopping.whenComplete((v,f)->Platform.runLater(()->{
|
||||
if(f!=null){closing=false;exitRequested=false;projectCloseRequested=false;error(f);refresh();return;}
|
||||
var oldProject=project;var oldController=controller;
|
||||
background(()->{if(oldController!=null)oldController.close();oldProject.close();return true;},(done,failure)->{
|
||||
var geometry=new WindowGeometry(stage.getX(),stage.getY(),stage.getWidth(),stage.getHeight(),stage.isMaximized());
|
||||
background(()->closeOwned(oldProject,oldController,geometry),(warning,failure)->{
|
||||
if(failure!=null){closing=false;exitRequested=false;projectCloseRequested=false;error(failure);refresh();return;}
|
||||
project=null;controller=null;closing=false;projectCloseRequested=false;play=null;notice.setText("");
|
||||
if(exitRequested)finishExit();else showChooser();
|
||||
if(viewport!=null){viewport.close();viewport=null;}if(viewContext!=null){viewContext.close();viewContext=null;}shell.workspace().getChildren().clear();
|
||||
if(exitRequested)finishExit();else {showChooser();if(warning!=null)error(warning);}
|
||||
});
|
||||
}));
|
||||
}
|
||||
private void finishExit(){close();stage.hide();Platform.exit();}
|
||||
public PlaybackViewport viewport(){return viewport;}
|
||||
public ProjectSession projectSession(){return project;}
|
||||
@Override public void close(){
|
||||
if(closed)return;closed=true;lifecycle.stop();if(viewport!=null)viewport.close();
|
||||
if(controller!=null)controller.close();if(project!=null)project.close();
|
||||
if(viewContext!=null)viewContext.close();context.close();resources.close();stage.setOnCloseRequest(null);
|
||||
private Throwable closeOwned(ProjectSession session,ExecutionController execution,WindowGeometry geometry){
|
||||
RuntimeException warning=null,failure=null;
|
||||
try{windows.save(session.projectReference(),geometry);}catch(RuntimeException error){warning=error;}
|
||||
try{if(execution!=null)execution.close();}catch(RuntimeException error){failure=error;}
|
||||
try{session.close();}catch(RuntimeException error){if(failure==null)failure=error;else failure.addSuppressed(error);}
|
||||
if(failure!=null){if(warning!=null)failure.addSuppressed(warning);throw failure;}return warning;
|
||||
}
|
||||
private void finishExit(){
|
||||
if(closed)return;closed=true;lifecycle.stop();hideLoading();stage.hide();launcherStage.hide();
|
||||
if(viewport!=null){viewport.close();viewport=null;}
|
||||
if(viewContext!=null)viewContext.close();launcherContext.close();context.close();
|
||||
stage.setOnCloseRequest(null);launcherStage.setOnCloseRequest(null);
|
||||
// Preference persistence may flush pending IO; keep it off the FX thread too.
|
||||
try{CompletableFuture.runAsync(resources::close,executor).whenComplete((v,f)->Platform.runLater(()->{
|
||||
if(f==null)shutdown.complete(null);else shutdown.completeExceptionally(f);
|
||||
if(exitPlatform)Platform.exit();
|
||||
}));}catch(RuntimeException failure){shutdown.completeExceptionally(failure);if(exitPlatform)Platform.exit();}
|
||||
}
|
||||
public PlaybackViewport viewport(){return viewport;}
|
||||
public ProjectSession projectSession(){return opening.busy()?null:project;}
|
||||
public Stage launcherStage(){return launcherStage;}
|
||||
public CompletionStage<Void> closeAsync(){if(!closed){exitRequested=true;requestCloseProject();}return shutdown;}
|
||||
@Override public void close(){closeAsync();}
|
||||
}
|
||||
|
||||
+5
@@ -17,6 +17,11 @@ public final class WindowResources implements AutoCloseable {
|
||||
initial=store.load();persistence=new SettingsPersistence(store);
|
||||
fonts=FontResources.load(System.err::println);messages=Messages.load(System.err::println);
|
||||
}
|
||||
/** Isolated presentation storage for embedded consumers and desktop qualification. */
|
||||
public WindowResources(PresentationSettings initial, SettingsStore store) {
|
||||
this.initial=initial;this.persistence=new SettingsPersistence(store);
|
||||
fonts=FontResources.load(System.err::println);messages=Messages.load(System.err::println);
|
||||
}
|
||||
public AppearanceContext context(){return new AppearanceContext(initial,messages,fonts,persistence::changed);}
|
||||
public AppearanceContext child(AppearanceContext parent){
|
||||
var child=new AppearanceContext(parent.settings(),messages,fonts,parent::update);
|
||||
|
||||
+49
@@ -3,6 +3,55 @@ projects.title=PROJECTS
|
||||
projects.open=Open project
|
||||
projects.forget=Forget
|
||||
projects.close=Close project
|
||||
projects.empty=No projects yet. Add an existing project or create a new one.
|
||||
projects.details=Version {0} · {1} · stdlib {2}
|
||||
projects.add=Add existing…
|
||||
projects.new=New project…
|
||||
projects.manifest=Project manifest (prometeu.json)
|
||||
projects.version=Version {0}
|
||||
projects.openFailed=Could not open the project: {0}
|
||||
projects.createdOpenFailed=The project was created, but could not be opened. Open it again from the list. {0}
|
||||
projects.cleanupFailed=Project cleanup needs attention. Retry cleanup before opening another project. {0}
|
||||
projects.retryCleanup=Retry cleanup
|
||||
feedback.error=Operation failed: {0}
|
||||
loading.VALIDATING=Validating project…
|
||||
loading.SESSION=Preparing Play session…
|
||||
loading.CATALOG=Updating known projects…
|
||||
loading.VIEW=Preparing project window…
|
||||
loading.READY=Ready to open
|
||||
loading.CLEANUP=Releasing project resources…
|
||||
wizard.name=Project name
|
||||
wizard.language=Language
|
||||
wizard.stdlib=Standard library
|
||||
wizard.source=Source root
|
||||
wizard.indentation=Indentation width (spaces)
|
||||
wizard.runtime=Runtime installation (optional)
|
||||
wizard.location=Parent location
|
||||
wizard.back=Back
|
||||
wizard.next=Next
|
||||
wizard.create=Create project
|
||||
wizard.cancel=Cancel
|
||||
wizard.step.0=1 · Name your game
|
||||
wizard.step.1=2 · Language and sources
|
||||
wizard.step.2=3 · Project details
|
||||
wizard.step.3=4 · Project location
|
||||
wizard.step.4=5 · Review and create
|
||||
wizard.description.0=Choose a name for your new game project.
|
||||
wizard.description.1=Select a language, standard library and source directory.
|
||||
wizard.description.2=Choose indentation and, optionally, a runtime installation. You can configure the runtime before Play.
|
||||
wizard.description.3=A new project directory will be created under this location.
|
||||
wizard.description.4=Review your choices. Creating the project will open it when ready.
|
||||
wizard.summary=Name: {0}\nLanguage: {1}\nStandard library: {2}\nSource root: {3}\nIndentation: {4} spaces\nRuntime: {5}\nParent location: {6}
|
||||
wizard.name.required=Enter a project name.
|
||||
wizard.language.required=Choose a language, standard library and source root.
|
||||
wizard.indentation.required=Choose a positive indentation width.
|
||||
wizard.location.required=Enter a valid parent location.
|
||||
wizard.creating=Creating project…
|
||||
wizard.failed=Could not finish creating the project under {0}. Check this location before trying again; some files may already exist. {1}
|
||||
wizard.stdlibOption={0} ({1})
|
||||
wizard.stability.DEFAULT=default
|
||||
wizard.stability.STABLE=stable
|
||||
wizard.stability.EXPERIMENTAL=experimental
|
||||
play.runtime=Runtime installation
|
||||
play.browse=Browse…
|
||||
play.memcard=Development save media
|
||||
|
||||
+49
@@ -3,6 +3,55 @@ projects.title=PROJETOS
|
||||
projects.open=Abrir projeto
|
||||
projects.forget=Esquecer
|
||||
projects.close=Fechar projeto
|
||||
projects.empty=Nenhum projeto ainda. Adicione um existente ou crie um novo.
|
||||
projects.details=Versão {0} · {1} · stdlib {2}
|
||||
projects.add=Adicionar existente…
|
||||
projects.new=Novo projeto…
|
||||
projects.manifest=Manifesto do projeto (prometeu.json)
|
||||
projects.version=Versão {0}
|
||||
projects.openFailed=Não foi possível abrir o projeto: {0}
|
||||
projects.createdOpenFailed=O projeto foi criado, mas não foi possível abri-lo. Abra-o novamente pela lista. {0}
|
||||
projects.cleanupFailed=A liberação do projeto precisa de atenção. Tente liberá-lo antes de abrir outro. {0}
|
||||
projects.retryCleanup=Tentar liberar novamente
|
||||
feedback.error=Falha na operação: {0}
|
||||
loading.VALIDATING=Validando projeto…
|
||||
loading.SESSION=Preparando sessão Play…
|
||||
loading.CATALOG=Atualizando projetos conhecidos…
|
||||
loading.VIEW=Preparando janela do projeto…
|
||||
loading.READY=Pronto para abrir
|
||||
loading.CLEANUP=Liberando recursos do projeto…
|
||||
wizard.name=Nome do projeto
|
||||
wizard.language=Linguagem
|
||||
wizard.stdlib=Biblioteca padrão
|
||||
wizard.source=Diretório de fontes
|
||||
wizard.indentation=Largura de indentação (espaços)
|
||||
wizard.runtime=Instalação do runtime (opcional)
|
||||
wizard.location=Localização pai
|
||||
wizard.back=Voltar
|
||||
wizard.next=Avançar
|
||||
wizard.create=Criar projeto
|
||||
wizard.cancel=Cancelar
|
||||
wizard.step.0=1 · Dê um nome ao seu jogo
|
||||
wizard.step.1=2 · Linguagem e fontes
|
||||
wizard.step.2=3 · Detalhes do projeto
|
||||
wizard.step.3=4 · Localização do projeto
|
||||
wizard.step.4=5 · Revisar e criar
|
||||
wizard.description.0=Escolha um nome para seu novo projeto de jogo.
|
||||
wizard.description.1=Selecione a linguagem, a biblioteca padrão e o diretório de fontes.
|
||||
wizard.description.2=Escolha a indentação e, opcionalmente, uma instalação do runtime. O runtime pode ser configurado antes de jogar.
|
||||
wizard.description.3=Um novo diretório de projeto será criado nesta localização.
|
||||
wizard.description.4=Confira suas escolhas. O projeto será aberto quando a criação terminar.
|
||||
wizard.summary=Nome: {0}\nLinguagem: {1}\nBiblioteca padrão: {2}\nDiretório de fontes: {3}\nIndentação: {4} espaços\nRuntime: {5}\nLocalização pai: {6}
|
||||
wizard.name.required=Informe um nome para o projeto.
|
||||
wizard.language.required=Escolha a linguagem, a biblioteca padrão e o diretório de fontes.
|
||||
wizard.indentation.required=Escolha uma largura de indentação positiva.
|
||||
wizard.location.required=Informe uma localização pai válida.
|
||||
wizard.creating=Criando projeto…
|
||||
wizard.failed=Não foi possível concluir a criação em {0}. Confira esta localização antes de tentar novamente; alguns arquivos podem já existir. {1}
|
||||
wizard.stdlibOption={0} ({1})
|
||||
wizard.stability.DEFAULT=padrão
|
||||
wizard.stability.STABLE=estável
|
||||
wizard.stability.EXPERIMENTAL=experimental
|
||||
play.runtime=Instalação do runtime
|
||||
play.browse=Procurar…
|
||||
play.memcard=Mídia de save para desenvolvimento
|
||||
|
||||
+2
@@ -61,6 +61,8 @@
|
||||
.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; }
|
||||
.list-view.studio-root .list-cell:filled:selected .label { -fx-text-fill: -studio-on-accent; }
|
||||
.studio-root .project-error { -fx-text-fill: -studio-error; }
|
||||
.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; }
|
||||
|
||||
+129
@@ -0,0 +1,129 @@
|
||||
package p.studio.ui.javafx2.window;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import p.studio.api.preferences.*;
|
||||
import p.studio.api.project.*;
|
||||
import p.studio.api.session.*;
|
||||
|
||||
import java.lang.reflect.Proxy;
|
||||
import java.nio.file.Path;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.*;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class ProjectOpeningTest {
|
||||
static final Path ROOT=Path.of("/tmp/loading-fixture");
|
||||
static final ProjectReference REF=new ProjectReference("Fixture","1.0","pbs",1,ProjectTarget.Game,ROOT);
|
||||
static final class Queue implements Executor {
|
||||
final ArrayDeque<Runnable> tasks=new ArrayDeque<>();boolean reject;
|
||||
public void execute(Runnable task){if(reject)throw new RejectedExecutionException("executor unavailable");tasks.add(task);}
|
||||
void next(){tasks.remove().run();}
|
||||
void drain(){while(!tasks.isEmpty())next();}
|
||||
}
|
||||
static final class Clock implements ProjectOpening.Timer {
|
||||
long now;
|
||||
final List<Job> jobs=new ArrayList<>();
|
||||
static final class Job {long deadline;Runnable action;boolean cancelled;}
|
||||
public Runnable after(long nanos,Runnable action){var job=new Job();job.deadline=now+nanos;job.action=action;jobs.add(job);return ()->job.cancelled=true;}
|
||||
void advance(long millis){now+=millis*1_000_000;for(var job:List.copyOf(jobs))if(!job.cancelled&&job.deadline<=now){job.cancelled=true;job.action.run();}}
|
||||
}
|
||||
static final class Fixture implements ProjectOpening.View {
|
||||
final Queue worker=new Queue();final Clock clock=new Clock();
|
||||
final List<ProjectOpening.Phase> phases=new ArrayList<>();
|
||||
final ProjectOpening opening;
|
||||
String failAt="";int opened,closed,presented,prepared,failed;boolean cleanupRequired,closeFails;
|
||||
Throwable lastFailure;
|
||||
Fixture(){
|
||||
ProjectCatalog catalog=new ProjectCatalog(){
|
||||
public Path projectsRoot(){return ROOT;}
|
||||
public List<ProjectReference> listProjects(){return List.of(REF);}
|
||||
public ProjectReference openProject(Path path){fail("catalog");return REF;}
|
||||
public ProjectReference openProjectManifest(Path path){return openProject(path);}
|
||||
public ProjectReference createProject(ProjectCreationRequest request){throw new AssertionError("not a creation");}
|
||||
};
|
||||
KnownProjects known=new KnownProjects(){
|
||||
public List<ProjectReference> listKnownProjects(){return List.of(REF);}
|
||||
public void remember(ProjectReference ref){fail("remember");}
|
||||
public void forget(ProjectReference ref){}
|
||||
};
|
||||
ProjectSessionFactory sessions=new ProjectSessionFactory(){
|
||||
public ProjectSession open(ProjectReference ref){throw new AssertionError("must use Play slice");}
|
||||
public ProjectSession openForPlay(ProjectReference ref){
|
||||
fail("session");opened++;
|
||||
return (ProjectSession)Proxy.newProxyInstance(getClass().getClassLoader(),new Class[]{ProjectSession.class},(proxy,method,args)->{
|
||||
if(method.getName().equals("close")){if(closeFails)throw new IllegalStateException("cleanup refused");closed++;return null;}
|
||||
if(method.getName().equals("projectReference"))return REF;
|
||||
throw new AssertionError(method.getName());
|
||||
});
|
||||
}
|
||||
};
|
||||
WindowStateStore windows=new WindowStateStore(){
|
||||
public Optional<WindowGeometry> load(ProjectReference ref){fail("geometry");return Optional.empty();}
|
||||
public void save(ProjectReference ref,WindowGeometry geometry){}
|
||||
};
|
||||
opening=new ProjectOpening(catalog,known,sessions,windows,worker,Runnable::run,()->clock.now,clock,this);
|
||||
}
|
||||
void fail(String stage){if(failAt.equals(stage))throw new IllegalStateException(stage+" failed");}
|
||||
public void phase(ProjectOpening.Phase phase){phases.add(phase);}
|
||||
public void prepare(ProjectSession session,WindowGeometry geometry){fail("view");prepared++;}
|
||||
public void present(){fail("present");presented++;}
|
||||
public void discard(){}
|
||||
public void failed(Throwable failure,boolean cleanupRequired){failed++;lastFailure=failure;this.cleanupRequired=cleanupRequired;}
|
||||
}
|
||||
@Test void fastOpeningWaitsOnlyRemainderAndPublishesRealPhases(){
|
||||
var f=new Fixture();f.opening.start(ROOT);f.worker.drain();
|
||||
assertEquals(1,f.prepared);assertEquals(0,f.presented);assertTrue(f.opening.busy());
|
||||
assertEquals(List.of(ProjectOpening.Phase.VALIDATING,ProjectOpening.Phase.SESSION,ProjectOpening.Phase.CATALOG,ProjectOpening.Phase.VIEW,ProjectOpening.Phase.READY),f.phases);
|
||||
f.clock.advance(999);assertEquals(0,f.presented);f.clock.advance(1);
|
||||
assertEquals(1,f.presented);assertEquals(0,f.closed);assertFalse(f.opening.busy());
|
||||
}
|
||||
@Test void slowOpeningHasNoExtraSecond(){
|
||||
var f=new Fixture();f.opening.start(ROOT);f.clock.advance(1500);f.worker.drain();
|
||||
assertEquals(1,f.presented);assertTrue(f.clock.jobs.isEmpty());
|
||||
}
|
||||
@Test void cancellationOwnsLateSessionAndDoesNotWaitForVisualMinimum(){
|
||||
var f=new Fixture();f.opening.start(ROOT);f.worker.next(); // session acquisition is queued
|
||||
var stopped=f.opening.cancel().toCompletableFuture();assertFalse(stopped.isDone());
|
||||
f.worker.drain();assertTrue(stopped.isDone());assertEquals(1,f.opened);assertEquals(1,f.closed);
|
||||
f.clock.advance(2000);assertEquals(0,f.presented);assertFalse(f.opening.busy());
|
||||
}
|
||||
@Test void cancellationDuringMinimumClosesPendingSessionAndInvalidatesTimer(){
|
||||
var f=new Fixture();f.opening.start(ROOT);f.worker.drain();
|
||||
var stopped=f.opening.cancel().toCompletableFuture();f.worker.drain();assertTrue(stopped.isDone());
|
||||
assertEquals(1,f.closed);f.clock.advance(2000);assertEquals(0,f.presented);assertEquals(0,f.failed);
|
||||
}
|
||||
@Test void cancellationWaitsForInFlightCatalogBeforeCleanup(){
|
||||
var f=new Fixture();f.opening.start(ROOT);f.worker.next();f.worker.next();
|
||||
var stopped=f.opening.cancel().toCompletableFuture();assertFalse(stopped.isDone());
|
||||
f.worker.drain();assertTrue(stopped.isDone());assertEquals(1,f.closed);
|
||||
}
|
||||
@ParameterizedTest @ValueSource(strings={"catalog","session","remember","geometry","view","present"})
|
||||
void everyFailureReturnsAfterCleanupAndMinimum(String stage){
|
||||
var f=new Fixture();f.failAt=stage;f.opening.start(ROOT);f.worker.drain();
|
||||
f.clock.advance(1000);f.worker.drain();
|
||||
assertEquals(1,f.failed);assertFalse(f.cleanupRequired);assertFalse(f.opening.busy());
|
||||
assertEquals(f.opened,f.closed);assertEquals(0,f.presented);assertEquals(stage+" failed",f.lastFailure.getMessage());
|
||||
f.failAt="";f.opening.start(ROOT);f.worker.drain();f.clock.advance(1000);assertEquals(1,f.presented);
|
||||
}
|
||||
@Test void failedCleanupRetainsOwnershipAndCanBeRetried(){
|
||||
var f=new Fixture();f.failAt="view";f.closeFails=true;f.opening.start(ROOT);f.worker.drain();
|
||||
assertEquals(0,f.failed);f.clock.advance(1000);
|
||||
assertTrue(f.opening.cleanupRequired());assertTrue(f.cleanupRequired);
|
||||
assertThrows(IllegalStateException.class,()->f.opening.start(ROOT));
|
||||
assertEquals("view failed",f.lastFailure.getMessage());assertEquals("cleanup refused",f.lastFailure.getSuppressed()[0].getMessage());
|
||||
f.closeFails=false;f.opening.retryCleanup();f.worker.drain();f.clock.advance(1000);
|
||||
assertEquals(1,f.closed);assertFalse(f.opening.busy());assertFalse(f.cleanupRequired);
|
||||
}
|
||||
@Test void rejectedExecutorBeforeSessionDoesNotRequireCleanupExecutor(){
|
||||
var f=new Fixture();f.worker.reject=true;f.opening.start(ROOT);f.clock.advance(1000);
|
||||
assertEquals(1,f.failed);assertFalse(f.opening.busy());assertFalse(f.cleanupRequired);
|
||||
}
|
||||
@Test void abortingFailedOpeningDuringMinimumDoesNotWaitOrPublishFailure(){
|
||||
var f=new Fixture();f.failAt="catalog";f.opening.start(ROOT);f.worker.drain();
|
||||
assertTrue(f.opening.abort().toCompletableFuture().isDone());f.clock.advance(1000);assertEquals(0,f.failed);
|
||||
f.failAt="";f.opening.start(ROOT);f.worker.drain();f.clock.advance(1000);assertEquals(1,f.presented);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user