01 /*
02 * Copyright 2008-2017 the original author or authors.
03 *
04 * Licensed under the Apache License, Version 2.0 (the "License");
05 * you may not use this file except in compliance with the License.
06 * You may obtain a copy of the License at
07 *
08 * http://www.apache.org/licenses/LICENSE-2.0
09 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16 package org.codehaus.griffon.runtime.javafx;
17
18 import griffon.core.ExceptionHandler;
19 import javafx.application.Platform;
20 import org.codehaus.griffon.runtime.core.threading.AbstractUIThreadManager;
21
22 import javax.annotation.Nonnull;
23 import javax.inject.Inject;
24 import java.util.concurrent.ExecutionException;
25 import java.util.concurrent.FutureTask;
26
27 import static java.util.Objects.requireNonNull;
28
29 /**
30 * @author Dean Iverson
31 */
32 public class JavaFXUIThreadManager extends AbstractUIThreadManager {
33 @Inject
34 private ExceptionHandler exceptionHandler;
35
36 /**
37 * True if the current thread is the UI thread.
38 */
39 public boolean isUIThread() {
40 return Platform.isFxApplicationThread();
41 }
42
43 @Override
44 public void runInsideUIAsync(@Nonnull Runnable runnable) {
45 requireNonNull(runnable, ERROR_RUNNABLE_NULL);
46 Platform.runLater(runnable);
47 }
48
49 @Override
50 public void runInsideUISync(@Nonnull final Runnable runnable) {
51 requireNonNull(runnable, ERROR_RUNNABLE_NULL);
52 if (isUIThread()) {
53 runnable.run();
54 } else {
55 FutureTask<Void> task = new FutureTask<>(() -> {
56 try {
57 runnable.run();
58 } catch (Throwable throwable) {
59 exceptionHandler.uncaughtException(Thread.currentThread(), throwable);
60 }
61 }, null);
62
63 Platform.runLater(task);
64 try {
65 task.get();
66 } catch (InterruptedException | ExecutionException e) {
67 exceptionHandler.uncaughtException(Thread.currentThread(), e);
68 }
69 }
70 }
71 }
|