2 * Jalview - A Sequence Alignment Editor and Viewer (Version 2.6)
3 * Copyright (C) 2010 J Procter, AM Waterhouse, G Barton, M Clamp, S Searle
5 * This file is part of Jalview.
7 * Jalview is free software: you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
11 * Jalview is distributed in the hope that it will be useful, but
12 * WITHOUT ANY WARRANTY; without even the implied warranty
13 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
14 * PURPOSE. See the GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License along with Jalview. If not, see <http://www.gnu.org/licenses/>.
22 import java.awt.event.*;
25 import org.apache.log4j.SimpleLayout;
28 * Simple Jalview Java Console. Version 1 - allows viewing of console output
29 * after desktop is created. Acquired with thanks from RJHM's site
30 * http://www.comweb.nl/java/Console/Console.html A simple Java Console for your
31 * application (Swing version) Requires Java 1.1.5 or higher Disclaimer the use
32 * of this source is at your own risk. Permision to use and distribute into your
33 * own applications RJHM van den Bergh , rvdb@comweb.nl
36 public class Console extends WindowAdapter implements WindowListener,
37 ActionListener, Runnable
41 private JTextArea textArea;
44 * unused - tally and limit for lines in console window int lines = 0;
48 int byteslim = 102400, bytescut = 76800; // 100k and 75k cut point.
50 private Thread reader, reader2, textAppender;
54 private final PrintStream stdout = System.out, stderr = System.err;
56 private PipedInputStream pin = new PipedInputStream();
58 private PipedInputStream pin2 = new PipedInputStream();
60 private StringBuffer displayPipe = new StringBuffer();
62 Thread errorThrower; // just for testing (Throws an Exception at this Console
64 // are we attached to some parent Desktop
65 Desktop parent = null;
69 // create all components and add them
70 Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
71 frame = initFrame("Java Console", screenSize.width / 2,
72 screenSize.height / 2, -1, -1);
76 private void initConsole(boolean visible)
78 initConsole(visible, true);
88 private void initConsole(boolean visible, boolean redirect)
90 // CutAndPasteTransfer cpt = new CutAndPasteTransfer();
91 // textArea = cpt.getTextArea();
92 textArea = new JTextArea();
93 textArea.setEditable(false);
94 JButton button = new JButton("clear");
97 frame.getContentPane().setLayout(new BorderLayout());
98 frame.getContentPane().add(new JScrollPane(textArea),
100 frame.getContentPane().add(button, BorderLayout.SOUTH);
101 frame.setVisible(visible);
102 updateConsole = visible;
103 frame.addWindowListener(this);
104 button.addActionListener(this);
113 quit = false; // signals the Threads that they should exit
115 // Starting two seperate threads to read from the PipedInputStreams
117 reader = new Thread(this);
118 reader.setDaemon(true);
121 reader2 = new Thread(this);
122 reader2.setDaemon(true);
124 // and a thread to append text to the textarea
125 textAppender = new Thread(this);
126 textAppender.setDaemon(true);
127 textAppender.start();
130 PipedOutputStream pout = null, perr = null;
132 public void redirectStreams()
138 pout = new PipedOutputStream(this.pin);
139 System.setOut(new PrintStream(pout, true));
140 } catch (java.io.IOException io)
142 textArea.append("Couldn't redirect STDOUT to this console\n"
144 io.printStackTrace(stderr);
145 } catch (SecurityException se)
147 textArea.append("Couldn't redirect STDOUT to this console\n"
149 se.printStackTrace(stderr);
154 perr = new PipedOutputStream(this.pin2);
155 System.setErr(new PrintStream(perr, true));
156 } catch (java.io.IOException io)
158 textArea.append("Couldn't redirect STDERR to this console\n"
160 io.printStackTrace(stderr);
161 } catch (SecurityException se)
163 textArea.append("Couldn't redirect STDERR to this console\n"
165 se.printStackTrace(stderr);
170 public void unredirectStreams()
176 System.setOut(stdout);
179 pin = new PipedInputStream();
181 } catch (java.io.IOException io)
183 textArea.append("Couldn't unredirect STDOUT to this console\n"
185 io.printStackTrace(stderr);
186 } catch (SecurityException se)
188 textArea.append("Couldn't unredirect STDOUT to this console\n"
190 se.printStackTrace(stderr);
195 System.setErr(stderr);
198 pin2 = new PipedInputStream();
200 } catch (java.io.IOException io)
202 textArea.append("Couldn't unredirect STDERR to this console\n"
204 io.printStackTrace(stderr);
205 } catch (SecurityException se)
207 textArea.append("Couldn't unredirect STDERR to this console\n"
209 se.printStackTrace(stderr);
217 // you may omit this part for your application
220 System.out.println("Hello World 2");
221 System.out.println("All fonts available to Graphic2D:\n");
222 GraphicsEnvironment ge = GraphicsEnvironment
223 .getLocalGraphicsEnvironment();
224 String[] fontNames = ge.getAvailableFontFamilyNames();
225 for (int n = 0; n < fontNames.length; n++)
226 System.out.println(fontNames[n]);
227 // Testing part: simple an error thrown anywhere in this JVM will be printed
229 // We do it with a seperate Thread becasue we don't wan't to break a Thread
230 // used by the Console.
231 System.out.println("\nLets throw an error on this console");
232 errorThrower = new Thread(this);
233 errorThrower.setDaemon(true);
234 errorThrower.start();
237 private JFrame initFrame(String string, int i, int j, int x, int y)
239 JFrame frame = new JFrame(string);
240 frame.setName(string);
245 frame.setBounds(x, y, i, j);
250 * attach a console to the desktop - the desktop will open it if requested.
254 public Console(Desktop desktop)
260 * attach a console to the desktop - the desktop will open it if requested.
263 * @param showjconsole
264 * - if true, then redirect stdout immediately
266 public Console(Desktop desktop, boolean showjconsole)
269 // window name - get x,y,width, height possibly scaled
270 Rectangle bounds = desktop.getLastKnownDimensions("JAVA_CONSOLE_");
273 frame = initFrame("Jalview Java Console", desktop.getWidth() / 2,
274 desktop.getHeight() / 4, desktop.getX(), desktop.getY());
278 frame = initFrame("Jalview Java Console", bounds.width,
279 bounds.height, bounds.x, bounds.y);
281 // desktop.add(frame);
283 JalviewAppender jappender = new JalviewAppender();
284 jappender.setLayout(new SimpleLayout());
285 JalviewAppender.setTextArea(textArea);
286 org.apache.log4j.Logger.getRootLogger().addAppender(jappender);
289 public synchronized void stopConsole()
294 * reader.notify(); reader2.notify(); if (errorThrower!=null)
295 * errorThrower.notify(); // stop all threads if (textAppender!=null)
296 * textAppender.notify();
304 } catch (Exception e)
311 } catch (Exception e)
316 textAppender.join(10);
317 } catch (Exception e)
321 if (!frame.isVisible())
328 public synchronized void windowClosed(WindowEvent evt)
330 frame.setVisible(false);
334 private void closeConsoleGui()
336 updateConsole = false;
344 parent.showConsole(false);
348 public synchronized void windowClosing(WindowEvent evt)
350 frame.setVisible(false); // default behaviour of JFrame
356 public synchronized void actionPerformed(ActionEvent evt)
359 // textArea.setText("");
362 public synchronized void run()
366 while (Thread.currentThread() == reader)
368 if (pin == null || pin.available() == 0)
373 if (pin.available() == 0)
377 } catch (InterruptedException ie)
382 while (pin.available() != 0)
384 String input = this.readLine(pin);
386 long time = System.nanoTime();
387 appendToTextArea(input);
388 // stderr.println("Time taken to stdout append:\t"
389 // + (System.nanoTime() - time) + " ns");
396 while (Thread.currentThread() == reader2)
398 if (pin2.available() == 0)
403 if (pin2.available() == 0)
407 } catch (InterruptedException ie)
411 while (pin2.available() != 0)
413 String input = this.readLine(pin2);
415 long time = System.nanoTime();
416 appendToTextArea(input);
417 // stderr.println("Time taken to stderr append:\t"
418 // + (System.nanoTime() - time) + " ns");
424 while (Thread.currentThread() == textAppender)
428 // check string buffer - if greater than console, clear console and
429 // replace with last segment of content, otherwise, append all to
432 while (displayPipe.length() > 0)
435 StringBuffer tmp = new StringBuffer(), replace;
436 synchronized (displayPipe)
438 replace = displayPipe;
441 // simply append whole buffer
442 textArea.append(replace.toString());
443 count += replace.length();
444 if (count > byteslim)
449 if (displayPipe.length() == 0)
454 if (displayPipe.length() == 0)
458 } catch (InterruptedException e)
469 } catch (InterruptedException e)
480 } catch (Exception e)
482 textArea.append("\nConsole reports an Internal error.");
483 textArea.append("The error is: " + e.getMessage());
484 // Need to uncomment this to ensure that line tally is synched.
486 stderr.println("Console reports an Internal error.\nThe error is: "
490 // just for testing (Throw a Nullpointer after 1 second)
491 if (Thread.currentThread() == errorThrower)
496 } catch (InterruptedException ie)
499 throw new NullPointerException(
500 "Application test: throwing an NullPointerException It should arrive at the console");
504 private void appendToTextArea(final String input)
506 if (updateConsole == false)
511 long time = System.nanoTime();
512 javax.swing.SwingUtilities.invokeLater(new Runnable()
516 displayPipe.append(input); // change to stringBuffer
517 // displayPipe.flush();
521 // stderr.println("Time taken to Spawnappend:\t" + (System.nanoTime() -
526 private String header = null;
528 private boolean updateConsole = false;
530 private synchronized void trimBuffer(boolean clear)
532 if (header == null && textArea.getLineCount() > 5)
536 header = textArea.getText(0, textArea.getLineStartOffset(5))
537 + "\nTruncated...\n";
538 } catch (Exception e)
544 int tlength = textArea.getDocument().getLength();
547 if (clear || (tlength > byteslim))
553 long time = System.nanoTime();
554 textArea.replaceRange(header, 0, tlength - bytescut);
555 // stderr.println("Time taken to cut:\t"
556 // + (System.nanoTime() - time) + " ns");
560 textArea.setText(header);
562 } catch (Exception e)
566 // lines = textArea.getLineCount();
572 public synchronized String readLine(PipedInputStream in)
579 int available = in.available();
582 byte b[] = new byte[available];
584 input = input + new String(b, 0, b.length);
585 // counts lines - we don't do this for speed.
586 // while ((lp = input.indexOf("\n", lp + 1)) > -1)
590 } while (!input.endsWith("\n") && !input.endsWith("\r\n") && !quit);
594 public static void main(String[] arg)
596 new Console().test(); // create console with not reference
600 public void setVisible(boolean selected)
602 frame.setVisible(selected);
603 if (selected == true)
606 updateConsole = true;
612 updateConsole = false;
616 public Rectangle getBounds()
620 return frame.getBounds();
626 * set the banner that appears at the top of the console output
630 public void setHeader(String string)
633 if (header.charAt(header.length() - 1) != '\n')
637 textArea.insert(header, 0);
645 public String getHeader()