KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > edu > rice > cs > util > text > ConsoleDocument


1 /*BEGIN_COPYRIGHT_BLOCK
2  *
3  * This file is part of DrJava. Download the current version of this project from http://www.drjava.org/
4  * or http://sourceforge.net/projects/drjava/
5  *
6  * DrJava Open Source License
7  *
8  * Copyright (C) 2001-2005 JavaPLT group at Rice University (javaplt@rice.edu). All rights reserved.
9  *
10  * Developed by: Java Programming Languages Team, Rice University, http://www.cs.rice.edu/~javaplt/
11  *
12  * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
13  * documentation files (the "Software"), to deal with the Software without restriction, including without limitation
14  * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and
15  * to permit persons to whom the Software is furnished to do so, subject to the following conditions:
16  *
17  * - Redistributions of source code must retain the above copyright notice, this list of conditions and the
18  * following disclaimers.
19  * - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
20  * following disclaimers in the documentation and/or other materials provided with the distribution.
21  * - Neither the names of DrJava, the JavaPLT, Rice University, nor the names of its contributors may be used to
22  * endorse or promote products derived from this Software without specific prior written permission.
23  * - Products derived from this software may not be called "DrJava" nor use the term "DrJava" as part of their
24  * names without prior written permission from the JavaPLT group. For permission, write to javaplt@rice.edu.
25  *
26  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
27  * THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
28  * CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
29  * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
30  * WITH THE SOFTWARE.
31  *
32  * END_COPYRIGHT_BLOCK*/

