working multiple missions
[des2015.git] / dsl / runtime / src / nl / ru / des / LCDPrinter.java
1 package nl.ru.des;
2
3 import java.io.IOException;
4 import java.io.OutputStream;
5 import java.io.PrintStream;
6 import java.util.Deque;
7 import java.util.LinkedList;
8
9 import lejos.hardware.lcd.TextLCD;
10 import lejos.utility.Delay;
11
12 public class LCDPrinter{
13 public static final int PRINTDELAY = 50;
14
15 private static class Message{
16 public String msg;
17 public boolean nl;
18
19 public Message(String msg, boolean nl){
20 this.msg = msg;
21 this.nl = nl;
22 }
23 }
24
25 private static Deque<Message> buffer = new LinkedList<Message>();
26
27 public static void startLCDPrinter(final TextLCD glcd) {
28 new Thread(new Runnable(){
29 @Override
30 public void run() {
31 while (true) {
32 if (!buffer.isEmpty()) {
33 Message c = buffer.remove();
34 if(c.msg.length() > glcd.getTextWidth()){
35 buffer.addFirst(new Message(c.msg.substring(glcd.getTextWidth(), c.msg.length()), c.nl));
36 c.msg = c.msg.substring(0, glcd.getTextWidth());
37 }
38 if(c.nl){
39 glcd.scroll();
40 } else {
41 glcd.clear(glcd.getTextHeight()-1);
42 }
43 glcd.drawString(c.msg, 0, glcd.getTextHeight()-1);
44 }
45 Delay.msDelay(PRINTDELAY);
46 }
47 }
48 }).start();
49 LCDPrinter.print("LCDThread started");
50 }
51
52 public static void print(String s){
53 print(s, true);
54 }
55
56 public synchronized static void print(String s, boolean nl){
57 buffer.addLast(new Message(s, nl));
58 }
59
60 public static PrintStream getPrefixedPrintstream(final String prefix, final TextLCD glcd){
61 return new PrintStream(new OutputStream(){
62 private char[] line = new char[glcd.getTextWidth()];
63 private int index = 0;
64
65 @Override
66 public void write(int b) throws IOException {
67 if(index == line.length-prefix.length() || b == '\n'){
68 LCDPrinter.print(prefix + String.valueOf(line, 0, index));
69 index = 0;
70 } else {
71 line[index++] = (char)b;
72 }
73 }
74 });
75 }
76 }