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 = LogLevel.INFO;
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);
121 private void initConsole(boolean visible)
123 initConsole(visible, true);
133 private void initConsole(boolean visible, boolean redirect)
135 // CutAndPasteTransfer cpt = new CutAndPasteTransfer();
136 // textArea = cpt.getTextArea();
137 textArea = new JTextArea();
138 textArea.setEditable(false);
140 DefaultCaret caret = (DefaultCaret) textArea.getCaret();
141 caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
142 // toggle autoscroll by clicking on the text area
143 Border pausedBorder = BorderFactory.createMatteBorder(2, 2, 2, 2,
144 textArea.getForeground());
145 Border noBorder = BorderFactory.createEmptyBorder(2, 2, 2, 2);
146 JScrollPane scrollPane = new JScrollPane(textArea);
147 scrollPane.setBorder(noBorder);
148 textArea.addMouseListener(new MouseAdapter()
150 public void mouseClicked(MouseEvent e)
152 if (e.getButton() == MouseEvent.BUTTON1)
154 if (caret.getUpdatePolicy() == DefaultCaret.ALWAYS_UPDATE)
156 caret.setUpdatePolicy(DefaultCaret.NEVER_UPDATE);
157 scrollPane.setBorder(pausedBorder);
161 caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
162 textArea.setCaretPosition(textArea.getDocument().getLength());
163 scrollPane.setBorder(noBorder);
169 JButton clearButton = new JButton(
170 MessageManager.getString("action.clear"));
171 JButton copyToClipboardButton = new JButton(
172 MessageManager.getString("label.copy_to_clipboard"));
173 copyToClipboardButton.addActionListener(new ActionListener()
175 public void actionPerformed(ActionEvent e)
177 copyConsoleTextToClipboard();
180 copyToClipboardButton.addMouseListener(new MouseAdapter()
182 private Color bg = textArea.getBackground();
184 private Color fg = textArea.getForeground();
186 public void mousePressed(MouseEvent e)
188 textArea.setBackground(textArea.getSelectionColor());
189 textArea.setForeground(textArea.getSelectedTextColor());
192 public void mouseReleased(MouseEvent e)
194 textArea.setBackground(bg);
195 textArea.setForeground(fg);
199 copyToClipboardButton.setToolTipText(
200 MessageManager.getString("label.copy_to_clipboard_tooltip"));
202 JLabel logLevelLabel = new JLabel(
203 MessageManager.getString("label.log_level") + ":");
205 // logLevelCombo.addItem(LogLevel.ALL);
206 logLevelCombo.addItem(LogLevel.TRACE);
207 logLevelCombo.addItem(LogLevel.DEBUG);
208 logLevelCombo.addItem(LogLevel.INFO);
209 logLevelCombo.addItem(LogLevel.WARN);
210 // logLevelCombo.addItem(LogLevel.ERROR);
211 // logLevelCombo.addItem(LogLevel.FATAL);
212 // logLevelCombo.addItem(LogLevel.ERROR);
213 // logLevelCombo.addItem(LogLevel.OFF);
214 // set startingLogLevel
215 startingLogLevel = Cache.log == null ? LogLevel.INFO
216 : Cache.log.getLevel();
217 setChosenLogLevelCombo();
218 logLevelCombo.addActionListener(new ActionListener()
220 public void actionPerformed(ActionEvent e)
222 if (Cache.log != null)
224 Cache.log.setLevel((LogLevel) logLevelCombo.getSelectedItem());
231 frame.getContentPane().setLayout(new BorderLayout());
232 frame.getContentPane().add(scrollPane, BorderLayout.CENTER);
233 JPanel southPanel = new JPanel();
234 southPanel.setLayout(new GridBagLayout());
236 JPanel logLevelPanel = new JPanel();
237 logLevelPanel.setAlignmentX(JPanel.LEFT_ALIGNMENT);
238 logLevelPanel.add(logLevelLabel);
239 logLevelPanel.add(logLevelCombo);
240 String logLevelTooltip = MessageManager.formatMessage(
241 "label.log_level_tooltip", startingLogLevel.toString());
242 logLevelLabel.setToolTipText(logLevelTooltip);
243 logLevelCombo.setToolTipText(logLevelTooltip);
245 GridBagConstraints gbc = new GridBagConstraints();
251 southPanel.add(logLevelPanel, gbc);
255 gbc.fill = GridBagConstraints.HORIZONTAL;
256 southPanel.add(clearButton, gbc);
260 gbc.fill = GridBagConstraints.NONE;
261 southPanel.add(copyToClipboardButton, gbc);
263 southPanel.setVisible(true);
264 frame.getContentPane().add(southPanel, BorderLayout.SOUTH);
265 frame.setVisible(visible);
266 updateConsole = visible;
267 frame.addWindowListener(this);
268 clearButton.addActionListener(this);
278 quit = false; // signals the Threads that they should exit
280 // Starting two seperate threads to read from the PipedInputStreams
282 reader = new Thread(this);
283 reader.setDaemon(true);
286 reader2 = new Thread(this);
287 reader2.setDaemon(true);
289 // and a thread to append text to the textarea
290 textAppender = new Thread(this);
291 textAppender.setDaemon(true);
292 textAppender.start();
295 frame.setIconImages(ChannelProperties.getIconList());
298 private void setChosenLogLevelCombo()
300 setChosenLogLevelCombo(startingLogLevel);
303 private void setChosenLogLevelCombo(LogLevel setLogLevel)
305 logLevelCombo.setSelectedItem(setLogLevel);
306 if (!logLevelCombo.getSelectedItem().equals(setLogLevel))
308 // setLogLevel not (yet) in list
309 if (setLogLevel != null && setLogLevel instanceof LogLevel)
311 // add new item to list (might be set via .jalview_properties)
312 boolean added = false;
313 for (int i = 0; i < logLevelCombo.getItemCount(); i++)
315 LogLevel l = (LogLevel) logLevelCombo.getItemAt(i);
316 if (l.compareTo(setLogLevel) >= 0)
318 logLevelCombo.insertItemAt(setLogLevel, i);
323 if (!added) // lower priority than others or some confusion -- add to
326 logLevelCombo.addItem(setLogLevel);
328 logLevelCombo.setSelectedItem(setLogLevel);
332 logLevelCombo.setSelectedItem(LogLevel.INFO);
337 private void copyConsoleTextToClipboard()
339 String consoleText = textArea.getText();
340 StringSelection consoleTextSelection = new StringSelection(consoleText);
341 Clipboard cb = Toolkit.getDefaultToolkit().getSystemClipboard();
342 cb.setContents(consoleTextSelection, null);
345 PipedOutputStream pout = null, perr = null;
347 public void redirectStreams()
353 pout = new PipedOutputStream(this.pin);
354 System.setOut(new PrintStream(pout, true));
355 } catch (java.io.IOException io)
357 textArea.append("Couldn't redirect STDOUT to this console\n"
359 io.printStackTrace(stderr);
360 } catch (SecurityException se)
362 textArea.append("Couldn't redirect STDOUT to this console\n"
364 se.printStackTrace(stderr);
369 perr = new PipedOutputStream(this.pin2);
370 System.setErr(new PrintStream(perr, true));
371 } catch (java.io.IOException io)
373 textArea.append("Couldn't redirect STDERR to this console\n"
375 io.printStackTrace(stderr);
376 } catch (SecurityException se)
378 textArea.append("Couldn't redirect STDERR to this console\n"
380 se.printStackTrace(stderr);
385 public void unredirectStreams()
391 System.setOut(stdout);
394 pin = new PipedInputStream();
396 } catch (java.io.IOException io)
398 textArea.append("Couldn't unredirect STDOUT to this console\n"
400 io.printStackTrace(stderr);
401 } catch (SecurityException se)
403 textArea.append("Couldn't unredirect STDOUT to this console\n"
405 se.printStackTrace(stderr);
410 System.setErr(stderr);
413 pin2 = new PipedInputStream();
415 } catch (java.io.IOException io)
417 textArea.append("Couldn't unredirect STDERR to this console\n"
419 io.printStackTrace(stderr);
420 } catch (SecurityException se)
422 textArea.append("Couldn't unredirect STDERR to this console\n"
424 se.printStackTrace(stderr);
432 // you may omit this part for your application
435 System.out.println("Hello World 2");
436 System.out.println("All fonts available to Graphic2D:\n");
437 GraphicsEnvironment ge = GraphicsEnvironment
438 .getLocalGraphicsEnvironment();
439 String[] fontNames = ge.getAvailableFontFamilyNames();
440 for (int n = 0; n < fontNames.length; n++)
442 System.out.println(fontNames[n]);
444 // Testing part: simple an error thrown anywhere in this JVM will be printed
446 // We do it with a seperate Thread becasue we don't wan't to break a Thread
447 // used by the Console.
448 System.out.println("\nLets throw an error on this console");
449 errorThrower = new Thread(this);
450 errorThrower.setDaemon(true);
451 errorThrower.start();
454 private JFrame initFrame(String string, int i, int j, int x, int y)
456 JFrame frame = new JFrame(string);
457 frame.setName(string);
466 frame.setBounds(x, y, i, j);
471 * attach a console to the desktop - the desktop will open it if requested.
475 public Console(Desktop desktop)
481 * attach a console to the desktop - the desktop will open it if requested.
484 * @param showjconsole
485 * - if true, then redirect stdout immediately
487 public Console(Desktop desktop, boolean showjconsole)
490 // window name - get x,y,width, height possibly scaled
491 Rectangle bounds = desktop.getLastKnownDimensions("JAVA_CONSOLE_");
495 ChannelProperties.getProperty("app_name") + " Java Console",
496 desktop.getWidth() / 2, desktop.getHeight() / 4,
497 desktop.getX(), desktop.getY());
502 ChannelProperties.getProperty("app_name") + " Java Console",
503 bounds.width, bounds.height, bounds.x, bounds.y);
505 frame.setMinimumSize(new Dimension(MIN_WIDTH, MIN_HEIGHT));
506 // desktop.add(frame);
508 LogLevel level = (LogLevel) logLevelCombo.getSelectedItem();
509 if (!Platform.isJS())
511 JalviewAppender jappender = new JalviewAppender(level);
512 JalviewAppender.setTextArea(textArea);
514 if (Cache.log != null && Cache.log instanceof JLoggerLog4j)
516 JLoggerLog4j.addAppender(Cache.log, jappender);
521 public synchronized void stopConsole()
526 * reader.notify(); reader2.notify(); if (errorThrower!=null)
527 * errorThrower.notify(); // stop all threads if (textAppender!=null)
528 * textAppender.notify();
536 } catch (Exception e)
543 } catch (Exception e)
548 textAppender.join(10);
549 } catch (Exception e)
553 if (!frame.isVisible())
561 public synchronized void windowClosed(WindowEvent evt)
563 frame.setVisible(false);
567 private void closeConsoleGui()
569 updateConsole = false;
577 parent.showConsole(false);
582 public synchronized void windowClosing(WindowEvent evt)
584 frame.setVisible(false); // default behaviour of JFrame
591 public synchronized void actionPerformed(ActionEvent evt)
594 // textArea.setText("");
598 public synchronized void run()
602 while (Thread.currentThread() == reader)
604 if (pin == null || pin.available() == 0)
609 if (pin.available() == 0)
613 } catch (InterruptedException ie)
618 while (pin.available() != 0)
620 String input = this.readLine(pin);
622 long time = System.nanoTime();
623 appendToTextArea(input);
624 // stderr.println("Time taken to stdout append:\t"
625 // + (System.nanoTime() - time) + " ns");
634 while (Thread.currentThread() == reader2)
636 if (pin2.available() == 0)
641 if (pin2.available() == 0)
645 } catch (InterruptedException ie)
649 while (pin2.available() != 0)
651 String input = this.readLine(pin2);
653 long time = System.nanoTime();
654 appendToTextArea(input);
655 // stderr.println("Time taken to stderr append:\t"
656 // + (System.nanoTime() - time) + " ns");
664 while (Thread.currentThread() == textAppender)
668 // check string buffer - if greater than console, clear console and
669 // replace with last segment of content, otherwise, append all to
672 while (displayPipe.length() > 0)
675 StringBuffer tmp = new StringBuffer(), replace;
676 synchronized (displayPipe)
678 replace = displayPipe;
681 // simply append whole buffer
682 textArea.append(replace.toString());
683 count += replace.length();
684 if (count > byteslim)
689 if (displayPipe.length() == 0)
694 if (displayPipe.length() == 0)
698 } catch (InterruptedException e)
708 } catch (InterruptedException e)
719 } catch (Exception e)
721 textArea.append("\nConsole reports an Internal error.");
722 textArea.append("The error is: " + e.getMessage());
723 // Need to uncomment this to ensure that line tally is synched.
726 "Console reports an Internal error.\nThe error is: " + e);
729 // just for testing (Throw a Nullpointer after 1 second)
730 if (Thread.currentThread() == errorThrower)
735 } catch (InterruptedException ie)
738 throw new NullPointerException(
739 MessageManager.getString("exception.application_test_npe"));
743 private void appendToTextArea(final String input)
745 if (updateConsole == false)
750 long time = System.nanoTime();
751 javax.swing.SwingUtilities.invokeLater(new Runnable()
756 displayPipe.append(input); // change to stringBuffer
757 // displayPipe.flush();
761 // stderr.println("Time taken to Spawnappend:\t" + (System.nanoTime() -
766 private String header = null;
768 private boolean updateConsole = false;
770 private synchronized void trimBuffer(boolean clear)
772 if (header == null && textArea.getLineCount() > 5)
776 header = textArea.getText(0, textArea.getLineStartOffset(5))
777 + "\nTruncated...\n";
778 } catch (Exception e)
784 int tlength = textArea.getDocument().getLength();
787 if (clear || (tlength > byteslim))
793 long time = System.nanoTime();
794 textArea.replaceRange(header, 0, tlength - bytescut);
795 // stderr.println("Time taken to cut:\t"
796 // + (System.nanoTime() - time) + " ns");
800 textArea.setText(header);
802 } catch (Exception e)
806 // lines = textArea.getLineCount();
812 public synchronized String readLine(PipedInputStream in)
819 int available = in.available();
824 byte b[] = new byte[available];
826 input = input + new String(b, 0, b.length);
827 // counts lines - we don't do this for speed.
828 // while ((lp = input.indexOf("\n", lp + 1)) > -1)
832 } while (!input.endsWith("\n") && !input.endsWith("\r\n") && !quit);
840 public static void main(String[] arg)
842 new Console().test(); // create console with not reference
846 public void setVisible(boolean selected)
848 frame.setVisible(selected);
849 if (selected == true)
851 setChosenLogLevelCombo();
853 updateConsole = true;
858 // reset log level to what it was before
859 if (Cache.log != null)
861 Cache.log.setLevel(startingLogLevel);
865 updateConsole = false;
869 public Rectangle getBounds()
873 return frame.getBounds();
879 * set the banner that appears at the top of the console output
883 public void setHeader(String string)
886 if (header.charAt(header.length() - 1) != '\n')
890 textArea.insert(header, 0);
898 public String getHeader()