001 /* $Id: ProcessIOPane.java 12 2007-07-27 09:48:53Z ringler $
002 * This class is part of the de.mospace.swing library.
003 * Copyright (C) 2005-2006 Moritz Ringler
004 *
005 * This program is free software; you can redistribute it and/or
006 * modify it under the terms of the GNU General Public License
007 * as published by the Free Software Foundation; either version 2
008 * of the License, or (at your option) any later version.
009 *
010 * This program is distributed in the hope that it will be useful,
011 * but WITHOUT ANY WARRANTY; without even the implied warranty of
012 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
013 * GNU General Public License for more details.
014 *
015 * You should have received a copy of the GNU General Public License
016 * along with this program; if not, write to the Free Software
017 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
018 */
019 package de.mospace.swing;
020
021 import java.awt.Font;
022 import java.awt.event.ActionEvent;
023 import java.awt.event.ActionListener;
024 import java.io.File;
025 import java.io.OutputStream;
026 import java.io.PrintStream;
027 import java.util.prefs.Preferences;
028 import javax.swing.AbstractAction;
029 import javax.swing.Action;
030 import javax.swing.JOptionPane;
031 import javax.swing.KeyStroke;
032 import javax.swing.event.ChangeEvent;
033 import javax.swing.event.ChangeListener;
034 import de.mospace.lang.ExceptionHandler;
035 import de.mospace.lang.ProcessRunnable;
036 import de.mospace.lang.RunnableQueue;
037 import de.mospace.swing.text.DocumentOutputStream;
038
039 /** A JComponent that provides a command line system shell. System processes
040 * are started by entering commands in the input field of this IOPane.
041 * Error and output streams of the system processes thus started are redirected
042 * to the output area of this IOPane. The commands are executed
043 * one after the other unless they end with an '&' character.
044 * ProcessIOPanes have a command line history but otherwise dispose of
045 * only very limited built-in capabilities ('cd' and 'clear',
046 * process interruption with CTRL-C, no I/O redirection). Run your
047 * operating system shell (e.g. bash) inside the ProcessIOPane if you need a
048 * fully-featured shell.
049 *
050 * @version $Revision: 12 $ ($Date: 2007-07-27 11:48:53 +0200 (Fr, 27 Jul 2007) $)
051 * @author Moritz Ringler
052 **/
053 public class ProcessIOPane extends IOPane{
054 //private boolean closeWhenDone = false;
055 private File pwd;
056 private final RunnableQueue myProcesses = new RunnableQueue();
057 private final OutputStream iopOut = new DocumentOutputStream(getDocument());
058 private static String systemShell = "";
059
060 private final ExceptionHandler printExceptionHandler = new ExceptionHandler(){
061 public void handleException(Throwable ex){
062 (new PrintStream(iopOut)).print(ex.getLocalizedMessage().trim()+"\n");
063 }
064 };
065 private final Action interruptAction = new AbstractAction(
066 GLOBALS.getString("Interrupt")){
067 public void actionPerformed(ActionEvent e){
068 interrupt();
069 }
070 };
071
072 private final Action clearAction = new AbstractAction(GLOBALS.getString("Clear")){
073 public void actionPerformed(ActionEvent e){
074 getOutputArea().setText("");
075 }
076 };
077
078 private final Action systemShellAction = new AbstractAction(GLOBALS.getString("System shell")){
079 public void actionPerformed(ActionEvent e){
080 if (systemShell == null || systemShell.equals("")){
081 setSystemShell(querySystemShell());
082 }
083 if (systemShell != null && !systemShell.equals("")){
084 execute(systemShell);
085 }
086 }
087 };
088
089 public void setSystemShell(String command){
090 systemShell = command;
091 getPref().put("systemShell", (command == null)? "" : command);
092 }
093
094 public String getSystemShell(){
095 return systemShell;
096 }
097
098 public String querySystemShell(){
099 return (String) JOptionPane.showInputDialog(
100 ProcessIOPane.this,
101 "Enter system shell command",
102 (systemShell == null || systemShell.equals(""))
103 ? guessSystemShell()
104 : systemShell
105 );
106 }
107
108 public static String guessSystemShell(){
109 String os = System.getProperty("os.name");
110 boolean isWindows = os.startsWith("Windows");
111 boolean isJava14 =
112 System.getProperty("java.version").equals("1.4") ||
113 System.getProperty("java.version").startsWith("1.4.");
114 String result = (isWindows)
115 ? "cmd.exe /Q"
116 : "bash";
117 if(!isJava14){ //getenv does not work in java14
118 if(isWindows){
119 try{
120 String comspec = System.getenv("COMSPEC");
121 if(comspec != null){
122 if(comspec.endsWith("command.com")){ /* command.com */
123 result = comspec;
124 } else if(comspec.endsWith("cmd.exe")){ /* use cmd.exe */
125 result = comspec + " /Q"; /* disable command echo */
126 }
127 }
128 } catch (Throwable ignore){
129 /* System.getEnv raises a java.lang.Error in Sun Java 1.4 */
130 }
131 } else {
132 /* assume we're using a unix flavour */
133 try {
134 /* look for SHELL environment variable */
135 String shell = System.getenv("SHELL");
136 if(shell != null){
137 result = shell;
138 }
139 } catch (Throwable ignore){
140 /* System.getEnv raises a java.lang.Error in Sun Java 1.4 */
141 }
142 }
143 if(result != null && result.endsWith("bash")){
144 result += " -l";
145 }
146 }
147 return result;
148 }
149
150 /** Returns the control actions for this ProcessIOPane.
151 * The first element in the returned array calls {@link #interrupt}
152 * in the body of its acionPerformed method. The second element
153 * removes all output from the output area of this IOPane.
154 **/
155 public Action[] getControlActions(){
156 return new Action[]{ interruptAction, clearAction};
157 }
158
159 public Action getSystemShellAction(){
160 return systemShellAction;
161 }
162
163 /**
164 * Creates a new ProcessIOPane.
165 *
166 * @param rows number of text rows >= 0
167 * @param cols number of text columns >= 0 in a row
168 * @throws IllegalArgumentException if the rows or columns arguments are negative.
169 */
170 public ProcessIOPane(int rows, int cols){
171 super(rows, cols);
172 init();
173 }
174
175 // static public void main(String[] argv){
176 // SwingUtilities.invokeLater(new Runnable(){
177 // public void run(){
178 // ProcessIOPane.test();
179 // }
180 // });
181 // }
182 //
183 // static private void test(){
184 // final ProcessIOPane iop = new ProcessIOPane(50,50);
185 // JFrame f = new JFrame(){
186 // /**Overridden so we can exit when window is closed*/
187 // protected void processWindowEvent(WindowEvent e) {
188 // super.processWindowEvent(e);
189 // if (e.getID() == WindowEvent.WINDOW_CLOSING) {
190 // iop.interrupt();
191 // System.exit(0);
192 // }
193 // }
194 // };
195 // f.getContentPane().add(iop);
196 // f.pack();
197 // f.setVisible(true);
198 // ProcessRunnable test = new ProcessRunnable("cat C:\\test.txt");
199 // iop.enqueue(test);
200 // }
201
202 /** Returns the RunnableQueue in which this ProcessIOPane stores jobs
203 * awaiting execution. Jobs that you enqueue directly to the returned
204 * RunnableQueue will not have their output and error streams redirected
205 * to this IOPane by default.
206 * @return the RunnableQueue assiociated with this ProcessIOPane
207 * @see #enqueue
208 **/
209 public RunnableQueue getRunnableQueue(){
210 return myProcesses;
211 }
212
213 /** Enqueues and executes the specified job as if it had been
214 * started from the input field of this ProcessIOPane.
215 * Jobs that you enqueue with this method will
216 * have their output and error streams redirected to
217 * and will get input from this IOPane.
218 * If <code> command.getWorkingDirectory() == null </code>
219 * the working directory of the command will be set to the working directory
220 * of this ProcessIOPane.
221 * @param command the job to enqueue and execute
222 * @see #getRunnableQueue
223 * @see RunnableQueue#enqueue
224 **/
225 public void enqueue(ProcessRunnable command){
226 if(pwd != null && command.getWorkingDirectory() == null){
227 command.setWorkingDirectory(pwd);
228 }
229 command.redirectOutputTo(iopOut);
230 command.redirectErrorsTo(iopOut);
231 myProcesses.enqueue(command);
232 if(!myProcesses.isRunning()){
233 myProcesses.start();
234 }
235 }
236
237 /** Runs the specified job in the calling thread.
238 * Jobs that you run with this method will
239 * have their output and error streams redirected to this IOPane.
240 * They will not be able to accept input from this IOPane.
241 **/
242 public void runInCallerThread(ProcessRunnable command){
243 command.redirectOutputTo(iopOut);
244 command.redirectErrorsTo(iopOut);
245 command.setWorkingDirectory(pwd);
246 try{
247 command.run();
248 } catch (Exception ex){
249 printExceptionHandler.handleException(ex);
250 }
251 }
252
253 /** Sets the working directory of new processes started from this
254 * IOPane. The working directory can be set interactively by using
255 * the 'cd' built-in.
256 */
257 public void setWorkingDirectory(String path){
258 final String ppath =
259 (path == null || path.length() == 0)
260 ? "."
261 : path;
262 try{
263 File newPwd = new File(ppath);
264 if (pwd != null && !newPwd.isAbsolute()){
265 newPwd = new File(pwd, ppath);
266 }
267 if(newPwd.isDirectory()){
268 pwd = newPwd.getCanonicalFile();
269 } else {
270 append("Argument to cd must be a directory.\n");
271 setWorkingDirectory(".");
272 }
273 } catch (Exception ex){
274 printExceptionHandler.handleException(ex);
275 }
276 }
277
278 public String getWorkingDirectory(){
279 return (pwd == null)? null : pwd.toString();
280 }
281
282 /** returns a new OutputStream that writes to the output area */
283 public OutputStream getOutputStream(){
284 return new DocumentOutputStream(getDocument());
285 }
286
287 private void execute(String command){
288 if(command == null){
289 return;
290 }
291 String strim = command.trim();
292
293 if (myProcesses.isRunning()){ /* forward input to currently running process */
294 try{
295 String s = command.endsWith("\n")
296 ? command
297 : command+"\n";
298 myProcesses.handleInput(s);
299 } catch (Exception ex){
300 ex.printStackTrace(new PrintStream(iopOut));
301 }
302
303 } else if (strim.length() == 0 || builtin(strim)){
304 /* do nothing for empty command
305 * execute builtins */
306 } else if (strim.endsWith("&")){ /* new background process */
307 strim = strim.substring(0,strim.length()-1).trim();
308 runInBackground(new ProcessRunnable(strim));
309
310 } else { /* new foreground process */
311 enqueue(new ProcessRunnable(strim));
312 }
313 }
314
315 /** Checks whether <code>s</code> is a built-in command and if so
316 * executes it.
317 **/
318 protected boolean builtin(String s){
319 boolean result = true;
320 if ("clear".equals(s)){ /* clear textarea */
321 clearAction.actionPerformed(null);
322
323 } else if (s.matches("^cd(\\s.+)?")){ /* change working directory */
324 String path = s.substring(2).trim();
325 setWorkingDirectory(path);
326 append(GLOBALS.getString("Working directory is ")+pwd.toString()+"\n");
327 } else {
328 result = false;
329 }
330 return result;
331 }
332
333 protected Preferences getPref(){
334 return Preferences.userNodeForPackage(ProcessIOPane.class);
335 }
336
337 private void init(){
338 systemShell = getPref().get("systemShell","");
339 removeActionListener(echoAL);
340 addActionListener(new ActionListener(){
341 public void actionPerformed(ActionEvent e){
342 execute(e.getActionCommand());
343 }
344 });
345 addActionListener(echoAL);
346 myProcesses.registerExceptionHandler(printExceptionHandler);
347 myProcesses.addChangeListener(new ChangeListener(){
348 public void stateChanged(ChangeEvent e){
349 prependPrompt = !myProcesses.isRunning();
350 }
351 });
352 getInput().getInputMap().put(KeyStroke.getKeyStroke("ctrl C"),"ir");
353 getInput().getActionMap().put("ir", interruptAction);
354 getOutputArea().setFont(new Font("Monospaced",Font.PLAIN,12));
355 }
356
357 private void runInBackground(final ProcessRunnable command){
358 (new Thread(){
359 public void run(){
360 runInCallerThread(command);
361 }
362 }).start();
363 }
364
365 /** Interrupts the currently running process and deletes all jobs
366 * awaiting execution. **/
367 public void interrupt(){
368 myProcesses.stop();
369 append("[kill]\n");
370 }
371 }