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.BorderFactory;
46 import javax.swing.JButton;
47 import javax.swing.JComboBox;
48 import javax.swing.JFrame;
49 import javax.swing.JLabel;
50 import javax.swing.JPanel;
51 import javax.swing.JScrollPane;
52 import javax.swing.JTextArea;
53 import javax.swing.border.Border;
54 import javax.swing.text.DefaultCaret;
56 import jalview.bin.Cache;
57 import jalview.log.JLoggerI.LogLevel;
58 import jalview.log.JLoggerLog4j;
59 import jalview.log.JalviewAppender;
60 import jalview.util.ChannelProperties;
61 import jalview.util.MessageManager;
62 import jalview.util.Platform;
65 * Simple Jalview Java Console. Version 1 - allows viewing of console output
66 * after desktop is created. Acquired with thanks from RJHM's site
67 * http://www.comweb.nl/java/Console/Console.html A simple Java Console for your
68 * application (Swing version) Requires Java 1.1.5 or higher Disclaimer the use
69 * of this source is at your own risk. Permision to use and distribute into your
70 * own applications RJHM van den Bergh , rvdb@comweb.nl
73 public class Console extends WindowAdapter
74 implements WindowListener, ActionListener, Runnable
78 private JTextArea textArea;
81 * unused - tally and limit for lines in console window int lines = 0;
85 int byteslim = 102400, bytescut = 76800; // 100k and 75k cut point.
87 private Thread reader, reader2, textAppender;
91 private final PrintStream stdout = System.out, stderr = System.err;
93 private PipedInputStream pin = new PipedInputStream();
95 private PipedInputStream pin2 = new PipedInputStream();
97 private StringBuffer displayPipe = new StringBuffer();
99 Thread errorThrower; // just for testing (Throws an Exception at this Console
101 // are we attached to some parent Desktop
102 Desktop parent = null;
104 private int MIN_WIDTH = 300;
106 private int MIN_HEIGHT = 250;
108 private JComboBox<LogLevel> logLevelCombo = new JComboBox<LogLevel>();
110 protected LogLevel startingLogLevel = null;
114 // create all components and add them
115 Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
116 frame = initFrame("Java Console", screenSize.width / 2,
117 screenSize.height / 2, -1, -1);
118 frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
122 private void initConsole(boolean visible)
124 initConsole(visible, true);
134 private void initConsole(boolean visible, boolean redirect)
136 // CutAndPasteTransfer cpt = new CutAndPasteTransfer();
137 // textArea = cpt.getTextArea();
138 textArea = new JTextArea();
139 textArea.setEditable(false);
141 DefaultCaret caret = (DefaultCaret) textArea.getCaret();
142 caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
143 // toggle autoscroll by clicking on the text area
144 Border pausedBorder = BorderFactory.createMatteBorder(2, 2, 2, 2,
145 textArea.getForeground());
146 Border noBorder = BorderFactory.createEmptyBorder(2, 2, 2, 2);
147 JScrollPane scrollPane = new JScrollPane(textArea);
148 scrollPane.setBorder(noBorder);
149 textArea.addMouseListener(new MouseAdapter()
152 public void mouseClicked(MouseEvent e)
154 if (e.getButton() == MouseEvent.BUTTON1)
156 if (caret.getUpdatePolicy() == DefaultCaret.ALWAYS_UPDATE)
158 caret.setUpdatePolicy(DefaultCaret.NEVER_UPDATE);
159 scrollPane.setBorder(pausedBorder);
163 caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
164 textArea.setCaretPosition(textArea.getDocument().getLength());
165 scrollPane.setBorder(noBorder);
171 JButton clearButton = new JButton(
172 MessageManager.getString("action.clear"));
173 JButton copyToClipboardButton = new JButton(
174 MessageManager.getString("label.copy_to_clipboard"));
175 copyToClipboardButton.addActionListener(new ActionListener()
178 public void actionPerformed(ActionEvent e)
180 copyConsoleTextToClipboard();
183 copyToClipboardButton.addMouseListener(new MouseAdapter()
185 private Color bg = textArea.getBackground();
187 private Color fg = textArea.getForeground();
190 public void mousePressed(MouseEvent e)
192 textArea.setBackground(textArea.getSelectionColor());
193 textArea.setForeground(textArea.getSelectedTextColor());
197 public void mouseReleased(MouseEvent e)
199 textArea.setBackground(bg);
200 textArea.setForeground(fg);
204 copyToClipboardButton.setToolTipText(
205 MessageManager.getString("label.copy_to_clipboard_tooltip"));
207 JLabel logLevelLabel = new JLabel(
208 MessageManager.getString("label.log_level") + ":");
210 // logLevelCombo.addItem(LogLevel.ALL);
211 logLevelCombo.addItem(LogLevel.TRACE);
212 logLevelCombo.addItem(LogLevel.DEBUG);
213 logLevelCombo.addItem(LogLevel.INFO);
214 logLevelCombo.addItem(LogLevel.WARN);
215 // logLevelCombo.addItem(LogLevel.ERROR);
216 // logLevelCombo.addItem(LogLevel.FATAL);
217 // logLevelCombo.addItem(LogLevel.ERROR);
218 // logLevelCombo.addItem(LogLevel.OFF);
219 // set startingLogLevel
220 if (jalview.bin.Console.log == null)
224 startingLogLevel = LogLevel
225 .valueOf(Cache.getDefault(Cache.JALVIEWLOGLEVEL, null));
226 } catch (IllegalArgumentException e1)
228 jalview.bin.Console.debug(
229 "Invalid value for preference " + Cache.JALVIEWLOGLEVEL);
230 } catch (NullPointerException e2)
232 // no value in preferences
235 if (startingLogLevel == null)
237 startingLogLevel = LogLevel.INFO;
243 startingLogLevel = jalview.bin.Console.log.getLevel();
245 setChosenLogLevelCombo();
246 logLevelCombo.addActionListener(new ActionListener()
249 public void actionPerformed(ActionEvent e)
251 if (jalview.bin.Console.log != null)
253 jalview.bin.Console.log
254 .setLevel((LogLevel) logLevelCombo.getSelectedItem());
261 frame.getContentPane().setLayout(new BorderLayout());
262 frame.getContentPane().add(scrollPane, BorderLayout.CENTER);
263 JPanel southPanel = new JPanel();
264 southPanel.setLayout(new GridBagLayout());
266 JPanel logLevelPanel = new JPanel();
267 logLevelPanel.setAlignmentX(JPanel.LEFT_ALIGNMENT);
268 logLevelPanel.add(logLevelLabel);
269 logLevelPanel.add(logLevelCombo);
270 String logLevelTooltip = MessageManager.formatMessage(
271 "label.log_level_tooltip", startingLogLevel.toString());
272 logLevelLabel.setToolTipText(logLevelTooltip);
273 logLevelCombo.setToolTipText(logLevelTooltip);
275 GridBagConstraints gbc = new GridBagConstraints();
281 southPanel.add(logLevelPanel, gbc);
285 gbc.fill = GridBagConstraints.HORIZONTAL;
286 southPanel.add(clearButton, gbc);
290 gbc.fill = GridBagConstraints.NONE;
291 southPanel.add(copyToClipboardButton, gbc);
293 southPanel.setVisible(true);
294 frame.getContentPane().add(southPanel, BorderLayout.SOUTH);
295 frame.setVisible(visible);
296 updateConsole = visible;
297 frame.addWindowListener(this);
298 clearButton.addActionListener(this);
308 quit = false; // signals the Threads that they should exit
310 // Starting two seperate threads to read from the PipedInputStreams
312 reader = new Thread(this);
313 reader.setDaemon(true);
316 reader2 = new Thread(this);
317 reader2.setDaemon(true);
319 // and a thread to append text to the textarea
320 textAppender = new Thread(this);
321 textAppender.setDaemon(true);
322 textAppender.start();
325 frame.setIconImages(ChannelProperties.getIconList());
328 private void setChosenLogLevelCombo()
330 setChosenLogLevelCombo(startingLogLevel);
333 private void setChosenLogLevelCombo(LogLevel setLogLevel)
335 logLevelCombo.setSelectedItem(setLogLevel);
336 if (!logLevelCombo.getSelectedItem().equals(setLogLevel))
338 // setLogLevel not (yet) in list
339 if (setLogLevel != null && setLogLevel instanceof LogLevel)
341 // add new item to list (might be set via .jalview_properties)
342 boolean added = false;
343 for (int i = 0; i < logLevelCombo.getItemCount(); i++)
345 LogLevel l = logLevelCombo.getItemAt(i);
346 if (l.compareTo(setLogLevel) >= 0)
348 logLevelCombo.insertItemAt(setLogLevel, i);
353 if (!added) // lower priority than others or some confusion -- add to
356 logLevelCombo.addItem(setLogLevel);
358 logLevelCombo.setSelectedItem(setLogLevel);
362 logLevelCombo.setSelectedItem(LogLevel.INFO);
367 private void copyConsoleTextToClipboard()
369 String consoleText = textArea.getText();
370 StringSelection consoleTextSelection = new StringSelection(consoleText);
371 Clipboard cb = Toolkit.getDefaultToolkit().getSystemClipboard();
372 cb.setContents(consoleTextSelection, null);
375 PipedOutputStream pout = null, perr = null;
377 public void redirectStreams()
383 pout = new PipedOutputStream(this.pin);
384 System.setOut(new PrintStream(pout, true));
385 } catch (java.io.IOException io)
387 textArea.append("Couldn't redirect STDOUT to this console\n"
389 io.printStackTrace(stderr);
390 } catch (SecurityException se)
392 textArea.append("Couldn't redirect STDOUT to this console\n"
394 se.printStackTrace(stderr);
399 perr = new PipedOutputStream(this.pin2);
400 System.setErr(new PrintStream(perr, true));
401 } catch (java.io.IOException io)
403 textArea.append("Couldn't redirect STDERR to this console\n"
405 io.printStackTrace(stderr);
406 } catch (SecurityException se)
408 textArea.append("Couldn't redirect STDERR to this console\n"
410 se.printStackTrace(stderr);
415 public void unredirectStreams()
421 System.setOut(stdout);
424 pin = new PipedInputStream();
426 } catch (java.io.IOException io)
428 textArea.append("Couldn't unredirect STDOUT to this console\n"
430 io.printStackTrace(stderr);
431 } catch (SecurityException se)
433 textArea.append("Couldn't unredirect STDOUT to this console\n"
435 se.printStackTrace(stderr);
440 System.setErr(stderr);
443 pin2 = new PipedInputStream();
445 } catch (java.io.IOException io)
447 textArea.append("Couldn't unredirect STDERR to this console\n"
449 io.printStackTrace(stderr);
450 } catch (SecurityException se)
452 textArea.append("Couldn't unredirect STDERR to this console\n"
454 se.printStackTrace(stderr);
462 // you may omit this part for your application
465 jalview.bin.Console.outPrintln("Hello World 2");
466 jalview.bin.Console.outPrintln("All fonts available to Graphic2D:\n");
467 GraphicsEnvironment ge = GraphicsEnvironment
468 .getLocalGraphicsEnvironment();
469 String[] fontNames = ge.getAvailableFontFamilyNames();
470 for (int n = 0; n < fontNames.length; n++)
472 jalview.bin.Console.outPrintln(fontNames[n]);
474 // Testing part: simple an error thrown anywhere in this JVM will be printed
476 // We do it with a seperate Thread becasue we don't wan't to break a Thread
477 // used by the Console.
478 jalview.bin.Console.outPrintln("\nLets throw an error on this console");
479 errorThrower = new Thread(this);
480 errorThrower.setDaemon(true);
481 errorThrower.start();
484 private JFrame initFrame(String string, int i, int j, int x, int y)
486 JFrame frame = new JFrame(string);
487 frame.setName(string);
496 frame.setBounds(x, y, i, j);
501 * attach a console to the desktop - the desktop will open it if requested.
505 public Console(Desktop desktop)
508 // window name - get x,y,width, height possibly scaled
509 Rectangle bounds = parent == null ? null
510 : parent.getLastKnownDimensions("JAVA_CONSOLE_");
514 ChannelProperties.getProperty("app_name") + " Java Console",
515 bounds.width, bounds.height, bounds.x, bounds.y);
517 else if (parent != null && parent.getWidth() > 0
518 && parent.getHeight() > 0)
521 ChannelProperties.getProperty("app_name") + " Java Console",
522 parent.getWidth() / 2, parent.getHeight() / 4, parent.getX(),
528 ChannelProperties.getProperty("app_name") + " Java Console",
529 MIN_WIDTH, MIN_HEIGHT, 10, 10);
531 frame.setMinimumSize(new Dimension(MIN_WIDTH, MIN_HEIGHT));
532 // parent.add(frame);
534 LogLevel level = (LogLevel) logLevelCombo.getSelectedItem();
535 if (!Platform.isJS())
537 JalviewAppender jappender = new JalviewAppender(level);
538 JalviewAppender.setTextArea(textArea);
540 if (jalview.bin.Console.log != null
541 && jalview.bin.Console.log instanceof JLoggerLog4j)
543 JLoggerLog4j.addAppender(jalview.bin.Console.log, jappender);
548 public synchronized void stopConsole()
553 * reader.notify(); reader2.notify(); if (errorThrower!=null)
554 * errorThrower.notify(); // stop all threads if (textAppender!=null)
555 * textAppender.notify();
563 } catch (Exception e)
565 jalview.bin.Console.debug("pin.close() error", e);
571 } catch (Exception e)
573 jalview.bin.Console.debug("pin2.close() error", e);
577 textAppender.join(10);
578 } catch (Exception e)
580 jalview.bin.Console.debug("textAppender.join(10) error", e);
584 if (!frame.isVisible())
593 public synchronized void windowClosed(WindowEvent evt)
595 frame.setVisible(false);
599 private void closeConsoleGui()
601 updateConsole = false;
609 parent.showConsole(false);
614 public synchronized void windowClosing(WindowEvent evt)
616 frame.setVisible(false); // default behaviour of JFrame
623 public synchronized void actionPerformed(ActionEvent evt)
626 // textArea.setText("");
630 public synchronized void run()
634 while (Thread.currentThread() == reader)
636 if (pin == null || pin.available() == 0)
641 if (pin.available() == 0)
645 } catch (InterruptedException ie)
647 jalview.bin.Console.debug("pin.available() error", ie);
651 while (pin.available() != 0)
653 String input = this.readLine(pin);
655 long time = System.nanoTime();
656 appendToTextArea(input);
657 // stderr.println("Time taken to stdout append:\t"
658 // + (System.nanoTime() - time) + " ns");
667 while (Thread.currentThread() == reader2)
669 if (pin2.available() == 0)
674 if (pin2.available() == 0)
678 } catch (InterruptedException ie)
680 jalview.bin.Console.debug("pin.available() error", ie);
683 while (pin2.available() != 0)
685 String input = this.readLine(pin2);
687 long time = System.nanoTime();
688 appendToTextArea(input);
689 // stderr.println("Time taken to stderr append:\t"
690 // + (System.nanoTime() - time) + " ns");
698 while (Thread.currentThread() == textAppender)
702 // check string buffer - if greater than console, clear console and
703 // replace with last segment of content, otherwise, append all to
706 while (displayPipe.length() > 0)
709 StringBuffer tmp = new StringBuffer(), replace;
710 synchronized (displayPipe)
712 replace = displayPipe;
715 // simply append whole buffer
716 textArea.append(replace.toString());
717 count += replace.length();
718 if (count > byteslim)
723 if (displayPipe.length() == 0)
728 if (displayPipe.length() == 0)
732 } catch (InterruptedException e)
734 jalview.bin.Console.debug("displayPipe.length() error", e);
743 } catch (InterruptedException e)
745 jalview.bin.Console.debug("this.wait(100) error", e);
754 } catch (Exception e)
756 textArea.append("\nConsole reports an Internal error.");
757 textArea.append("The error is: " + e.getMessage());
758 // Need to uncomment this to ensure that line tally is synched.
761 "Console reports an Internal error.\nThe error is: " + e);
764 // just for testing (Throw a Nullpointer after 1 second)
765 if (Thread.currentThread() == errorThrower)
770 } catch (InterruptedException ie)
772 jalview.bin.Console.debug("this.wait(1000) error", ie);
774 throw new NullPointerException(
775 MessageManager.getString("exception.application_test_npe"));
779 private void appendToTextArea(final String input)
781 if (updateConsole == false)
786 long time = System.nanoTime();
787 javax.swing.SwingUtilities.invokeLater(new Runnable()
792 displayPipe.append(input); // change to stringBuffer
793 // displayPipe.flush();
797 // stderr.println("Time taken to Spawnappend:\t" + (System.nanoTime() -
802 private String header = null;
804 private boolean updateConsole = false;
806 private synchronized void trimBuffer(boolean clear)
808 if (header == null && textArea.getLineCount() > 5)
812 header = textArea.getText(0, textArea.getLineStartOffset(5))
813 + "\nTruncated...\n";
814 } catch (Exception e)
816 jalview.bin.Console.warn("textArea Exception", e);
820 int tlength = textArea.getDocument().getLength();
823 if (clear || (tlength > byteslim))
829 long time = System.nanoTime();
830 textArea.replaceRange(header, 0, tlength - bytescut);
831 // stderr.println("Time taken to cut:\t"
832 // + (System.nanoTime() - time) + " ns");
836 textArea.setText(header);
838 } catch (Exception e)
840 jalview.bin.Console.warn("textArea Exception", e);
842 // lines = textArea.getLineCount();
848 public synchronized String readLine(PipedInputStream in)
855 int available = in.available();
860 byte b[] = new byte[available];
862 input = input + new String(b, 0, b.length);
863 // counts lines - we don't do this for speed.
864 // while ((lp = input.indexOf("\n", lp + 1)) > -1)
868 } while (!input.endsWith("\n") && !input.endsWith("\r\n") && !quit);
876 public static void main(String[] arg)
878 new Console().test(); // create console with not reference
882 public void setVisible(boolean selected)
884 frame.setVisible(selected);
885 if (selected == true)
887 setChosenLogLevelCombo();
889 updateConsole = true;
894 // reset log level to what it was before
895 if (jalview.bin.Console.log != null)
897 jalview.bin.Console.log.setLevel(startingLogLevel);
901 updateConsole = false;
905 public Rectangle getBounds()
909 return frame.getBounds();
915 * set the banner that appears at the top of the console output
919 public void setHeader(String string)
922 if (header.charAt(header.length() - 1) != '\n')
926 textArea.insert(header, 0);
934 public String getHeader()