33
34 package edu.rice.cs.util.text;
35
36 import java.awt.print.*;
37
38 import edu.rice.cs.drjava.model.print.DrJavaBook;
39
40 import edu.rice.cs.util.UnexpectedException;
41 import edu.rice.cs.util.text.EditDocumentInterface;
42 import edu.rice.cs.util.text.DocumentEditCondition;
43 import edu.rice.cs.util.text.EditDocumentException;
44
45 /** @version $Id: ConsoleDocument.java 4037 2006-11-20 20:04:32Z rcartwright $ */
46 public class ConsoleDocument implements EditDocumentInterface {
47   
48   /** Default text style. */
49   public static final String JavaDoc DEFAULT_STYLE = "default";
50
51   /** Style for System.out */
52   public static final String JavaDoc SYSTEM_OUT_STYLE = "System.out";
53
54   /** Style for System.err */
55   public static final String JavaDoc SYSTEM_ERR_STYLE = "System.err";
56
57   /** Style for System.in */
58   public static final String JavaDoc SYSTEM_IN_STYLE = "System.in";
59
60   /** The default prompt to use in the console. */
61   public static final String JavaDoc DEFAULT_CONSOLE_PROMPT = "";
62
63   /** The document storing the text for this console model. */
64   protected final EditDocumentInterface _document;
65
66   /** A runnable command to use for a notification beep. */
67   protected volatile Runnable JavaDoc _beep;
68
69   /** Index in the document of the first place that is editable. */
70   protected volatile int _promptPos;
71
72   /** String to use for the prompt. */
73   protected volatile String JavaDoc _prompt;
74
75   /** Whether the document currently has a prompt and is ready to accept input. */
76   protected volatile boolean _hasPrompt;
77   
78   /** The book object used for printing that represents several pages */
79   protected DrJavaBook _book;
80
81   /** Creates a new ConsoleDocument with the given EditDocumentInterface.
82    * @param adapter the EditDocumentInterface to use
83    */

84   public ConsoleDocument(EditDocumentInterface adapter) {
85     _document = adapter;
86     
87     _beep = new Runnable JavaDoc() { public void run() { } };
88     _promptPos = 0;
89     _prompt = DEFAULT_CONSOLE_PROMPT;
90     _hasPrompt = false;
91    
92     // Prevent any edits before the prompt!
93
_document.setEditCondition(new ConsoleEditCondition());
94   }
95
96   /** @return true iff this document has a prompt and is ready to accept input. */
97   public boolean hasPrompt() { return _hasPrompt; }
98
99   /** Accessor for the string used for the prompt. */
100   public String JavaDoc getPrompt() { return _prompt; }
101
102   /** Sets the string to use for the prompt.
103    * @param prompt String to use for the prompt.
104    */

105   public void setPrompt(String JavaDoc prompt) {
106     acquireWriteLock();
107     _prompt = prompt;
108     releaseWriteLock();
109   }
110
111   /** Gets the object which determines whether an insert/remove edit should be applied based on the inputs.
112    * @return the DocumentEditCondition to determine legality of inputs
113    */

114   public DocumentEditCondition getEditCondition() { return _document.getEditCondition(); }
115
116   /** Provides an object which can determine whether an insert or remove edit should be applied, based on
117    * the inputs.
118    * @param condition Object to determine legality of inputs
119    */

120   public void setEditCondition(DocumentEditCondition condition) { _document.setEditCondition(condition); }
121
122   /** Returns the first location in the document where editing is allowed. */
123   public int getPromptPos() { return _promptPos; }
124
125   /** Sets the prompt position.
126    * @param newPos the new position.
127    */

128   public void setPromptPos(int newPos) {
129     acquireReadLock();
130     _promptPos = newPos;
131     releaseReadLock();
132   }
133
134   /** Sets a runnable action to use as a beep.
135    * @param beep Runnable beep command
136    */

137   public void setBeep(Runnable JavaDoc beep) {
138     acquireReadLock();
139     _beep = beep;
140     releaseReadLock();
141   }
142
143   /** Resets the document to a clean state. */
144   public void reset(String JavaDoc banner) {
145     acquireWriteLock();
146     try {
147       forceRemoveText(0, _document.getLength());
148       forceInsertText(0, banner, DEFAULT_STYLE);
149       _promptPos = 0;
150     }
151     catch (EditDocumentException e) { throw new UnexpectedException(e); }
152     finally { releaseWriteLock(); }
153   }
154
155   /** Prints a prompt for a new input. */
156   public void insertPrompt() {
157     acquireWriteLock();
158     try {
159 // append(_prompt, DEFAULT_STYLE); // need forceAppend!
160
// _promptPos = _document.getLength();
161
// _hasPrompt = true;
162
forceInsertText(_document.getLength(), _prompt, DEFAULT_STYLE);
163       _promptPos = _document.getLength();
164       _hasPrompt = true;
165        
166     }
167     catch (EditDocumentException e) { throw new UnexpectedException(e); }
168     finally { releaseWriteLock(); }
169   }
170
171   /** Disables the prompt in this document. */
172   public void disablePrompt() {
173     acquireWriteLock();
174     try {
175     _hasPrompt = false;
176     _promptPos = _document.getLength();
177     }
178     finally { releaseWriteLock(); }
179   }
180
181   /** Inserts a new line at the given position.
182    * @param pos Position to insert the new line
183    */

184   public void insertNewLine(int pos) {
185     // Correct the position if necessary
186
acquireWriteLock();
187     try {
188       int len = _document.getLength();
189       if (pos > len) pos = len;
190       else if (pos < 0) pos = 0;
191       
192       String JavaDoc newLine = System.getProperty("line.separator");
193       insertText(pos, newLine, DEFAULT_STYLE);
194     }
195     catch (EditDocumentException e) { throw new UnexpectedException(e); }
196     finally { releaseWriteLock(); }
197   }
198
199   /** Gets the position immediately before the prompt, or the doc length if there is no prompt. */
200   public int getPositionBeforePrompt() {
201     acquireReadLock();
202     int len = _document.getLength();
203     try {
204       if (_hasPrompt) {
205         int promptStart = _promptPos - _prompt.length();
206         return (promptStart < len && promptStart >= 0) ? promptStart : len; // ensure position is within document
207
}
208       return len;
209     }
210     finally { releaseReadLock(); }
211   }
212
213   /** Inserts the given string with the given attributes just before the most recent prompt.
214    * @param text String to insert
215    * @param style name of style to format the string
216    */

217   public void insertBeforeLastPrompt(String JavaDoc text, String JavaDoc style) {
218     acquireWriteLock();
219     try {
220       int pos = getPositionBeforePrompt();
221       _promptPos += text.length();
222       _addToStyleLists(pos, text, style);
223       _document.forceInsertText(pos, text, style);
224     }
225     catch (EditDocumentException ble) { throw new UnexpectedException(ble); }
226     finally { releaseWriteLock(); }
227   }
228
229   /** Inserts a string into the document at the given offset and named style, if the edit condition allows it.
230    * @param offs Offset into the document
231    * @param str String to be inserted
232    * @param style Name of the style to use. Must have been added using addStyle.
233    * @throws EditDocumentException if the offset is illegal
234    */

235   public void insertText(int offs, String JavaDoc str, String JavaDoc style) throws EditDocumentException {
236     acquireWriteLock();
237     try {
238       if (offs < _promptPos) _beep.run();
239       else {
240         _addToStyleLists(offs, str, style);
241         _document.insertText(offs, str, style);
242       }
243     }
244     finally { releaseWriteLock(); }
245   }
246   
247   /** Appends a string to this in the given named style, if the edit condition allows it.
248    * @param str String to be inserted
249    * @param style Name of the style to use. Must have been added using addStyle.
250    * @throws EditDocumentException if the offset is illegal
251    */

252   public void append(String JavaDoc str, String JavaDoc style) throws EditDocumentException {
253     acquireWriteLock();
254     try {
255       int offs = _document.getLength();
256       _addToStyleLists(offs, str, style);
257       _document.insertText(offs, str, style);
258     }
259     finally { releaseWriteLock(); }
260   }
261   
262   /** Inserts a string into the document at the given offset and the given named style, regardless of the edit
263    * condition.
264    * @param offs Offset into the document
265    * @param str String to be inserted
266    * @param style Name of the style to use. Must have been added using addStyle.
267    * @throws EditDocumentException if the offset is illegal
268    */

269   public void forceInsertText(int offs, String JavaDoc str, String JavaDoc style) throws EditDocumentException {
270     acquireWriteLock();
271     try {
272       _addToStyleLists(offs, str, style);
273       _document.forceInsertText(offs, str, style);
274     }
275     finally { releaseWriteLock(); }
276   }
277   
278   private void _addToStyleLists(int offs, String JavaDoc str, String JavaDoc style) {
279     if (_document instanceof SwingDocument)
280       ((SwingDocument)_document).addColoring(offs, offs + str.length(), style);
281   }
282   /** Removes a portion of the document, if the edit condition allows it.
283    * @param offs Offset to start deleting from
284    * @param len Number of characters to remove
285    * @throws EditDocumentException if the offset or length are illegal
286    */

287   public void removeText(int offs, int len) throws EditDocumentException {
288     acquireWriteLock();
289     try {
290       if (offs < _promptPos) _beep.run();
291       else _document.removeText(offs, len);
292     }
293     finally { releaseWriteLock(); }
294   }
295
296   /** Removes a portion of the document, regardless of the edit condition.
297    * @param offs Offset to start deleting from
298    * @param len Number of characters to remove
299    * @throws EditDocumentException if the offset or length are illegal
300    */

301   public void forceRemoveText(int offs, int len) throws EditDocumentException {
302     _document.forceRemoveText(offs, len);
303   }
304
305   /** Returns the length of the document. */
306   public int getLength() { return _document.getLength(); }
307
308   /** Returns a portion of the document.
309    * @param offs First offset of the desired text
310    * @param len Number of characters to return
311    * @throws EditDocumentException if the offset or length are illegal
312    */

313   public String JavaDoc getDocText(int offs, int len) throws EditDocumentException {
314     return _document.getDocText(offs, len);
315   }
316
317   /** Returns the entire text of the document. Identical to getText() in AbstractDocumentInterface.
318    * @throws EditDocumentException if the offset or length are illegal
319    */

320   public String JavaDoc getText() {
321     acquireWriteLock();
322     try {
323       return _document.getDocText(0, getLength());
324     }
325     finally { releaseWriteLock(); }
326   }
327   
328   /** Returns the string that the user has entered at the current prompt.
329    * May contain newline characters.
330    */

331   public String JavaDoc getCurrentInput() {
332     acquireReadLock();
333     try {
334       try { return getDocText(_promptPos, _document.getLength() - _promptPos); }
335       catch (EditDocumentException e) { throw new UnexpectedException(e); }
336     }
337     finally { releaseReadLock(); }
338   }
339
340   /** Clears the current input text. */
341   public void clearCurrentInput() { _clearCurrentInputText(); }
342
343   /** Removes the text from the current prompt to the end of the document. */
344   protected void _clearCurrentInputText() {
345     acquireWriteLock();
346     try {
347       // Delete old value of current line
348
removeText(_promptPos, _document.getLength() - _promptPos);
349     }
350     catch (EditDocumentException ble) { throw new UnexpectedException(ble); }
351     finally { releaseWriteLock(); }
352   }
353   
354   /* Returns the default style for a "console" document. */
355   public String JavaDoc getDefaultStyle() { return ConsoleDocument.DEFAULT_STYLE; }
356
357   /** Returns the Pageable object for printing.
358    * @return A Pageable representing this document.
359    */

360   public Pageable getPageable() throws IllegalStateException JavaDoc { return _book; }
361   
362   /** This method tells the document to prepare all the DrJavaBook and PagePrinter objects. */
363   public void preparePrintJob() {
364     _book = new DrJavaBook(getDocText(0, getLength()), "Console", new PageFormat());
365   }
366   
367   /** Prints the given document by bringing up a "Print" window. */
368   public void print() throws PrinterException {
369     preparePrintJob();
370     PrinterJob printJob = PrinterJob.getPrinterJob();
371     printJob.setPageable(_book);
372     if (printJob.printDialog()) printJob.print();
373     cleanUpPrintJob();
374   }
375   
376   /** Clears the pageable object used to hold the print job. */
377   public void cleanUpPrintJob() { _book = null; }
378   
379   /** Class ensuring that attempts to edit document lines above the prompt are rejected. */
380   class ConsoleEditCondition extends DocumentEditCondition {
381     public boolean canInsertText(int offs) { return canRemoveText(offs); }
382     
383     public boolean canRemoveText(int offs) {
384       if (offs < _promptPos) {
385         _beep.run();
386         return false;
387       }
388       return true;
389     }
390   }
391   
392   /* Locking operations */
393   
394   /** Swing-style acquireReadLock(). */
395   public void acquireReadLock() { _document.acquireReadLock(); }
396   
397   /** Swing-style releaseReadLock(). */
398   public void releaseReadLock() { _document.releaseReadLock(); }
399   
400   /** Swing-style writeLock(). */
401   public void acquireWriteLock() { _document.acquireWriteLock(); }
402   
403   /** Swing-style writeUnlock(). */
404   public void releaseWriteLock() { _document.releaseWriteLock(); }
405   
406 // public int getLockState() { return _document.getLockState(); }
407
}
408
Popular Tags