ReplDocument.java 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  1. package kawa;
  2. import java.awt.*;
  3. import java.awt.event.*;
  4. import javax.swing.*;
  5. import javax.swing.event.*;
  6. import javax.swing.text.*;
  7. import java.util.ArrayList;
  8. import gnu.kawa.io.Path;
  9. import gnu.kawa.io.QueueReader;
  10. import gnu.kawa.swingviews.SwingContent;
  11. import gnu.expr.Language;
  12. import gnu.expr.ModuleBody;
  13. import gnu.lists.CharBuffer;
  14. import gnu.mapping.*;
  15. /** A Swing document that implements a read-eval-print-loop. */
  16. public class ReplDocument extends DefaultStyledDocument
  17. implements DocumentListener, FocusListener
  18. {
  19. //public static javax.swing.text.html.StyleSheet styles
  20. // = new javax.swing.text.html.StyleSheet();
  21. public static StyleContext styles = new javax.swing.text.StyleContext();
  22. static public Style defaultStyle = styles.addStyle("default",null);
  23. public static Style inputStyle = styles.addStyle("input", null);
  24. public static Style redStyle = styles.addStyle("red", null);
  25. static Style blueStyle = styles.addStyle("blue", null);
  26. static Style promptStyle = styles.addStyle("prompt", null);
  27. static {
  28. StyleConstants.setForeground(redStyle, Color.red);
  29. StyleConstants.setForeground(blueStyle, Color.blue);
  30. StyleConstants.setForeground(promptStyle, Color.green);
  31. StyleConstants.setBold(inputStyle, true);
  32. }
  33. /** The pane, if any, that contains this document and has focus. */
  34. JTextPane pane;
  35. int paneCount;
  36. SwingContent content;
  37. final QueueReader in_r;
  38. final GuiInPort in_p;
  39. final ReplPaneOutPort out_stream, err_stream;
  40. Language language;
  41. Environment environment;
  42. Future thread;
  43. /** The offset where output from process is inserted. */
  44. public int outputMark = 0;
  45. /** End of pending input.
  46. * If {@code endMark > 0} then the area between outputMark and endMark
  47. * is pending input that hasn't been sent to the process yet. */
  48. public int endMark = -1;
  49. int length = 0;
  50. public ReplDocument (Language language, Environment penvironment,
  51. boolean shared)
  52. {
  53. this(new SwingContent(), language, penvironment, shared);
  54. }
  55. private ReplDocument (SwingContent content, Language language,
  56. Environment penvironment, final boolean shared)
  57. {
  58. super(content, styles);
  59. this.content = content;
  60. ModuleBody.exitIncrement();
  61. addDocumentListener(this);
  62. this.language = language;
  63. in_r = new QueueReader() {
  64. @Override
  65. public void checkAvailable()
  66. {
  67. checkingPendingInput();
  68. };
  69. };
  70. out_stream = new ReplPaneOutPort(this, "/dev/stdout", defaultStyle);
  71. err_stream = new ReplPaneOutPort(this, "/dev/stderr", redStyle);
  72. in_p = new GuiInPort(in_r, Path.valueOf("/dev/stdin"),
  73. out_stream, this);
  74. thread = Future.make(new kawa.repl(language) {
  75. @Override
  76. public Object apply0 ()
  77. {
  78. Environment env = Environment.getCurrent();
  79. if (shared)
  80. env.setIndirectDefines();
  81. environment = env;
  82. Shell.run(language, env);
  83. SwingUtilities.invokeLater(new Runnable() {
  84. public void run() { ReplDocument.this.fireDocumentClosed(); }
  85. });
  86. return Values.empty;
  87. }
  88. }, penvironment, in_p, out_stream, err_stream);
  89. thread.start();
  90. }
  91. void enter ()
  92. {
  93. // In the future we might handle curses-like applicatons, which
  94. // outputMark may be moved backwards. In that case the normal
  95. // case is that caret position >= outputMark and all the intervening
  96. // text has style inputStyle, in which case we do:
  97. // Find the first character following outputMark that is either
  98. // - the final newline in the buffer (in which case insert a newline
  99. // at the end and treat as the following case);
  100. // - a non-final newline (in which case pass the intervening text
  101. // and the following newline are stuffed into the in queue,
  102. // and the outputMark is set after the newline);
  103. // - a character whose style is not inputStyle is seen (in which
  104. // case the intervening text plus a final newline are stuffed
  105. // into the 'in' queue, and the outputMark is moved to just
  106. // before the non-inputStyle character).
  107. // In the second case, if there is more input following the newline,
  108. // we defer the rest until the inferior requests a new line. This
  109. // is so any output and prompt can get properly interleaved.
  110. // For now, since we don't support backwards movement, we don't
  111. // check for inputStyle, in this case.
  112. // Otherwise, we do similar to Emacs shell mode:
  113. // Select the line containing the caret, stripping of any
  114. // characters that have prompt style, and add a newline.
  115. // That should be sent to the inferior, and copied it before outputMark.
  116. int pos = pane.getCaretPosition();
  117. CharBuffer b = content.buffer;
  118. int len = b.length() - 1; // Ignore final newline.
  119. endMark = -1;
  120. if (pos >= outputMark)
  121. {
  122. int lineAfterCaret = b.indexOf('\n', pos);
  123. if (lineAfterCaret == len)
  124. {
  125. if (len > outputMark && b.charAt(len-1) == '\n')
  126. lineAfterCaret--;
  127. else
  128. insertString(len, "\n", null);
  129. }
  130. endMark = lineAfterCaret;
  131. // Note we don't actually send the input line to the inferior
  132. // directly. That happens in ReplDocument.checkingPendingInput,
  133. // which is invoked by the inferior thread when it is woken up here.
  134. // We do it this way to handle interleaving prompts and other output
  135. // with multi-line input, including type-ahead.
  136. synchronized (in_r)
  137. {
  138. in_r.notifyAll();
  139. }
  140. if (pos <= lineAfterCaret)
  141. pane.setCaretPosition(lineAfterCaret+1);
  142. }
  143. else
  144. {
  145. int lineBefore = pos == 0 ? 0 : 1 + b.lastIndexOf('\n', pos-1);
  146. Element el = getCharacterElement(lineBefore);
  147. int lineAfter = b.indexOf('\n', pos);
  148. // Strip initial prompt:
  149. if (el.getAttributes().isEqual(ReplDocument.promptStyle))
  150. lineBefore = el.getEndOffset();
  151. String str;
  152. if (lineAfter < 0)
  153. str = b.substring(lineBefore, len)+'\n';
  154. else
  155. str = b.substring(lineBefore, lineAfter+1);
  156. pane.setCaretPosition(outputMark);
  157. write(str, ReplDocument.inputStyle);
  158. if (in_r != null) {
  159. in_r.append(str, 0, str.length());
  160. }
  161. }
  162. }
  163. /** Delete old text, prior to line containing outputMark. */
  164. public synchronized void deleteOldText ()
  165. {
  166. try
  167. {
  168. String str = getText(0, outputMark);
  169. int lineBefore = (outputMark <= 0 ? 0
  170. : (str.lastIndexOf('\n', outputMark-1)) + 1);
  171. remove(0, lineBefore);
  172. // Changelistener updates outputMark and endMark.
  173. }
  174. catch (BadLocationException ex)
  175. {
  176. /* #ifdef use:java.lang.Throwable.getCause */
  177. throw new Error(ex);
  178. /* #else */
  179. // throw new WrappedException(ex);
  180. /* #endif */
  181. }
  182. }
  183. @Override
  184. public void insertString(int pos, String str, AttributeSet style)
  185. {
  186. try
  187. {
  188. super.insertString(pos, str, style);
  189. }
  190. catch (BadLocationException ex)
  191. {
  192. /* #ifdef use:java.lang.Throwable.getCause */
  193. throw new Error(ex);
  194. /* #else */
  195. // throw new WrappedException(ex);
  196. /* #endif */
  197. }
  198. }
  199. /** Insert output from the client at the outputMark.
  200. * Done indirectly, using SwingUtilities.invokeLater, so it can and should
  201. * should be called by user threads, not the event thread.
  202. */
  203. public void write (final String str, final AttributeSet style)
  204. {
  205. SwingUtilities.invokeLater(new Runnable() {
  206. public void run()
  207. {
  208. boolean moveCaret
  209. = pane != null && pane.getCaretPosition() == outputMark;
  210. insertString(outputMark, str, style);
  211. int len = str.length();
  212. outputMark += len;
  213. if (moveCaret)
  214. pane.setCaretPosition(outputMark);
  215. }
  216. });
  217. }
  218. /** Check if there is any pending input.
  219. * Can and should be called by user threads, not the event thread.
  220. * The tricky aspect is supporting type-ahead and other multi-line input,
  221. * since we want prompts and other output to be properly interleaved.
  222. */
  223. public void checkingPendingInput ()
  224. {
  225. SwingUtilities.invokeLater(new Runnable() {
  226. public void run()
  227. {
  228. // For now, we don't support moving the outputMark using escape
  229. // sequences, so inputStart is always just outputMark.
  230. int inputStart = outputMark;
  231. if (inputStart <= endMark)
  232. {
  233. gnu.lists.CharBuffer b = content.buffer;
  234. int lineAfter = b.indexOf('\n', inputStart);
  235. if (lineAfter == endMark)
  236. endMark = -1;
  237. if (inputStart == outputMark) // Currently, always true.
  238. outputMark = lineAfter+1;
  239. if (in_r != null) {
  240. synchronized (in_r) {
  241. in_r.append(b, inputStart, lineAfter+1);
  242. in_r.notifyAll();
  243. }
  244. }
  245. }
  246. }
  247. });
  248. }
  249. public void focusGained(FocusEvent e)
  250. {
  251. Object source = e.getSource();
  252. if (source instanceof ReplPane)
  253. {
  254. pane = (ReplPane) source;
  255. //pane.getCaret().setDot(outputMark);
  256. }
  257. else
  258. pane = null;
  259. }
  260. public void focusLost(FocusEvent e)
  261. {
  262. pane = null;
  263. }
  264. public void changedUpdate (DocumentEvent e) { textValueChanged(e); }
  265. public void insertUpdate (DocumentEvent e) { textValueChanged(e); }
  266. public void removeUpdate (DocumentEvent e) { textValueChanged(e); }
  267. public synchronized void textValueChanged (DocumentEvent e) {
  268. // Update outputMark and endMark
  269. // Note that inserting at outputMark doesn't change outputMark,
  270. // That is done by the write method.
  271. int pos = e.getOffset();
  272. int delta = getLength() - length;
  273. length += delta;
  274. if (pos < outputMark)
  275. outputMark += delta;
  276. else if (pos - delta < outputMark)
  277. outputMark = pos;
  278. if (endMark >= 0)
  279. {
  280. if (pos < endMark)
  281. endMark += delta;
  282. else if (pos - delta < endMark)
  283. endMark = pos;
  284. }
  285. }
  286. void close () {
  287. in_r.appendEOF();
  288. // Give thread chance to finish and clean up
  289. try {
  290. Thread.sleep(100);
  291. } catch (InterruptedException ex) {
  292. }
  293. // Thread.stop is deprecated in JDK 1.2, but I see no good
  294. // alternative. (Thread.destroy is not implemented!)
  295. thread.stop();
  296. fireDocumentClosed();
  297. ModuleBody.exitDecrement();
  298. }
  299. // Either null, a single DocumentCloseListener or an ArrayList of the latter.
  300. Object closeListeners;
  301. /** Register a DocumentCloseListener. */
  302. public void addDocumentCloseListener (DocumentCloseListener listener)
  303. {
  304. if (closeListeners == null)
  305. closeListeners = listener;
  306. else
  307. {
  308. ArrayList vec;
  309. if (closeListeners instanceof ArrayList)
  310. vec = (ArrayList) closeListeners;
  311. else
  312. {
  313. vec = new ArrayList(10);
  314. vec.add(closeListeners);
  315. closeListeners = vec;
  316. }
  317. vec.add(listener);
  318. }
  319. }
  320. public void removeDocumentCloseListener (DocumentCloseListener listener)
  321. {
  322. if (closeListeners instanceof DocumentCloseListener)
  323. {
  324. if (closeListeners == listener)
  325. closeListeners = null;
  326. }
  327. else if (closeListeners != null)
  328. {
  329. ArrayList vec = (ArrayList) closeListeners;
  330. for (int i = vec.size(); --i >= 0; )
  331. {
  332. if (vec.get(i) == listener)
  333. vec.remove(i);
  334. }
  335. if (vec.isEmpty())
  336. closeListeners = null;
  337. }
  338. }
  339. void fireDocumentClosed ()
  340. {
  341. if (closeListeners instanceof DocumentCloseListener)
  342. ((DocumentCloseListener) closeListeners).closed(this);
  343. else if (closeListeners != null)
  344. {
  345. ArrayList vec = (ArrayList) closeListeners;
  346. for (int i = vec.size(); --i >= 0; )
  347. ((DocumentCloseListener) vec.get(i)).closed(this);
  348. }
  349. }
  350. /** Listener interface for when a document closes. */
  351. public static interface DocumentCloseListener
  352. {
  353. /** Called when a ReplDocument closes. */
  354. public void closed (ReplDocument doc);
  355. }
  356. }