KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > snow > texteditor > SimpleDocument


1 package snow.texteditor;
2
3 import snow.utils.DateUtils;
4 import snow.Basics;
5 import javax.swing.text.*;
6 import javax.swing.*;
7 import java.awt.*;
8 import java.util.*;
9 import java.io.*;
10
11 /** A simple styled document with highlighter, errors, writers, ...
12 */

13 public class SimpleDocument extends DefaultStyledDocument implements Appendable JavaDoc
14 {
15   public SimpleColorHighlighter searchHighlighter = new SimpleColorHighlighter( new Color(30,190,30,70) );
16                     // UIManager.getColor("Tree.selectionBackground"));
17
public SimpleColorHighlighter autoSelectHighlighter = new SimpleColorHighlighter( new Color(120, 120, 120, 50) );
18
19   public SimpleDocument()
20   {
21     super();
22
23     //Style defaultStyle = this.getStyle("default");
24
Style def = StyleContext.getDefaultStyleContext().getStyle(StyleContext.DEFAULT_STYLE);
25
26     Style regular = addStyle("regular", def); // the base
27

28     this.addStyle("body", regular);
29
30     Style error = this.addStyle("error", regular);
31     StyleConstants.setForeground(error, Color.red);
32
33     Style bold = this.addStyle("bold", regular);
34     StyleConstants.setBold(bold, true);
35
36     Style section = this.addStyle("section", regular);
37     StyleConstants.setBold(section, true);
38     StyleConstants.setFontSize(section, StyleConstants.getFontSize(section)+4);
39
40     // no more used ?
41
Style highlightStyle = this.addStyle("highlight", regular);
42     StyleConstants.setBackground(highlightStyle, Color.blue);
43     StyleConstants.setForeground(highlightStyle, Color.white);
44
45     setTabsForDoc(2,20);
46   } // Constructor
47

48
49 /** slow !
50 */

51   public char getCharAt(int pos)
52   {
53     try
54     {
55       return this.getText(pos,1).charAt(0);
56     }
57     catch(Exception JavaDoc e)
58     {
59       System.err.println("Cannot read char at "+pos+" in doc: "+e.getMessage());
60       e.printStackTrace();
61       return 0;
62     }
63   }
64
65   /** @return the text from start(comprise) to end (non comprise)
66   */

67   public String JavaDoc getTextFromTo(int start, int end)
68   {
69     if(start==-1) return "";
70     if(end<=start) return "";
71
72     try
73     {
74       return getText(start, end-start);
75     }
76     catch(Exception JavaDoc e) { e.printStackTrace(); }
77     return "";
78   }
79
80
81   public void append(String JavaDoc s)
82   {
83     this.insertString(s, this.getLength());
84   }
85
86   public void appendLine(String JavaDoc s)
87   {
88     this.insertString(s+"\r\n", this.getLength());
89   }
90
91   public void appendDatedLine(String JavaDoc s)
92   {
93     // not human (Yesterday, ...)
94
this.insertString(DateUtils.formatDateAndTimeFix(System.currentTimeMillis())+": "+s+"\r\n", this.getLength());
95   }
96
97   public void appendErrorLine(String JavaDoc s)
98   {
99     try
100     {
101       this.insertString(this.getLength(), s+"\r\n", this.getStyle("error"));
102     }
103     catch(Exception JavaDoc e)
104     {
105       System.err.println("Cannot write text in doc:\n"+s);
106     }
107   }
108
109   public void appendError(String JavaDoc s)
110   {
111     try
112     {
113       this.insertString(this.getLength(), s, this.getStyle("error"));
114     }
115     catch(Exception JavaDoc e)
116     {
117       System.err.println("Cannot write text in doc:\n"+s);
118     }
119   }
120
121   public void appendBold(String JavaDoc s)
122   {
123     try
124     {
125       this.insertString(this.getLength(), s, this.getStyle("bold"));
126     }
127     catch(Exception JavaDoc e)
128     {
129       System.err.println("Cannot write text in doc:\n"+s);
130     }
131   }
132
133   public void appendSection(String JavaDoc s)
134   {
135     try
136     {
137       this.insertString(this.getLength(), s, this.getStyle("section"));
138     }
139     catch(Exception JavaDoc e)
140     {
141       System.err.println("Cannot write text in doc:\n"+s);
142     }
143   }
144
145   /** Called from the search/replace dialog...
146   */

147   public void replace(String JavaDoc txt, int pos, int len)
148   {
149      //try
150
{
151           //Element pe = getCharacterElement(pos);
152
//this.replace(pos, len, txt, pe.getAttributes());
153
// TEST MODE !!
154
this.setCharacterAttributes(pos, len, this.getStyle("highlight"), true);
155
156      }
157      //catch (BadLocationException e) {}
158
}
159
160   public void setText(String JavaDoc text)
161   {
162     clearDocument();
163     insertString(text, 0);
164   }
165
166   public void clearDocument()
167   {
168     writeLock();
169     try
170     {
171      this.remove(0, this.getLength());
172     }
173     catch(Exception JavaDoc ignored) { Basics.ignore(ignored); }
174     finally
175     {
176       writeUnlock();
177     }
178   }
179
180     double viewMagnification = 1.0;
181
182     /** called from editor to view the whole document with a bigger font
183     */

184     public void increaseFontSize()
185     {
186        viewMagnification *= 1.1;
187        rescaleFontSizes();
188     }
189
190     /** called from editor to view the whole document with a smaller font
191     */

192     public void decreaseFontSize()
193     {
194        viewMagnification /= 1.1;
195        rescaleFontSizes();
196     }
197
198     /** use the global viewMagnification factor
199     */

200     private void rescaleFontSizes()
201     {
202        int baseSize = UIManager.getFont("EditorPane.font").getSize(); // this is the user font from the look and feel ...
203

204        // ok, changing this cause change of comment, error, ... styles
205
Style s = this.getStyle("default");
206        //int fs = StyleConstants.getFontSize(s);
207
//System.out.println("actual regular fs: " + baseSize);
208

209        StyleConstants.setFontSize(s, (int) Math.round(viewMagnification*baseSize));
210     }
211
212   public void insertString(String JavaDoc s, int pos)
213   {
214     writeLock();
215     try
216     {
217      this.insertString(pos, s, this.getStyle("body")); // [Jan2006] use body style instead of the last !
218
}
219     catch(Exception JavaDoc ignored) { Basics.ignore(ignored); }
220     finally
221     {
222       writeUnlock();
223     }
224   }
225
226   /** gets the whole text !
227   */

228   public String JavaDoc getText()
229   {
230     readLock();
231     try
232     {
233       return this.getText(0, this.getLength());
234     }
235     catch(Exception JavaDoc err)
236     {
237       throw new RuntimeException JavaDoc(err);
238     }
239     finally
240     {
241       readUnlock();
242     }
243   }
244
245
246   //
247
// "Searchable"
248
//
249

250   /** @return -1 if not found
251   * @param ignoreCase if true, the text to search for must be passed in uppercase
252   */

253   public int search(String JavaDoc str, int from, boolean ignoreCase)
254   {
255     if(from <0) from = 0; // important !
256

257     readLock();
258     try
259     {
260       String JavaDoc textPart = this.getTextFromTo(from, this.getLength());
261       if(ignoreCase) textPart = textPart.toUpperCase();
262       int posPart = textPart.indexOf(str);
263       if(posPart==-1) return -1;
264       return posPart+from;
265     }
266     finally
267     {
268       readUnlock();
269     }
270     //return -1;
271
}
272
273
274   /** @return -1 if not found
275   * @param ignoreCase if true, the text to search for must be passed in uppercase
276   */

277   public int searchBackward(String JavaDoc str, int from, boolean ignoreCase)
278   {
279     if(from <0) from = this.getLength(); // important !
280

281     readLock();
282     try
283     {
284       String JavaDoc textPart = this.getTextFromTo(0, from);
285       if(ignoreCase) textPart = textPart.toUpperCase();
286       int posPart = textPart.lastIndexOf(str);
287       if(posPart==-1) return -1;
288       return posPart;
289     }
290     finally
291     {
292       readUnlock();
293     }
294     //return -1;
295
}
296
297
298   /** set the tab to be used for the document
299    */

300   public void setTabsForDoc(int tabWidth, int nTabs)
301   {
302      int fs = 12;
303      try
304      {
305        fs = UIManager.getFont("EditorPane.font").getSize();
306      }
307      catch(Exception JavaDoc e) {e.printStackTrace();}
308
309      int tabWidthInDPI = fs * tabWidth;
310
311      TabStop[] tabs = new TabStop[nTabs];
312      double tab = fs*tabWidth;
313      for (int j = 0; j < tabs.length; j++)
314      {
315         //System.out.println(""+tab);
316
tabs[j] = new TabStop((float) tab, TabStop.ALIGN_LEFT, TabStop.LEAD_NONE );
317         tab += tabWidthInDPI;
318      }
319      TabSet tabSet = new TabSet(tabs);
320      setTabsForDoc(tabSet);
321   }
322
323   public void setTabsForDoc(TabSet tabSet)
324   {
325      SimpleAttributeSet attributes = new SimpleAttributeSet();
326      StyleConstants.setTabSet(attributes, tabSet);
327      try
328      {
329         setParagraphAttributes(0, getLength(), attributes, false);
330      }
331      catch(Exception JavaDoc e)
332      {
333         throw new RuntimeException JavaDoc("Cannot set tabs: "+e.getMessage());
334      }
335   }
336
337   /** append txt with all lines prepended with prependLine (ex: "out> ")
338   * don't forget the CR at end...
339   */

340   public void appendNamed(String JavaDoc txt, String JavaDoc prependLine)
341   {
342      BufferedReader in = new BufferedReader(new StringReader(txt));
343      String JavaDoc line = null;
344      try
345      {
346       while( (line=in.readLine())!=null)
347       {
348          append("\n"+prependLine+line);
349       }
350      }
351      catch(Exception JavaDoc e)
352      {
353         appendError("Cannot read line: "+e.getMessage());
354      }
355   }
356
357   //
358
// Appendable
359
//
360
public Appendable JavaDoc append(char c)
361   {
362     this.append(""+c);
363     return this;
364   }
365   public Appendable JavaDoc append(CharSequence JavaDoc csq)
366   {
367     this.append(csq);
368     return this;
369   }
370
371   public Appendable JavaDoc append(CharSequence JavaDoc csq, int start, int end)
372   {
373     this.append(csq.subSequence(start,end));
374     return this;
375   }
376
377
378   // Allow connecting system.out / err
379
//
380

381   public PrintStream createPrintStreamForThisDocument(boolean errorMode)
382   {
383     //avoid passing null
384
OutputStream os = new OutputStream()
385     {
386        public void write( int b ) {
387        }
388     };
389
390     FilterOutputStream fs = new FilterOutputStream(os)
391     {
392          /*@Override
393          public synchronized void write(final int b) throws IOException
394          {
395
396          }*/

397          @Override JavaDoc
398          public synchronized void write(final byte[] b, final int off, final int len) throws IOException
399          {
400            append(new String JavaDoc(b, off, len));
401          }
402          @Override JavaDoc
403          public synchronized void write(final byte[] b) throws IOException
404          {
405            append(new String JavaDoc(b));
406          }
407     };
408     return new PrintStream(fs);
409   }
410
411
412   // Allow transparently writing in this document using a Writer
413
//
414

415   public Writer createWriterForThisDocument(boolean errorMode)
416   {
417     return new DocWriter(errorMode);
418   }
419
420   class DocWriter extends Writer
421   {
422     boolean errorWriter;
423     public DocWriter(boolean errorWriter)
424     {
425       super(SimpleDocument.this);
426       errorWriter = errorWriter;
427     }
428
429     public void flush()
430     {
431     }
432
433     public void write(char[] cbuf, int off, int len)
434     {
435        try
436        {
437          if(errorWriter)
438          {
439             SimpleDocument.this.append(new String JavaDoc(cbuf,off,len)); // don't add directly here !!! (infinite loop !)
440
}
441          else
442          {
443             SimpleDocument.this.append(new String JavaDoc(cbuf,off,len)); // don't add directly here !!! (infinite loop !)
444
}
445        }
446        catch(Exception JavaDoc e)
447        {
448          appendErrorLine("\r\ncannot append char buffer: "+e.getMessage());
449        }
450     }
451
452     public void close()
453     {
454     }
455   }
456
457
458 }
Popular Tags