View Javadoc
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  
28  import java.lang.reflect.Proxy;
29  import javax.annotation.Nonnull;
30  import java.util.HashMap;
31  import java.util.Map;
32  import java.util.concurrent.CountDownLatch;
33  import java.util.concurrent.Executor;
34  import java.util.concurrent.TimeUnit;
35  import java.util.concurrent.atomic.AtomicReference;
36  import java.io.IOException;
37  import javafx.fxml.FXMLLoader;
38  import javafx.scene.Node;
39  import javafx.application.Platform;
40  import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
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.util.JavaFXSafeProxy;
45  import lombok.Getter;
46  import lombok.extern.slf4j.Slf4j;
47  
48  /***************************************************************************************************************************************************************
49   *
50   * This facility class create a thread-safe proxy for the JavaFX delegate (controller). Thread-safe means that it can
51   * be called by any thread and the JavaFX UI related stuff will be safely invoked in the JavaFX UI Thread.
52   * It is usually used in this way:
53   *
54   * <pre>
55   * // This is a Spring bean
56   * public class JavaFxFooBarPresentation implements FooBarPresentation
57   *   {
58   *     private static final String FXML_URL = "/my/package/javafx/FooBar.fxml";
59   *
60   *     {@literal @}Inject
61   *     private FlowController flowController;
62   *
63   *     private final NodeAndDelegate nad = createNodeAndDelegate(getClass(), FXML_URL);
64   *
65   *     private final FooBarPresentation delegate = nad.getDelegate();
66   *
67   *     public void showUp()
68   *       {
69   *         flowController.doSomething(nad.getNode());
70   *       }
71   *
72   *     public void showData (final String data)
73   *       {
74   *         delegate.showData(data);
75   *       }
76   *   }
77   * </pre>
78   *
79   * The method {@link #createNodeAndDelegate(java.lang.Class, java.lang.String)} safely invokes the {@link FXMLLoader}
80   * and returns a {@link NodeAndDelegate} that contains both the visual {@link Node} and its delegate (controller).
81   *
82   * The latter is wrapped by a safe proxy that makes sure that any method invocation (such as {@code showData()} in the
83   * example is again executed in the JavaFX UI Thread. This means that the Presentation object methods can be invoked
84   * in any thread.
85   *
86   * For method returning {@code void}, the method invocation is asynchronous; that is, the caller is not blocked waiting
87   * for the method execution completion. If a return value is provided, the invocation is synchronous, and the caller
88   * will correctly wait the completion of the execution in order to get the result value.
89   *
90   * A typical JavaFX delegate (controller) looks like:
91   *
92   * <pre>
93   * // This is not a Spring bean - created by the FXMLLoader
94   * public class JavaFxFooBarPresentationDelegate implements FooBarPresentation
95   *   {
96   *     {@literal @}FXML
97   *     private Label label;
98   *
99   *     {@literal @}FXML
100  *     private Button button;
101  *
102  *     {@literal @}Inject // the only thing that can be injected, by means of JavaFXSafeProxyCreator
103  *     private JavaFxBinder binder;
104  *
105  *     {@literal @}Override
106  *     public void bind (final UserAction action)
107  *       {
108  *         binder.bind(button, action);
109  *       }
110  *
111  *     {@literal @}Override
112  *     public void showData (final String data)
113  *       {
114  *         label.setText(data);
115  *       }
116  *  }
117  * </pre>
118  *
119  * Not only all the methods invoked on the delegate are guaranteed to run in the JavaFX UI thread, but also its
120  * constructor, as per JavaFX requirements.
121  *
122  * A Presentation Delegate must not try to have dependency injection from Spring (for instance, by means of AOP),
123  * otherwise a deadlock could be triggered. Injection in constructors is safe.
124  *
125  * @author  Fabrizio Giudici
126  *
127  **************************************************************************************************************************************************************/
128 @Slf4j
129 public class JavaFXSafeProxyCreator
130   {
131     private static final String P_TIMEOUT = JavaFXSafeProxyCreator.class.getName() + ".initTimeout";
132     private static final int initializerTimeout = Integer.getInteger(P_TIMEOUT, 10);
133 
134     public static final Map<Class<?>, Object> BEANS = new HashMap<>();
135 
136     @Getter
137     private static final ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
138 
139     @Getter
140     private static final JavaFXBinder javaFxBinder = new DefaultJavaFXBinder(executor);
141 
142     @Getter
143     private static final ToolBarModel toolBarModel = new JavaFXToolBarModel();
144 
145     static
146       {
147         executor.setWaitForTasksToCompleteOnShutdown(false);
148         executor.setThreadNamePrefix("javafxBinder-");
149         // Fix for STB-26
150         executor.setCorePoolSize(1);
151         executor.setMaxPoolSize(1);
152         executor.setQueueCapacity(10000);
153         BEANS.put(JavaFXBinder.class, javaFxBinder);
154         BEANS.put(Executor.class, executor);
155         BEANS.put(ToolBarModel.class, toolBarModel);
156       }
157 
158     private JavaFXSafeProxyCreator () {}
159 
160     /***********************************************************************************************************************************************************
161      * Creates a {@link NodeAndDelegate} for the given presentation class. The FXML resource name is inferred by
162      * default, For instance, is the class is named {@code JavaFXFooBarPresentation}, the resource name is
163      * {@code FooBar.fxml} and searched in the same packages as the class.
164      *
165      * @see #createNodeAndDelegate(java.lang.Class, java.lang.String)
166      *
167      * @since 1.0-ALPHA-13
168      *
169      * @param   presentationClass   the class of the presentation for which the resources must be created.
170      **********************************************************************************************************************************************************/
171     @Nonnull
172     public static <T> NodeAndDelegate<T> createNodeAndDelegate (@Nonnull final Class<T> presentationClass)
173       {
174         final var resource = presentationClass.getSimpleName().replaceAll("^JavaFX", "")
175                                               .replaceAll("^JavaFx", "")
176                                               .replaceAll("Presentation$", "")
177                              + ".fxml";
178         return createNodeAndDelegate(presentationClass, resource);
179       }
180 
181     /***********************************************************************************************************************************************************
182      * Creates a {@link NodeAndDelegate} for the given presentation class.
183      *
184      * @param   presentationClass   the class of the presentation for which the resources must be created.
185      * @param   fxmlResourcePath    the path of the FXML resource
186      **********************************************************************************************************************************************************/
187     @Nonnull
188     public static <T> NodeAndDelegate<T> createNodeAndDelegate (@Nonnull final Class<T> presentationClass, @Nonnull final String fxmlResourcePath)
189       {
190         log.debug("createNodeAndDelegate({}, {})", presentationClass, fxmlResourcePath);
191 
192         final var latch = new CountDownLatch(1);
193         final var nad = new AtomicReference<NodeAndDelegate<T>>();
194         final var exception = new AtomicReference<RuntimeException>();
195 
196         if (Platform.isFxApplicationThread())
197           {
198             try
199               {
200                 return NodeAndDelegate.load(presentationClass, fxmlResourcePath);
201               }
202             catch (IOException e)
203               {
204                 exception.set(new RuntimeException(e));
205               }
206           }
207 
208         Platform.runLater(() ->
209           {
210             try
211               {
212                 nad.set(NodeAndDelegate.load(presentationClass, fxmlResourcePath));
213               }
214             catch (RuntimeException e)
215               {
216                 exception.set(e);
217               }
218             catch (Exception e)
219               {
220                 exception.set(new RuntimeException(e));
221               }
222 
223             latch.countDown();
224           });
225 
226         try
227           {
228             log.debug("Waiting for NodeAndDelegate initialisation in JavaFX thread...");
229             log.debug("If deadlocks and you need longer time with the debugger, set {} (current value: {})", P_TIMEOUT, initializerTimeout);
230             latch.await(initializerTimeout, TimeUnit.SECONDS); // FIXME
231           }
232         catch (InterruptedException e)
233           {
234             throw new RuntimeException(e);
235           }
236 
237         if (exception.get() != null)
238           {
239             throw exception.get();
240           }
241 
242         if (nad.get() == null)
243           {
244             final var message = String.format("Likely deadlock in the JavaFX Thread: couldn't create NodeAndDelegate: %s, %s",
245                                               presentationClass, fxmlResourcePath);
246             throw new RuntimeException(message);
247           }
248 
249         return nad.get();
250       }
251 
252     /***********************************************************************************************************************************************************
253      *
254      **********************************************************************************************************************************************************/
255     @Nonnull
256     public static <T> T createSafeProxy (@Nonnull final T target, final Class<T> interfaceClass)
257       {
258         return (T)Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class[] { interfaceClass }, new JavaFXSafeProxy<>(target));
259       }
260   }