KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > snow > text > SimpleDocument


1 package snow.text;
2
3 import snow.Basics;
4 import javax.swing.text.*;
5 import javax.swing.*;
6 import java.awt.*;
7 import java.util.*;
8 import java.io.*;
9
10 public class SimpleDocument extends DefaultStyledDocument implements Appendable JavaDoc
11 {
12
13   public SimpleColorHighlighter searchHighlighter = new SimpleColorHighlighter( new Color(30,190,30,70) );
14                    // UIManager.getColor("Tree.selectionBackground"));
15

16   public SimpleDocument()
17   {
18     super();
19
20     //Style defaultStyle = this.getStyle("default");
21
Style def = StyleContext.getDefaultStyleContext().getStyle(StyleContext.DEFAULT_STYLE);
22
23     Style regular = addStyle("regular", def); // the base
24

25     this.addStyle("body", regular);
26
27     Style error = this.addStyle("error", regular);
28     StyleConstants.setForeground(error, Color.red);
29
30     // no more used ?
31
Style highlightStyle = this.addStyle("highlight", regular);
32     StyleConstants.setBackground(highlightStyle, Color.blue);
33     StyleConstants.setForeground(highlightStyle, Color.white);
34
35     setTabsForDoc(2,20);
36   } // Constructor
37

38
39 /** slow !
40 */

41   public char getCharAt(int pos)
42   {
43     try
44     {
45       return this.getText(pos,1).charAt(0);
46     }
47     catch(Exception JavaDoc e)
48     {
49       System.err.println("Cannot read char at "+pos+" in doc: "+e.getMessage());
50       e.printStackTrace();
51       return 0;
52     }
53   }
54
55   /** @return the text from start(comprise) to end (non comprise)
56   */

57   public String JavaDoc getTextFromTo(int start, int end)
58   {
59     if(start==-1) return "";
60     if(end<=start) return "";
61
62     try
63     {
64       return getText(start, end-start);
65     }
66     catch(Exception JavaDoc e) { e.printStackTrace(); }
67     return "";
68   }
69
70
71   public void append(String JavaDoc s)
72   {
73     this.insertString(s, this.getLength());
74   }
75
76   public void appendLine(String JavaDoc s)
77   {
78     this.insertString(s+"\r\n", this.getLength());
79   }
80
81   public void appendErrorLine(String JavaDoc s)
82   {
83     try
84     {
85       this.insertString(this.getLength(), s+"\r\n", this.getStyle("error"));
86     }
87     catch(Exception JavaDoc e)
88     {
89       System.err.println("Cannot write text in doc:\n"+s);
90     }
91   }
92
93   public void appendError(String JavaDoc s)
94   {
95     try
96     {
97       this.insertString(this.getLength(), s, this.getStyle("error"));
98     }
99     catch(Exception JavaDoc e)
100     {
101       System.err.println("Cannot write text in doc:\n"+s);
102     }
103   }
104
105   /** called from the search/replace dialog...
106   */

107   public void replace(String JavaDoc txt, int pos, int len)
108   {
109      //try
110
{
111           //Element pe = getCharacterElement(pos);
112
//this.replace(pos, len, txt, pe.getAttributes());
113
// TEST MODE !!
114
this.setCharacterAttributes(pos, len, this.getStyle("highlight"), true);
115
116      }
117      //catch (BadLocationException e) {}
118
}
119
120   public void setText(String JavaDoc text)
121   {
122     clearDocument();
123     insertString(text, 0);
124   }
125
126   public void clearDocument()
127   {
128     writeLock();
129     try
130     {
131      this.remove(0, this.getLength());
132     }
133     catch(Exception JavaDoc ignored) { Basics.ignore(ignored); }
134     finally
135     {
136       writeUnlock();
137     }
138   }
139
140     double viewMagnification = 1.0;
141
142     /** called from editor to view the whole document with a bigger font
143     */

144     public void increaseFontSize()
145     {
146        viewMagnification *= 1.1;
147        rescaleFontSizes();
148     }
149
150     /** called from editor to view the whole document with a smaller font
151     */

152     public void decreaseFontSize()
153     {
154        viewMagnification /= 1.1;
155        rescaleFontSizes();
156     }
157
158     /** use the global viewMagnification factor
159     */

160     private void rescaleFontSizes()
161     {
162        int baseSize = UIManager.getFont("EditorPane.font").getSize(); // this is the user font from the look and feel ...
163

164        // ok, changing this cause change of comment, error, ... styles
165
Style s = this.getStyle("default");
166        //int fs = StyleConstants.getFontSize(s);
167
//System.out.println("actual regular fs: " + baseSize);
168

169        StyleConstants.setFontSize(s, (int) Math.round(viewMagnification*baseSize));
170     }
171
172   public void insertString(String JavaDoc s, int pos)
173   {
174     writeLock();
175     try
176     {
177      this.insertString(pos, s, this.getStyle("body")); // [Jan2006] use body style instead of the last !
178
}
179     catch(Exception JavaDoc ignored) { Basics.ignore(ignored); }
180     finally
181     {
182       writeUnlock();
183     }
184   }
185
186   /** gets the whole text !
187   */

188   public String JavaDoc getText()
189   {
190     readLock();
191     try
192     {
193       return this.getText(0, this.getLength());
194     }
195     catch(Exception JavaDoc err)
196     {
197       throw new RuntimeException JavaDoc(err);
198     }
199     finally
200     {
201       readUnlock();
202     }
203   }
204
205
206   //
207
// "Searchable"
208
//
209

210   /** @return -1 if not found
211   * @param ignoreCase if true, the text to search for must be passed in uppercase
212   */

213   public int search(String JavaDoc str, int from, boolean ignoreCase)
214   {
215     if(from <0) from = 0; // important !
216

217     readLock();
218     try
219     {
220       String JavaDoc textPart = this.getTextFromTo(from, this.getLength());
221       if(ignoreCase) textPart = textPart.toUpperCase();
222       int posPart = textPart.indexOf(str);
223       if(posPart==-1) return -1;
224       return posPart+from;
225     }
226     finally
227     {
228       readUnlock();
229     }
230     //return -1;
231
}
232
233
234   /** @return -1 if not found
235   * @param ignoreCase if true, the text to search for must be passed in uppercase
236   */

237   public int searchBackward(String JavaDoc str, int from, boolean ignoreCase)
238   {
239     if(from <0) from = this.getLength(); // important !
240

241     readLock();
242     try
243     {
244       String JavaDoc textPart = this.getTextFromTo(0, from);
245       if(ignoreCase) textPart = textPart.toUpperCase();
246       int posPart = textPart.lastIndexOf(str);
247       if(posPart==-1) return -1;
248       return posPart;
249     }
250     finally
251     {
252       readUnlock();
253     }
254     //return -1;
255
}
256
257
258   /** set the tab to be used for the document
259    */

260   public void setTabsForDoc(int tabWidth, int nTabs)
261   {
262      int fs = 12;
263      try
264      {
265        fs = UIManager.getFont("EditorPane.font").getSize();
266      }
267      catch(Exception JavaDoc e) {e.printStackTrace();}
268
269      int tabWidthInDPI = fs * tabWidth;
270
271      TabStop[] tabs = new TabStop[nTabs];
272      double tab = fs*tabWidth;
273      for (int j = 0; j < tabs.length; j++)
274      {
275         //System.out.println(""+tab);
276
tabs[j] = new TabStop((float) tab, TabStop.ALIGN_LEFT, TabStop.LEAD_NONE );
277         tab += tabWidthInDPI;
278      }
279      TabSet tabSet = new TabSet(tabs);
280      setTabsForDoc(tabSet);
281   }
282
283   public void setTabsForDoc(TabSet tabSet)
284   {
285      SimpleAttributeSet attributes = new SimpleAttributeSet();
286      StyleConstants.setTabSet(attributes, tabSet);
287      try
288      {
289         setParagraphAttributes(0, getLength(), attributes, false);
290      }
291      catch(Exception JavaDoc e)
292      {
293         throw new RuntimeException JavaDoc("Cannot set tabs: "+e.getMessage());
294      }
295   }
296
297   /** append txt with all lines prepended with prependLine (ex: "out> ")
298   */

299   public void appendNamed(String JavaDoc txt, String JavaDoc prependLine)
300   {
301      BufferedReader in = new BufferedReader(new StringReader(txt));
302      String JavaDoc line = null;
303      try
304      {
305       while( (line=in.readLine())!=null)
306       {
307          append("\n"+prependLine+line);
308       }
309      }
310      catch(Exception JavaDoc e)
311      {
312         appendError("Cannot read line: "+e.getMessage());
313      }
314   }
315
316   //
317
// Appendable
318
//
319
public Appendable JavaDoc append(char c)
320   {
321     this.append(""+c);
322     return this;
323   }
324   public Appendable JavaDoc append(CharSequence JavaDoc csq)
325   {
326     this.append(csq);
327     return this;
328   }
329
330   public Appendable JavaDoc append(CharSequence JavaDoc csq, int start, int end)
331   {
332     this.append(csq.subSequence(start,end));
333     return this;
334   }
335
336
337
338   // Allow transparently writing in this document using a Writer
339
//
340

341   public Writer createWriterForThisDocument(boolean errorMode)
342   {
343     return new DocWriter(errorMode);
344   }
345
346   class DocWriter extends Writer
347   {
348     boolean errorWriter;
349     public DocWriter(boolean errorWriter)
350     {
351       super(SimpleDocument.this);
352       errorWriter = errorWriter;
353     }
354
355     public void flush()
356     {
357     }
358
359     public void write(char[] cbuf, int off, int len)
360     {
361        try
362        {
363          if(errorWriter)
364          {
365             SimpleDocument.this.append(new String JavaDoc(cbuf,off,len)); // don't add directly here !!! (infinite loop !)
366
}
367          else
368          {
369             SimpleDocument.this.append(new String JavaDoc(cbuf,off,len)); // don't add directly here !!! (infinite loop !)
370
}
371        }
372        catch(Exception JavaDoc e)
373        {
374          appendErrorLine("\r\ncannot append char buffer: "+e.getMessage());
375        }
376     }
377
378     public void close()
379     {
380     }
381   }
382
383
384
385 } // SimpleDocument
Popular Tags