Commit | Line | Data |
---|---|---|
a3b510ab NR |
1 | package com.googlecode.lanterna.gui2; |
2 | ||
3 | import java.io.IOException; | |
4 | import java.util.Queue; | |
5 | import java.util.concurrent.CountDownLatch; | |
6 | import java.util.concurrent.LinkedBlockingQueue; | |
7 | ||
8 | /** | |
9 | * Created by martin on 20/06/15. | |
10 | */ | |
11 | public abstract class AbstractTextGUIThread implements TextGUIThread { | |
12 | ||
13 | protected final TextGUI textGUI; | |
14 | protected final Queue<Runnable> customTasks; | |
15 | protected ExceptionHandler exceptionHandler; | |
16 | ||
17 | public AbstractTextGUIThread(TextGUI textGUI) { | |
18 | this.exceptionHandler = new ExceptionHandler() { | |
19 | @Override | |
20 | public boolean onIOException(IOException e) { | |
21 | e.printStackTrace(); | |
22 | return true; | |
23 | } | |
24 | ||
25 | @Override | |
26 | public boolean onRuntimeException(RuntimeException e) { | |
27 | e.printStackTrace(); | |
28 | return true; | |
29 | } | |
30 | }; | |
31 | this.textGUI = textGUI; | |
32 | this.customTasks = new LinkedBlockingQueue<Runnable>(); | |
33 | } | |
34 | ||
35 | @Override | |
36 | public void invokeLater(Runnable runnable) throws IllegalStateException { | |
37 | if(Thread.currentThread() == getThread()) { | |
38 | runnable.run(); | |
39 | } | |
40 | else { | |
41 | customTasks.add(runnable); | |
42 | } | |
43 | } | |
44 | ||
45 | @Override | |
46 | public void setExceptionHandler(ExceptionHandler exceptionHandler) { | |
47 | if(exceptionHandler == null) { | |
48 | throw new IllegalArgumentException("Cannot call setExceptionHandler(null)"); | |
49 | } | |
50 | this.exceptionHandler = exceptionHandler; | |
51 | } | |
52 | ||
53 | @Override | |
54 | public synchronized boolean processEventsAndUpdate() throws IOException { | |
55 | if(getThread() != Thread.currentThread()) { | |
56 | throw new IllegalStateException("Calling processEventAndUpdate outside of GUI thread"); | |
57 | } | |
58 | textGUI.processInput(); | |
59 | while(!customTasks.isEmpty()) { | |
60 | Runnable r = customTasks.poll(); | |
61 | if(r != null) { | |
62 | r.run(); | |
63 | } | |
64 | } | |
65 | if(textGUI.isPendingUpdate()) { | |
66 | textGUI.updateScreen(); | |
67 | return true; | |
68 | } | |
69 | return false; | |
70 | } | |
71 | ||
72 | @Override | |
73 | public void invokeAndWait(final Runnable runnable) throws IllegalStateException, InterruptedException { | |
74 | final CountDownLatch countDownLatch = new CountDownLatch(1); | |
75 | invokeLater(new Runnable() { | |
76 | @Override | |
77 | public void run() { | |
78 | runnable.run(); | |
79 | countDownLatch.countDown(); | |
80 | } | |
81 | }); | |
82 | countDownLatch.await(); | |
83 | } | |
84 | } |