2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
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
10 * of the License, or (at your option) any later version.
12 * Jalview is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty
14 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 * PURPOSE. See the GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
19 * The Jalview Authors are detailed in the 'AUTHORS' file.
23 import jalview.util.MessageManager;
25 import java.awt.BorderLayout;
26 import java.awt.Dimension;
27 import java.awt.GraphicsEnvironment;
28 import java.awt.Rectangle;
29 import java.awt.Toolkit;
30 import java.awt.event.ActionEvent;
31 import java.awt.event.ActionListener;
32 import java.awt.event.WindowAdapter;
33 import java.awt.event.WindowEvent;
34 import java.awt.event.WindowListener;
35 import java.io.IOException;
36 import java.io.PipedInputStream;
37 import java.io.PipedOutputStream;
38 import java.io.PrintStream;
40 import javax.swing.JButton;
41 import javax.swing.JFrame;
42 import javax.swing.JScrollPane;
43 import javax.swing.JTextArea;
45 import org.apache.log4j.SimpleLayout;
48 * Simple Jalview Java Console. Version 1 - allows viewing of console output
49 * after desktop is created. Acquired with thanks from RJHM's site
50 * http://www.comweb.nl/java/Console/Console.html A simple Java Console for your
51 * application (Swing version) Requires Java 1.1.5 or higher Disclaimer the use
52 * of this source is at your own risk. Permision to use and distribute into your
53 * own applications RJHM van den Bergh , rvdb@comweb.nl
56 public class Console extends WindowAdapter implements WindowListener,
57 ActionListener, Runnable
61 private JTextArea textArea;
64 * unused - tally and limit for lines in console window int lines = 0;
68 int byteslim = 102400, bytescut = 76800; // 100k and 75k cut point.
70 private Thread reader, reader2, textAppender;
74 private final PrintStream stdout = System.out, stderr = System.err;
76 private PipedInputStream pin = new PipedInputStream();
78 private PipedInputStream pin2 = new PipedInputStream();
80 private StringBuffer displayPipe = new StringBuffer();
82 Thread errorThrower; // just for testing (Throws an Exception at this Console
84 // are we attached to some parent Desktop
85 Desktop parent = null;
89 // create all components and add them
90 Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
91 frame = initFrame("Java Console", screenSize.width / 2,
92 screenSize.height / 2, -1, -1);
96 private void initConsole(boolean visible)
98 initConsole(visible, true);
108 private void initConsole(boolean visible, boolean redirect)
110 // CutAndPasteTransfer cpt = new CutAndPasteTransfer();
111 // textArea = cpt.getTextArea();
112 textArea = new JTextArea();
113 textArea.setEditable(false);
114 JButton button = new JButton(MessageManager.getString("action.clear"));
117 frame.getContentPane().setLayout(new BorderLayout());
118 frame.getContentPane().add(new JScrollPane(textArea),
119 BorderLayout.CENTER);
120 frame.getContentPane().add(button, BorderLayout.SOUTH);
121 frame.setVisible(visible);
122 updateConsole = visible;
123 frame.addWindowListener(this);
124 button.addActionListener(this);
133 quit = false; // signals the Threads that they should exit
135 // Starting two seperate threads to read from the PipedInputStreams
137 reader = new Thread(this);
138 reader.setDaemon(true);
141 reader2 = new Thread(this);
142 reader2.setDaemon(true);
144 // and a thread to append text to the textarea
145 textAppender = new Thread(this);
146 textAppender.setDaemon(true);
147 textAppender.start();
150 PipedOutputStream pout = null, perr = null;
152 public void redirectStreams()
158 pout = new PipedOutputStream(this.pin);
159 System.setOut(new PrintStream(pout, true));
160 } catch (java.io.IOException io)
162 textArea.append("Couldn't redirect STDOUT to this console\n"
164 io.printStackTrace(stderr);
165 } catch (SecurityException se)
167 textArea.append("Couldn't redirect STDOUT to this console\n"
169 se.printStackTrace(stderr);
174 perr = new PipedOutputStream(this.pin2);
175 System.setErr(new PrintStream(perr, true));
176 } catch (java.io.IOException io)
178 textArea.append("Couldn't redirect STDERR to this console\n"
180 io.printStackTrace(stderr);
181 } catch (SecurityException se)
183 textArea.append("Couldn't redirect STDERR to this console\n"
185 se.printStackTrace(stderr);
190 public void unredirectStreams()
196 System.setOut(stdout);
199 pin = new PipedInputStream();
201 } catch (java.io.IOException io)
203 textArea.append("Couldn't unredirect STDOUT to this console\n"
205 io.printStackTrace(stderr);
206 } catch (SecurityException se)
208 textArea.append("Couldn't unredirect STDOUT to this console\n"
210 se.printStackTrace(stderr);
215 System.setErr(stderr);
218 pin2 = new PipedInputStream();
220 } catch (java.io.IOException io)
222 textArea.append("Couldn't unredirect STDERR to this console\n"
224 io.printStackTrace(stderr);
225 } catch (SecurityException se)
227 textArea.append("Couldn't unredirect STDERR to this console\n"
229 se.printStackTrace(stderr);
237 // you may omit this part for your application
240 System.out.println("Hello World 2");
241 System.out.println("All fonts available to Graphic2D:\n");
242 GraphicsEnvironment ge = GraphicsEnvironment
243 .getLocalGraphicsEnvironment();
244 String[] fontNames = ge.getAvailableFontFamilyNames();
245 for (int n = 0; n < fontNames.length; n++)
246 System.out.println(fontNames[n]);
247 // Testing part: simple an error thrown anywhere in this JVM will be printed
249 // We do it with a seperate Thread becasue we don't wan't to break a Thread
250 // used by the Console.
251 System.out.println("\nLets throw an error on this console");
252 errorThrower = new Thread(this);
253 errorThrower.setDaemon(true);
254 errorThrower.start();
257 private JFrame initFrame(String string, int i, int j, int x, int y)
259 JFrame frame = new JFrame(string);
260 frame.setName(string);
265 frame.setBounds(x, y, i, j);
270 * attach a console to the desktop - the desktop will open it if requested.
274 public Console(Desktop desktop)
280 * attach a console to the desktop - the desktop will open it if requested.
283 * @param showjconsole
284 * - if true, then redirect stdout immediately
286 public Console(Desktop desktop, boolean showjconsole)
289 // window name - get x,y,width, height possibly scaled
290 Rectangle bounds = desktop.getLastKnownDimensions("JAVA_CONSOLE_");
293 frame = initFrame("Jalview Java Console", desktop.getWidth() / 2,
294 desktop.getHeight() / 4, desktop.getX(), desktop.getY());
298 frame = initFrame("Jalview Java Console", bounds.width,
299 bounds.height, bounds.x, bounds.y);
301 // desktop.add(frame);
303 JalviewAppender jappender = new JalviewAppender();
304 jappender.setLayout(new SimpleLayout());
305 JalviewAppender.setTextArea(textArea);
306 org.apache.log4j.Logger.getRootLogger().addAppender(jappender);
309 public synchronized void stopConsole()
314 * reader.notify(); reader2.notify(); if (errorThrower!=null)
315 * errorThrower.notify(); // stop all threads if (textAppender!=null)
316 * textAppender.notify();
324 } catch (Exception e)
331 } catch (Exception e)
336 textAppender.join(10);
337 } catch (Exception e)
341 if (!frame.isVisible())
348 public synchronized void windowClosed(WindowEvent evt)
350 frame.setVisible(false);
354 private void closeConsoleGui()
356 updateConsole = false;
364 parent.showConsole(false);
368 public synchronized void windowClosing(WindowEvent evt)
370 frame.setVisible(false); // default behaviour of JFrame
376 public synchronized void actionPerformed(ActionEvent evt)
379 // textArea.setText("");
382 public synchronized void run()
386 while (Thread.currentThread() == reader)
388 if (pin == null || pin.available() == 0)
393 if (pin.available() == 0)
397 } catch (InterruptedException ie)
402 while (pin.available() != 0)
404 String input = this.readLine(pin);
406 long time = System.nanoTime();
407 appendToTextArea(input);
408 // stderr.println("Time taken to stdout append:\t"
409 // + (System.nanoTime() - time) + " ns");
416 while (Thread.currentThread() == reader2)
418 if (pin2.available() == 0)
423 if (pin2.available() == 0)
427 } catch (InterruptedException ie)
431 while (pin2.available() != 0)
433 String input = this.readLine(pin2);
435 long time = System.nanoTime();
436 appendToTextArea(input);
437 // stderr.println("Time taken to stderr append:\t"
438 // + (System.nanoTime() - time) + " ns");
444 while (Thread.currentThread() == textAppender)
448 // check string buffer - if greater than console, clear console and
449 // replace with last segment of content, otherwise, append all to
452 while (displayPipe.length() > 0)
455 StringBuffer tmp = new StringBuffer(), replace;
456 synchronized (displayPipe)
458 replace = displayPipe;
461 // simply append whole buffer
462 textArea.append(replace.toString());
463 count += replace.length();
464 if (count > byteslim)
469 if (displayPipe.length() == 0)
474 if (displayPipe.length() == 0)
478 } catch (InterruptedException e)
489 } catch (InterruptedException e)
500 } catch (Exception e)
502 textArea.append("\nConsole reports an Internal error.");
503 textArea.append("The error is: " + e.getMessage());
504 // Need to uncomment this to ensure that line tally is synched.
506 stderr.println("Console reports an Internal error.\nThe error is: "
510 // just for testing (Throw a Nullpointer after 1 second)
511 if (Thread.currentThread() == errorThrower)
516 } catch (InterruptedException ie)
519 throw new NullPointerException(
520 MessageManager.getString("exception.application_test_npe"));
524 private void appendToTextArea(final String input)
526 if (updateConsole == false)
531 long time = System.nanoTime();
532 javax.swing.SwingUtilities.invokeLater(new Runnable()
536 displayPipe.append(input); // change to stringBuffer
537 // displayPipe.flush();
541 // stderr.println("Time taken to Spawnappend:\t" + (System.nanoTime() -
546 private String header = null;
548 private boolean updateConsole = false;
550 private synchronized void trimBuffer(boolean clear)
552 if (header == null && textArea.getLineCount() > 5)
556 header = textArea.getText(0, textArea.getLineStartOffset(5))
557 + "\nTruncated...\n";
558 } catch (Exception e)
564 int tlength = textArea.getDocument().getLength();
567 if (clear || (tlength > byteslim))
573 long time = System.nanoTime();
574 textArea.replaceRange(header, 0, tlength - bytescut);
575 // stderr.println("Time taken to cut:\t"
576 // + (System.nanoTime() - time) + " ns");
580 textArea.setText(header);
582 } catch (Exception e)
586 // lines = textArea.getLineCount();
592 public synchronized String readLine(PipedInputStream in)
599 int available = in.available();
602 byte b[] = new byte[available];
604 input = input + new String(b, 0, b.length);
605 // counts lines - we don't do this for speed.
606 // while ((lp = input.indexOf("\n", lp + 1)) > -1)
610 } while (!input.endsWith("\n") && !input.endsWith("\r\n") && !quit);
614 public static void main(String[] arg)
616 new Console().test(); // create console with not reference
620 public void setVisible(boolean selected)
622 frame.setVisible(selected);
623 if (selected == true)
626 updateConsole = true;
632 updateConsole = false;
636 public Rectangle getBounds()
640 return frame.getBounds();
646 * set the banner that appears at the top of the console output
650 public void setHeader(String string)
653 if (header.charAt(header.length() - 1) != '\n')
657 textArea.insert(header, 0);
665 public String getHeader()