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