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.SwingUtilities;
54 import javax.swing.border.Border;
55 import javax.swing.text.DefaultCaret;
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);
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()
151 public void mouseClicked(MouseEvent e)
153 if (e.getButton() == MouseEvent.BUTTON1)
155 if (caret.getUpdatePolicy() == DefaultCaret.ALWAYS_UPDATE)
157 caret.setUpdatePolicy(DefaultCaret.NEVER_UPDATE);
158 scrollPane.setBorder(pausedBorder);
162 caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
163 textArea.setCaretPosition(textArea.getDocument().getLength());
164 scrollPane.setBorder(noBorder);
170 JButton clearButton = new JButton(
171 MessageManager.getString("action.clear"));
172 JButton copyToClipboardButton = new JButton(
173 MessageManager.getString("label.copy_to_clipboard"));
174 copyToClipboardButton.addActionListener(new ActionListener()
176 public void actionPerformed(ActionEvent e)
178 copyConsoleTextToClipboard();
181 copyToClipboardButton.addMouseListener(new MouseAdapter()
183 private Color bg = textArea.getBackground();
185 private Color fg = textArea.getForeground();
187 public void mousePressed(MouseEvent e)
189 textArea.setBackground(textArea.getSelectionColor());
190 textArea.setForeground(textArea.getSelectedTextColor());
193 public void mouseReleased(MouseEvent e)
195 textArea.setBackground(bg);
196 textArea.setForeground(fg);
200 copyToClipboardButton.setToolTipText(
201 MessageManager.getString("label.copy_to_clipboard_tooltip"));
203 JLabel logLevelLabel = new JLabel(
204 MessageManager.getString("label.log_level") + ":");
206 // logLevelCombo.addItem(LogLevel.ALL);
207 logLevelCombo.addItem(LogLevel.TRACE);
208 logLevelCombo.addItem(LogLevel.DEBUG);
209 logLevelCombo.addItem(LogLevel.INFO);
210 logLevelCombo.addItem(LogLevel.WARN);
211 // logLevelCombo.addItem(LogLevel.ERROR);
212 // logLevelCombo.addItem(LogLevel.FATAL);
213 // logLevelCombo.addItem(LogLevel.ERROR);
214 // logLevelCombo.addItem(LogLevel.OFF);
215 // set startingLogLevel
216 startingLogLevel = jalview.bin.Console.log == null ? LogLevel.INFO
217 : jalview.bin.Console.log.getLevel();
218 setChosenLogLevelCombo();
219 logLevelCombo.addActionListener(new ActionListener()
221 public void actionPerformed(ActionEvent e)
223 if (jalview.bin.Console.log != null)
225 jalview.bin.Console.log
226 .setLevel((LogLevel) logLevelCombo.getSelectedItem());
233 frame.getContentPane().setLayout(new BorderLayout());
234 frame.getContentPane().add(scrollPane, BorderLayout.CENTER);
235 JPanel southPanel = new JPanel();
236 southPanel.setLayout(new GridBagLayout());
238 JPanel logLevelPanel = new JPanel();
239 logLevelPanel.setAlignmentX(JPanel.LEFT_ALIGNMENT);
240 logLevelPanel.add(logLevelLabel);
241 logLevelPanel.add(logLevelCombo);
242 String logLevelTooltip = MessageManager.formatMessage(
243 "label.log_level_tooltip", startingLogLevel.toString());
244 logLevelLabel.setToolTipText(logLevelTooltip);
245 logLevelCombo.setToolTipText(logLevelTooltip);
247 GridBagConstraints gbc = new GridBagConstraints();
253 southPanel.add(logLevelPanel, gbc);
257 gbc.fill = GridBagConstraints.HORIZONTAL;
258 southPanel.add(clearButton, gbc);
262 gbc.fill = GridBagConstraints.NONE;
263 southPanel.add(copyToClipboardButton, gbc);
265 southPanel.setVisible(true);
266 frame.getContentPane().add(southPanel, BorderLayout.SOUTH);
267 frame.setVisible(visible);
268 updateConsole = visible;
269 frame.addWindowListener(this);
270 clearButton.addActionListener(this);
280 quit = false; // signals the Threads that they should exit
282 // Starting two seperate threads to read from the PipedInputStreams
284 reader = new Thread(this);
285 reader.setDaemon(true);
288 reader2 = new Thread(this);
289 reader2.setDaemon(true);
291 // and a thread to append text to the textarea
292 textAppender = new Thread(this);
293 textAppender.setDaemon(true);
294 textAppender.start();
297 frame.setIconImages(ChannelProperties.getIconList());
300 private void setChosenLogLevelCombo()
302 setChosenLogLevelCombo(startingLogLevel);
305 private void setChosenLogLevelCombo(LogLevel setLogLevel)
307 logLevelCombo.setSelectedItem(setLogLevel);
308 if (!logLevelCombo.getSelectedItem().equals(setLogLevel))
310 // setLogLevel not (yet) in list
311 if (setLogLevel != null && setLogLevel instanceof LogLevel)
313 // add new item to list (might be set via .jalview_properties)
314 boolean added = false;
315 for (int i = 0; i < logLevelCombo.getItemCount(); i++)
317 LogLevel l = (LogLevel) logLevelCombo.getItemAt(i);
318 if (l.compareTo(setLogLevel) >= 0)
320 logLevelCombo.insertItemAt(setLogLevel, i);
325 if (!added) // lower priority than others or some confusion -- add to
328 logLevelCombo.addItem(setLogLevel);
330 logLevelCombo.setSelectedItem(setLogLevel);
334 logLevelCombo.setSelectedItem(LogLevel.INFO);
339 private void copyConsoleTextToClipboard()
341 String consoleText = textArea.getText();
342 StringSelection consoleTextSelection = new StringSelection(consoleText);
343 Clipboard cb = Toolkit.getDefaultToolkit().getSystemClipboard();
344 cb.setContents(consoleTextSelection, null);
347 PipedOutputStream pout = null, perr = null;
349 public void redirectStreams()
355 pout = new PipedOutputStream(this.pin);
356 System.setOut(new PrintStream(pout, true));
357 } catch (java.io.IOException io)
359 textArea.append("Couldn't redirect STDOUT to this console\n"
361 io.printStackTrace(stderr);
362 } catch (SecurityException se)
364 textArea.append("Couldn't redirect STDOUT to this console\n"
366 se.printStackTrace(stderr);
371 perr = new PipedOutputStream(this.pin2);
372 System.setErr(new PrintStream(perr, true));
373 } catch (java.io.IOException io)
375 textArea.append("Couldn't redirect STDERR to this console\n"
377 io.printStackTrace(stderr);
378 } catch (SecurityException se)
380 textArea.append("Couldn't redirect STDERR to this console\n"
382 se.printStackTrace(stderr);
387 public void unredirectStreams()
393 System.setOut(stdout);
396 pin = new PipedInputStream();
398 } catch (java.io.IOException io)
400 textArea.append("Couldn't unredirect STDOUT to this console\n"
402 io.printStackTrace(stderr);
403 } catch (SecurityException se)
405 textArea.append("Couldn't unredirect STDOUT to this console\n"
407 se.printStackTrace(stderr);
412 System.setErr(stderr);
415 pin2 = new PipedInputStream();
417 } catch (java.io.IOException io)
419 textArea.append("Couldn't unredirect STDERR to this console\n"
421 io.printStackTrace(stderr);
422 } catch (SecurityException se)
424 textArea.append("Couldn't unredirect STDERR to this console\n"
426 se.printStackTrace(stderr);
434 // you may omit this part for your application
437 jalview.bin.Console.outPrintln("Hello World 2");
438 jalview.bin.Console.outPrintln("All fonts available to Graphic2D:\n");
439 GraphicsEnvironment ge = GraphicsEnvironment
440 .getLocalGraphicsEnvironment();
441 String[] fontNames = ge.getAvailableFontFamilyNames();
442 for (int n = 0; n < fontNames.length; n++)
444 jalview.bin.Console.outPrintln(fontNames[n]);
446 // Testing part: simple an error thrown anywhere in this JVM will be printed
448 // We do it with a seperate Thread becasue we don't wan't to break a Thread
449 // used by the Console.
450 jalview.bin.Console.outPrintln("\nLets throw an error on this console");
451 errorThrower = new Thread(this);
452 errorThrower.setDaemon(true);
453 errorThrower.start();
456 private JFrame initFrame(String string, int i, int j, int x, int y)
458 JFrame frame = new JFrame(string);
459 frame.setName(string);
468 frame.setBounds(x, y, i, j);
473 * attach a console to the desktop - the desktop will open it if requested.
477 public Console(Desktop desktop)
483 * attach a console to the desktop - the desktop will open it if requested.
486 * @param showjconsole
487 * - if true, then redirect stdout immediately
489 public Console(Desktop desktop, boolean showjconsole)
492 // window name - get x,y,width, height possibly scaled
493 Rectangle bounds = desktop.getLastKnownDimensions("JAVA_CONSOLE_");
497 ChannelProperties.getProperty("app_name") + " Java Console",
498 desktop.getWidth() / 2, desktop.getHeight() / 4,
499 desktop.getX(), desktop.getY());
504 ChannelProperties.getProperty("app_name") + " Java Console",
505 bounds.width, bounds.height, bounds.x, bounds.y);
507 frame.setMinimumSize(new Dimension(MIN_WIDTH, MIN_HEIGHT));
508 // desktop.add(frame);
510 LogLevel level = (LogLevel) logLevelCombo.getSelectedItem();
511 if (!Platform.isJS())
513 JalviewAppender jappender = new JalviewAppender(level);
514 JalviewAppender.setTextArea(textArea);
516 if (jalview.bin.Console.log != null
517 && jalview.bin.Console.log instanceof JLoggerLog4j)
519 JLoggerLog4j.addAppender(jalview.bin.Console.log, jappender);
524 public synchronized void stopConsole()
529 * reader.notify(); reader2.notify(); if (errorThrower!=null)
530 * errorThrower.notify(); // stop all threads if (textAppender!=null)
531 * textAppender.notify();
539 } catch (Exception e)
546 } catch (Exception e)
551 textAppender.join(10);
552 } catch (Exception e)
557 if (!frame.isVisible())
566 public synchronized void windowClosed(WindowEvent evt)
568 frame.setVisible(false);
572 private void closeConsoleGui()
574 updateConsole = false;
582 parent.showConsole(false);
587 public synchronized void windowClosing(WindowEvent evt)
589 frame.setVisible(false); // default behaviour of JFrame
596 public synchronized void actionPerformed(ActionEvent evt)
599 // textArea.setText("");
603 public synchronized void run()
607 while (Thread.currentThread() == reader)
609 if (pin == null || pin.available() == 0)
614 // if (pin.available() == 0)
616 // trimBuffer(false);
618 } catch (InterruptedException ie)
623 while (pin.available() != 0)
625 String input = this.readLine(pin);
627 long time = System.nanoTime();
628 appendToTextArea(input);
629 // stderr.println("Time taken to stdout append:\t"
630 // + (System.nanoTime() - time) + " ns");
639 while (Thread.currentThread() == reader2)
641 if (pin2.available() == 0)
646 if (pin2.available() == 0)
650 } catch (InterruptedException ie)
654 while (pin2.available() != 0)
656 String input = this.readLine(pin2);
658 long time = System.nanoTime();
659 appendToTextArea(input);
660 // stderr.println("Time taken to stderr append:\t"
661 // + (System.nanoTime() - time) + " ns");
669 while (Thread.currentThread() == textAppender)
673 // check string buffer - if greater than console, clear console and
674 // replace with last segment of content, otherwise, append all to
676 while (displayPipe.length() > 0)
678 StringBuffer tmp = new StringBuffer(), replace;
679 synchronized (displayPipe)
681 replace = displayPipe;
684 // Append formatted message to textarea using the Swing Thread.
685 SwingUtilities.invokeLater(new Runnable()
689 textArea.append(replace.toString());
694 if (displayPipe.length() == 0)
699 if (displayPipe.length() == 0)
701 // post a trim on Swing Thread.
702 SwingUtilities.invokeLater(new Runnable()
710 } catch (InterruptedException e)
720 } catch (InterruptedException e)
731 } catch (Exception e)
733 textArea.append("\nConsole reports an Internal error.");
734 textArea.append("The error is: " + e.getMessage());
735 // Need to uncomment this to ensure that line tally is synched.
738 "Console reports an Internal error.\nThe error is: " + e);
741 // just for testing (Throw a Nullpointer after 1 second)
742 if (Thread.currentThread() == errorThrower)
747 } catch (InterruptedException ie)
750 throw new NullPointerException(
751 MessageManager.getString("exception.application_test_npe"));
755 private void appendToTextArea(final String input)
757 if (updateConsole == false)
762 long time = System.nanoTime();
763 javax.swing.SwingUtilities.invokeLater(new Runnable()
768 displayPipe.append(input);
771 // stderr.println("Time taken to Spawnappend:\t" + (System.nanoTime() -
776 private String header = null;
778 private boolean updateConsole = false;
780 private synchronized void trimBuffer(boolean clear)
782 if (header == null && textArea.getLineCount() > 5)
786 header = textArea.getText(0, textArea.getLineStartOffset(5))
787 + "\nTruncated...\n";
788 } catch (Exception e)
794 int tlength = textArea.getDocument().getLength();
797 if (clear || (tlength > byteslim))
803 long time = System.nanoTime();
804 textArea.replaceRange(header, 0, tlength - bytescut);
805 // stderr.println("Time taken to cut:\t"
806 // + (System.nanoTime() - time) + " ns");
810 textArea.setText(header);
812 } catch (Exception e)
816 // lines = textArea.getLineCount();
822 public synchronized String readLine(PipedInputStream in)
829 int available = in.available();
834 byte b[] = new byte[available];
836 input = input + new String(b, 0, b.length);
837 // counts lines - we don't do this for speed.
838 // while ((lp = input.indexOf("\n", lp + 1)) > -1)
842 } while (!input.endsWith("\n") && !input.endsWith("\r\n") && !quit);
850 public static void main(String[] arg)
852 new Console().test(); // create console with not reference
856 public void setVisible(boolean selected)
858 frame.setVisible(selected);
859 if (selected == true)
861 setChosenLogLevelCombo();
863 updateConsole = true;
868 // reset log level to what it was before
869 if (jalview.bin.Console.log != null)
871 jalview.bin.Console.log.setLevel(startingLogLevel);
875 updateConsole = false;
879 public Rectangle getBounds()
883 return frame.getBounds();
889 * set the banner that appears at the top of the console output
893 public void setHeader(String string)
896 if (header.charAt(header.length() - 1) != '\n')
900 textArea.insert(header, 0);
908 public String getHeader()