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 logLevelCombo = new JComboBox();
107 // create all components and add them
108 Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
109 frame = initFrame("Java Console", screenSize.width / 2,
110 screenSize.height / 2, -1, -1);
114 private void initConsole(boolean visible)
116 initConsole(visible, true);
126 private void initConsole(boolean visible, boolean redirect)
128 // CutAndPasteTransfer cpt = new CutAndPasteTransfer();
129 // textArea = cpt.getTextArea();
130 textArea = new JTextArea();
131 textArea.setEditable(false);
132 JButton clearButton = new JButton(
133 MessageManager.getString("action.clear"));
134 JButton copyToClipboardButton = new JButton(
135 MessageManager.getString("label.copy_to_clipboard"));
136 copyToClipboardButton.addActionListener(new ActionListener()
138 public void actionPerformed(ActionEvent e)
140 copyConsoleTextToClipboard();
143 copyToClipboardButton.addMouseListener(new MouseAdapter()
145 private Color bg = textArea.getBackground();
147 public void mousePressed(MouseEvent e)
149 textArea.setBackground(textArea.getSelectionColor());
152 public void mouseReleased(MouseEvent e)
154 textArea.setBackground(bg);
158 copyToClipboardButton.setToolTipText(
159 MessageManager.getString("label.copy_to_clipboard_tooltip"));
161 JLabel logLevelLabel = new JLabel(
162 MessageManager.getString("label.log_level") + ":");
164 // logLevelCombo.addItem(Level.ALL);
165 logLevelCombo.addItem(Level.DEBUG);
166 logLevelCombo.addItem(Level.INFO);
167 logLevelCombo.addItem(Level.WARN);
168 // logLevelCombo.addItem(Level.ERROR);
169 // logLevelCombo.addItem(Level.FATAL);
170 // logLevelCombo.addItem(Level.OFF);
171 // logLevelCombo.addItem(Level.TRACE);
172 setChosenLogLevelCombo();
173 logLevelCombo.addActionListener(new ActionListener()
175 public void actionPerformed(ActionEvent e)
177 if (Cache.log != null)
179 Cache.log.setLevel((Level) logLevelCombo.getSelectedItem());
186 frame.getContentPane().setLayout(new BorderLayout());
187 frame.getContentPane().add(new JScrollPane(textArea),
188 BorderLayout.CENTER);
189 JPanel southPanel = new JPanel();
190 southPanel.setLayout(new GridBagLayout());
192 JPanel logLevelPanel = new JPanel();
193 logLevelPanel.setAlignmentX(JPanel.LEFT_ALIGNMENT);
194 logLevelPanel.add(logLevelLabel);
195 logLevelPanel.add(logLevelCombo);
196 logLevelLabel.setToolTipText(
197 MessageManager.getString("label.log_level_tooltip"));
198 logLevelCombo.setToolTipText(
199 MessageManager.getString("label.log_level_tooltip"));
201 GridBagConstraints gbc = new GridBagConstraints();
207 southPanel.add(logLevelPanel, gbc);
211 gbc.fill = GridBagConstraints.HORIZONTAL;
212 southPanel.add(clearButton, gbc);
216 gbc.fill = GridBagConstraints.NONE;
217 southPanel.add(copyToClipboardButton, gbc);
219 southPanel.setVisible(true);
220 frame.getContentPane().add(southPanel, BorderLayout.SOUTH);
221 frame.setVisible(visible);
222 updateConsole = visible;
223 frame.addWindowListener(this);
224 clearButton.addActionListener(this);
234 quit = false; // signals the Threads that they should exit
236 // Starting two seperate threads to read from the PipedInputStreams
238 reader = new Thread(this);
239 reader.setDaemon(true);
242 reader2 = new Thread(this);
243 reader2.setDaemon(true);
245 // and a thread to append text to the textarea
246 textAppender = new Thread(this);
247 textAppender.setDaemon(true);
248 textAppender.start();
251 private void setChosenLogLevelCombo()
253 Level currentLogLevel = Cache.log == null ? Level.INFO
254 : Cache.log.getLevel();
255 logLevelCombo.setSelectedItem(currentLogLevel);
256 if (!logLevelCombo.getSelectedItem().equals(currentLogLevel))
258 logLevelCombo.setSelectedItem(Level.INFO);
262 private void copyConsoleTextToClipboard()
264 String consoleText = textArea.getText();
265 StringSelection consoleTextSelection = new StringSelection(consoleText);
266 Clipboard cb = Toolkit.getDefaultToolkit().getSystemClipboard();
267 cb.setContents(consoleTextSelection, null);
270 private void setLogLevel()
275 PipedOutputStream pout = null, perr = null;
277 public void redirectStreams()
283 pout = new PipedOutputStream(this.pin);
284 System.setOut(new PrintStream(pout, true));
285 } catch (java.io.IOException io)
287 textArea.append("Couldn't redirect STDOUT to this console\n"
289 io.printStackTrace(stderr);
290 } catch (SecurityException se)
292 textArea.append("Couldn't redirect STDOUT to this console\n"
294 se.printStackTrace(stderr);
299 perr = new PipedOutputStream(this.pin2);
300 System.setErr(new PrintStream(perr, true));
301 } catch (java.io.IOException io)
303 textArea.append("Couldn't redirect STDERR to this console\n"
305 io.printStackTrace(stderr);
306 } catch (SecurityException se)
308 textArea.append("Couldn't redirect STDERR to this console\n"
310 se.printStackTrace(stderr);
315 public void unredirectStreams()
321 System.setOut(stdout);
324 pin = new PipedInputStream();
326 } catch (java.io.IOException io)
328 textArea.append("Couldn't unredirect STDOUT to this console\n"
330 io.printStackTrace(stderr);
331 } catch (SecurityException se)
333 textArea.append("Couldn't unredirect STDOUT to this console\n"
335 se.printStackTrace(stderr);
340 System.setErr(stderr);
343 pin2 = new PipedInputStream();
345 } catch (java.io.IOException io)
347 textArea.append("Couldn't unredirect STDERR to this console\n"
349 io.printStackTrace(stderr);
350 } catch (SecurityException se)
352 textArea.append("Couldn't unredirect STDERR to this console\n"
354 se.printStackTrace(stderr);
362 // you may omit this part for your application
365 System.out.println("Hello World 2");
366 System.out.println("All fonts available to Graphic2D:\n");
367 GraphicsEnvironment ge = GraphicsEnvironment
368 .getLocalGraphicsEnvironment();
369 String[] fontNames = ge.getAvailableFontFamilyNames();
370 for (int n = 0; n < fontNames.length; n++)
372 System.out.println(fontNames[n]);
374 // Testing part: simple an error thrown anywhere in this JVM will be printed
376 // We do it with a seperate Thread becasue we don't wan't to break a Thread
377 // used by the Console.
378 System.out.println("\nLets throw an error on this console");
379 errorThrower = new Thread(this);
380 errorThrower.setDaemon(true);
381 errorThrower.start();
384 private JFrame initFrame(String string, int i, int j, int x, int y)
386 JFrame frame = new JFrame(string);
387 frame.setName(string);
396 frame.setBounds(x, y, i, j);
401 * attach a console to the desktop - the desktop will open it if requested.
405 public Console(Desktop desktop)
411 * attach a console to the desktop - the desktop will open it if requested.
414 * @param showjconsole
415 * - if true, then redirect stdout immediately
417 public Console(Desktop desktop, boolean showjconsole)
420 // window name - get x,y,width, height possibly scaled
421 Rectangle bounds = desktop.getLastKnownDimensions("JAVA_CONSOLE_");
424 frame = initFrame("Jalview Java Console", desktop.getWidth() / 2,
425 desktop.getHeight() / 4, desktop.getX(), desktop.getY());
429 frame = initFrame("Jalview Java Console", bounds.width, bounds.height,
432 frame.setMinimumSize(new Dimension(MIN_WIDTH, MIN_HEIGHT));
433 // desktop.add(frame);
435 JalviewAppender jappender = new JalviewAppender();
436 jappender.setLayout(new SimpleLayout());
437 JalviewAppender.setTextArea(textArea);
438 org.apache.log4j.Logger.getRootLogger().addAppender(jappender);
441 public synchronized void stopConsole()
446 * reader.notify(); reader2.notify(); if (errorThrower!=null)
447 * errorThrower.notify(); // stop all threads if (textAppender!=null)
448 * textAppender.notify();
456 } catch (Exception e)
463 } catch (Exception e)
468 textAppender.join(10);
469 } catch (Exception e)
473 if (!frame.isVisible())
481 public synchronized void windowClosed(WindowEvent evt)
483 frame.setVisible(false);
487 private void closeConsoleGui()
489 updateConsole = false;
497 parent.showConsole(false);
502 public synchronized void windowClosing(WindowEvent evt)
504 frame.setVisible(false); // default behaviour of JFrame
511 public synchronized void actionPerformed(ActionEvent evt)
514 // textArea.setText("");
518 public synchronized void run()
522 while (Thread.currentThread() == reader)
524 if (pin == null || pin.available() == 0)
529 if (pin.available() == 0)
533 } catch (InterruptedException ie)
538 while (pin.available() != 0)
540 String input = this.readLine(pin);
542 long time = System.nanoTime();
543 appendToTextArea(input);
544 // stderr.println("Time taken to stdout append:\t"
545 // + (System.nanoTime() - time) + " ns");
554 while (Thread.currentThread() == reader2)
556 if (pin2.available() == 0)
561 if (pin2.available() == 0)
565 } catch (InterruptedException ie)
569 while (pin2.available() != 0)
571 String input = this.readLine(pin2);
573 long time = System.nanoTime();
574 appendToTextArea(input);
575 // stderr.println("Time taken to stderr append:\t"
576 // + (System.nanoTime() - time) + " ns");
584 while (Thread.currentThread() == textAppender)
588 // check string buffer - if greater than console, clear console and
589 // replace with last segment of content, otherwise, append all to
592 while (displayPipe.length() > 0)
595 StringBuffer tmp = new StringBuffer(), replace;
596 synchronized (displayPipe)
598 replace = displayPipe;
601 // simply append whole buffer
602 textArea.append(replace.toString());
603 count += replace.length();
604 if (count > byteslim)
609 if (displayPipe.length() == 0)
614 if (displayPipe.length() == 0)
618 } catch (InterruptedException e)
628 } catch (InterruptedException e)
639 } catch (Exception e)
641 textArea.append("\nConsole reports an Internal error.");
642 textArea.append("The error is: " + e.getMessage());
643 // Need to uncomment this to ensure that line tally is synched.
646 "Console reports an Internal error.\nThe error is: " + e);
649 // just for testing (Throw a Nullpointer after 1 second)
650 if (Thread.currentThread() == errorThrower)
655 } catch (InterruptedException ie)
658 throw new NullPointerException(
659 MessageManager.getString("exception.application_test_npe"));
663 private void appendToTextArea(final String input)
665 if (updateConsole == false)
670 long time = System.nanoTime();
671 javax.swing.SwingUtilities.invokeLater(new Runnable()
676 displayPipe.append(input); // change to stringBuffer
677 // displayPipe.flush();
681 // stderr.println("Time taken to Spawnappend:\t" + (System.nanoTime() -
686 private String header = null;
688 private boolean updateConsole = false;
690 private synchronized void trimBuffer(boolean clear)
692 if (header == null && textArea.getLineCount() > 5)
696 header = textArea.getText(0, textArea.getLineStartOffset(5))
697 + "\nTruncated...\n";
698 } catch (Exception e)
704 int tlength = textArea.getDocument().getLength();
707 if (clear || (tlength > byteslim))
713 long time = System.nanoTime();
714 textArea.replaceRange(header, 0, tlength - bytescut);
715 // stderr.println("Time taken to cut:\t"
716 // + (System.nanoTime() - time) + " ns");
720 textArea.setText(header);
722 } catch (Exception e)
726 // lines = textArea.getLineCount();
732 public synchronized String readLine(PipedInputStream in)
739 int available = in.available();
744 byte b[] = new byte[available];
746 input = input + new String(b, 0, b.length);
747 // counts lines - we don't do this for speed.
748 // while ((lp = input.indexOf("\n", lp + 1)) > -1)
752 } while (!input.endsWith("\n") && !input.endsWith("\r\n") && !quit);
760 public static void main(String[] arg)
762 new Console().test(); // create console with not reference
766 public void setVisible(boolean selected)
768 frame.setVisible(selected);
769 if (selected == true)
771 setChosenLogLevelCombo();
773 updateConsole = true;
778 // reset log level to user preference
779 if (Cache.log != null)
781 String userLogLevel = Cache.getDefault("logs.Jalview.level",
782 Level.INFO.toString());
783 Cache.log.setLevel(Level.toLevel(userLogLevel));
787 updateConsole = false;
791 public Rectangle getBounds()
795 return frame.getBounds();
801 * set the banner that appears at the top of the console output
805 public void setHeader(String string)
808 if (header.charAt(header.length() - 1) != '\n')
812 textArea.insert(header, 0);
820 public String getHeader()