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 fx(Callable action)throws Exception { var task=new FutureTask<>(action);Platform.runLater(task);return task.get(15,TimeUnit.SECONDS); } static void await(Callable condition)throws Exception { long end=System.nanoTime()+TimeUnit.SECONDS.toNanos(15); while(System.nanoTime()();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(); 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(); WindowStateStore windows=new WindowStateStore(){ public Optional 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)stage.getScene().lookup("#theme-select")).setValue(Theme.LIGHT); ((ComboBox)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)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