Fix UTF8 bug, create first executable JAR file
[jvcard.git] / src / com / googlecode / lanterna / gui2 / AbstractTextGUIThread.java
... / ...
CommitLineData
1package com.googlecode.lanterna.gui2;
2
3import java.io.IOException;
4import java.util.Queue;
5import java.util.concurrent.CountDownLatch;
6import java.util.concurrent.LinkedBlockingQueue;
7
8/**
9 * Created by martin on 20/06/15.
10 */
11public 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 customTasks.add(runnable);
38 }
39
40 @Override
41 public void setExceptionHandler(ExceptionHandler exceptionHandler) {
42 if(exceptionHandler == null) {
43 throw new IllegalArgumentException("Cannot call setExceptionHandler(null)");
44 }
45 this.exceptionHandler = exceptionHandler;
46 }
47
48 @Override
49 public synchronized boolean processEventsAndUpdate() throws IOException {
50 if(getThread() != Thread.currentThread()) {
51 throw new IllegalStateException("Calling processEventAndUpdate outside of GUI thread");
52 }
53 textGUI.processInput();
54 while(!customTasks.isEmpty()) {
55 Runnable r = customTasks.poll();
56 if(r != null) {
57 r.run();
58 }
59 }
60 if(textGUI.isPendingUpdate()) {
61 textGUI.updateScreen();
62 return true;
63 }
64 return false;
65 }
66
67 @Override
68 public void invokeAndWait(final Runnable runnable) throws IllegalStateException, InterruptedException {
69 if(Thread.currentThread() == getThread()) {
70 runnable.run();
71 }
72 else {
73 final CountDownLatch countDownLatch = new CountDownLatch(1);
74 invokeLater(new Runnable() {
75 @Override
76 public void run() {
77 try {
78 runnable.run();
79 }
80 finally {
81 countDownLatch.countDown();
82 }
83 }
84 });
85 countDownLatch.await();
86 }
87 }
88}