📄 console.java
字号:
/* * 01/25/2003 - 14:02:55 * * Console.java - A console (emulates system terminal) * Copyright (C) 1999-2003 Romain Guy * romain.guy@jext.org * www.jext.org * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */package org.jext.console;import java.io.*;import java.net.*;import java.awt.*;import java.awt.event.*;import javax.swing.*;import javax.swing.text.Document;import javax.swing.text.StyleConstants;import javax.swing.text.SimpleAttributeSet;import javax.swing.text.BadLocationException;import org.jext.*;import org.jext.console.commands.*;import org.python.util.InteractiveInterpreter;import org.jext.scripting.python.Run;/** * An internal console which provide different kinds of * prompts and which allows to execute both internal and * external (OS specific) commands. The console is embedded * in a <code>JScrollPane</code> and handles it by itself. * @author Romain Guy */public class Console extends JScrollPane{ /** DOS prompt: /export/home/guy > */ public static final int DOS_PROMPT = 0; /** Jext prompt: Gfx@/export/home/guy > */ public static final int JEXT_PROMPT = 1; /** Linux prompt: guy@csdlyon$ */ public static final int LINUX_PROMPT = 2; /** SunOS prompt: csdlyon% */ public static final int SUNOS_PROMPT = 3; /** Default prompt types: DOS, Jext, Linux and SunOS **/ public static final String[] DEFAULT_PROMPTS = { "$p >", "$u@$p >", "$u@$h$$ ", "$h% " }; // current separators used in command lines //private static final String COMPLETION_SEPARATORS = " \t;:/\\\"\'"; private static final String COMPLETION_SEPARATORS = " \t;:\"\'"; // commands private Command currentCmd, firstCmd; // parent private JextFrame parent; // processes specific private ConsoleProcess cProcess; /**This parser is used as interpreter for the Jython mode*/ private InteractiveInterpreter parser; /**This buffer stores the incomplete Python command lines*/ private StringBuffer pythonBuf = new StringBuffer(); // private fields private String current; private Document outputDocument; private ConsoleTextPane textArea; private HistoryModel historyModel = new HistoryModel(25); /**This is the point from where starts the text the user can edit. The text * before was either output or (from the user but accepted with <Enter>)*/ private int userLimit = 0; /**This is where the user-typed text that hasn't still be accepted ends. If it's * before the document length, the user cannot type.*/ private int typingLocation = 0; /**If the command is taken from the history, this is its position inside it: * 0 for the last command, 1 for the one before and so on; if it's -1, the command * doesn't come from the history.*/ private int index = -1; // colors public Color errorColor = Color.red; public Color promptColor = Color.blue; public Color outputColor = Color.black; public Color infoColor = new Color(0, 165, 0); // prompt private boolean displayPath; private String prompt, hostName, oldPath = new String(); private String promptPattern = DEFAULT_PROMPTS[JEXT_PROMPT]; private boolean alwaysAllowType = false; private Command evalCom = null; /** * Instanciates a new console without displaying prompt. * @param parent <code>Jext</code> parent */ public Console(JextFrame parent) { this(parent, false); } /** * Creates a new console, embedding it in a <code>JScrollPane</code>. * By default console help is displayed. * @param parent <code>Jext</code> parent * @param display If set on true, prompt is displayed */ public Console(JextFrame parent, boolean display) { super(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); this.parent = parent; // load commands from previous sessions load(); textArea = new ConsoleTextPane(this); textArea.setFont(new Font("Monospaced", Font.PLAIN, 11)); outputDocument = textArea.getDocument(); append(Jext.getProperty("console.welcome"), infoColor, false, true); if (display) displayPrompt(); getViewport().setView(textArea); FontMetrics fm = getFontMetrics(textArea.getFont()); setPreferredSize(new Dimension(40 * fm.charWidth('m'), 6 * fm.getHeight())); setMinimumSize(getPreferredSize()); setMaximumSize(getPreferredSize()); setBorder(null); initCommands(); } /** * Returns this Console's parent. */ public JextFrame getParentFrame() { return parent; } /** * Return the <code>Document</code> in which output is performed. */ public Document getOutputDocument() { return outputDocument; } /** * Adds a command to the linked list of commands. */ public void addCommand(Command command) { if (command == null) return; currentCmd.next = command; currentCmd = command; } /** * Return true if command is built-in. If command is built-in, * it is also executed. * @param command Command to check and execute */ private boolean builtInCommand(String command) { boolean ret = false; Command _currentCmd = firstCmd; while (_currentCmd != null) { if (_currentCmd.handleCommand(this, command)) { ret = true; break; } _currentCmd = _currentCmd.next; } return ret; } // inits commands list private void initCommands() { firstCmd = currentCmd = new ClearCommand(); addCommand(new JythonCommand()); addCommand(new ChangeDirCommand()); addCommand(new ExitCommand()); addCommand(new FileCommand()); addCommand(new HomeCommand()); addCommand(new HttpCommand()); addCommand(new HelpCommand()); addCommand(new ListCommand()); addCommand(new PwdCommand()); addCommand(new RunCommand()); addCommand(evalCom = new EvalCommand()); } /** * Set console background color. * @param color <code>Color</code> to be used */ public void setBgColor(Color color) { textArea.setBackground(color); } /** * Set console error color. * @param color <code>Color</code> to be used */ public void setErrorColor(Color color) { errorColor = color; } /** * Set console prompt color. * @param color <code>Color</code> to be used */ public void setPromptColor(Color color) { promptColor = color; } /** * Set console output color. * @param color <code>Color</code> to be used */ public void setOutputColor(Color color) { outputColor = color; textArea.setForeground(color); textArea.setCaretColor(color); } /** * Set console info color. * @param color <code>Color</code> to be used */ public void setInfoColor(Color color) { infoColor = color; } /** * Set console selection color. * @param color <code>Color</code> to be used */ public void setSelectionColor(Color color) { textArea.setSelectionColor(color); } /** * Save the history. */ public void save() { for (int i = 0; i < historyModel.getSize(); i++) Jext.setProperty("console.history." + i, historyModel.getItem(i)); } /** * Load the last saved history. */ public void load() { String s; for (int i = 24 ; i >= 0; i--) { s = Jext.getProperty("console.history." + i); if (s != null) historyModel.addItem(s); } } /** * Set the prompt pattern. * @param type The prompt pattern */ public void setPromptPattern(String prompt) { if (prompt == null) return; promptPattern = prompt; displayPath = false; buildPrompt(); } /** * Get prompt pattern. */ public String getPromptPattern() { return promptPattern; } /** * Displays the prompt according to the current selected * prompt type. */ public void displayPrompt() { if (prompt == null || displayPath) buildPrompt(); if (Jext.getBooleanProperty("console.jythonMode")) //append('\n' + "[python] " + prompt, promptColor); append("[python] " + prompt, promptColor); else //append('\n' + prompt, promptColor); append(prompt, promptColor); typingLocation = userLimit = outputDocument.getLength(); } // builds the prompt according to the prompt pattern private void buildPrompt() { if (displayPath && oldPath.equals(System.getProperty("user.dir"))) return; displayPath = false; StringBuffer buf = new StringBuffer(); if (hostName == null) { try { hostName = InetAddress.getLocalHost().getHostName(); } catch (UnknownHostException uhe) { } } for (int i = 0; i < promptPattern.length(); i++) { char c = promptPattern.charAt(i); switch(c) { case '$': if (i == promptPattern.length() - 1) buf.append(c); else { switch (promptPattern.charAt(++i)) { case 'p': // current path buf.append(oldPath = System.getProperty("user.dir")); displayPath = true; break; case 'u': // user name buf.append(System.getProperty("user.name")); break; case 'h': // host name buf.append(hostName); break; case '$': buf.append('$'); break; } } break; default: buf.append(c); } } prompt = buf.toString(); } private class Appender implements Runnable { private String text; private Color color; private boolean italic, bold; Appender(String _text, Color _color, boolean _italic, boolean _bold) { text = _text; color = _color; italic = _italic; bold = _bold; } public void run() { SimpleAttributeSet style = new SimpleAttributeSet(); if (color != null) style.addAttribute(StyleConstants.Foreground, color); StyleConstants.setBold(style, bold); StyleConstants.setItalic(style, italic); try { outputDocument.insertString(outputDocument.getLength(), text, style); } catch(BadLocationException bl) { } textArea.setCaretPosition(outputDocument.getLength()); } } /** * This method appends text in the text area. * @param text The text to append * @param color The color of the text * @param italic Set to true will append italic text * @param bold Set to true will append bold text */ private void append(String text, Color color, boolean italic, boolean bold) { Runnable appender = new Appender(text, color, italic, bold); if (SwingUtilities.isEventDispatchThread()) { appender.run(); } else { SwingUtilities.invokeLater(appender); } } /** * This method appends text in the text area. * @param text The text to append in the text area * @apram color The color of the text to append */ public void append(String text, Color color) { append(text, color, false, false); } /** * Adds a command to the history. * @param command Command to add in the history */ public void addHistory(String command) { historyModel.addItem(command); index = -1; } /** * Remove a char from current command line. * Stands for BACKSPACE action. */
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -