01 /*
02 * Copyright 2008-2016 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(final @Nonnull Runnable runnable) {
51 requireNonNull(runnable, ERROR_RUNNABLE_NULL);
52 if (isUIThread()) {
53 runnable.run();
54 } else {
55 FutureTask<Void> task = new FutureTask<>(new Runnable() {
56 @Override
57 public void run() {
58 try {
59 runnable.run();
60 } catch (Throwable throwable) {
61 exceptionHandler.uncaughtException(Thread.currentThread(), throwable);
62 }
63 }
64 }, null);
65
66 Platform.runLater(task);
67 try {
68 task.get();
69 } catch (InterruptedException | ExecutionException e) {
70 exceptionHandler.uncaughtException(Thread.currentThread(), e);
71 }
72 }
73 }
74 }
|