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.setLevel((LogLevel) logLevelCombo.getSelectedItem());
230 frame.getContentPane().setLayout(new BorderLayout());
231 frame.getContentPane().add(scrollPane, BorderLayout.CENTER);
232 JPanel southPanel = new JPanel();
233 southPanel.setLayout(new GridBagLayout());
235 JPanel logLevelPanel = new JPanel();
236 logLevelPanel.setAlignmentX(JPanel.LEFT_ALIGNMENT);
237 logLevelPanel.add(logLevelLabel);
238 logLevelPanel.add(logLevelCombo);
239 String logLevelTooltip = MessageManager.formatMessage(
240 "label.log_level_tooltip", startingLogLevel.toString());
241 logLevelLabel.setToolTipText(logLevelTooltip);
242 logLevelCombo.setToolTipText(logLevelTooltip);
244 GridBagConstraints gbc = new GridBagConstraints();
250 southPanel.add(logLevelPanel, gbc);
254 gbc.fill = GridBagConstraints.HORIZONTAL;
255 southPanel.add(clearButton, gbc);
259 gbc.fill = GridBagConstraints.NONE;
260 southPanel.add(copyToClipboardButton, gbc);
262 southPanel.setVisible(true);
263 frame.getContentPane().add(southPanel, BorderLayout.SOUTH);
264 frame.setVisible(visible);
265 updateConsole = visible;
266 frame.addWindowListener(this);
267 clearButton.addActionListener(this);
277 quit = false; // signals the Threads that they should exit
279 // Starting two seperate threads to read from the PipedInputStreams
281 reader = new Thread(this);
282 reader.setDaemon(true);
285 reader2 = new Thread(this);
286 reader2.setDaemon(true);
288 // and a thread to append text to the textarea
289 textAppender = new Thread(this);
290 textAppender.setDaemon(true);
291 textAppender.start();
294 frame.setIconImages(ChannelProperties.getIconList());
297 private void setChosenLogLevelCombo()
299 setChosenLogLevelCombo(startingLogLevel);
302 private void setChosenLogLevelCombo(LogLevel setLogLevel)
304 logLevelCombo.setSelectedItem(setLogLevel);
305 if (!logLevelCombo.getSelectedItem().equals(setLogLevel))
307 // setLogLevel not (yet) in list
308 if (setLogLevel != null && setLogLevel instanceof LogLevel)
310 // add new item to list (might be set via .jalview_properties)
311 boolean added = false;
312 for (int i = 0; i < logLevelCombo.getItemCount(); i++)
314 LogLevel l = (LogLevel) logLevelCombo.getItemAt(i);
315 if (l.compareTo(setLogLevel) >= 0)
317 logLevelCombo.insertItemAt(setLogLevel, i);
322 if (!added) // lower priority than others or some confusion -- add to
325 logLevelCombo.addItem(setLogLevel);
327 logLevelCombo.setSelectedItem(setLogLevel);
331 logLevelCombo.setSelectedItem(LogLevel.INFO);
336 private void copyConsoleTextToClipboard()
338 String consoleText = textArea.getText();
339 StringSelection consoleTextSelection = new StringSelection(consoleText);
340 Clipboard cb = Toolkit.getDefaultToolkit().getSystemClipboard();
341 cb.setContents(consoleTextSelection, null);
344 PipedOutputStream pout = null, perr = null;
346 public void redirectStreams()
352 pout = new PipedOutputStream(this.pin);
353 System.setOut(new PrintStream(pout, true));
354 } catch (java.io.IOException io)
356 textArea.append("Couldn't redirect STDOUT to this console\n"
358 io.printStackTrace(stderr);
359 } catch (SecurityException se)
361 textArea.append("Couldn't redirect STDOUT to this console\n"
363 se.printStackTrace(stderr);
368 perr = new PipedOutputStream(this.pin2);
369 System.setErr(new PrintStream(perr, true));
370 } catch (java.io.IOException io)
372 textArea.append("Couldn't redirect STDERR to this console\n"
374 io.printStackTrace(stderr);
375 } catch (SecurityException se)
377 textArea.append("Couldn't redirect STDERR to this console\n"
379 se.printStackTrace(stderr);
384 public void unredirectStreams()
390 System.setOut(stdout);
393 pin = new PipedInputStream();
395 } catch (java.io.IOException io)
397 textArea.append("Couldn't unredirect STDOUT to this console\n"
399 io.printStackTrace(stderr);
400 } catch (SecurityException se)
402 textArea.append("Couldn't unredirect STDOUT to this console\n"
404 se.printStackTrace(stderr);
409 System.setErr(stderr);
412 pin2 = new PipedInputStream();
414 } catch (java.io.IOException io)
416 textArea.append("Couldn't unredirect STDERR to this console\n"
418 io.printStackTrace(stderr);
419 } catch (SecurityException se)
421 textArea.append("Couldn't unredirect STDERR to this console\n"
423 se.printStackTrace(stderr);
431 // you may omit this part for your application
434 System.out.println("Hello World 2");
435 System.out.println("All fonts available to Graphic2D:\n");
436 GraphicsEnvironment ge = GraphicsEnvironment
437 .getLocalGraphicsEnvironment();
438 String[] fontNames = ge.getAvailableFontFamilyNames();
439 for (int n = 0; n < fontNames.length; n++)
441 System.out.println(fontNames[n]);
443 // Testing part: simple an error thrown anywhere in this JVM will be printed
445 // We do it with a seperate Thread becasue we don't wan't to break a Thread
446 // used by the Console.
447 System.out.println("\nLets throw an error on this console");
448 errorThrower = new Thread(this);
449 errorThrower.setDaemon(true);
450 errorThrower.start();
453 private JFrame initFrame(String string, int i, int j, int x, int y)
455 JFrame frame = new JFrame(string);
456 frame.setName(string);
465 frame.setBounds(x, y, i, j);
470 * attach a console to the desktop - the desktop will open it if requested.
474 public Console(Desktop desktop)
480 * attach a console to the desktop - the desktop will open it if requested.
483 * @param showjconsole
484 * - if true, then redirect stdout immediately
486 public Console(Desktop desktop, boolean showjconsole)
489 // window name - get x,y,width, height possibly scaled
490 Rectangle bounds = desktop.getLastKnownDimensions("JAVA_CONSOLE_");
494 ChannelProperties.getProperty("app_name") + " Java Console",
495 desktop.getWidth() / 2, desktop.getHeight() / 4,
496 desktop.getX(), desktop.getY());
501 ChannelProperties.getProperty("app_name") + " Java Console",
502 bounds.width, bounds.height, bounds.x, bounds.y);
504 frame.setMinimumSize(new Dimension(MIN_WIDTH, MIN_HEIGHT));
505 // desktop.add(frame);
507 LogLevel level = (LogLevel) logLevelCombo.getSelectedItem();
508 if (!Platform.isJS())
510 JalviewAppender jappender = new JalviewAppender(level);
511 JalviewAppender.setTextArea(textArea);
513 if (jalview.bin.Console.log != null && jalview.bin.Console.log instanceof JLoggerLog4j)
515 JLoggerLog4j.addAppender(jalview.bin.Console.log, jappender);
520 public synchronized void stopConsole()
525 * reader.notify(); reader2.notify(); if (errorThrower!=null)
526 * errorThrower.notify(); // stop all threads if (textAppender!=null)
527 * textAppender.notify();
535 } catch (Exception e)
542 } catch (Exception e)
547 textAppender.join(10);
548 } catch (Exception e)
552 if (!frame.isVisible())
560 public synchronized void windowClosed(WindowEvent evt)
562 frame.setVisible(false);
566 private void closeConsoleGui()
568 updateConsole = false;
576 parent.showConsole(false);
581 public synchronized void windowClosing(WindowEvent evt)
583 frame.setVisible(false); // default behaviour of JFrame
590 public synchronized void actionPerformed(ActionEvent evt)
593 // textArea.setText("");
597 public synchronized void run()
601 while (Thread.currentThread() == reader)
603 if (pin == null || pin.available() == 0)
608 if (pin.available() == 0)
612 } catch (InterruptedException ie)
617 while (pin.available() != 0)
619 String input = this.readLine(pin);
621 long time = System.nanoTime();
622 appendToTextArea(input);
623 // stderr.println("Time taken to stdout append:\t"
624 // + (System.nanoTime() - time) + " ns");
633 while (Thread.currentThread() == reader2)
635 if (pin2.available() == 0)
640 if (pin2.available() == 0)
644 } catch (InterruptedException ie)
648 while (pin2.available() != 0)
650 String input = this.readLine(pin2);
652 long time = System.nanoTime();
653 appendToTextArea(input);
654 // stderr.println("Time taken to stderr append:\t"
655 // + (System.nanoTime() - time) + " ns");
663 while (Thread.currentThread() == textAppender)
667 // check string buffer - if greater than console, clear console and
668 // replace with last segment of content, otherwise, append all to
671 while (displayPipe.length() > 0)
674 StringBuffer tmp = new StringBuffer(), replace;
675 synchronized (displayPipe)
677 replace = displayPipe;
680 // simply append whole buffer
681 textArea.append(replace.toString());
682 count += replace.length();
683 if (count > byteslim)
688 if (displayPipe.length() == 0)
693 if (displayPipe.length() == 0)
697 } catch (InterruptedException e)
707 } catch (InterruptedException e)
718 } catch (Exception e)
720 textArea.append("\nConsole reports an Internal error.");
721 textArea.append("The error is: " + e.getMessage());
722 // Need to uncomment this to ensure that line tally is synched.
725 "Console reports an Internal error.\nThe error is: " + e);
728 // just for testing (Throw a Nullpointer after 1 second)
729 if (Thread.currentThread() == errorThrower)
734 } catch (InterruptedException ie)
737 throw new NullPointerException(
738 MessageManager.getString("exception.application_test_npe"));
742 private void appendToTextArea(final String input)
744 if (updateConsole == false)
749 long time = System.nanoTime();
750 javax.swing.SwingUtilities.invokeLater(new Runnable()
755 displayPipe.append(input); // change to stringBuffer
756 // displayPipe.flush();
760 // stderr.println("Time taken to Spawnappend:\t" + (System.nanoTime() -
765 private String header = null;
767 private boolean updateConsole = false;
769 private synchronized void trimBuffer(boolean clear)
771 if (header == null && textArea.getLineCount() > 5)
775 header = textArea.getText(0, textArea.getLineStartOffset(5))
776 + "\nTruncated...\n";
777 } catch (Exception e)
783 int tlength = textArea.getDocument().getLength();
786 if (clear || (tlength > byteslim))
792 long time = System.nanoTime();
793 textArea.replaceRange(header, 0, tlength - bytescut);
794 // stderr.println("Time taken to cut:\t"
795 // + (System.nanoTime() - time) + " ns");
799 textArea.setText(header);
801 } catch (Exception e)
805 // lines = textArea.getLineCount();
811 public synchronized String readLine(PipedInputStream in)
818 int available = in.available();
823 byte b[] = new byte[available];
825 input = input + new String(b, 0, b.length);
826 // counts lines - we don't do this for speed.
827 // while ((lp = input.indexOf("\n", lp + 1)) > -1)
831 } while (!input.endsWith("\n") && !input.endsWith("\r\n") && !quit);
839 public static void main(String[] arg)
841 new Console().test(); // create console with not reference
845 public void setVisible(boolean selected)
847 frame.setVisible(selected);
848 if (selected == true)
850 setChosenLogLevelCombo();
852 updateConsole = true;
857 // reset log level to what it was before
858 if (jalview.bin.Console.log != null)
860 jalview.bin.Console.log.setLevel(startingLogLevel);
864 updateConsole = false;
868 public Rectangle getBounds()
872 return frame.getBounds();
878 * set the banner that appears at the top of the console output
882 public void setHeader(String string)
885 if (header.charAt(header.length() - 1) != '\n')
889 textArea.insert(header, 0);
897 public String getHeader()