1 /*
2 * *************************************************************************************************************************************************************
3 *
4 * SteelBlue: DCI User Interfaces
5 * http://tidalwave.it/projects/steelblue
6 *
7 * Copyright (C) 2015 - 2025 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 jakarta.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.ui.javafx.impl.DefaultJavaFXBinder;
42 import it.tidalwave.ui.javafx.impl.DefaultJavaFXMenuBarControl;
43 import it.tidalwave.ui.javafx.impl.DefaultJavaFXToolBarControl;
44 import it.tidalwave.ui.javafx.impl.util.JavaFXSafeProxy;
45 import it.tidalwave.util.PreferencesHandler;
46 import lombok.Getter;
47 import lombok.extern.slf4j.Slf4j;
48
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
135 public static final Map<Class<?>, Object> BEANS = new HashMap<>();
136
137 @Getter
138 private static final ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
139
140 @Getter
141 private static final JavaFXBinder javaFxBinder = new DefaultJavaFXBinder(executor);
142
143 @Getter
144 private static final JavaFXToolBarControl toolBarControl = new DefaultJavaFXToolBarControl();
145
146 @Getter
147 private static final JavaFXMenuBarControl menuBarControl = new DefaultJavaFXMenuBarControl();
148
149 static
150 {
151 executor.setWaitForTasksToCompleteOnShutdown(false);
152 executor.setThreadNamePrefix("javafxBinder-");
153 // Fix for STB-26
154 executor.setCorePoolSize(1);
155 executor.setMaxPoolSize(1);
156 executor.setQueueCapacity(10000);
157 BEANS.put(JavaFXBinder.class, javaFxBinder);
158 BEANS.put(Executor.class, executor);
159 BEANS.put(JavaFXToolBarControl.class, toolBarControl);
160 BEANS.put(JavaFXMenuBarControl.class, menuBarControl);
161 BEANS.put(PreferencesHandler.class, PreferencesHandler.getInstance());
162 }
163
164 private JavaFXSafeProxyCreator () {}
165
166 /***********************************************************************************************************************************************************
167 * Creates a {@link NodeAndDelegate} for the given presentation class. The FXML resource name is inferred by
168 * default, For instance, is the class is named {@code JavaFXFooBarPresentation}, the resource name is
169 * {@code FooBar.fxml} and searched in the same packages as the class.
170 *
171 * @see #createNodeAndDelegate(java.lang.Class, java.lang.String)
172 *
173 * @since 1.0-ALPHA-13
174 *
175 * @param presentationClass the class of the presentation for which the resources must be created.
176 **********************************************************************************************************************************************************/
177 @Nonnull
178 public static <T> NodeAndDelegate<T> createNodeAndDelegate (@Nonnull final Class<T> presentationClass)
179 {
180 final var resource = presentationClass.getSimpleName().replaceAll("^JavaFX", "")
181 .replaceAll("^JavaFx", "")
182 .replaceAll("Presentation$", "")
183 + ".fxml";
184 return createNodeAndDelegate(presentationClass, resource);
185 }
186
187 /***********************************************************************************************************************************************************
188 * Creates a {@link NodeAndDelegate} for the given presentation class.
189 *
190 * @param presentationClass the class of the presentation for which the resources must be created.
191 * @param fxmlResourcePath the path of the FXML resource
192 **********************************************************************************************************************************************************/
193 @Nonnull
194 public static <T> NodeAndDelegate<T> createNodeAndDelegate (@Nonnull final Class<T> presentationClass, @Nonnull final String fxmlResourcePath)
195 {
196 log.debug("createNodeAndDelegate({}, {})", presentationClass, fxmlResourcePath);
197
198 final var latch = new CountDownLatch(1);
199 final var nad = new AtomicReference<NodeAndDelegate<T>>();
200 final var exception = new AtomicReference<RuntimeException>();
201
202 if (Platform.isFxApplicationThread())
203 {
204 try
205 {
206 return NodeAndDelegate.load(presentationClass, fxmlResourcePath);
207 }
208 catch (IOException e)
209 {
210 exception.set(new RuntimeException(e));
211 }
212 }
213
214 Platform.runLater(() ->
215 {
216 try
217 {
218 nad.set(NodeAndDelegate.load(presentationClass, fxmlResourcePath));
219 }
220 catch (RuntimeException e)
221 {
222 exception.set(e);
223 }
224 catch (Exception e)
225 {
226 exception.set(new RuntimeException(e));
227 }
228
229 latch.countDown();
230 });
231
232 try
233 {
234 log.debug("Waiting for NodeAndDelegate initialisation in JavaFX thread...");
235 log.debug("If deadlocks and you need longer time with the debugger, set {} (current value: {})", P_TIMEOUT, initializerTimeout);
236 latch.await(initializerTimeout, TimeUnit.SECONDS); // FIXME
237 }
238 catch (InterruptedException e)
239 {
240 throw new RuntimeException(e);
241 }
242
243 if (exception.get() != null)
244 {
245 throw exception.get();
246 }
247
248 if (nad.get() == null)
249 {
250 final var message = String.format("Likely deadlock in the JavaFX Thread: couldn't create NodeAndDelegate: %s, %s",
251 presentationClass, fxmlResourcePath);
252 throw new RuntimeException(message);
253 }
254
255 return nad.get();
256 }
257
258 /***********************************************************************************************************************************************************
259 *
260 **********************************************************************************************************************************************************/
261 @Nonnull
262 public static <T> T createSafeProxy (@Nonnull final T target, final Class<?>[] interfaces)
263 {
264 return (T)Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), interfaces, new JavaFXSafeProxy<>(target));
265 }
266 }