PivotUIThreadManager.java
01 /*
02  * Copyright 2008-2014 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.pivot;
17 
18 import griffon.core.GriffonExceptionHandler;
19 import org.codehaus.griffon.runtime.core.threading.AbstractUIThreadManager;
20 
21 import javax.annotation.Nonnull;
22 import javax.inject.Inject;
23 import java.awt.EventQueue;
24 import java.lang.reflect.InvocationTargetException;
25 
26 /**
27  * Executes code honoring Pivot's threading model.
28  *
29  @author Andres Almiray
30  @since 2.0.0
31  */
32 public class PivotUIThreadManager extends AbstractUIThreadManager {
33     private final GriffonExceptionHandler exceptionHandler;
34 
35     @Inject
36     public PivotUIThreadManager(@Nonnull GriffonExceptionHandler exceptionHandler) {
37         this.exceptionHandler = exceptionHandler;
38     }
39 
40     public boolean isUIThread() {
41         return EventQueue.isDispatchThread();
42     }
43 
44     @Override
45     public void runInsideUIAsync(@Nonnull Runnable runnable) {
46         EventQueue.invokeLater(runnable);
47     }
48 
49     @Override
50     public void runInsideUISync(final @Nonnull Runnable runnable) {
51         if (isUIThread()) {
52             runnable.run();
53         else {
54             try {
55                 EventQueue.invokeAndWait(runnable);
56             catch (InterruptedException e) {
57                 exceptionHandler.uncaughtException(Thread.currentThread(), e);
58             catch (InvocationTargetException e) {
59                 exceptionHandler.uncaughtException(Thread.currentThread(), e.getTargetException());
60             }
61         }
62     }
63 }