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.JButton;
46 import javax.swing.JComboBox;
47 import javax.swing.JFrame;
48 import javax.swing.JLabel;
49 import javax.swing.JPanel;
50 import javax.swing.JScrollPane;
51 import javax.swing.JTextArea;
53 import org.apache.log4j.Level;
54 import org.apache.log4j.SimpleLayout;
56 import jalview.bin.Cache;
57 import jalview.util.MessageManager;
60 * Simple Jalview Java Console. Version 1 - allows viewing of console output
61 * after desktop is created. Acquired with thanks from RJHM's site
62 * http://www.comweb.nl/java/Console/Console.html A simple Java Console for your
63 * application (Swing version) Requires Java 1.1.5 or higher Disclaimer the use
64 * of this source is at your own risk. Permision to use and distribute into your
65 * own applications RJHM van den Bergh , rvdb@comweb.nl
68 public class Console extends WindowAdapter
69 implements WindowListener, ActionListener, Runnable
73 private JTextArea textArea;
76 * unused - tally and limit for lines in console window int lines = 0;
80 int byteslim = 102400, bytescut = 76800; // 100k and 75k cut point.
82 private Thread reader, reader2, textAppender;
86 private final PrintStream stdout = System.out, stderr = System.err;
88 private PipedInputStream pin = new PipedInputStream();
90 private PipedInputStream pin2 = new PipedInputStream();
92 private StringBuffer displayPipe = new StringBuffer();
94 Thread errorThrower; // just for testing (Throws an Exception at this Console
96 // are we attached to some parent Desktop
97 Desktop parent = null;
99 private int MIN_WIDTH = 300;
101 private int MIN_HEIGHT = 250;
103 private JComboBox logLevelCombo = new JComboBox();
107 // create all components and add them
108 Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
109 frame = initFrame("Java Console", screenSize.width / 2,
110 screenSize.height / 2, -1, -1);
114 private void initConsole(boolean visible)
116 initConsole(visible, true);
126 private void initConsole(boolean visible, boolean redirect)
128 // CutAndPasteTransfer cpt = new CutAndPasteTransfer();
129 // textArea = cpt.getTextArea();
130 textArea = new JTextArea();
131 textArea.setEditable(false);
132 JButton clearButton = new JButton(
133 MessageManager.getString("action.clear"));
134 JButton copyToClipboardButton = new JButton(
135 MessageManager.getString("label.copy_to_clipboard"));
136 copyToClipboardButton.addActionListener(new ActionListener()
138 public void actionPerformed(ActionEvent e)
140 copyConsoleTextToClipboard();
143 copyToClipboardButton.addMouseListener(new MouseAdapter()
145 private Color bg = textArea.getBackground();
147 public void mousePressed(MouseEvent e)
149 textArea.setBackground(textArea.getSelectionColor());
152 public void mouseReleased(MouseEvent e)
154 textArea.setBackground(bg);
158 copyToClipboardButton.setToolTipText(
159 MessageManager.getString("label.copy_to_clipboard_tooltip"));
161 JLabel logLevelLabel = new JLabel(
162 MessageManager.getString("label.log_level") + ":");
164 // logLevelCombo.addItem(Level.ALL);
165 logLevelCombo.addItem(Level.TRACE);
166 logLevelCombo.addItem(Level.DEBUG);
167 logLevelCombo.addItem(Level.INFO);
168 logLevelCombo.addItem(Level.WARN);
169 // logLevelCombo.addItem(Level.ERROR);
170 // logLevelCombo.addItem(Level.FATAL);
171 // logLevelCombo.addItem(Level.OFF);
172 setChosenLogLevelCombo();
173 logLevelCombo.addActionListener(new ActionListener()
175 public void actionPerformed(ActionEvent e)
177 if (Cache.log != null)
179 Cache.log.setLevel((Level) logLevelCombo.getSelectedItem());
186 frame.getContentPane().setLayout(new BorderLayout());
187 frame.getContentPane().add(new JScrollPane(textArea),
188 BorderLayout.CENTER);
189 JPanel southPanel = new JPanel();
190 southPanel.setLayout(new GridBagLayout());
192 JPanel logLevelPanel = new JPanel();
193 logLevelPanel.setAlignmentX(JPanel.LEFT_ALIGNMENT);
194 logLevelPanel.add(logLevelLabel);
195 logLevelPanel.add(logLevelCombo);
196 logLevelLabel.setToolTipText(
197 MessageManager.getString("label.log_level_tooltip"));
198 logLevelCombo.setToolTipText(
199 MessageManager.getString("label.log_level_tooltip"));
201 GridBagConstraints gbc = new GridBagConstraints();
207 southPanel.add(logLevelPanel, gbc);
211 gbc.fill = GridBagConstraints.HORIZONTAL;
212 southPanel.add(clearButton, gbc);
216 gbc.fill = GridBagConstraints.NONE;
217 southPanel.add(copyToClipboardButton, gbc);
219 southPanel.setVisible(true);
220 frame.getContentPane().add(southPanel, BorderLayout.SOUTH);
221 frame.setVisible(visible);
222 updateConsole = visible;
223 frame.addWindowListener(this);
224 clearButton.addActionListener(this);
234 quit = false; // signals the Threads that they should exit
236 // Starting two seperate threads to read from the PipedInputStreams
238 reader = new Thread(this);
239 reader.setDaemon(true);
242 reader2 = new Thread(this);
243 reader2.setDaemon(true);
245 // and a thread to append text to the textarea
246 textAppender = new Thread(this);
247 textAppender.setDaemon(true);
248 textAppender.start();
251 private void setChosenLogLevelCombo()
253 Level currentLogLevel = Cache.log == null ? Level.INFO
254 : Cache.log.getLevel();
255 logLevelCombo.setSelectedItem(currentLogLevel);
256 if (!logLevelCombo.getSelectedItem().equals(currentLogLevel)) // currentLogLevel
259 if (currentLogLevel != null && currentLogLevel instanceof Level)
261 // add new item to list (might be set via .jalview_properties)
262 boolean added = false;
263 for (int i = 0; i < logLevelCombo.getItemCount(); i++)
265 Level l = (Level) logLevelCombo.getItemAt(i);
266 if (l.isGreaterOrEqual(currentLogLevel))
268 logLevelCombo.insertItemAt(currentLogLevel, i);
273 if (!added) // lower priority than others or some confusion -- add to
276 logLevelCombo.addItem(currentLogLevel);
278 logLevelCombo.setSelectedItem(currentLogLevel);
282 logLevelCombo.setSelectedItem(Level.INFO);
287 private void copyConsoleTextToClipboard()
289 String consoleText = textArea.getText();
290 StringSelection consoleTextSelection = new StringSelection(consoleText);
291 Clipboard cb = Toolkit.getDefaultToolkit().getSystemClipboard();
292 cb.setContents(consoleTextSelection, null);
295 PipedOutputStream pout = null, perr = null;
297 public void redirectStreams()
303 pout = new PipedOutputStream(this.pin);
304 System.setOut(new PrintStream(pout, true));
305 } catch (java.io.IOException io)
307 textArea.append("Couldn't redirect STDOUT to this console\n"
309 io.printStackTrace(stderr);
310 } catch (SecurityException se)
312 textArea.append("Couldn't redirect STDOUT to this console\n"
314 se.printStackTrace(stderr);
319 perr = new PipedOutputStream(this.pin2);
320 System.setErr(new PrintStream(perr, true));
321 } catch (java.io.IOException io)
323 textArea.append("Couldn't redirect STDERR to this console\n"
325 io.printStackTrace(stderr);
326 } catch (SecurityException se)
328 textArea.append("Couldn't redirect STDERR to this console\n"
330 se.printStackTrace(stderr);
335 public void unredirectStreams()
341 System.setOut(stdout);
344 pin = new PipedInputStream();
346 } catch (java.io.IOException io)
348 textArea.append("Couldn't unredirect STDOUT to this console\n"
350 io.printStackTrace(stderr);
351 } catch (SecurityException se)
353 textArea.append("Couldn't unredirect STDOUT to this console\n"
355 se.printStackTrace(stderr);
360 System.setErr(stderr);
363 pin2 = new PipedInputStream();
365 } catch (java.io.IOException io)
367 textArea.append("Couldn't unredirect STDERR to this console\n"
369 io.printStackTrace(stderr);
370 } catch (SecurityException se)
372 textArea.append("Couldn't unredirect STDERR to this console\n"
374 se.printStackTrace(stderr);
382 // you may omit this part for your application
385 System.out.println("Hello World 2");
386 System.out.println("All fonts available to Graphic2D:\n");
387 GraphicsEnvironment ge = GraphicsEnvironment
388 .getLocalGraphicsEnvironment();
389 String[] fontNames = ge.getAvailableFontFamilyNames();
390 for (int n = 0; n < fontNames.length; n++)
392 System.out.println(fontNames[n]);
394 // Testing part: simple an error thrown anywhere in this JVM will be printed
396 // We do it with a seperate Thread becasue we don't wan't to break a Thread
397 // used by the Console.
398 System.out.println("\nLets throw an error on this console");
399 errorThrower = new Thread(this);
400 errorThrower.setDaemon(true);
401 errorThrower.start();
404 private JFrame initFrame(String string, int i, int j, int x, int y)
406 JFrame frame = new JFrame(string);
407 frame.setName(string);
416 frame.setBounds(x, y, i, j);
421 * attach a console to the desktop - the desktop will open it if requested.
425 public Console(Desktop desktop)
431 * attach a console to the desktop - the desktop will open it if requested.
434 * @param showjconsole
435 * - if true, then redirect stdout immediately
437 public Console(Desktop desktop, boolean showjconsole)
440 // window name - get x,y,width, height possibly scaled
441 Rectangle bounds = desktop.getLastKnownDimensions("JAVA_CONSOLE_");
444 frame = initFrame("Jalview Java Console", desktop.getWidth() / 2,
445 desktop.getHeight() / 4, desktop.getX(), desktop.getY());
449 frame = initFrame("Jalview Java Console", bounds.width, bounds.height,
452 frame.setMinimumSize(new Dimension(MIN_WIDTH, MIN_HEIGHT));
453 // desktop.add(frame);
455 JalviewAppender jappender = new JalviewAppender();
456 jappender.setLayout(new SimpleLayout());
457 JalviewAppender.setTextArea(textArea);
458 org.apache.log4j.Logger.getRootLogger().addAppender(jappender);
461 public synchronized void stopConsole()
466 * reader.notify(); reader2.notify(); if (errorThrower!=null)
467 * errorThrower.notify(); // stop all threads if (textAppender!=null)
468 * textAppender.notify();
476 } catch (Exception e)
483 } catch (Exception e)
488 textAppender.join(10);
489 } catch (Exception e)
493 if (!frame.isVisible())
501 public synchronized void windowClosed(WindowEvent evt)
503 frame.setVisible(false);
507 private void closeConsoleGui()
509 updateConsole = false;
517 parent.showConsole(false);
522 public synchronized void windowClosing(WindowEvent evt)
524 frame.setVisible(false); // default behaviour of JFrame
531 public synchronized void actionPerformed(ActionEvent evt)
534 // textArea.setText("");
538 public synchronized void run()
542 while (Thread.currentThread() == reader)
544 if (pin == null || pin.available() == 0)
549 if (pin.available() == 0)
553 } catch (InterruptedException ie)
558 while (pin.available() != 0)
560 String input = this.readLine(pin);
562 long time = System.nanoTime();
563 appendToTextArea(input);
564 // stderr.println("Time taken to stdout append:\t"
565 // + (System.nanoTime() - time) + " ns");
574 while (Thread.currentThread() == reader2)
576 if (pin2.available() == 0)
581 if (pin2.available() == 0)
585 } catch (InterruptedException ie)
589 while (pin2.available() != 0)
591 String input = this.readLine(pin2);
593 long time = System.nanoTime();
594 appendToTextArea(input);
595 // stderr.println("Time taken to stderr append:\t"
596 // + (System.nanoTime() - time) + " ns");
604 while (Thread.currentThread() == textAppender)
608 // check string buffer - if greater than console, clear console and
609 // replace with last segment of content, otherwise, append all to
612 while (displayPipe.length() > 0)
615 StringBuffer tmp = new StringBuffer(), replace;
616 synchronized (displayPipe)
618 replace = displayPipe;
621 // simply append whole buffer
622 textArea.append(replace.toString());
623 count += replace.length();
624 if (count > byteslim)
629 if (displayPipe.length() == 0)
634 if (displayPipe.length() == 0)
638 } catch (InterruptedException e)
648 } catch (InterruptedException e)
659 } catch (Exception e)
661 textArea.append("\nConsole reports an Internal error.");
662 textArea.append("The error is: " + e.getMessage());
663 // Need to uncomment this to ensure that line tally is synched.
666 "Console reports an Internal error.\nThe error is: " + e);
669 // just for testing (Throw a Nullpointer after 1 second)
670 if (Thread.currentThread() == errorThrower)
675 } catch (InterruptedException ie)
678 throw new NullPointerException(
679 MessageManager.getString("exception.application_test_npe"));
683 private void appendToTextArea(final String input)
685 if (updateConsole == false)
690 long time = System.nanoTime();
691 javax.swing.SwingUtilities.invokeLater(new Runnable()
696 displayPipe.append(input); // change to stringBuffer
697 // displayPipe.flush();
701 // stderr.println("Time taken to Spawnappend:\t" + (System.nanoTime() -
706 private String header = null;
708 private boolean updateConsole = false;
710 private synchronized void trimBuffer(boolean clear)
712 if (header == null && textArea.getLineCount() > 5)
716 header = textArea.getText(0, textArea.getLineStartOffset(5))
717 + "\nTruncated...\n";
718 } catch (Exception e)
724 int tlength = textArea.getDocument().getLength();
727 if (clear || (tlength > byteslim))
733 long time = System.nanoTime();
734 textArea.replaceRange(header, 0, tlength - bytescut);
735 // stderr.println("Time taken to cut:\t"
736 // + (System.nanoTime() - time) + " ns");
740 textArea.setText(header);
742 } catch (Exception e)
746 // lines = textArea.getLineCount();
752 public synchronized String readLine(PipedInputStream in)
759 int available = in.available();
764 byte b[] = new byte[available];
766 input = input + new String(b, 0, b.length);
767 // counts lines - we don't do this for speed.
768 // while ((lp = input.indexOf("\n", lp + 1)) > -1)
772 } while (!input.endsWith("\n") && !input.endsWith("\r\n") && !quit);
780 public static void main(String[] arg)
782 new Console().test(); // create console with not reference
786 public void setVisible(boolean selected)
788 frame.setVisible(selected);
789 if (selected == true)
791 setChosenLogLevelCombo();
793 updateConsole = true;
798 // reset log level to user preference
799 if (Cache.log != null)
801 String userLogLevel = Cache.getDefault("logs.Jalview.level",
802 Level.INFO.toString());
803 Cache.log.setLevel(Level.toLevel(userLogLevel));
807 updateConsole = false;
811 public Rectangle getBounds()
815 return frame.getBounds();
821 * set the banner that appears at the top of the console output
825 public void setHeader(String string)
828 if (header.charAt(header.length() - 1) != '\n')
832 textArea.insert(header, 0);
840 public String getHeader()