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.log.JLoggerI.LogLevel;
57 import jalview.log.JLoggerLog4j;
58 import jalview.log.JalviewAppender;
59 import jalview.util.ChannelProperties;
60 import jalview.util.MessageManager;
61 import jalview.util.Platform;
64 * Simple Jalview Java Console. Version 1 - allows viewing of console output
65 * after desktop is created. Acquired with thanks from RJHM's site
66 * http://www.comweb.nl/java/Console/Console.html A simple Java Console for your
67 * application (Swing version) Requires Java 1.1.5 or higher Disclaimer the use
68 * of this source is at your own risk. Permision to use and distribute into your
69 * own applications RJHM van den Bergh , rvdb@comweb.nl
72 public class Console extends WindowAdapter
73 implements WindowListener, ActionListener, Runnable
77 private JTextArea textArea;
80 * unused - tally and limit for lines in console window int lines = 0;
84 int byteslim = 102400, bytescut = 76800; // 100k and 75k cut point.
86 private Thread reader, reader2, textAppender;
90 private final PrintStream stdout = System.out, stderr = System.err;
92 private PipedInputStream pin = new PipedInputStream();
94 private PipedInputStream pin2 = new PipedInputStream();
96 private StringBuffer displayPipe = new StringBuffer();
98 Thread errorThrower; // just for testing (Throws an Exception at this Console
100 // are we attached to some parent Desktop
101 Desktop parent = null;
103 private int MIN_WIDTH = 300;
105 private int MIN_HEIGHT = 250;
107 private JComboBox<LogLevel> logLevelCombo = new JComboBox<LogLevel>();
109 protected LogLevel startingLogLevel = LogLevel.INFO;
113 // create all components and add them
114 Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
115 frame = initFrame("Java Console", screenSize.width / 2,
116 screenSize.height / 2, -1, -1);
120 private void initConsole(boolean visible)
122 initConsole(visible, true);
132 private void initConsole(boolean visible, boolean redirect)
134 // CutAndPasteTransfer cpt = new CutAndPasteTransfer();
135 // textArea = cpt.getTextArea();
136 textArea = new JTextArea();
137 textArea.setEditable(false);
139 DefaultCaret caret = (DefaultCaret) textArea.getCaret();
140 caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
141 // toggle autoscroll by clicking on the text area
142 Border pausedBorder = BorderFactory.createMatteBorder(2, 2, 2, 2,
143 textArea.getForeground());
144 Border noBorder = BorderFactory.createEmptyBorder(2, 2, 2, 2);
145 JScrollPane scrollPane = new JScrollPane(textArea);
146 scrollPane.setBorder(noBorder);
147 textArea.addMouseListener(new MouseAdapter()
149 public void mouseClicked(MouseEvent e)
151 if (e.getButton() == MouseEvent.BUTTON1)
153 if (caret.getUpdatePolicy() == DefaultCaret.ALWAYS_UPDATE)
155 caret.setUpdatePolicy(DefaultCaret.NEVER_UPDATE);
156 scrollPane.setBorder(pausedBorder);
160 caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
161 textArea.setCaretPosition(textArea.getDocument().getLength());
162 scrollPane.setBorder(noBorder);
168 JButton clearButton = new JButton(
169 MessageManager.getString("action.clear"));
170 JButton copyToClipboardButton = new JButton(
171 MessageManager.getString("label.copy_to_clipboard"));
172 copyToClipboardButton.addActionListener(new ActionListener()
174 public void actionPerformed(ActionEvent e)
176 copyConsoleTextToClipboard();
179 copyToClipboardButton.addMouseListener(new MouseAdapter()
181 private Color bg = textArea.getBackground();
183 private Color fg = textArea.getForeground();
185 public void mousePressed(MouseEvent e)
187 textArea.setBackground(textArea.getSelectionColor());
188 textArea.setForeground(textArea.getSelectedTextColor());
191 public void mouseReleased(MouseEvent e)
193 textArea.setBackground(bg);
194 textArea.setForeground(fg);
198 copyToClipboardButton.setToolTipText(
199 MessageManager.getString("label.copy_to_clipboard_tooltip"));
201 JLabel logLevelLabel = new JLabel(
202 MessageManager.getString("label.log_level") + ":");
204 // logLevelCombo.addItem(LogLevel.ALL);
205 logLevelCombo.addItem(LogLevel.TRACE);
206 logLevelCombo.addItem(LogLevel.DEBUG);
207 logLevelCombo.addItem(LogLevel.INFO);
208 logLevelCombo.addItem(LogLevel.WARN);
209 // logLevelCombo.addItem(LogLevel.ERROR);
210 // logLevelCombo.addItem(LogLevel.FATAL);
211 // logLevelCombo.addItem(LogLevel.ERROR);
212 // logLevelCombo.addItem(LogLevel.OFF);
213 // set startingLogLevel
214 startingLogLevel = jalview.bin.Console.log == null ? LogLevel.INFO
215 : jalview.bin.Console.log.getLevel();
216 setChosenLogLevelCombo();
217 logLevelCombo.addActionListener(new ActionListener()
219 public void actionPerformed(ActionEvent e)
221 if (jalview.bin.Console.log != null)
223 jalview.bin.Console.log
224 .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 (jalview.bin.Console.log != null
515 && jalview.bin.Console.log instanceof JLoggerLog4j)
517 JLoggerLog4j.addAppender(jalview.bin.Console.log, jappender);
522 public synchronized void stopConsole()
527 * reader.notify(); reader2.notify(); if (errorThrower!=null)
528 * errorThrower.notify(); // stop all threads if (textAppender!=null)
529 * textAppender.notify();
537 } catch (Exception e)
544 } catch (Exception e)
549 textAppender.join(10);
550 } catch (Exception e)
554 if (!frame.isVisible())
562 public synchronized void windowClosed(WindowEvent evt)
564 frame.setVisible(false);
568 private void closeConsoleGui()
570 updateConsole = false;
578 parent.showConsole(false);
583 public synchronized void windowClosing(WindowEvent evt)
585 frame.setVisible(false); // default behaviour of JFrame
592 public synchronized void actionPerformed(ActionEvent evt)
595 // textArea.setText("");
599 public synchronized void run()
603 while (Thread.currentThread() == reader)
605 if (pin == null || pin.available() == 0)
610 if (pin.available() == 0)
614 } catch (InterruptedException ie)
619 while (pin.available() != 0)
621 String input = this.readLine(pin);
623 long time = System.nanoTime();
624 appendToTextArea(input);
625 // stderr.println("Time taken to stdout append:\t"
626 // + (System.nanoTime() - time) + " ns");
635 while (Thread.currentThread() == reader2)
637 if (pin2.available() == 0)
642 if (pin2.available() == 0)
646 } catch (InterruptedException ie)
650 while (pin2.available() != 0)
652 String input = this.readLine(pin2);
654 long time = System.nanoTime();
655 appendToTextArea(input);
656 // stderr.println("Time taken to stderr append:\t"
657 // + (System.nanoTime() - time) + " ns");
665 while (Thread.currentThread() == textAppender)
669 // check string buffer - if greater than console, clear console and
670 // replace with last segment of content, otherwise, append all to
673 while (displayPipe.length() > 0)
676 StringBuffer tmp = new StringBuffer(), replace;
677 synchronized (displayPipe)
679 replace = displayPipe;
682 // simply append whole buffer
683 textArea.append(replace.toString());
684 count += replace.length();
685 if (count > byteslim)
690 if (displayPipe.length() == 0)
695 if (displayPipe.length() == 0)
699 } catch (InterruptedException e)
709 } catch (InterruptedException e)
720 } catch (Exception e)
722 textArea.append("\nConsole reports an Internal error.");
723 textArea.append("The error is: " + e.getMessage());
724 // Need to uncomment this to ensure that line tally is synched.
727 "Console reports an Internal error.\nThe error is: " + e);
730 // just for testing (Throw a Nullpointer after 1 second)
731 if (Thread.currentThread() == errorThrower)
736 } catch (InterruptedException ie)
739 throw new NullPointerException(
740 MessageManager.getString("exception.application_test_npe"));
744 private void appendToTextArea(final String input)
746 if (updateConsole == false)
751 long time = System.nanoTime();
752 javax.swing.SwingUtilities.invokeLater(new Runnable()
757 displayPipe.append(input); // change to stringBuffer
758 // displayPipe.flush();
762 // stderr.println("Time taken to Spawnappend:\t" + (System.nanoTime() -
767 private String header = null;
769 private boolean updateConsole = false;
771 private synchronized void trimBuffer(boolean clear)
773 if (header == null && textArea.getLineCount() > 5)
777 header = textArea.getText(0, textArea.getLineStartOffset(5))
778 + "\nTruncated...\n";
779 } catch (Exception e)
785 int tlength = textArea.getDocument().getLength();
788 if (clear || (tlength > byteslim))
794 long time = System.nanoTime();
795 textArea.replaceRange(header, 0, tlength - bytescut);
796 // stderr.println("Time taken to cut:\t"
797 // + (System.nanoTime() - time) + " ns");
801 textArea.setText(header);
803 } catch (Exception e)
807 // lines = textArea.getLineCount();
813 public synchronized String readLine(PipedInputStream in)
820 int available = in.available();
825 byte b[] = new byte[available];
827 input = input + new String(b, 0, b.length);
828 // counts lines - we don't do this for speed.
829 // while ((lp = input.indexOf("\n", lp + 1)) > -1)
833 } while (!input.endsWith("\n") && !input.endsWith("\r\n") && !quit);
841 public static void main(String[] arg)
843 new Console().test(); // create console with not reference
847 public void setVisible(boolean selected)
849 frame.setVisible(selected);
850 if (selected == true)
852 setChosenLogLevelCombo();
854 updateConsole = true;
859 // reset log level to what it was before
860 if (jalview.bin.Console.log != null)
862 jalview.bin.Console.log.setLevel(startingLogLevel);
866 updateConsole = false;
870 public Rectangle getBounds()
874 return frame.getBounds();
880 * set the banner that appears at the top of the console output
884 public void setHeader(String string)
887 if (header.charAt(header.length() - 1) != '\n')
891 textArea.insert(header, 0);
899 public String getHeader()