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 java.awt.BorderLayout;
24 import java.awt.Color;
25 import java.awt.Dimension;
26 import java.awt.GraphicsEnvironment;
27 import java.awt.GridBagConstraints;
28 import java.awt.GridBagLayout;
29 import java.awt.Rectangle;
30 import java.awt.Toolkit;
31 import java.awt.datatransfer.Clipboard;
32 import java.awt.datatransfer.StringSelection;
33 import java.awt.event.ActionEvent;
34 import java.awt.event.ActionListener;
35 import java.awt.event.MouseAdapter;
36 import java.awt.event.MouseEvent;
37 import java.awt.event.WindowAdapter;
38 import java.awt.event.WindowEvent;
39 import java.awt.event.WindowListener;
40 import java.io.IOException;
41 import java.io.PipedInputStream;
42 import java.io.PipedOutputStream;
43 import java.io.PrintStream;
45 import javax.swing.JButton;
46 import javax.swing.JComboBox;
47 import javax.swing.JFrame;
48 import javax.swing.JLabel;
49 import javax.swing.JPanel;
50 import javax.swing.JScrollPane;
51 import javax.swing.JTextArea;
53 import org.apache.log4j.Level;
54 import org.apache.log4j.SimpleLayout;
56 import jalview.bin.Cache;
57 import jalview.util.MessageManager;
60 * Simple Jalview Java Console. Version 1 - allows viewing of console output
61 * after desktop is created. Acquired with thanks from RJHM's site
62 * http://www.comweb.nl/java/Console/Console.html A simple Java Console for your
63 * application (Swing version) Requires Java 1.1.5 or higher Disclaimer the use
64 * of this source is at your own risk. Permision to use and distribute into your
65 * own applications RJHM van den Bergh , rvdb@comweb.nl
68 public class Console extends WindowAdapter
69 implements WindowListener, ActionListener, Runnable
73 private JTextArea textArea;
76 * unused - tally and limit for lines in console window int lines = 0;
80 int byteslim = 102400, bytescut = 76800; // 100k and 75k cut point.
82 private Thread reader, reader2, textAppender;
86 private final PrintStream stdout = System.out, stderr = System.err;
88 private PipedInputStream pin = new PipedInputStream();
90 private PipedInputStream pin2 = new PipedInputStream();
92 private StringBuffer displayPipe = new StringBuffer();
94 Thread errorThrower; // just for testing (Throws an Exception at this Console
96 // are we attached to some parent Desktop
97 Desktop parent = null;
99 private int MIN_WIDTH = 300;
101 private int MIN_HEIGHT = 250;
103 private JComboBox<Level> logLevelCombo = new JComboBox<Level>();
105 protected Level startingLogLevel = Level.INFO;
109 // create all components and add them
110 Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
111 frame = initFrame("Java Console", screenSize.width / 2,
112 screenSize.height / 2, -1, -1);
116 private void initConsole(boolean visible)
118 initConsole(visible, true);
128 private void initConsole(boolean visible, boolean redirect)
130 // CutAndPasteTransfer cpt = new CutAndPasteTransfer();
131 // textArea = cpt.getTextArea();
132 textArea = new JTextArea();
133 textArea.setEditable(false);
134 JButton clearButton = new JButton(
135 MessageManager.getString("action.clear"));
136 JButton copyToClipboardButton = new JButton(
137 MessageManager.getString("label.copy_to_clipboard"));
138 copyToClipboardButton.addActionListener(new ActionListener()
140 public void actionPerformed(ActionEvent e)
142 copyConsoleTextToClipboard();
145 copyToClipboardButton.addMouseListener(new MouseAdapter()
147 private Color bg = textArea.getBackground();
149 private Color fg = textArea.getForeground();
151 public void mousePressed(MouseEvent e)
153 textArea.setBackground(textArea.getSelectionColor());
154 textArea.setForeground(textArea.getSelectedTextColor());
157 public void mouseReleased(MouseEvent e)
159 textArea.setBackground(bg);
160 textArea.setForeground(fg);
164 copyToClipboardButton.setToolTipText(
165 MessageManager.getString("label.copy_to_clipboard_tooltip"));
167 JLabel logLevelLabel = new JLabel(
168 MessageManager.getString("label.log_level") + ":");
170 // logLevelCombo.addItem(Level.ALL);
171 logLevelCombo.addItem(Level.TRACE);
172 logLevelCombo.addItem(Level.DEBUG);
173 logLevelCombo.addItem(Level.INFO);
174 logLevelCombo.addItem(Level.WARN);
175 // logLevelCombo.addItem(Level.ERROR);
176 // logLevelCombo.addItem(Level.FATAL);
177 // logLevelCombo.addItem(Level.OFF);
178 // set startingLogLevel
179 startingLogLevel = Cache.log == null ? Level.INFO
180 : Cache.log.getLevel();
181 setChosenLogLevelCombo();
182 logLevelCombo.addActionListener(new ActionListener()
184 public void actionPerformed(ActionEvent e)
186 if (Cache.log != null)
188 Cache.log.setLevel((Level) logLevelCombo.getSelectedItem());
195 frame.getContentPane().setLayout(new BorderLayout());
196 frame.getContentPane().add(new JScrollPane(textArea),
197 BorderLayout.CENTER);
198 JPanel southPanel = new JPanel();
199 southPanel.setLayout(new GridBagLayout());
201 JPanel logLevelPanel = new JPanel();
202 logLevelPanel.setAlignmentX(JPanel.LEFT_ALIGNMENT);
203 logLevelPanel.add(logLevelLabel);
204 logLevelPanel.add(logLevelCombo);
205 String logLevelTooltip = MessageManager.formatMessage(
206 "label.log_level_tooltip", startingLogLevel.toString());
207 logLevelLabel.setToolTipText(logLevelTooltip);
208 logLevelCombo.setToolTipText(logLevelTooltip);
210 GridBagConstraints gbc = new GridBagConstraints();
216 southPanel.add(logLevelPanel, gbc);
220 gbc.fill = GridBagConstraints.HORIZONTAL;
221 southPanel.add(clearButton, gbc);
225 gbc.fill = GridBagConstraints.NONE;
226 southPanel.add(copyToClipboardButton, gbc);
228 southPanel.setVisible(true);
229 frame.getContentPane().add(southPanel, BorderLayout.SOUTH);
230 frame.setVisible(visible);
231 updateConsole = visible;
232 frame.addWindowListener(this);
233 clearButton.addActionListener(this);
243 quit = false; // signals the Threads that they should exit
245 // Starting two seperate threads to read from the PipedInputStreams
247 reader = new Thread(this);
248 reader.setDaemon(true);
251 reader2 = new Thread(this);
252 reader2.setDaemon(true);
254 // and a thread to append text to the textarea
255 textAppender = new Thread(this);
256 textAppender.setDaemon(true);
257 textAppender.start();
260 private void setChosenLogLevelCombo()
262 setChosenLogLevelCombo(startingLogLevel);
265 private void setChosenLogLevelCombo(Level setLogLevel)
267 logLevelCombo.setSelectedItem(setLogLevel);
268 if (!logLevelCombo.getSelectedItem().equals(setLogLevel))
270 // setLogLevel not (yet) in list
271 if (setLogLevel != null && setLogLevel instanceof Level)
273 // add new item to list (might be set via .jalview_properties)
274 boolean added = false;
275 for (int i = 0; i < logLevelCombo.getItemCount(); i++)
277 Level l = (Level) logLevelCombo.getItemAt(i);
278 if (l.isGreaterOrEqual(setLogLevel))
280 logLevelCombo.insertItemAt(setLogLevel, i);
285 if (!added) // lower priority than others or some confusion -- add to
288 logLevelCombo.addItem(setLogLevel);
290 logLevelCombo.setSelectedItem(setLogLevel);
294 logLevelCombo.setSelectedItem(Level.INFO);
299 private void copyConsoleTextToClipboard()
301 String consoleText = textArea.getText();
302 StringSelection consoleTextSelection = new StringSelection(consoleText);
303 Clipboard cb = Toolkit.getDefaultToolkit().getSystemClipboard();
304 cb.setContents(consoleTextSelection, null);
307 PipedOutputStream pout = null, perr = null;
309 public void redirectStreams()
315 pout = new PipedOutputStream(this.pin);
316 System.setOut(new PrintStream(pout, true));
317 } catch (java.io.IOException io)
319 textArea.append("Couldn't redirect STDOUT to this console\n"
321 io.printStackTrace(stderr);
322 } catch (SecurityException se)
324 textArea.append("Couldn't redirect STDOUT to this console\n"
326 se.printStackTrace(stderr);
331 perr = new PipedOutputStream(this.pin2);
332 System.setErr(new PrintStream(perr, true));
333 } catch (java.io.IOException io)
335 textArea.append("Couldn't redirect STDERR to this console\n"
337 io.printStackTrace(stderr);
338 } catch (SecurityException se)
340 textArea.append("Couldn't redirect STDERR to this console\n"
342 se.printStackTrace(stderr);
347 public void unredirectStreams()
353 System.setOut(stdout);
356 pin = new PipedInputStream();
358 } catch (java.io.IOException io)
360 textArea.append("Couldn't unredirect STDOUT to this console\n"
362 io.printStackTrace(stderr);
363 } catch (SecurityException se)
365 textArea.append("Couldn't unredirect STDOUT to this console\n"
367 se.printStackTrace(stderr);
372 System.setErr(stderr);
375 pin2 = new PipedInputStream();
377 } catch (java.io.IOException io)
379 textArea.append("Couldn't unredirect STDERR to this console\n"
381 io.printStackTrace(stderr);
382 } catch (SecurityException se)
384 textArea.append("Couldn't unredirect STDERR to this console\n"
386 se.printStackTrace(stderr);
394 // you may omit this part for your application
397 System.out.println("Hello World 2");
398 System.out.println("All fonts available to Graphic2D:\n");
399 GraphicsEnvironment ge = GraphicsEnvironment
400 .getLocalGraphicsEnvironment();
401 String[] fontNames = ge.getAvailableFontFamilyNames();
402 for (int n = 0; n < fontNames.length; n++)
404 System.out.println(fontNames[n]);
406 // Testing part: simple an error thrown anywhere in this JVM will be printed
408 // We do it with a seperate Thread becasue we don't wan't to break a Thread
409 // used by the Console.
410 System.out.println("\nLets throw an error on this console");
411 errorThrower = new Thread(this);
412 errorThrower.setDaemon(true);
413 errorThrower.start();
416 private JFrame initFrame(String string, int i, int j, int x, int y)
418 JFrame frame = new JFrame(string);
419 frame.setName(string);
428 frame.setBounds(x, y, i, j);
433 * attach a console to the desktop - the desktop will open it if requested.
437 public Console(Desktop desktop)
443 * attach a console to the desktop - the desktop will open it if requested.
446 * @param showjconsole
447 * - if true, then redirect stdout immediately
449 public Console(Desktop desktop, boolean showjconsole)
452 // window name - get x,y,width, height possibly scaled
453 Rectangle bounds = desktop.getLastKnownDimensions("JAVA_CONSOLE_");
456 frame = initFrame("Jalview Java Console", desktop.getWidth() / 2,
457 desktop.getHeight() / 4, desktop.getX(), desktop.getY());
461 frame = initFrame("Jalview Java Console", bounds.width, bounds.height,
464 frame.setMinimumSize(new Dimension(MIN_WIDTH, MIN_HEIGHT));
465 // desktop.add(frame);
467 JalviewAppender jappender = new JalviewAppender();
468 jappender.setLayout(new SimpleLayout());
469 JalviewAppender.setTextArea(textArea);
470 org.apache.log4j.Logger.getRootLogger().addAppender(jappender);
473 public synchronized void stopConsole()
478 * reader.notify(); reader2.notify(); if (errorThrower!=null)
479 * errorThrower.notify(); // stop all threads if (textAppender!=null)
480 * textAppender.notify();
488 } catch (Exception e)
495 } catch (Exception e)
500 textAppender.join(10);
501 } catch (Exception e)
505 if (!frame.isVisible())
513 public synchronized void windowClosed(WindowEvent evt)
515 frame.setVisible(false);
519 private void closeConsoleGui()
521 updateConsole = false;
529 parent.showConsole(false);
534 public synchronized void windowClosing(WindowEvent evt)
536 frame.setVisible(false); // default behaviour of JFrame
543 public synchronized void actionPerformed(ActionEvent evt)
546 // textArea.setText("");
550 public synchronized void run()
554 while (Thread.currentThread() == reader)
556 if (pin == null || pin.available() == 0)
561 if (pin.available() == 0)
565 } catch (InterruptedException ie)
570 while (pin.available() != 0)
572 String input = this.readLine(pin);
574 long time = System.nanoTime();
575 appendToTextArea(input);
576 // stderr.println("Time taken to stdout append:\t"
577 // + (System.nanoTime() - time) + " ns");
586 while (Thread.currentThread() == reader2)
588 if (pin2.available() == 0)
593 if (pin2.available() == 0)
597 } catch (InterruptedException ie)
601 while (pin2.available() != 0)
603 String input = this.readLine(pin2);
605 long time = System.nanoTime();
606 appendToTextArea(input);
607 // stderr.println("Time taken to stderr append:\t"
608 // + (System.nanoTime() - time) + " ns");
616 while (Thread.currentThread() == textAppender)
620 // check string buffer - if greater than console, clear console and
621 // replace with last segment of content, otherwise, append all to
624 while (displayPipe.length() > 0)
627 StringBuffer tmp = new StringBuffer(), replace;
628 synchronized (displayPipe)
630 replace = displayPipe;
633 // simply append whole buffer
634 textArea.append(replace.toString());
635 count += replace.length();
636 if (count > byteslim)
641 if (displayPipe.length() == 0)
646 if (displayPipe.length() == 0)
650 } catch (InterruptedException e)
661 } catch (InterruptedException e)
672 } catch (Exception e)
674 textArea.append("\nConsole reports an Internal error.");
675 textArea.append("The error is: " + e.getMessage());
676 // Need to uncomment this to ensure that line tally is synched.
679 "Console reports an Internal error.\nThe error is: " + e);
682 // just for testing (Throw a Nullpointer after 1 second)
683 if (Thread.currentThread() == errorThrower)
688 } catch (InterruptedException ie)
691 throw new NullPointerException(
692 MessageManager.getString("exception.application_test_npe"));
696 private void appendToTextArea(final String input)
698 if (updateConsole == false)
703 long time = System.nanoTime();
704 javax.swing.SwingUtilities.invokeLater(new Runnable()
709 displayPipe.append(input); // change to stringBuffer
710 // displayPipe.flush();
714 // stderr.println("Time taken to Spawnappend:\t" + (System.nanoTime() -
719 private String header = null;
721 private boolean updateConsole = false;
723 private synchronized void trimBuffer(boolean clear)
725 if (header == null && textArea.getLineCount() > 5)
729 header = textArea.getText(0, textArea.getLineStartOffset(5))
730 + "\nTruncated...\n";
731 } catch (Exception e)
737 int tlength = textArea.getDocument().getLength();
740 if (clear || (tlength > byteslim))
746 long time = System.nanoTime();
747 textArea.replaceRange(header, 0, tlength - bytescut);
748 // stderr.println("Time taken to cut:\t"
749 // + (System.nanoTime() - time) + " ns");
753 textArea.setText(header);
755 } catch (Exception e)
759 // lines = textArea.getLineCount();
765 public synchronized String readLine(PipedInputStream in)
772 int available = in.available();
777 byte b[] = new byte[available];
779 input = input + new String(b, 0, b.length);
780 // counts lines - we don't do this for speed.
781 // while ((lp = input.indexOf("\n", lp + 1)) > -1)
785 } while (!input.endsWith("\n") && !input.endsWith("\r\n") && !quit);
789 public static void main(String[] arg)
791 new Console().test(); // create console with not reference
795 public void setVisible(boolean selected)
797 frame.setVisible(selected);
798 if (selected == true)
800 setChosenLogLevelCombo();
802 updateConsole = true;
807 // reset log level to what it was before
808 if (Cache.log != null)
810 Cache.log.setLevel(startingLogLevel);
814 updateConsole = false;
818 public Rectangle getBounds()
822 return frame.getBounds();
828 * set the banner that appears at the top of the console output
832 public void setHeader(String string)
835 if (header.charAt(header.length() - 1) != '\n')
839 textArea.insert(header, 0);
847 public String getHeader()