Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Merge branch 'ivank-fixes':

  * On startup, focus is now inside the REPL
  * New shortcut ctrl-c stops the REPL thread
  * New shortcut ctrl-d closes the REPL window
  * Fixed shortcut shift-Home
  * *print-length* and *print-level* are set by default to avoid runaway output
  * Debug REPL now supports Clojure 1.4.0
  * New option :font controls the font used
  * New option :init sets the init function run on startup in the REPL thread
  * New option :prompt sets the function that prints the REPL prompt
  * New option :eval controls the eval function
  * REPL window is now 972px wide by default
  • Loading branch information...
commit 57533f31a11cb9e9e9a447cdbd321e81b14b7f9b 2 parents 98db171 + 4c1fbed
@ivan ivan authored
View
3  .gitignore
@@ -1,4 +1,5 @@
pom.xml
*jar
lib
-classes
+classes
+*.class
View
4 project.clj
@@ -1,10 +1,10 @@
-(defproject swingrepl "1.3.0"
+(defproject swingrepl "1.4.0-SNAPSHOT"
:source-path "src/clj"
:java-source-path "src/jvm"
:java-fork "true"
:javac-debug "true"
:description "A Swing Clojure REPL using BeanShell's JConsole"
- :dependencies [[org.clojure/clojure "1.3.0-alpha2"]]
+ :dependencies [[org.clojure/clojure "1.3.0"]]
:dev-dependencies [[lein-javac "1.2.1-SNAPSHOT"]
[swank-clojure "1.3.0-SNAPSHOT"]]
:hooks [leiningen.hooks.javac]
View
112 src/clj/org/dipert/swingrepl/main.clj
@@ -1,7 +1,9 @@
(ns org.dipert.swingrepl.main
"Swing Clojure REPL using BeanShell's JConsole"
- (:require clojure.main)
+ (:require clojure.main clojure.repl)
(:import (javax.swing JFrame)
+ (java.awt.event WindowEvent)
+ (java.awt Font)
(bsh.util JConsole))
(:gen-class))
@@ -10,42 +12,66 @@
clj-version
(apply str (interpose \. (map *clojure-version* [:major :minor :incremental]))))
-(def ^{:doc "Default REPL display options"
+(defn- set-safe-printing! []
+ (set! *print-level* 15)
+ (set! *print-length* 103))
+
+(def ^{:doc "Default REPL options"
:private false}
default-opts
- {:width 600
+ {:width 972
:height 400
- :title (str "Clojure " clj-version)
+ :font (Font. "Monospaced" Font/PLAIN 14)
+ :title (str "Clojure " clj-version " REPL")
+ :prompt #(print "user=> ")
+ :init set-safe-printing!
+ :eval eval
:on-close JFrame/DISPOSE_ON_CLOSE})
+(def ^{:doc "Default debug REPL options"
+ :private false}
+ default-dbg-opts
+ {:title (str "Clojure " clj-version " Debug REPL")
+ :prompt #(print "dr => ")
+ :eval (comment "See make-dbg-repl-jframe")})
+
+(defn- make-repl-thread [console & repl-args]
+ (binding [*out* (.getOut console)
+ *in* (clojure.lang.LineNumberingPushbackReader. (.getIn console))
+ *err* (.getOut console)]
+ (Thread. (bound-fn []
+ (apply clojure.main/repl repl-args)))))
+
+(defn- window-closing-dispatcher [window]
+ #(.dispatchEvent window (WindowEvent. window WindowEvent/WINDOW_CLOSING)))
+
(defn make-repl-jframe
"Displays a JFrame with JConsole and attached REPL."
([] (make-repl-jframe {}))
([optmap]
- (let [options (merge default-opts optmap)
- {:keys [title width height on-close]} options
- jframe (doto (JFrame. title)
- (.setSize width height)
- (.setDefaultCloseOperation on-close)
- (.setLocationRelativeTo nil)
- (.setVisible true))]
- (let [console (bsh.util.JConsole.)]
- (doto (.getContentPane jframe)
- (.setLayout (java.awt.BorderLayout.))
- (.add console))
- (doto jframe
- (.pack)
- (.setSize width height))
- (binding [*out* (.getOut console)
- *in* (clojure.lang.LineNumberingPushbackReader. (.getIn console))
- *err* (.getOut console)]
- (.start (Thread. (bound-fn [] (clojure.main/main)))))))))
-
+ (let [options (merge default-opts optmap)
+ {:keys [title width height font on-close prompt init eval]} options
+ jframe (doto (JFrame. title)
+ (.setSize width height)
+ (.setDefaultCloseOperation on-close)
+ (.setLocationRelativeTo nil))]
+ (let [console (bsh.util.JConsole. font)]
+ (doto (.getContentPane jframe)
+ (.setLayout (java.awt.BorderLayout.))
+ (.add console))
+ (doto jframe
+ (.pack)
+ (.setSize width height))
+ (.requestFocus console)
+ (let [thread (make-repl-thread console :prompt prompt :init init :eval eval)
+ stopper (clojure.repl/thread-stopper thread)]
+ (doto console
+ (.setInterruptFunction (fn [reason] (stopper reason)))
+ (.setEOFFunction (window-closing-dispatcher jframe)))
+ (.start thread)
+ (.setVisible jframe true))))))
-;; Debug swing macro
-;
-; Can't take credit for the debug macro, came from here:
-; http://gist.github.com/252421
+; local-bindings and eval-with-locals are from http://gist.github.com/252421
; Inspired by George Jahad's version: http://georgejahad.com/clojure/debug-repl.html
(defmacro local-bindings
"Produces a map of the names of local bindings to their values."
@@ -53,7 +79,7 @@
(let [symbols (map key @clojure.lang.Compiler/LOCAL_ENV)]
(zipmap (map (fn [sym] `(quote ~sym)) symbols) symbols)))
-(declare *locals*)
+(declare ^:dynamic *locals*)
(defn eval-with-locals
"Evals a form with given locals. The locals should be a map of symbols to
values."
@@ -74,33 +100,15 @@
(foo 3)
This will pop up the debugging REPL, you should be able to access the var 'a'
- from the REPL.
- "
+ from the REPL."
([] `(make-dbg-repl-jframe {}))
([optmap]
- `(let [opts# (merge default-opts ~optmap)
- jframe# (doto (JFrame. (:title opts#))
- (.setSize (:width opts#) (:height opts#))
- (.setDefaultCloseOperation (:on-close opts#))
- (.setLocationRelativeTo nil)
- (.setVisible true))]
- (let [console# (bsh.util.JConsole.)]
- (doto (.getContentPane jframe#)
- (.setLayout (java.awt.BorderLayout.))
- (.add console#))
- (doto jframe#
- (.pack)
- (.setSize (:width opts#) (:height opts#)))
- (binding [*out* (.getOut console#)
- *in* (clojure.lang.LineNumberingPushbackReader. (.getIn console#))
- *err* (.getOut console#)]
- (.start (Thread. (bound-fn []
- (clojure.main/repl
- :prompt #(print "dr => ")
- :eval (partial eval-with-locals (local-bindings)))))))))))
-
+ `(make-repl-jframe (merge
+ default-opts
+ default-dbg-opts
+ {:eval (partial eval-with-locals (local-bindings))}
+ ~optmap))))
(defn -main
[& args]
(make-repl-jframe {:on-close JFrame/EXIT_ON_CLOSE}))
-
View
28 src/jvm/bsh/ConsoleInterface.java
@@ -37,18 +37,24 @@
import java.io.*;
/**
- The capabilities of a minimal console for BeanShell.
- Stream I/O and optimized print for output.
-
- A simple console may ignore some of these or map them to trivial
- implementations. e.g. print() with color can be mapped to plain text.
- @see bsh.util.GUIConsoleInterface
-*/
+ * The capabilities of a minimal console for BeanShell.
+ * Stream I/O and optimized print for output.
+ * <p/>
+ * A simple console may ignore some of these or map them to trivial
+ * implementations. e.g. print() with color can be mapped to plain text.
+ *
+ * @see bsh.util.GUIConsoleInterface
+ */
public interface ConsoleInterface {
public Reader getIn();
+
public PrintWriter getOut();
+
public PrintWriter getErr();
- public void println( Object o );
- public void print( Object o );
- public void error( Object o );
-}
+
+ public void println(Object o);
+
+ public void print(Object o);
+
+ public void error(Object o);
+}
View
31 src/jvm/bsh/util/GUIConsoleInterface.java
@@ -34,22 +34,25 @@
package bsh.util;
import bsh.ConsoleInterface;
+
import java.awt.Color;
/**
- Additional capabilities of an interactive console for BeanShell.
- Althought this is called "GUIConsoleInterface" it might just as well be
- used by a more sophisticated text-only command line.
- <p>
- Note: we may want to express the command line history, editing,
- and cut & paste functionality here as well at some point.
-*/
-public interface GUIConsoleInterface extends ConsoleInterface
-{
- public void print( Object o, Color color );
- public void setNameCompletion( NameCompletion nc );
-
- /** e.g. the wait cursor */
- public void setWaitFeedback( boolean on );
+ * Additional capabilities of an interactive console for BeanShell.
+ * Althought this is called "GUIConsoleInterface" it might just as well be
+ * used by a more sophisticated text-only command line.
+ * <p/>
+ * Note: we may want to express the command line history, editing,
+ * and cut & paste functionality here as well at some point.
+ */
+public interface GUIConsoleInterface extends ConsoleInterface {
+ public void print(Object o, Color color);
+
+ public void setNameCompletion(NameCompletion nc);
+
+ /**
+ * e.g. the wait cursor
+ */
+ public void setWaitFeedback(boolean on);
}
View
1,017 src/jvm/bsh/util/JConsole.java
@@ -1,37 +1,37 @@
/*****************************************************************************
-* *
-* This file is part of the BeanShell Java Scripting distribution. *
-* Documentation and updates may be found at http://www.beanshell.org/ *
-* *
-* Sun Public License Notice: *
-* *
-* The contents of this file are subject to the Sun Public License Version *
-* 1.0 (the "License"); you may not use this file except in compliance with *
-* the License. A copy of the License is available at http://www.sun.com *
-* *
-* The Original Code is BeanShell. The Initial Developer of the Original *
-* Code is Pat Niemeyer. Portions created by Pat Niemeyer are Copyright *
-* (C) 2000. All Rights Reserved. *
-* *
-* GNU Public License Notice: *
-* *
-* Alternatively, the contents of this file may be used under the terms of *
-* the GNU Lesser General Public License (the "LGPL"), in which case the *
-* provisions of LGPL are applicable instead of those above. If you wish to *
-* allow use of your version of this file only under the terms of the LGPL *
-* and not to allow others to use your version of this file under the SPL, *
-* indicate your decision by deleting the provisions above and replace *
-* them with the notice and other provisions required by the LGPL. If you *
-* do not delete the provisions above, a recipient may use your version of *
-* this file under either the SPL or the LGPL. *
-* *
-* Patrick Niemeyer (pat@pat.net) *
-* Author of Learning Java, O'Reilly & Associates *
-* http://www.pat.net/~pat/ *
-* *
-*****************************************************************************/
-
-package bsh.util;
+ * *
+ * This file is part of the BeanShell Java Scripting distribution. *
+ * Documentation and updates may be found at http://www.beanshell.org/ *
+ * *
+ * Sun Public License Notice: *
+ * *
+ * The contents of this file are subject to the Sun Public License Version *
+ * 1.0 (the "License"); you may not use this file except in compliance with *
+ * the License. A copy of the License is available at http://www.sun.com *
+ * *
+ * The Original Code is BeanShell. The Initial Developer of the Original *
+ * Code is Pat Niemeyer. Portions created by Pat Niemeyer are Copyright *
+ * (C) 2000. All Rights Reserved. *
+ * *
+ * GNU Public License Notice: *
+ * *
+ * Alternatively, the contents of this file may be used under the terms of *
+ * the GNU Lesser General Public License (the "LGPL"), in which case the *
+ * provisions of LGPL are applicable instead of those above. If you wish to *
+ * allow use of your version of this file only under the terms of the LGPL *
+ * and not to allow others to use your version of this file under the SPL, *
+ * indicate your decision by deleting the provisions above and replace *
+ * them with the notice and other provisions required by the LGPL. If you *
+ * do not delete the provisions above, a recipient may use your version of *
+ * this file under either the SPL or the LGPL. *
+ * *
+ * Patrick Niemeyer (pat@pat.net) *
+ * Author of Learning Java, O'Reilly & Associates *
+ * http://www.pat.net/~pat/ *
+ * *
+ *****************************************************************************/
+
+package bsh.util;
import java.awt.Component;
import java.awt.Font;
@@ -45,42 +45,52 @@
import java.awt.Cursor;
import javax.swing.text.*;
import javax.swing.*;
+import clojure.lang.IFn;
// Things that are not in the core packages
import bsh.util.NameCompletion;
/**
-A JFC/Swing based console for the BeanShell desktop.
-This is a descendant of the old AWTConsole.
+ * A JFC/Swing based console for the BeanShell desktop.
+ * This is a descendant of the old AWTConsole.
+ * <p/>
+ * Improvements by: Mark Donszelmann <Mark.Donszelmann@cern.ch>
+ * including Cut & Paste
+ * <p/>
+ * Improvements by: Daniel Leuck
+ * including Color and Image support, key press bug workaround
+ */
+public class JConsole extends JScrollPane
+ implements GUIConsoleInterface, Runnable, KeyListener,
+ MouseListener, ActionListener, PropertyChangeListener {
+ private final static String CUT = "Cut";
+ private final static String COPY = "Copy";
+ private final static String PASTE = "Paste";
+
+ private IFn interruptFunction;
+ private IFn eofFunction;
+ private Writer outPipe;
+ private Reader inPipe;
+ private Reader in;
+ private PrintWriter out;
+
+ public Reader getIn() {
+ return in;
+ }
+
+ public PrintWriter getOut() {
+ return out;
+ }
-Improvements by: Mark Donszelmann <Mark.Donszelmann@cern.ch>
-including Cut & Paste
+ public PrintWriter getErr() {
+ return out;
+ }
-Improvements by: Daniel Leuck
-including Color and Image support, key press bug workaround
-*/
-public class JConsole extends JScrollPane
-implements GUIConsoleInterface, Runnable, KeyListener,
-MouseListener, ActionListener, PropertyChangeListener
-{
- private final static String CUT = "Cut";
- private final static String COPY = "Copy";
- private final static String PASTE = "Paste";
-
- private Writer outPipe;
- private Reader inPipe;
- private Reader in;
- private PrintWriter out;
-
- public Reader getIn() { return in; }
- public PrintWriter getOut() { return out; }
- public PrintWriter getErr() { return out; }
-
- private int cmdStart = 0;
- private Vector <String>history = new Vector<String>();
- private String startedLine;
- private int histLine = 0;
+ private int cmdStart = 0;
+ private Vector<String> history = new Vector<String>();
+ private String startedLine;
+ private int histLine = 0;
private JPopupMenu menu;
private JTextPane text;
@@ -93,35 +103,36 @@
private boolean gotUp = true;
public JConsole() {
- this(null, null);
+ this(null, null, new Font("Monospaced", Font.PLAIN, 14));
}
- public JConsole( Reader cin, Writer cout )
- {
+ public JConsole(Font font) {
+ this(null, null, font);
+ }
+
+ public JConsole(Reader cin, Writer cout, Font font) {
super();
// Special TextPane which catches for cut and paste, both L&F keys and
// programmatic behaviour
- text = new JTextPane( doc=new DefaultStyledDocument() )
- {
- public void cut() {
- if (text.getCaretPosition() < cmdStart) {
+ text = new JTextPane(doc = new DefaultStyledDocument()) {
+ public void cut() {
+ if (text.getCaretPosition() < cmdStart) {
super.copy();
} else {
super.cut();
}
}
- public void paste() {
+ public void paste() {
forceCaretMoveToEnd();
super.paste();
}
};
- Font font = new Font("Monospaced",Font.PLAIN,14);
+ text.setFont(font);
text.setText("");
- text.setFont( font );
- text.setMargin( new Insets(7,5,7,5) );
+ text.setMargin(new Insets(7, 5, 7, 5));
text.addKeyListener(this);
setViewportView(text);
@@ -136,158 +147,198 @@ public void paste() {
// make sure popup menu follows Look & Feel
UIManager.addPropertyChangeListener(this);
- outPipe = cout;
- if ( outPipe == null ) {
- outPipe = new PipedWriter();
+ outPipe = cout;
+ if (outPipe == null) {
+ outPipe = new PipedWriter();
try {
- in = new PipedReader((PipedWriter)outPipe);
- } catch ( IOException e ) {
+ in = new PipedReader((PipedWriter) outPipe);
+ } catch (IOException e) {
print("Console internal error (1)...", Color.red);
}
}
inPipe = cin;
- if ( inPipe == null ) {
+ if (inPipe == null) {
PipedWriter pout = new PipedWriter();
- out = new PrintWriter( pout );
+ out = new PrintWriter(pout);
try {
inPipe = new PipedReader(pout);
- } catch ( IOException e ) { print("Console internal error: "+e); }
+ } catch (IOException e) {
+ print("Console internal error: " + e);
}
- // Start the inpipe watcher
- new Thread( this ).start();
+ }
+ // Start the inpipe watcher
+ new Thread(this).start();
- requestFocus();
- }
+ requestFocus();
+ }
- public void requestFocus()
- {
- super.requestFocus();
- text.requestFocus();
- }
+ public void setInterruptFunction(IFn interruptFunction) {
+ this.interruptFunction = interruptFunction;
+ }
- public void keyPressed( KeyEvent e ) {
- type( e );
- gotUp=false;
- }
+ public void setEOFFunction(IFn eofFunction) {
+ this.eofFunction = eofFunction;
+ }
- public void keyTyped(KeyEvent e) {
- type( e );
- }
+ public void requestFocus() {
+ super.requestFocus();
+ text.requestFocus();
+ }
- public void keyReleased(KeyEvent e) {
- gotUp=true;
- type( e );
- }
+ public void keyPressed(KeyEvent e) {
+ type(e);
+ gotUp = false;
+ }
+
+ public void keyTyped(KeyEvent e) {
+ type(e);
+ }
+
+ public void keyReleased(KeyEvent e) {
+ gotUp = true;
+ type(e);
+ }
- private synchronized void type( KeyEvent e ) {
- switch ( e.getKeyCode() )
- {
- case ( KeyEvent.VK_ENTER ):
+ private synchronized void type(KeyEvent e) {
+ switch (e.getKeyCode()) {
+ case (KeyEvent.VK_ENTER):
if (e.getID() == KeyEvent.KEY_PRESSED) {
- if (gotUp) {
- enter();
- resetCommandStart();
- text.setCaretPosition(cmdStart);
- }
+ enter();
+ resetCommandStart();
+ text.setCaretPosition(cmdStart);
}
e.consume();
text.repaint();
break;
- case ( KeyEvent.VK_UP ):
+ case (KeyEvent.VK_UP):
if (e.getID() == KeyEvent.KEY_PRESSED) {
historyUp();
}
e.consume();
break;
- case ( KeyEvent.VK_DOWN ):
+ case (KeyEvent.VK_DOWN):
if (e.getID() == KeyEvent.KEY_PRESSED) {
historyDown();
}
e.consume();
break;
- case ( KeyEvent.VK_LEFT ):
- case ( KeyEvent.VK_BACK_SPACE ):
- case ( KeyEvent.VK_DELETE ):
+ case (KeyEvent.VK_LEFT):
if (text.getCaretPosition() <= cmdStart) {
- // This doesn't work for backspace.
- // See default case for workaround
e.consume();
}
break;
- case ( KeyEvent.VK_RIGHT ):
+ case (KeyEvent.VK_BACK_SPACE):
+ if (text.getSelectedText() == null) {
+ if(text.getCaretPosition() <= cmdStart) {
+ e.consume();
+ }
+ } else {
+ if(text.getCaretPosition() < cmdStart) {
+ e.consume();
+ }
+ // TODO: prevent deletion when the caret is at
+ // the end of the user=> marker
+ }
+ // See also default: case for backspace workaround
+ break;
+
+ case (KeyEvent.VK_DELETE):
+ if (text.getCaretPosition() < cmdStart) {
+ e.consume();
+ }
+ // TODO: prevent deletion when the caret is at
+ // the end of the user=> marker
+ break;
+
+ case (KeyEvent.VK_RIGHT):
forceCaretMoveToStart();
break;
- case ( KeyEvent.VK_HOME ):
- text.setCaretPosition(cmdStart);
+ case (KeyEvent.VK_HOME):
+ if ((e.getModifiers() & InputEvent.SHIFT_MASK) > 0) {
+ text.moveCaretPosition(cmdStart);
+ } else {
+ text.setCaretPosition(cmdStart);
+ }
e.consume();
break;
- case ( KeyEvent.VK_U ): // clear line
- if ( (e.getModifiers() & InputEvent.CTRL_MASK) > 0 ) {
- replaceRange( "", cmdStart, textLength());
+ case (KeyEvent.VK_U): // clear line
+ if ((e.getModifiers() & InputEvent.CTRL_MASK) > 0) {
+ replaceRange("", cmdStart, textLength());
histLine = 0;
e.consume();
}
break;
- case ( KeyEvent.VK_ALT ):
- case ( KeyEvent.VK_CAPS_LOCK ):
- case ( KeyEvent.VK_CONTROL ):
- case ( KeyEvent.VK_META ):
- case ( KeyEvent.VK_SHIFT ):
- case ( KeyEvent.VK_PRINTSCREEN ):
- case ( KeyEvent.VK_SCROLL_LOCK ):
- case ( KeyEvent.VK_PAUSE ):
- case ( KeyEvent.VK_INSERT ):
- case ( KeyEvent.VK_F1):
- case ( KeyEvent.VK_F2):
- case ( KeyEvent.VK_F3):
- case ( KeyEvent.VK_F4):
- case ( KeyEvent.VK_F5):
- case ( KeyEvent.VK_F6):
- case ( KeyEvent.VK_F7):
- case ( KeyEvent.VK_F8):
- case ( KeyEvent.VK_F9):
- case ( KeyEvent.VK_F10):
- case ( KeyEvent.VK_F11):
- case ( KeyEvent.VK_F12):
- case ( KeyEvent.VK_ESCAPE ):
+ case (KeyEvent.VK_D): // "end of input"
+ if ((e.getModifiers() & InputEvent.CTRL_MASK) > 0) {
+ e.consume();
+ if(this.eofFunction != null) {
+ this.eofFunction.invoke();
+ }
+ }
+ break;
+
+ case (KeyEvent.VK_ALT):
+ case (KeyEvent.VK_CAPS_LOCK):
+ case (KeyEvent.VK_CONTROL):
+ case (KeyEvent.VK_META):
+ case (KeyEvent.VK_SHIFT):
+ case (KeyEvent.VK_PRINTSCREEN):
+ case (KeyEvent.VK_SCROLL_LOCK):
+ case (KeyEvent.VK_PAUSE):
+ case (KeyEvent.VK_INSERT):
+ case (KeyEvent.VK_F1):
+ case (KeyEvent.VK_F2):
+ case (KeyEvent.VK_F3):
+ case (KeyEvent.VK_F4):
+ case (KeyEvent.VK_F5):
+ case (KeyEvent.VK_F6):
+ case (KeyEvent.VK_F7):
+ case (KeyEvent.VK_F8):
+ case (KeyEvent.VK_F9):
+ case (KeyEvent.VK_F10):
+ case (KeyEvent.VK_F11):
+ case (KeyEvent.VK_F12):
+ case (KeyEvent.VK_ESCAPE):
// only modifier pressed
break;
- // Control-C
- case ( KeyEvent.VK_C ):
- if (text.getSelectedText() == null) {
- if (( (e.getModifiers() & InputEvent.CTRL_MASK) > 0 )
- && (e.getID() == KeyEvent.KEY_PRESSED)) {
- append("^C");
+ // Control-C
+ case (KeyEvent.VK_C):
+ if (text.getSelectedText() == null) { // Ctrl-C also copies text
+ if (((e.getModifiers() & InputEvent.CTRL_MASK) > 0)
+ && (e.getID() == KeyEvent.KEY_PRESSED)) {
+ //append("^C");
+ if(interruptFunction != null) {
+ interruptFunction.invoke("User pressed Ctrl-C");
+ }
}
e.consume();
}
break;
- case ( KeyEvent.VK_TAB ):
+ case (KeyEvent.VK_TAB):
if (e.getID() == KeyEvent.KEY_RELEASED) {
- String part = text.getText().substring( cmdStart );
- doCommandCompletion( part );
+ String part = text.getText().substring(cmdStart);
+ doCommandCompletion(part);
}
e.consume();
break;
- default:
- if (
- (e.getModifiers() &
- (InputEvent.CTRL_MASK
- | InputEvent.ALT_MASK | InputEvent.META_MASK)) == 0 )
- {
+ default:
+ if (
+ (e.getModifiers() &
+ (InputEvent.CTRL_MASK
+ | InputEvent.ALT_MASK | InputEvent.META_MASK)) == 0) {
// plain character
forceCaretMoveToEnd();
}
@@ -296,84 +347,91 @@ private synchronized void type( KeyEvent e ) {
The getKeyCode function always returns VK_UNDEFINED for
keyTyped events, so backspace is not fully consumed.
*/
- if (e.paramString().indexOf("Backspace") != -1)
- {
- if (text.getCaretPosition() <= cmdStart) {
- e.consume();
- break;
+ if (e.paramString().indexOf("Backspace") != -1) {
+ if (text.getCaretPosition() <= cmdStart) {
+ e.consume();
+ break;
+ }
}
- }
- break;
+ break;
}
}
- private void doCommandCompletion( String part ) {
- if ( nameCompletion == null )
+ private void doCommandCompletion(String part) {
+ if (nameCompletion == null) {
return;
+ }
- int i=part.length()-1;
+ int i = part.length() - 1;
// Character.isJavaIdentifierPart() How convenient for us!!
- while (
- i >= 0 &&
- ( Character.isJavaIdentifierPart(part.charAt(i))
- || part.charAt(i) == '.' )
- )
+ while (
+ i >= 0 &&
+ (Character.isJavaIdentifierPart(part.charAt(i))
+ || part.charAt(i) == '.')
+ ) {
i--;
+ }
- part = part.substring(i+1);
+ part = part.substring(i + 1);
- if ( part.length() < 2 ) // reasonable completion length
+ if (part.length() < 2) // reasonable completion length
+ {
return;
+ }
//System.out.println("completing part: "+part);
// no completion
- String [] complete = nameCompletion.completeName(part);
- if ( complete.length == 0 ) {
+ String[] complete = nameCompletion.completeName(part);
+ if (complete.length == 0) {
java.awt.Toolkit.getDefaultToolkit().beep();
return;
}
// Found one completion (possibly what we already have)
- if ( complete.length == 1 && !complete.equals(part) ) {
+ if (complete.length == 1 && !complete.equals(part)) {
String append = complete[0].substring(part.length());
- append( append );
+ append(append);
return;
}
// Found ambiguous, show (some of) them
String line = text.getText();
- String command = line.substring( cmdStart );
+ String command = line.substring(cmdStart);
// Find prompt
- for(i=cmdStart; line.charAt(i) != '\n' && i > 0; i--);
- String prompt = line.substring( i+1, cmdStart );
+ for (i = cmdStart; line.charAt(i) != '\n' && i > 0; i--) {
+ ;
+ }
+ String prompt = line.substring(i + 1, cmdStart);
// Show ambiguous
StringBuffer sb = new StringBuffer("\n");
- for( i=0; i<complete.length && i<SHOW_AMBIG_MAX; i++)
- sb.append( complete[i] +"\n" );
- if ( i == SHOW_AMBIG_MAX )
+ for (i = 0; i < complete.length && i < SHOW_AMBIG_MAX; i++) {
+ sb.append(complete[i] + "\n");
+ }
+ if (i == SHOW_AMBIG_MAX) {
sb.append("...\n");
+ }
- print( sb, Color.gray );
- print( prompt ); // print resets command start
- append( command ); // append does not reset command start
+ print(sb, Color.gray);
+ print(prompt); // print resets command start
+ append(command); // append does not reset command start
}
private void resetCommandStart() {
cmdStart = textLength();
}
- private void append(String string) {
+ private void append(String string) {
int slen = textLength();
text.select(slen, slen);
text.replaceSelection(string);
}
- private String replaceRange(Object s, int start, int end) {
+ private String replaceRange(Object s, int start, int end) {
String st = s.toString();
text.select(start, end);
text.replaceSelection(st);
@@ -381,102 +439,108 @@ private String replaceRange(Object s, int start, int end) {
return st;
}
- private void forceCaretMoveToEnd() {
- if (text.getCaretPosition() < cmdStart) {
+ private void forceCaretMoveToEnd() {
+ if (text.getCaretPosition() < cmdStart) {
// move caret first!
text.setCaretPosition(textLength());
}
text.repaint();
}
- private void forceCaretMoveToStart() {
- if (text.getCaretPosition() < cmdStart) {
+ private void forceCaretMoveToStart() {
+ if (text.getCaretPosition() < cmdStart) {
// move caret first!
}
text.repaint();
}
- private void enter() {
+ private void enter() {
String s = getCmd();
- if ( s.length() == 0 ) // special hack for empty return!
+ if (s.length() == 0) // special hack for empty return!
+ {
s = ";\n";
- else {
- history.addElement( s );
- s = s +"\n";
+ } else {
+ history.addElement(s);
+ s = s + "\n";
}
append("\n");
histLine = 0;
- acceptLine( s );
+ acceptLine(s);
text.repaint();
}
private String getCmd() {
String s = "";
try {
- s = text.getText(cmdStart, textLength() - cmdStart);
- } catch (BadLocationException e) {
+ s = text.getText(cmdStart, textLength() - cmdStart);
+ } catch (BadLocationException e) {
// should not happen
- System.out.println("Internal JConsole Error: "+e);
+ System.out.println("Internal JConsole Error: " + e);
}
return s;
}
- private void historyUp() {
- if ( history.size() == 0 )
+ private void historyUp() {
+ if (history.size() == 0) {
return;
- if ( histLine == 0 ) // save current line
+ }
+ if (histLine == 0) // save current line
+ {
startedLine = getCmd();
- if ( histLine < history.size() ) {
+ }
+ if (histLine < history.size()) {
histLine++;
showHistoryLine();
}
}
- private void historyDown() {
- if ( histLine == 0 )
+ private void historyDown() {
+ if (histLine == 0) {
return;
+ }
histLine--;
showHistoryLine();
}
- private void showHistoryLine() {
+ private void showHistoryLine() {
String showline;
- if ( histLine == 0 )
+ if (histLine == 0) {
showline = startedLine;
- else
- showline = (String)history.elementAt( history.size() - histLine );
+ } else {
+ showline = (String) history.elementAt(history.size() - histLine);
+ }
- replaceRange( showline, cmdStart, textLength() );
+ replaceRange(showline, cmdStart, textLength());
text.setCaretPosition(textLength());
text.repaint();
}
String ZEROS = "000";
- private void acceptLine( String line )
- {
+ private void acceptLine(String line) {
//FIXME: what did this do?
//line = buf.toString();
- if (outPipe == null )
+ if (outPipe == null) {
print("Console internal error: cannot output ...", Color.red);
- else
- try {
- outPipe.write( line );
- outPipe.flush();
- } catch ( IOException e ) {
- outPipe = null;
- throw new RuntimeException("Console pipe broken...");
+ } else {
+ try {
+ outPipe.write(line);
+ outPipe.flush();
+ } catch (IOException e) {
+ outPipe = null;
+ throw new RuntimeException("Console pipe broken...");
+ }
}
//text.repaint();
}
public void println(Object o) {
- print( String.valueOf(o) + "\n" );
+ print(String.valueOf(o) + "\n");
text.repaint();
}
@@ -487,19 +551,19 @@ public void run() {
resetCommandStart();
text.setCaretPosition(cmdStart);
}
- });
- }
+ });
+ }
- /**
- * Prints "\\n" (i.e. newline)
- */
+ /**
+ * Prints "\\n" (i.e. newline)
+ */
public void println() {
print("\n");
text.repaint();
}
- public void error( Object o ) {
- print( o, Color.red );
+ public void error(Object o) {
+ print(o, Color.red);
}
public void println(Icon icon) {
@@ -509,8 +573,9 @@ public void println(Icon icon) {
}
public void print(final Icon icon) {
- if (icon==null)
+ if (icon == null) {
return;
+ }
invokeAndWait(new Runnable() {
public void run() {
@@ -518,278 +583,288 @@ public void run() {
resetCommandStart();
text.setCaretPosition(cmdStart);
}
- });
- }
+ });
+ }
- public void print(Object s, Font font) {
- print(s, font, null);
- }
+ public void print(Object s, Font font) {
+ print(s, font, null);
+ }
- public void print(Object s, Color color) {
- print(s, null, color);
- }
+ public void print(Object s, Color color) {
+ print(s, null, color);
+ }
- public void print(final Object o, final Font font, final Color color) {
- invokeAndWait(new Runnable() {
- public void run() {
- AttributeSet old = getStyle();
- setStyle(font, color);
- append(String.valueOf(o));
- resetCommandStart();
- text.setCaretPosition(cmdStart);
- setStyle(old, true);
- }
- });
+ public void print(final Object o, final Font font, final Color color) {
+ invokeAndWait(new Runnable() {
+ public void run() {
+ AttributeSet old = getStyle();
+ setStyle(font, color);
+ append(String.valueOf(o));
+ resetCommandStart();
+ text.setCaretPosition(cmdStart);
+ setStyle(old, true);
}
+ });
+ }
- public void print(
- Object s,
- String fontFamilyName,
- int size,
- Color color
- ) {
+ public void print(
+ Object s,
+ String fontFamilyName,
+ int size,
+ Color color
+ ) {
+
+ print(s, fontFamilyName, size, color, false, false, false);
+ }
- print(s,fontFamilyName,size,color,false,false,false);
+ public void print(
+ final Object o,
+ final String fontFamilyName,
+ final int size,
+ final Color color,
+ final boolean bold,
+ final boolean italic,
+ final boolean underline
+ ) {
+ invokeAndWait(new Runnable() {
+ public void run() {
+ AttributeSet old = getStyle();
+ setStyle(fontFamilyName, size, color, bold, italic, underline);
+ append(String.valueOf(o));
+ resetCommandStart();
+ text.setCaretPosition(cmdStart);
+ setStyle(old, true);
}
+ });
+ }
- public void print(
- final Object o,
- final String fontFamilyName,
- final int size,
- final Color color,
- final boolean bold,
- final boolean italic,
- final boolean underline
- )
- {
- invokeAndWait(new Runnable() {
- public void run() {
- AttributeSet old = getStyle();
- setStyle(fontFamilyName, size, color, bold, italic, underline);
- append(String.valueOf(o));
- resetCommandStart();
- text.setCaretPosition(cmdStart);
- setStyle(old, true);
- }
- });
- }
+ private AttributeSet setStyle(Font font) {
+ return setStyle(font, null);
+ }
- private AttributeSet setStyle(Font font) {
- return setStyle(font, null);
- }
+ private AttributeSet setStyle(Color color) {
+ return setStyle(null, color);
+ }
- private AttributeSet setStyle(Color color) {
- return setStyle(null, color);
- }
+ private AttributeSet setStyle(Font font, Color color) {
+ if (font != null) {
+ return setStyle(font.getFamily(), font.getSize(), color,
+ font.isBold(), font.isItalic(),
+ StyleConstants.isUnderline(getStyle()));
+ } else {
+ return setStyle(null, -1, color);
+ }
+ }
- private AttributeSet setStyle( Font font, Color color)
- {
- if (font!=null)
- return setStyle( font.getFamily(), font.getSize(), color,
- font.isBold(), font.isItalic(),
- StyleConstants.isUnderline(getStyle()) );
- else
- return setStyle(null,-1,color);
- }
+ private AttributeSet setStyle(
+ String fontFamilyName, int size, Color color) {
+ MutableAttributeSet attr = new SimpleAttributeSet();
+ if (color != null) {
+ StyleConstants.setForeground(attr, color);
+ }
+ if (fontFamilyName != null) {
+ StyleConstants.setFontFamily(attr, fontFamilyName);
+ }
+ if (size != -1) {
+ StyleConstants.setFontSize(attr, size);
+ }
- private AttributeSet setStyle (
- String fontFamilyName, int size, Color color)
- {
- MutableAttributeSet attr = new SimpleAttributeSet();
- if (color!=null)
- StyleConstants.setForeground(attr, color);
- if (fontFamilyName!=null)
- StyleConstants.setFontFamily(attr, fontFamilyName);
- if (size!=-1)
- StyleConstants.setFontSize(attr, size);
+ setStyle(attr);
- setStyle(attr);
+ return getStyle();
+ }
- return getStyle();
- }
+ private AttributeSet setStyle(
+ String fontFamilyName,
+ int size,
+ Color color,
+ boolean bold,
+ boolean italic,
+ boolean underline
+ ) {
+ MutableAttributeSet attr = new SimpleAttributeSet();
+ if (color != null) {
+ StyleConstants.setForeground(attr, color);
+ }
+ if (fontFamilyName != null) {
+ StyleConstants.setFontFamily(attr, fontFamilyName);
+ }
+ if (size != -1) {
+ StyleConstants.setFontSize(attr, size);
+ }
+ StyleConstants.setBold(attr, bold);
+ StyleConstants.setItalic(attr, italic);
+ StyleConstants.setUnderline(attr, underline);
- private AttributeSet setStyle(
- String fontFamilyName,
- int size,
- Color color,
- boolean bold,
- boolean italic,
- boolean underline
- )
- {
- MutableAttributeSet attr = new SimpleAttributeSet();
- if (color!=null)
- StyleConstants.setForeground(attr, color);
- if (fontFamilyName!=null)
- StyleConstants.setFontFamily(attr, fontFamilyName);
- if (size!=-1)
- StyleConstants.setFontSize(attr, size);
- StyleConstants.setBold(attr, bold);
- StyleConstants.setItalic(attr, italic);
- StyleConstants.setUnderline(attr, underline);
-
- setStyle(attr);
-
- return getStyle();
- }
+ setStyle(attr);
- private void setStyle(AttributeSet attributes) {
- setStyle(attributes, false);
- }
+ return getStyle();
+ }
- private void setStyle(AttributeSet attributes, boolean overWrite) {
- text.setCharacterAttributes(attributes, overWrite);
- }
+ private void setStyle(AttributeSet attributes) {
+ setStyle(attributes, false);
+ }
- private AttributeSet getStyle() {
- return text.getCharacterAttributes();
- }
+ private void setStyle(AttributeSet attributes, boolean overWrite) {
+ text.setCharacterAttributes(attributes, overWrite);
+ }
- public void setFont( Font font ) {
- super.setFont( font );
+ private AttributeSet getStyle() {
+ return text.getCharacterAttributes();
+ }
- if ( text != null )
- text.setFont( font );
- }
+ public void setFont(Font font) {
+ super.setFont(font);
- private void inPipeWatcher() throws IOException {
- char [] ca = new char [256]; // arbitrary blocking factor
- int read;
- while ( (read = inPipe.read(ca)) != -1 ) {
- print( new String(ca, 0, read) );
- //text.repaint();
- }
+ if (text != null) {
+ text.setFont(font);
+ }
+ }
- println("Console: Input closed...");
- }
+ private void inPipeWatcher() throws IOException {
+ char[] ca = new char[256]; // arbitrary blocking factor
+ int read;
+ while ((read = inPipe.read(ca)) != -1) {
+ print(new String(ca, 0, read));
+ //text.repaint();
+ }
- public void run() {
- try {
- inPipeWatcher();
- } catch ( IOException e ) {
- print("Console: I/O Error: "+e+"\n", Color.red);
- }
- }
+ println("Console: Input closed...");
+ }
- public String toString() {
- return "BeanShell console";
- }
+ public void run() {
+ try {
+ inPipeWatcher();
+ } catch (IOException e) {
+ print("Console: I/O Error: " + e + "\n", Color.red);
+ }
+ }
- // MouseListener Interface
- public void mouseClicked(MouseEvent event) {
- }
+ public String toString() {
+ return "BeanShell console";
+ }
- public void mousePressed(MouseEvent event) {
- if (event.isPopupTrigger()) {
- menu.show(
- (Component)event.getSource(), event.getX(), event.getY());
- }
- }
+ // MouseListener Interface
+ public void mouseClicked(MouseEvent event) {
+ }
- public void mouseReleased(MouseEvent event) {
- if (event.isPopupTrigger()) {
- menu.show((Component)event.getSource(), event.getX(),
- event.getY());
- }
- text.repaint();
- }
+ public void mousePressed(MouseEvent event) {
+ if (event.isPopupTrigger()) {
+ menu.show(
+ (Component) event.getSource(), event.getX(), event.getY());
+ }
+ }
- public void mouseEntered(MouseEvent event) { }
+ public void mouseReleased(MouseEvent event) {
+ if (event.isPopupTrigger()) {
+ menu.show((Component) event.getSource(), event.getX(),
+ event.getY());
+ }
+ text.repaint();
+ }
- public void mouseExited(MouseEvent event) { }
+ public void mouseEntered(MouseEvent event) {
+ }
- // property change
- public void propertyChange(PropertyChangeEvent event) {
- if (event.getPropertyName().equals("lookAndFeel")) {
- SwingUtilities.updateComponentTreeUI(menu);
- }
- }
+ public void mouseExited(MouseEvent event) {
+ }
- // handle cut, copy and paste
- public void actionPerformed(ActionEvent event) {
- String cmd = event.getActionCommand();
- if (cmd.equals(CUT)) {
- text.cut();
- } else if (cmd.equals(COPY)) {
- text.copy();
- } else if (cmd.equals(PASTE)) {
- text.paste();
- }
- }
+ // property change
+ public void propertyChange(PropertyChangeEvent event) {
+ if (event.getPropertyName().equals("lookAndFeel")) {
+ SwingUtilities.updateComponentTreeUI(menu);
+ }
+ }
- /**
- * If not in the event thread run via SwingUtilities.invokeAndWait()
- */
- private void invokeAndWait(Runnable run) {
- if(!SwingUtilities.isEventDispatchThread()) {
- try {
- SwingUtilities.invokeAndWait(run);
- } catch(Exception e) {
- // shouldn't happen
- e.printStackTrace();
- }
- } else {
- run.run();
- }
- }
+ // handle cut, copy and paste
+ public void actionPerformed(ActionEvent event) {
+ String cmd = event.getActionCommand();
+ if (cmd.equals(CUT)) {
+ text.cut();
+ } else if (cmd.equals(COPY)) {
+ text.copy();
+ } else if (cmd.equals(PASTE)) {
+ text.paste();
+ }
+ }
- /**
- I don't think this is necessary anymore.
-
- The overridden read method in this class will not throw "Broken pipe"
- IOExceptions; It will simply wait for new writers and data.
- This is used by the JConsole internal read thread to allow writers
- in different (and in particular ephemeral) threads to write to the pipe.
- It also checks a little more frequently than the original read().
- Warning: read() will not even error on a read to an explicitly closed
- pipe (override closed to for that).
-
- public static class BlockingPipedReader extends PipedReader {
- boolean closed;
- public BlockingPipedReader( PipedWriter pout )
- throws IOException
- {
- super(pout);
- }
- // FIXME
- public synchronized int read() throws IOException {
- if ( closed )
- throw new IOException("stream closed");
-
- while (super.in < 0) { // While no data
- notifyAll(); // Notify any writers to wake up
- try {
- wait(750);
- } catch ( InterruptedException e ) {
- throw new InterruptedIOException();
- }
- }
- // This is what the superclass does.
- int ret = buffer[super.out++] & 0xFF;
- if (super.out >= buffer.length)
- super.out = 0;
- if (super.in == super.out)
- super.in = -1; // now empty
- return ret;
- }
- public void close() throws IOException {
- closed = true;
- super.close();
+ /**
+ * If not in the event thread run via SwingUtilities.invokeAndWait()
+ */
+ private void invokeAndWait(Runnable run) {
+ if (!SwingUtilities.isEventDispatchThread()) {
+ try {
+ SwingUtilities.invokeAndWait(run);
+ } catch (Exception e) {
+ // shouldn't happen
+ e.printStackTrace();
}
-
- } */
-
-
- public void setNameCompletion( NameCompletion nc ) {
- this.nameCompletion = nc;
+ } else {
+ run.run();
}
+ }
+
+ /**
+ * I don't think this is necessary anymore.
+ * <p/>
+ * The overridden read method in this class will not throw "Broken pipe"
+ * IOExceptions; It will simply wait for new writers and data.
+ * This is used by the JConsole internal read thread to allow writers
+ * in different (and in particular ephemeral) threads to write to the pipe.
+ * It also checks a little more frequently than the original read().
+ * Warning: read() will not even error on a read to an explicitly closed
+ * pipe (override closed to for that).
+ * <p/>
+ * public static class BlockingPipedReader extends PipedReader {
+ * boolean closed;
+ * public BlockingPipedReader( PipedWriter pout )
+ * throws IOException
+ * {
+ * super(pout);
+ * }
+ * // FIXME
+ * public synchronized int read() throws IOException {
+ * if ( closed )
+ * throw new IOException("stream closed");
+ * <p/>
+ * while (super.in < 0) { // While no data
+ * notifyAll(); // Notify any writers to wake up
+ * try {
+ * wait(750);
+ * } catch ( InterruptedException e ) {
+ * throw new InterruptedIOException();
+ * }
+ * }
+ * // This is what the superclass does.
+ * int ret = buffer[super.out++] & 0xFF;
+ * if (super.out >= buffer.length)
+ * super.out = 0;
+ * if (super.in == super.out)
+ * super.in = -1; // now empty
+ * return ret;
+ * }
+ * public void close() throws IOException {
+ * closed = true;
+ * super.close();
+ * }
+ * <p/>
+ * }
+ */
+
+
+ public void setNameCompletion(NameCompletion nc) {
+ this.nameCompletion = nc;
+ }
- public void setWaitFeedback( boolean on ) {
- if ( on )
- setCursor( Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR) );
- else
- setCursor( Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR) );
+ public void setWaitFeedback(boolean on) {
+ if (on) {
+ setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
+ } else {
+ setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
}
+ }
- private int textLength() { return text.getDocument().getLength(); }
-}
+ private int textLength() {
+ return text.getDocument().getLength();
+ }
+}
View
31 src/jvm/bsh/util/NameCompletion.java
@@ -36,22 +36,21 @@
import java.util.*;
/**
- The interface for name completion.
-*/
-public interface NameCompletion
-{
+ * The interface for name completion.
+ */
+public interface NameCompletion {
/**
- Return an array containing a string element of the maximum
- unambiguous namespace completion or, if there is no common prefix,
- return the list of ambiguous names.
- e.g.
- input: "java.l"
- output: [ "java.lang." ]
- input: "java.lang."
- output: [ "java.lang.Thread", "java.lang.Integer", ... ]
-
- Note: Alternatively, make a NameCompletionResult object someday...
- */
- public String [] completeName( String part );
+ * Return an array containing a string element of the maximum
+ * unambiguous namespace completion or, if there is no common prefix,
+ * return the list of ambiguous names.
+ * e.g.
+ * input: "java.l"
+ * output: [ "java.lang." ]
+ * input: "java.lang."
+ * output: [ "java.lang.Thread", "java.lang.Integer", ... ]
+ * <p/>
+ * Note: Alternatively, make a NameCompletionResult object someday...
+ */
+ public String[] completeName(String part);
}
Please sign in to comment.
Something went wrong with that request. Please try again.