JavaFXSafeProxyCreator.java

  1. /*
  2.  * *************************************************************************************************************************************************************
  3.  *
  4.  * SteelBlue: DCI User Interfaces
  5.  * http://tidalwave.it/projects/steelblue
  6.  *
  7.  * Copyright (C) 2015 - 2024 by Tidalwave s.a.s. (http://tidalwave.it)
  8.  *
  9.  * *************************************************************************************************************************************************************
  10.  *
  11.  * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
  12.  * You may obtain a copy of the License at
  13.  *
  14.  *     http://www.apache.org/licenses/LICENSE-2.0
  15.  *
  16.  * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
  17.  * CONDITIONS OF ANY KIND, either express or implied.  See the License for the specific language governing permissions and limitations under the License.
  18.  *
  19.  * *************************************************************************************************************************************************************
  20.  *
  21.  * git clone https://bitbucket.org/tidalwave/steelblue-src
  22.  * git clone https://github.com/tidalwave-it/steelblue-src
  23.  *
  24.  * *************************************************************************************************************************************************************
  25.  */
  26. package it.tidalwave.ui.javafx;

  27. import java.lang.reflect.Proxy;
  28. import javax.annotation.Nonnull;
  29. import java.util.HashMap;
  30. import java.util.Map;
  31. import java.util.concurrent.CountDownLatch;
  32. import java.util.concurrent.Executor;
  33. import java.util.concurrent.TimeUnit;
  34. import java.util.concurrent.atomic.AtomicReference;
  35. import java.io.IOException;
  36. import javafx.fxml.FXMLLoader;
  37. import javafx.scene.Node;
  38. import javafx.application.Platform;
  39. import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
  40. import it.tidalwave.role.ui.MenuBarModel;
  41. import it.tidalwave.role.ui.ToolBarModel;
  42. import it.tidalwave.role.ui.javafx.JavaFXBinder;
  43. import it.tidalwave.role.ui.javafx.impl.DefaultJavaFXBinder;
  44. import it.tidalwave.role.ui.javafx.impl.JavaFXMenuBarModel;
  45. import it.tidalwave.role.ui.javafx.impl.JavaFXToolBarModel;
  46. import it.tidalwave.role.ui.javafx.impl.util.JavaFXSafeProxy;
  47. import lombok.Getter;
  48. import lombok.extern.slf4j.Slf4j;

  49. /***************************************************************************************************************************************************************
  50.  *
  51.  * This facility class create a thread-safe proxy for the JavaFX delegate (controller). Thread-safe means that it can
  52.  * be called by any thread and the JavaFX UI related stuff will be safely invoked in the JavaFX UI Thread.
  53.  * It is usually used in this way:
  54.  *
  55.  * <pre>
  56.  * // This is a Spring bean
  57.  * public class JavaFxFooBarPresentation implements FooBarPresentation
  58.  *   {
  59.  *     private static final String FXML_URL = "/my/package/javafx/FooBar.fxml";
  60.  *
  61.  *     {@literal @}Inject
  62.  *     private FlowController flowController;
  63.  *
  64.  *     private final NodeAndDelegate nad = createNodeAndDelegate(getClass(), FXML_URL);
  65.  *
  66.  *     private final FooBarPresentation delegate = nad.getDelegate();
  67.  *
  68.  *     public void showUp()
  69.  *       {
  70.  *         flowController.doSomething(nad.getNode());
  71.  *       }
  72.  *
  73.  *     public void showData (final String data)
  74.  *       {
  75.  *         delegate.showData(data);
  76.  *       }
  77.  *   }
  78.  * </pre>
  79.  *
  80.  * The method {@link #createNodeAndDelegate(java.lang.Class, java.lang.String)} safely invokes the {@link FXMLLoader}
  81.  * and returns a {@link NodeAndDelegate} that contains both the visual {@link Node} and its delegate (controller).
  82.  *
  83.  * The latter is wrapped by a safe proxy that makes sure that any method invocation (such as {@code showData()} in the
  84.  * example is again executed in the JavaFX UI Thread. This means that the Presentation object methods can be invoked
  85.  * in any thread.
  86.  *
  87.  * For method returning {@code void}, the method invocation is asynchronous; that is, the caller is not blocked waiting
  88.  * for the method execution completion. If a return value is provided, the invocation is synchronous, and the caller
  89.  * will correctly wait the completion of the execution in order to get the result value.
  90.  *
  91.  * A typical JavaFX delegate (controller) looks like:
  92.  *
  93.  * <pre>
  94.  * // This is not a Spring bean - created by the FXMLLoader
  95.  * public class JavaFxFooBarPresentationDelegate implements FooBarPresentation
  96.  *   {
  97.  *     {@literal @}FXML
  98.  *     private Label label;
  99.  *
  100.  *     {@literal @}FXML
  101.  *     private Button button;
  102.  *
  103.  *     {@literal @}Inject // the only thing that can be injected, by means of JavaFXSafeProxyCreator
  104.  *     private JavaFxBinder binder;
  105.  *
  106.  *     {@literal @}Override
  107.  *     public void bind (final UserAction action)
  108.  *       {
  109.  *         binder.bind(button, action);
  110.  *       }
  111.  *
  112.  *     {@literal @}Override
  113.  *     public void showData (final String data)
  114.  *       {
  115.  *         label.setText(data);
  116.  *       }
  117.  *  }
  118.  * </pre>
  119.  *
  120.  * Not only all the methods invoked on the delegate are guaranteed to run in the JavaFX UI thread, but also its
  121.  * constructor, as per JavaFX requirements.
  122.  *
  123.  * A Presentation Delegate must not try to have dependency injection from Spring (for instance, by means of AOP),
  124.  * otherwise a deadlock could be triggered. Injection in constructors is safe.
  125.  *
  126.  * @author  Fabrizio Giudici
  127.  *
  128.  **************************************************************************************************************************************************************/
  129. @Slf4j
  130. public class JavaFXSafeProxyCreator
  131.   {
  132.     private static final String P_TIMEOUT = JavaFXSafeProxyCreator.class.getName() + ".initTimeout";
  133.     private static final int initializerTimeout = Integer.getInteger(P_TIMEOUT, 10);

  134.     public static final Map<Class<?>, Object> BEANS = new HashMap<>();

  135.     @Getter
  136.     private static final ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();

  137.     @Getter
  138.     private static final JavaFXBinder javaFxBinder = new DefaultJavaFXBinder(executor);

  139.     @Getter
  140.     private static final ToolBarModel toolBarModel = new JavaFXToolBarModel();

  141.     @Getter
  142.     private static final MenuBarModel menuBarModel = new JavaFXMenuBarModel();

  143.     static
  144.       {
  145.         executor.setWaitForTasksToCompleteOnShutdown(false);
  146.         executor.setThreadNamePrefix("javafxBinder-");
  147.         // Fix for STB-26
  148.         executor.setCorePoolSize(1);
  149.         executor.setMaxPoolSize(1);
  150.         executor.setQueueCapacity(10000);
  151.         BEANS.put(JavaFXBinder.class, javaFxBinder);
  152.         BEANS.put(Executor.class, executor);
  153.         BEANS.put(ToolBarModel.class, toolBarModel);
  154.         BEANS.put(MenuBarModel.class, menuBarModel);
  155.       }

  156.     private JavaFXSafeProxyCreator () {}

  157.     /***********************************************************************************************************************************************************
  158.      * Creates a {@link NodeAndDelegate} for the given presentation class. The FXML resource name is inferred by
  159.      * default, For instance, is the class is named {@code JavaFXFooBarPresentation}, the resource name is
  160.      * {@code FooBar.fxml} and searched in the same packages as the class.
  161.      *
  162.      * @see #createNodeAndDelegate(java.lang.Class, java.lang.String)
  163.      *
  164.      * @since 1.0-ALPHA-13
  165.      *
  166.      * @param   presentationClass   the class of the presentation for which the resources must be created.
  167.      **********************************************************************************************************************************************************/
  168.     @Nonnull
  169.     public static <T> NodeAndDelegate<T> createNodeAndDelegate (@Nonnull final Class<T> presentationClass)
  170.       {
  171.         final var resource = presentationClass.getSimpleName().replaceAll("^JavaFX", "")
  172.                                               .replaceAll("^JavaFx", "")
  173.                                               .replaceAll("Presentation$", "")
  174.                              + ".fxml";
  175.         return createNodeAndDelegate(presentationClass, resource);
  176.       }

  177.     /***********************************************************************************************************************************************************
  178.      * Creates a {@link NodeAndDelegate} for the given presentation class.
  179.      *
  180.      * @param   presentationClass   the class of the presentation for which the resources must be created.
  181.      * @param   fxmlResourcePath    the path of the FXML resource
  182.      **********************************************************************************************************************************************************/
  183.     @Nonnull
  184.     public static <T> NodeAndDelegate<T> createNodeAndDelegate (@Nonnull final Class<T> presentationClass, @Nonnull final String fxmlResourcePath)
  185.       {
  186.         log.debug("createNodeAndDelegate({}, {})", presentationClass, fxmlResourcePath);

  187.         final var latch = new CountDownLatch(1);
  188.         final var nad = new AtomicReference<NodeAndDelegate<T>>();
  189.         final var exception = new AtomicReference<RuntimeException>();

  190.         if (Platform.isFxApplicationThread())
  191.           {
  192.             try
  193.               {
  194.                 return NodeAndDelegate.load(presentationClass, fxmlResourcePath);
  195.               }
  196.             catch (IOException e)
  197.               {
  198.                 exception.set(new RuntimeException(e));
  199.               }
  200.           }

  201.         Platform.runLater(() ->
  202.           {
  203.             try
  204.               {
  205.                 nad.set(NodeAndDelegate.load(presentationClass, fxmlResourcePath));
  206.               }
  207.             catch (RuntimeException e)
  208.               {
  209.                 exception.set(e);
  210.               }
  211.             catch (Exception e)
  212.               {
  213.                 exception.set(new RuntimeException(e));
  214.               }

  215.             latch.countDown();
  216.           });

  217.         try
  218.           {
  219.             log.debug("Waiting for NodeAndDelegate initialisation in JavaFX thread...");
  220.             log.debug("If deadlocks and you need longer time with the debugger, set {} (current value: {})", P_TIMEOUT, initializerTimeout);
  221.             latch.await(initializerTimeout, TimeUnit.SECONDS); // FIXME
  222.           }
  223.         catch (InterruptedException e)
  224.           {
  225.             throw new RuntimeException(e);
  226.           }

  227.         if (exception.get() != null)
  228.           {
  229.             throw exception.get();
  230.           }

  231.         if (nad.get() == null)
  232.           {
  233.             final var message = String.format("Likely deadlock in the JavaFX Thread: couldn't create NodeAndDelegate: %s, %s",
  234.                                               presentationClass, fxmlResourcePath);
  235.             throw new RuntimeException(message);
  236.           }

  237.         return nad.get();
  238.       }

  239.     /***********************************************************************************************************************************************************
  240.      *
  241.      **********************************************************************************************************************************************************/
  242.     @Nonnull
  243.     public static <T> T createSafeProxy (@Nonnull final T target, final Class<?>[] interfaces)
  244.       {
  245.         return (T)Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), interfaces, new JavaFXSafeProxy<>(target));
  246.       }
  247.   }