Added
Link Here
|
1 |
/* |
2 |
* Sun Public License Notice |
3 |
* |
4 |
* The contents of this file are subject to the Sun Public License |
5 |
* Version 1.0 (the "License"). You may not use this file except in |
6 |
* compliance with the License. A copy of the License is available at |
7 |
* http://www.sun.com/ |
8 |
* |
9 |
* The Original Code is NetBeans. The Initial Developer of the Original |
10 |
* Code is Sun Microsystems, Inc. Portions Copyright 1997-2003 Sun |
11 |
* Microsystems, Inc. All Rights Reserved. |
12 |
*/ |
13 |
|
14 |
/* |
15 |
* HtmlRenderer.java |
16 |
* |
17 |
* Created on January 2, 2004, 12:49 AM |
18 |
*/ |
19 |
package org.openide.awt; |
20 |
|
21 |
import org.openide.ErrorManager; |
22 |
|
23 |
import javax.swing.*; |
24 |
import javax.swing.table.TableCellRenderer; |
25 |
import javax.swing.tree.TreeCellRenderer; |
26 |
import java.awt.*; |
27 |
import java.awt.font.LineMetrics; |
28 |
import java.awt.geom.Area; |
29 |
import java.awt.geom.Rectangle2D; |
30 |
import java.util.*; |
31 |
|
32 |
/** |
33 |
* A lightweight html renderer supporting a minimal subset of HTML used for |
34 |
* markup purposes only - basic font styles, colors, etc. Also supports |
35 |
* named logical colors specified by a preceding ! character for specifying |
36 |
* colors that should be looked up in the current look and feel's UIDefaults |
37 |
* (e.g. <code><font color=&!textText&></code>). |
38 |
* <p> |
39 |
* Provides a generic cell renderer implementation which can be used for trees, tables, |
40 |
* lists, combo boxes, etc. |
41 |
* <p> |
42 |
* If you only need to paint some HTML quickly, use the static methods for |
43 |
* painting - <code>renderString</code>, <code>renderPlainString</code> or |
44 |
* <code>renderHtml</code>. These methods differ as follows: |
45 |
* <ul> |
46 |
* <li><b>renderString</b> will check the string for opening HTML tags |
47 |
* (upper or lower but not mixed case) and call either <code>renderPlainString</code> |
48 |
* or <code>renderHtml</code> as appropriate. Note this method does not tolerate |
49 |
* whitespace in opening html tags - it expects exactly 6 characters to make up |
50 |
* the opening tag if present.</li> |
51 |
* <li><b>renderPlainString</b> simply renders a string to the graphics context, |
52 |
* takes the same agruments as <code>renderHtml</code>, but will also honor |
53 |
* <code>STYLE_TRUNCATE</code>, so strings can be rendered with trailing |
54 |
* elipsis if there is not enough space</li> |
55 |
* <li><b>renderHtml</b> renders whatever is passed to it as HTML, regardless |
56 |
* of whether it has opening HTML tags or not. It can be used to render plain |
57 |
* strings, but <code>renderPlainString</code> is faster for that. It is useful |
58 |
* if you want to render a string you <strong>know</strong> to be compliant |
59 |
* HTML markup, but which does not have opening and closing HTML tags (though |
60 |
* they are harmless if present). </li> |
61 |
* <p> |
62 |
* This parser is designed entirely for performance; there are no separate parsing |
63 |
* and rendering loops. In order to acheive its performance, some trade offs |
64 |
* are required. |
65 |
* <strong>To reiterate: This is not a forgiving HTML parser - the HTML supplied |
66 |
* must follow the guidelines documented here!</strong> |
67 |
* <p> |
68 |
* The following tags are supported, in upper or lower (but not mixed) case: |
69 |
* |
70 |
* <table> |
71 |
* <tr> |
72 |
* <td><B></td> |
73 |
* <td>Boldface text</td> |
74 |
* </tr> |
75 |
* <tr> |
76 |
* <td><S></td> |
77 |
* <td>Strikethrough text</td> |
78 |
* </tr> |
79 |
* <tr> |
80 |
* <td><U></td> |
81 |
* <td>Underline text</td> |
82 |
* </tr> |
83 |
* <tr> |
84 |
* <td><I></td> |
85 |
* <td>Italic text</td> |
86 |
* </tr> |
87 |
* <tr> |
88 |
* <td><EM></td> |
89 |
* <td>Emphasized text (same as italic)</td> |
90 |
* </tr> |
91 |
* <tr> |
92 |
* <td><STRONG></td> |
93 |
* <td>Strong text (same as bold)</td> |
94 |
* </tr> |
95 |
* <tr> |
96 |
* <td><font></td> |
97 |
* <td>Font color - font attributes other than color are not supported. Colors |
98 |
* may be specified as hexidecimal strings, such as #FF0000 or as logical colors |
99 |
* defined in the current look and feel by specifying a ! character as the first |
100 |
* character of the color name. Logical colors are colors available from the |
101 |
* current look and feel's UIManager. For example, <code><font |
102 |
* color="!Tree.background"></code> will set the font color to the |
103 |
* result of <code>UIManager.getColor("Tree.background")</code>. |
104 |
* <strong>Font size tags are not supported.</strong> |
105 |
* </td> |
106 |
* </tr> |
107 |
* </table> |
108 |
* The lightweight html renderer supports the following named sgml character |
109 |
* entities: <code>quot, lt, amp, lsquo, rsquo, ldquo, rdquo, ndash, mdash, ne, |
110 |
* le, ge, copy, reg, trade. </code>. It also supports numeric entities |
111 |
* (e.g. <code>&8822;</code>). |
112 |
* <p><b>Why not use the JDK's HTML support?</b> The JDK's HTML support works |
113 |
* well for stable components, but suffers from performance problems in the |
114 |
* case of cell renderers - each call to set the text (which happens once per |
115 |
* cell, per paint) causes a document tree to be created in memory. For small, |
116 |
* markup only strings, this is overkill. For rendering short strings |
117 |
* (for example, in a tree or table cell renderer) |
118 |
* with limited HTML, this method is approximately 10x faster than standard |
119 |
* Swing HTML rendering. |
120 |
* |
121 |
* <P><B><U>Specifying logical colors</U></B><BR> |
122 |
* Hardcoded text colors are undesirable, as they can be incompatible (even |
123 |
* invisible) on some look and feels or themes, depending on the background |
124 |
* color. |
125 |
* The lightweight HTML renderer supports a non-standard syntax for specifying |
126 |
* font colors via a key for a color in the UI defaults for the current look |
127 |
* and feel. This is accomplished by prefixing the key name with a <code>!</code> |
128 |
* character. For example: <code><font color='!controlShadow'></code>. |
129 |
* |
130 |
* <P><B><U>Modes of operation</U></B><BR> |
131 |
* This method supports two modes of operation: |
132 |
* <OL> |
133 |
* <LI><CODE>STYLE_CLIP</CODE> - as much text as will fit in the pixel width passed |
134 |
* to the method should be painted, and the text should be cut off at the maximum |
135 |
* width or clip rectangle maximum X boundary for the graphics object, whichever is |
136 |
* smaller.</LI> |
137 |
* <LI><CODE>STYLE_TRUNCATE</CODE> - paint as much text as will fit in the pixel |
138 |
* width passed to the method, but paint the last three characters as .'s, in the |
139 |
* same manner as a JLabel truncates its text when the available space is too |
140 |
* small.</LI> |
141 |
* </OL> |
142 |
* <P> |
143 |
* The paint methods can also be used in non-painting mode to establish the space |
144 |
* necessary to paint a string. This is accomplished by passing the value of the |
145 |
* <code>paint</code> argument as false. The return value will be the required |
146 |
* width in pixels |
147 |
* to display the text. Note that in order to retrieve an |
148 |
* accurate value, the argument for available width should be passed |
149 |
* as <code>Integer.MAX_VALUE</code> or an appropriate maximum size - otherwise |
150 |
* the return value will either be the passed maximum width or the required |
151 |
* width, whichever is smaller. Also, the clip shape for the passed graphics |
152 |
* object should be null or a value larger than the maximum possible render size, |
153 |
* or text size measurement will stop at the clip bounds. <code>HtmlRenderer.getGraphics()</code> |
154 |
* will always return non-null and non-clipped, and is suitable to pass in such a |
155 |
* situation. |
156 |
* <P> |
157 |
* |
158 |
* @since 4.30 |
159 |
* @see org.openide.nodes.Node#getHtmlDisplayName |
160 |
* @see org.openide.filesystems.FileSystem.HtmlStatus |
161 |
* @author Tim Boudreau |
162 |
*/ |
163 |
public final class HtmlRenderer { |
164 |
private static HtmlRendererImpl LABEL = null; |
165 |
|
166 |
private HtmlRenderer() { |
167 |
//do nothing |
168 |
} |
169 |
|
170 |
/** |
171 |
* Returns an instance of Renderer which may be used as a table/tree/list cell renderer. |
172 |
* This method must be called on the AWT event thread. If you <strong>know</strong> you will |
173 |
* be passing it legal HTML (legal as documented here), call <code>setHtml(true)</code> on the |
174 |
* result of this call <strong>after calling getNNNCellRenderer</code> to provide this hint. |
175 |
* |
176 |
* @return A cell renderer that can render HTML. |
177 |
*/ |
178 |
public static final Renderer createRenderer () { |
179 |
return new HtmlRendererImpl(); |
180 |
} |
181 |
|
182 |
/** |
183 |
* For HTML rendering jobs outside of trees/lists/tables, returns a JLabel which will paint its text using |
184 |
* the lightweight HTML renderer. The result of this call will implement the <code>Renderer</code> interface. |
185 |
* To use, simply call <code>sharedLabel()</code>, configure the text, etc., and paint it to a graphics context |
186 |
* (SwingUtilities.paintComponent() is not needed - simply call paint (Graphics), which is much faster), or |
187 |
* take its preferred size if using it to measure text dimensions. |
188 |
* <p> |
189 |
* Do not hold a reference to the return value of this call - other code may reconfigure it unexpectedly. |
190 |
* The shared instance's state is reset to default font, alignment, etc., on each call to <code>sharedLabel</code>. |
191 |
* <p> |
192 |
* This method must be called only from the AWT event thread; this is enforced with assertions. |
193 |
* |
194 |
* @return A JLabel which can render a subset of html very quickly |
195 |
* @param renderStyle The rendering style. Currently supported are STYLE_TRUNCATE and STYLE_CLIP. |
196 |
* @param isHtml Null if the text might or might not be HTML and will have opening HTML tags if it is. |
197 |
* Boolean.TRUE if the text is definitely HTML, and might not have opening HTML tags. |
198 |
* Boolean.FALSE if the text should be rendered as plain text even <i>if</i> it contains |
199 |
* HTML markup. |
200 |
*/ |
201 |
public static final JLabel sharedLabel (int renderStyle, Boolean isHtml) { |
202 |
assert SwingUtilities.isEventDispatchThread() : "HtmlRenderer.sharedLabel " + //NOI18N |
203 |
"may only be accessed on the event dispatch thread"; //NOI18N |
204 |
|
205 |
switch (renderStyle) { |
206 |
case STYLE_TRUNCATE : |
207 |
case STYLE_CLIP : |
208 |
break; |
209 |
default : |
210 |
throw new IllegalArgumentException ("Unknown render style " + renderStyle); //NOI18N |
211 |
} |
212 |
|
213 |
if (LABEL == null) { |
214 |
LABEL = new HtmlRendererImpl(); |
215 |
} else { |
216 |
LABEL.reset(); |
217 |
} |
218 |
|
219 |
if (isHtml != null) { |
220 |
LABEL.setHtml(isHtml.booleanValue()); |
221 |
} |
222 |
|
223 |
LABEL.setRenderStyle(renderStyle); |
224 |
return LABEL; |
225 |
} |
226 |
|
227 |
/** Interface aggregating TableCellRenderer, TreeCellRenderer and ListCellRenderer. |
228 |
* Return type of <code>sharedInstance()</code>. |
229 |
*/ |
230 |
public interface Renderer extends TableCellRenderer, TreeCellRenderer, ListCellRenderer { |
231 |
/** Indicate that the component being rendered has keyboard focus. NetBeans requires that a different |
232 |
* selection color be used depending on whether the view has focus. |
233 |
* |
234 |
* @param parentFocused Whether or not the focused selection color should be used |
235 |
*/ |
236 |
void setParentFocused (boolean parentFocused); |
237 |
|
238 |
/** |
239 |
* Indicate that the text should be painted centered below the icon. This is primarily used |
240 |
* by org.openide.explorer.view.IconView |
241 |
* |
242 |
* @param centered Whether or not centered painting should be used. |
243 |
*/ |
244 |
void setCentered (boolean centered); |
245 |
|
246 |
/** |
247 |
* Set a number of pixels the icon and text should be indented. Used by ChoiceView and ListView to |
248 |
* fake tree-style nesting. This value has no effect if <code>setCentered(true)</code> has been called. |
249 |
* |
250 |
* @param pixels The number of pixels to indent |
251 |
*/ |
252 |
void setIndent (int pixels); |
253 |
|
254 |
/** |
255 |
* Explicitly tell the renderer it is going to receive HTML markup, or it is not. If the renderer should |
256 |
* check the string for opening HTML tags to determine this, don't call this method. If you <strong>know</strong> |
257 |
* the string will be compliant HTML, it is preferable to call this method with true; if you want to intentionally |
258 |
* render HTML markup literally, call this method with false. |
259 |
* |
260 |
* @param val |
261 |
*/ |
262 |
void setHtml (boolean val); |
263 |
|
264 |
/** |
265 |
* Set the rendering style - this can be JLabel-style truncated-with-elipsis (...) text, or clipped text. |
266 |
* The default is STYLE_CLIP. |
267 |
* |
268 |
* @param style The text style |
269 |
*/ |
270 |
void setRenderStyle (int style); |
271 |
|
272 |
/** Set the icon to be used for painting |
273 |
* |
274 |
* @param icon An icon or null |
275 |
*/ |
276 |
void setIcon (Icon icon); |
277 |
|
278 |
/** Clear any stale data from previous use by other components, |
279 |
* clearing the icon, text, disabled state and other customizations, returning the component |
280 |
* to its initialized state. This is done automatically when get*CellRenderer() is called, |
281 |
* and to the shared instance when <code>sharedLabel()</code> is called.<p> |
282 |
* Users of the static <code>sharedLabel()</code> method may want to call this method if they |
283 |
* use the returned instance more than once without again calling <code>sharedLabel()</code>. |
284 |
*/ |
285 |
void reset(); |
286 |
|
287 |
/** Set the text to be displayed. Use this if the object being rendered's toString() does not |
288 |
* return a real user-displayable string, after calling get**CellRenderer(). Typically after calling |
289 |
* this one calls setHtml() if the text is known to either be or not be HTML markup. |
290 |
* |
291 |
* @param txt The text that should be displayed |
292 |
*/ |
293 |
void setText (String txt); |
294 |
|
295 |
/** |
296 |
* Convenience method to set the gap between the icon and text. |
297 |
* |
298 |
* @param gap an integer number of pixels |
299 |
*/ |
300 |
void setIconTextGap (int gap); |
301 |
} |
302 |
|
303 |
/** Stack object used during HTML rendering to hold previous colors in |
304 |
* the case of nested color entries. */ |
305 |
private static Stack colorStack = new Stack(); |
306 |
/** Constant used by <code>renderString</code>, <code>renderPlainString</code> |
307 |
* <code>renderHTML</code>, and <code>HtmlRenderer.setRenderStyle</code> |
308 |
* if painting should simply be cut off at the boundary of the cooordinates passed. */ |
309 |
public static final int STYLE_CLIP=0; |
310 |
/** Constant used by <code>renderString</code>, <code>renderPlainString</code> |
311 |
* <code>renderHTML</code> and <code>HtmlRenderer.setRenderStyle</code> if |
312 |
* painting should produce an ellipsis (...) |
313 |
* if the text would overlap the boundary of the coordinates passed */ |
314 |
public static final int STYLE_TRUNCATE=1; |
315 |
/** Constant used by <code>renderString</code>, <code>renderPlainString</code> |
316 |
* <code>renderHTML</code> and <code>HtmlRenderer.setRenderStyle</code> |
317 |
* if painting should word wrap the text. In |
318 |
* this case, the return value of any of the above methods will be the |
319 |
* height, rather than width painted. */ |
320 |
private static final int STYLE_WORDWRAP=2; |
321 |
/** System property to cause exceptions to be thrown when unparsable |
322 |
* html is encountered */ |
323 |
private static final boolean strictHtml = Boolean.getBoolean( |
324 |
"netbeans.lwhtml.strict"); //NOI18N |
325 |
/** Cache for strings which have produced errors, so we don't post an |
326 |
* error message more than once */ |
327 |
private static Set badStrings=null; |
328 |
/** Definitions for a limited subset of sgml character entities */ |
329 |
private static final Object[] entities = new Object[] { |
330 |
new char[] {'g','t'}, new char[] {'l','t'}, //NOI18N |
331 |
new char[] {'q','u','o','t'}, new char[] {'a','m','p'}, //NOI18N |
332 |
new char[] {'l','s','q','u','o'}, //NOI18N |
333 |
new char[] {'r','s','q','u','o'}, //NOI18N |
334 |
new char[] {'l','d','q','u','o'}, //NOI18N |
335 |
new char[] {'r','d','q','u','o'}, //NOI18N |
336 |
new char[] {'n','d','a','s','h'}, //NOI18N |
337 |
new char[] {'m','d','a','s','h'}, //NOI18N |
338 |
new char[] {'n','e'}, //NOI18N |
339 |
new char[] {'l','e'}, //NOI18N |
340 |
new char[] {'g','e'}, //NOI18N |
341 |
|
342 |
new char[] {'c','o','p','y'}, //NOI18N |
343 |
new char[] {'r','e','g'}, //NOI18N |
344 |
new char[] {'t','r','a','d','e'} //NOI18N |
345 |
//The rest of the SGML entities are left as an excercise for the reader |
346 |
}; //NOI18N |
347 |
/** Mappings for the array of sgml character entities to characters */ |
348 |
private static final char[] entitySubstitutions = new char[] { |
349 |
'>','<','"','&',8216, 8217, 8220, 8221, 8211, 8212, 8800, 8804, 8805, //NOI18N |
350 |
169, 174, 8482 |
351 |
}; |
352 |
|
353 |
/**Render a string to a graphics instance, using the same API as renderHTML(). |
354 |
* Can render a string using JLabel-style ellipsis (...) in the case that |
355 |
* it will not fit in the passed rectangle, if the style parameter is |
356 |
* STYLE_CLIP. Returns the width in pixels successfully painted. |
357 |
* <strong>This method is not thread-safe and should not be called off |
358 |
* the AWT thread.</strong> |
359 |
* |
360 |
* @see #renderHTML */ |
361 |
public static double renderPlainString(String s, Graphics g, int x, int y, int w, int h, Font f, Color defaultColor, int style, boolean paint) { |
362 |
assert SwingUtilities.isEventDispatchThread(); |
363 |
//per Jarda's request, keep the word wrapping code but don't expose it. |
364 |
if (style < 0 || style > 1) { |
365 |
throw new IllegalArgumentException( |
366 |
"Unknown rendering mode: " + style); //NOI18N |
367 |
} |
368 |
return _renderPlainString(s, g, x, y, w, h, f, defaultColor, style, |
369 |
paint); |
370 |
} |
371 |
|
372 |
private static double _renderPlainString(String s, Graphics g, int x, int y, int w, int h, Font f, Color foreground, int style, boolean paint) { |
373 |
FontMetrics fm = g.getFontMetrics(f); |
374 |
Rectangle2D r = fm.getStringBounds(s, g); |
375 |
if (paint) { |
376 |
g.setColor(foreground); |
377 |
g.setFont(f); |
378 |
if ((r.getWidth() <= w) || (style == STYLE_CLIP)) { |
379 |
g.drawString(s, x, y); |
380 |
} else { |
381 |
char[] chars = new char[s.length()]; |
382 |
s.getChars(0, s.length()-1, chars, 0); |
383 |
if (chars.length == 0) { |
384 |
return 0; |
385 |
} |
386 |
double chWidth = r.getWidth() / chars.length; |
387 |
int estCharsOver = new Double((r.getWidth() - w) / chWidth).intValue(); |
388 |
if (style == STYLE_TRUNCATE) { |
389 |
int length = chars.length - estCharsOver; |
390 |
if (length <=0) { |
391 |
return 0; |
392 |
} |
393 |
if (paint) { |
394 |
if (length > 3) { |
395 |
Arrays.fill(chars, length-3, length, '.'); //NOI18N |
396 |
g.drawChars(chars, 0, length, x, y); |
397 |
} else { |
398 |
Shape shape = g.getClip(); |
399 |
if (s != null) { |
400 |
Area area = new Area(shape); |
401 |
area.intersect (new Area(new Rectangle(x,y,w,h))); |
402 |
g.setClip(area); |
403 |
} else { |
404 |
g.setClip(new Rectangle(x,y,w,h)); |
405 |
} |
406 |
g.drawString("...", x,y); |
407 |
g.setClip(shape); |
408 |
} |
409 |
} |
410 |
} else { |
411 |
//TODO implement plaintext word wrap if we want to support it at some point |
412 |
} |
413 |
} |
414 |
} |
415 |
return r.getWidth(); |
416 |
} |
417 |
|
418 |
/** Render a string to a graphics context, using HTML markup if the string |
419 |
* begins with html tags. Delegates to <code>renderPlainString()</code> |
420 |
* or <code>renderHTML()</code> as appropriate. See the documentation for |
421 |
* <code>renderHTML()</code> for details of the subset of HTML that is |
422 |
* supported. |
423 |
* @param s The string to render |
424 |
* @param g A graphics object into which the string should be drawn, or which should be |
425 |
* used for calculating the appropriate size |
426 |
* @param x The x coordinate to paint at. |
427 |
* @param y The y position at which to paint. Note that this method does not calculate font |
428 |
* height/descent - this value should be the baseline for the line of text, not |
429 |
* the upper corner of the rectangle to paint in. |
430 |
* @param w The maximum width within which to paint. |
431 |
* @param h The maximum height within which to paint. |
432 |
* @param f The base font to be used for painting or calculating string width/height. |
433 |
* @param defaultColor The base color to use if no font color is specified as html tags |
434 |
* @param style The wrapping style to use, either <code>STYLE_CLIP</CODE>, |
435 |
* or <CODE>STYLE_TRUNCATE</CODE> |
436 |
* @param paint True if actual painting should occur. If false, this method will not actually |
437 |
* paint anything, only return a value representing the width/height needed to |
438 |
* paint the passed string. |
439 |
* @return The width in pixels required |
440 |
* to paint the complete string, or the passed parameter <code>w</code> if it is |
441 |
* smaller than the required width. |
442 |
*/ |
443 |
public static double renderString(String s, Graphics g, int x, int y, int w, int h, Font f, Color defaultColor, int style, boolean paint) { |
444 |
if (s.startsWith("<html") || s.startsWith("<HTML")) { //NOI18N |
445 |
if (style < 0 || style > 1) { |
446 |
throw new IllegalArgumentException( |
447 |
"Unknown rendering mode: " + style); //NOI18N |
448 |
} |
449 |
return _renderHTML(6, s, g, x, y, w, h, f, defaultColor, style, paint); |
450 |
} else { |
451 |
return renderPlainString(s, g, x, y, w, h, f, defaultColor, style, paint); |
452 |
} |
453 |
} |
454 |
|
455 |
/** Render a string as HTML using a fast, lightweight renderer supporting a limited |
456 |
* subset of HTML. The following tags are supported, in upper or lower case: |
457 |
* |
458 |
* <table> |
459 |
* <tr> |
460 |
* <td><B></td> |
461 |
* <td>Boldface text</td> |
462 |
* </tr> |
463 |
* <tr> |
464 |
* <td><S></td> |
465 |
* <td>Strikethrough text</td> |
466 |
* </tr> |
467 |
* <tr> |
468 |
* <td><U></td> |
469 |
* <td>Underline text</td> |
470 |
* </tr> |
471 |
* <tr> |
472 |
* <td><I></td> |
473 |
* <td>Italic text</td> |
474 |
* </tr> |
475 |
* <tr> |
476 |
* <td><EM></td> |
477 |
* <td>Emphasized text (same as italic)</td> |
478 |
* </tr> |
479 |
* <tr> |
480 |
* <td><STRONG></td> |
481 |
* <td>Strong text (same as bold)</td> |
482 |
* </tr> |
483 |
* <tr> |
484 |
* <td><font></td> |
485 |
* <td>Font color - font attributes other than color are not supported. Colors |
486 |
* may be specified as hexidecimal strings, such as #FF0000 or as logical colors |
487 |
* defined in the current look and feel by specifying a ! character as the first |
488 |
* character of the color name. Logical colors are colors available from the |
489 |
* current look and feel's UIManager. For example, <code><font |
490 |
* color="!Tree.background"></code> will set the font color to the |
491 |
* result of <code>UIManager.getColor("Tree.background")</code>. |
492 |
* <strong>Font size tags are not supported.</strong> |
493 |
* </td> |
494 |
* </tr> |
495 |
* </table> |
496 |
* The lightweight html renderer supports the following named sgml character |
497 |
* entities: <code>quot, lt, amp, lsquo, rsquo, ldquo, rdquo, ndash, mdash, ne, |
498 |
* le, ge, copy, reg, trade. </code>. It also supports numeric entities |
499 |
* (e.g. <code>&#8822;</code>). |
500 |
* <p><b>When to use this method instead of the JDK's HTML support: </b> when |
501 |
* rendering short strings (for example, in a tree or table cell renderer) |
502 |
* with limited HTML, this method is approximately 10x faster than JDK HTML |
503 |
* rendering (it does not build and parse a document tree). |
504 |
* |
505 |
* <P><B><U>Specifying logical colors</U></B><BR> |
506 |
* Hardcoded text colors are undesirable, as they can be incompatible (even |
507 |
* invisible) on some look and feels or themes. |
508 |
* The lightweight HTML renderer supports a non-standard syntax for specifying |
509 |
* font colors via a key for a color in the UI defaults for the current look |
510 |
* and feel. This is accomplished by prefixing the key name with a <code>!</code> |
511 |
* character. For example: <code><font color='!controlShadow'></code>. |
512 |
* |
513 |
* <P><B><U>Modes of operation</U></B><BR> |
514 |
* This method supports two modes of operation: |
515 |
* <OL> |
516 |
* <LI><CODE>STYLE_CLIP</CODE> - as much text as will fit in the pixel width passed |
517 |
* to the method should be painted, and the text should be cut off at the maximum |
518 |
* width or clip rectangle maximum X boundary for the graphics object, whichever is |
519 |
* smaller.</LI> |
520 |
* <LI><CODE>STYLE_TRUNCATE</CODE> - paint as much text as will fit in the pixel |
521 |
* width passed to the method, but paint the last three characters as .'s, in the |
522 |
* same manner as a JLabel truncates its text when the available space is too |
523 |
* small.</LI> |
524 |
* </OL> |
525 |
* <P> |
526 |
* This method can also be used in non-painting mode to establish the space |
527 |
* necessary to paint a string. This is accomplished by passing the value of the |
528 |
* <code>paint</code> argument as false. The return value will be the required |
529 |
* width in pixels |
530 |
* to display the text. Note that in order to retrieve an |
531 |
* accurate value, the argument for available width should be passed |
532 |
* as <code>Integer.MAX_VALUE</code> or an appropriate maximum size - otherwise |
533 |
* the return value will either be the passed maximum width or the required |
534 |
* width, whichever is smaller. Also, the clip shape for the passed graphics |
535 |
* object should be null or a value larger than the maximum possible render size. |
536 |
* <P> |
537 |
* This method will log a warning if it encounters HTML markup it cannot |
538 |
* render. To aid diagnostics, if NetBeans is run with the argument |
539 |
* <code>-J-Dnetbeans.lwhtml.strict=true</code> an exception will be thrown |
540 |
* when an attempt is made to render unsupported HTML.</code><p> |
541 |
* <p> |
542 |
* @param s The string to render |
543 |
* @param g A graphics object into which the string should be drawn, or which should be |
544 |
* used for calculating the appropriate size |
545 |
* @param x The x coordinate to paint at. |
546 |
* @param y The y position at which to paint. Note that this method does not calculate font |
547 |
* height/descent - this value should be the baseline for the line of text, not |
548 |
* the upper corner of the rectangle to paint in. |
549 |
* @param w The maximum width within which to paint. |
550 |
* @param h The maximum height within which to paint. |
551 |
* @param f The base font to be used for painting or calculating string width/height. |
552 |
* @param defaultColor The base color to use if no font color is specified as html tags |
553 |
* @param style The wrapping style to use, either <code>STYLE_CLIP</CODE>, |
554 |
* or <CODE>STYLE_TRUNCATE</CODE> |
555 |
* @param paint True if actual painting should occur. If false, this method will not actually |
556 |
* paint anything, only return a value representing the width/height needed to |
557 |
* paint the passed string. |
558 |
* @return The width in pixels required |
559 |
* to paint the complete string, or the passed parameter <code>w</code> if it is |
560 |
* smaller than the required width. |
561 |
*/ |
562 |
public static double renderHTML(String s, Graphics g, int x, int y, |
563 |
int w, int h, Font f, |
564 |
Color defaultColor, int style, |
565 |
boolean paint) { |
566 |
|
567 |
assert SwingUtilities.isEventDispatchThread(); |
568 |
|
569 |
//per Jarda's request, keep the word wrapping code but don't expose it. |
570 |
if (style < 0 || style > 1) { |
571 |
throw new IllegalArgumentException( |
572 |
"Unknown rendering mode: " + style); //NOI18N |
573 |
} |
574 |
return _renderHTML(0, s, g, x, y, w, h, f, defaultColor, style, |
575 |
paint); |
576 |
} |
577 |
|
578 |
/** Implementation of HTML rendering */ |
579 |
private static double _renderHTML(int pos, String s, Graphics g, int x, |
580 |
int y, int w, int h, Font f, Color defaultColor, int style, |
581 |
boolean paint) { |
582 |
|
583 |
//Thread safety - avoid allocating memory for the common case |
584 |
Stack colorStack = SwingUtilities.isEventDispatchThread() ? |
585 |
HtmlRenderer.colorStack : new Stack(); |
586 |
|
587 |
g.setColor(defaultColor); |
588 |
g.setFont(f); |
589 |
char[] chars = s.toCharArray(); |
590 |
int origX = x; |
591 |
boolean done = false; //flag if rendering completed, either by finishing the string or running out of space |
592 |
boolean inTag = false; //flag if the current position is inside a tag, and the tag should be processed rather than rendering |
593 |
boolean inClosingTag = false; //flag if the current position is inside a closing tag |
594 |
boolean strikethrough = false; //flag if a strikethrough line should be painted |
595 |
boolean underline = false; //flag if an underline should be painted |
596 |
boolean bold = false; //flag if text is currently bold |
597 |
boolean italic = false; //flag if text is currently italic |
598 |
boolean truncated = false; //flag if the last possible character has been painted, and the next loop should paint "..." and return |
599 |
double widthPainted = 0; //the total width painted, for calculating needed space |
600 |
double heightPainted = 0; //the total height painted, for calculating needed space |
601 |
boolean lastWasWhitespace = false; //flag to skip additional whitespace if one whitespace char already painted |
602 |
double lastHeight=0; //the last line height, for calculating total required height |
603 |
FontMetrics baseFontMetrics = g.getFontMetrics(g.getFont()); |
604 |
|
605 |
|
606 |
double dotWidth = 0; |
607 |
//Calculate the width of a . character if we may need to truncate |
608 |
if (style == STYLE_TRUNCATE) { |
609 |
dotWidth = g.getFontMetrics().charWidth('.'); //NOI18N |
610 |
} |
611 |
|
612 |
/* How this all works, for anyone maintaining this code (hopefully it will |
613 |
never need it): |
614 |
1. The string is converted to a char array |
615 |
2. Loop over the characters. Variable pos is the current point. |
616 |
2a. See if we're in a tag by or'ing inTag with currChar == '<' |
617 |
If WE ARE IN A TAG: |
618 |
2a1: is it an opening tag? |
619 |
If YES: |
620 |
- Identify the tag, Configure the Graphics object with |
621 |
the appropriate font, color, etc. Set pos = the first |
622 |
character after the tag |
623 |
If NO (it's a closing tag) |
624 |
- Identify the tag. Reconfigure the Graphics object |
625 |
with the state it should be in outside the tag |
626 |
(reset the font if italic, pop a color off the stack, etc.) |
627 |
2b. If WE ARE NOT IN A TAG |
628 |
- Locate the next < or & character or the end of the string |
629 |
- Paint the characters using the Graphics object |
630 |
- Check underline and strikethrough tags, and paint line if |
631 |
needed |
632 |
See if we're out of space, and do the right thing for the style |
633 |
(paint ..., give up or skip to the next line) |
634 |
*/ |
635 |
|
636 |
//Clear any junk left behind from a previous rendering loop |
637 |
colorStack.clear(); |
638 |
|
639 |
//Enter the painting loop |
640 |
while (!done) { |
641 |
if (pos == s.length()) { |
642 |
return widthPainted; |
643 |
} |
644 |
//see if we're in a tag |
645 |
try { |
646 |
inTag |= chars[pos] == '<'; |
647 |
} catch (ArrayIndexOutOfBoundsException e) { |
648 |
//Should there be any problem, give a meaningful enough |
649 |
//message to reproduce the problem |
650 |
ArrayIndexOutOfBoundsException aib = |
651 |
new ArrayIndexOutOfBoundsException( |
652 |
"HTML rendering failed at position " + pos + " in String \"" //NOI18N |
653 |
+ s + "\". Please report this at http://www.netbeans.org"); //NOI18N |
654 |
|
655 |
if (strictHtml) { |
656 |
throw aib; |
657 |
} else { |
658 |
ErrorManager.getDefault().notify (ErrorManager.WARNING, aib); |
659 |
return renderPlainString(s, g, x, y, w, h, f, defaultColor, style, paint); |
660 |
} |
661 |
} |
662 |
inClosingTag = inTag && (pos+1 < chars.length) && chars[pos+1] == '/'; //NOI18N |
663 |
|
664 |
if (truncated) { |
665 |
//Then we've almost run out of space, time to print ... and quit |
666 |
g.setColor(defaultColor); |
667 |
g.setFont(f); |
668 |
if (paint) { |
669 |
g.drawString("...", x, y); //NOI18N |
670 |
} |
671 |
done = true; |
672 |
} else if (inTag) { |
673 |
//If we're in a tag, don't paint, process it |
674 |
pos++; |
675 |
int tagEnd = pos; |
676 |
while (!done && (chars[tagEnd] != '>')) { |
677 |
done = tagEnd == chars.length -1; |
678 |
tagEnd++; |
679 |
} |
680 |
|
681 |
if (inClosingTag) { |
682 |
//Handle closing tags by resetting the Graphics object (font, etc.) |
683 |
pos++; |
684 |
switch (chars[pos]) { |
685 |
case 'P' : //NOI18N |
686 |
case 'p' : //NOI18N |
687 |
case 'H' : //NOI18N |
688 |
case 'h' : break; //ignore html opening/closing tags |
689 |
case 'B' : //NOI18N |
690 |
case 'b' : //NOI18N |
691 |
if (chars[pos+1] == 'r' || chars[pos+1] == 'R') { |
692 |
break; |
693 |
} |
694 |
if (!bold) { |
695 |
throwBadHTML("Closing bold tag w/o " + //NOI18N |
696 |
"opening bold tag", pos, chars); //NOI18N |
697 |
} |
698 |
if (italic) { |
699 |
g.setFont(f.deriveFont(Font.ITALIC)); |
700 |
} else { |
701 |
g.setFont(f.deriveFont(Font.PLAIN)); |
702 |
} |
703 |
bold = false; |
704 |
break; |
705 |
case 'E' : //NOI18N |
706 |
case 'e' : //em tag |
707 |
case 'I' : //NOI18N |
708 |
case 'i' : //NOI18N |
709 |
if (bold) { |
710 |
g.setFont(f.deriveFont(Font.BOLD)); |
711 |
} else { |
712 |
g.setFont(f.deriveFont(Font.PLAIN)); |
713 |
} |
714 |
if (!italic) { |
715 |
throwBadHTML("Closing italics tag w/o" //NOI18N |
716 |
+ "opening italics tag", pos, chars); //NOI18N |
717 |
} |
718 |
italic = false; |
719 |
break; |
720 |
case 'S' : //NOI18N |
721 |
case 's' : //NOI18N |
722 |
switch (chars[pos+1]) { |
723 |
case 'T' : //NOI18N |
724 |
case 't' : if (italic) { //NOI18N |
725 |
g.setFont(f.deriveFont( |
726 |
Font.ITALIC)); |
727 |
} else { |
728 |
g.setFont(f.deriveFont( |
729 |
Font.PLAIN)); |
730 |
} |
731 |
bold = false; |
732 |
break; |
733 |
case '>' : //NOI18N |
734 |
strikethrough = false; |
735 |
break; |
736 |
} |
737 |
break; |
738 |
case 'U' : //NOI18N |
739 |
case 'u' : underline = false; //NOI18N |
740 |
break; |
741 |
case 'F' : //NOI18N |
742 |
case 'f' : //NOI18N |
743 |
if (colorStack.isEmpty()) { |
744 |
g.setColor(defaultColor); |
745 |
} else { |
746 |
g.setColor((Color) colorStack.pop()); |
747 |
} |
748 |
break; |
749 |
default : |
750 |
throwBadHTML( |
751 |
"Malformed or unsupported HTML", //NOI18N |
752 |
pos, chars); |
753 |
} |
754 |
} else { |
755 |
//Okay, we're in an opening tag. See which one and configure the Graphics object |
756 |
switch (chars[pos]) { |
757 |
case 'B' : //NOI18N |
758 |
case 'b' : //NOI18N |
759 |
switch (chars[pos+1]) { |
760 |
case 'R' : //NOI18N |
761 |
case 'r' : //NOI18N |
762 |
if (style == STYLE_WORDWRAP) { |
763 |
x = origX; |
764 |
int lineHeight = g.getFontMetrics().getHeight(); |
765 |
y += lineHeight; |
766 |
heightPainted += lineHeight; |
767 |
widthPainted = 0; |
768 |
} |
769 |
break; |
770 |
case '>' : |
771 |
bold = true; |
772 |
if (italic) { |
773 |
g.setFont(f.deriveFont(Font.BOLD | Font.ITALIC)); |
774 |
} else { |
775 |
g.setFont(f.deriveFont(Font.BOLD)); |
776 |
} |
777 |
break; |
778 |
} |
779 |
break; |
780 |
case 'e' : //NOI18N //em tag |
781 |
case 'E' : //NOI18N |
782 |
case 'I' : //NOI18N |
783 |
case 'i' : //NOI18N |
784 |
italic = true; |
785 |
if (bold) { |
786 |
g.setFont(f.deriveFont(Font.ITALIC | Font.BOLD)); |
787 |
} else { |
788 |
g.setFont(f.deriveFont(Font.ITALIC)); |
789 |
} |
790 |
break; |
791 |
case 'S' : //NOI18N |
792 |
case 's' : //NOI18N |
793 |
switch (chars[pos+1]) { |
794 |
case '>' : |
795 |
strikethrough = true; |
796 |
break; |
797 |
case 'T' : |
798 |
case 't' : |
799 |
bold = true; |
800 |
if (italic) { |
801 |
g.setFont(f.deriveFont(Font.BOLD | Font.ITALIC)); |
802 |
} else { |
803 |
g.setFont(f.deriveFont(Font.BOLD)); |
804 |
} |
805 |
break; |
806 |
} |
807 |
break; |
808 |
case 'U' : //NOI18N |
809 |
case 'u' : //NOI18N |
810 |
underline = true; |
811 |
break; |
812 |
case 'f' : //NOI18N |
813 |
case 'F' : //NOI18N |
814 |
Color c = findColor(chars, pos, tagEnd); |
815 |
colorStack.push(g.getColor()); |
816 |
g.setColor(c); |
817 |
break; |
818 |
case 'P' : //NOI18N |
819 |
case 'p' : //NOI18N |
820 |
if (style == STYLE_WORDWRAP) { |
821 |
x = origX; |
822 |
int lineHeight=g.getFontMetrics().getHeight(); |
823 |
y += lineHeight + (lineHeight / 2); |
824 |
heightPainted = y + lineHeight; |
825 |
widthPainted = 0; |
826 |
} |
827 |
break; |
828 |
case 'H' : |
829 |
case 'h' : //Just an opening HTML tag |
830 |
if (pos == 1) { |
831 |
break; |
832 |
} |
833 |
default : throwBadHTML( |
834 |
"Malformed or unsupported HTML", pos, chars); //NOI18N |
835 |
} |
836 |
} |
837 |
|
838 |
pos = tagEnd + (done ? 0 : 1); |
839 |
inTag = false; |
840 |
} else { |
841 |
//Okay, we're not in a tag, we need to paint |
842 |
|
843 |
if (lastWasWhitespace) { |
844 |
//Skip multiple whitespace characters |
845 |
while (pos < s.length() && Character.isWhitespace(chars[pos])) { |
846 |
pos++; |
847 |
} |
848 |
//Check strings terminating with multiple whitespace - |
849 |
//otherwise could get an AIOOBE here |
850 |
if (pos == chars.length - 1) { |
851 |
return style != STYLE_WORDWRAP ? widthPainted : heightPainted; |
852 |
} |
853 |
} |
854 |
|
855 |
//Flag to indicate if an ampersand entity was processed, |
856 |
//so the resulting & doesn't get treated as the beginning of |
857 |
//another entity (and loop endlessly) |
858 |
boolean isAmp=false; |
859 |
//Flag to indicate the next found < character really should |
860 |
//be painted (it came from an entity), it is not the beginning |
861 |
//of a tag |
862 |
boolean nextLtIsEntity=false; |
863 |
int nextTag = chars.length-1; |
864 |
if ((chars[pos] == '&')) { //NOI18N |
865 |
boolean inEntity=pos != chars.length-1; |
866 |
if (inEntity) { |
867 |
int newPos = substEntity(chars, pos+1); |
868 |
inEntity = newPos != -1; |
869 |
if (inEntity) { |
870 |
pos = newPos; |
871 |
isAmp = chars[pos] == '&'; //NOI18N |
872 |
//flag it so the next iteration won't think the < |
873 |
//starts a tag |
874 |
nextLtIsEntity = chars[pos] == '<'; |
875 |
} else { |
876 |
nextLtIsEntity = false; |
877 |
isAmp = true; |
878 |
} |
879 |
} |
880 |
} else { |
881 |
nextLtIsEntity=false; |
882 |
} |
883 |
|
884 |
for (int i=pos; i < chars.length; i++) { |
885 |
if (((chars[i] == '<') && (!nextLtIsEntity)) || ((chars[i] == '&') && !isAmp)) { //NOI18N |
886 |
nextTag = i-1; |
887 |
break; |
888 |
} |
889 |
//Reset these flags so we don't skip all & or < chars for the rest of the string |
890 |
isAmp = false; |
891 |
nextLtIsEntity=false; |
892 |
} |
893 |
|
894 |
|
895 |
FontMetrics fm = g.getFont() == f ? baseFontMetrics : g.getFontMetrics(g.getFont()); |
896 |
|
897 |
//Get the bounds of the substring we'll paint |
898 |
Rectangle2D r = fm.getStringBounds(chars, pos, nextTag + 1, g); |
899 |
//Store the height, so we can add it if we're in word wrap mode, |
900 |
//to return the height painted |
901 |
lastHeight = r.getHeight(); |
902 |
//Work out the length of this tag |
903 |
int length = (nextTag + 1) - pos; |
904 |
|
905 |
//Flag to be set to true if we run out of space |
906 |
boolean goToNextRow = false; |
907 |
|
908 |
//Flag that the current line is longer than the available width, |
909 |
//and should be wrapped without finding a word boundary |
910 |
boolean brutalWrap = false; |
911 |
//Work out the per-character avg width of the string, for estimating |
912 |
//when we'll be out of space and should start the ... in truncate |
913 |
//mode |
914 |
double chWidth; |
915 |
|
916 |
if (style == STYLE_TRUNCATE) { |
917 |
//if we're truncating, use the width of one dot from an |
918 |
//ellipsis to get an accurate result for truncation |
919 |
chWidth = dotWidth; |
920 |
} else { |
921 |
//calculate an average character width |
922 |
chWidth= r.getWidth() / (nextTag - pos); |
923 |
//can return this sometimes, so handle it |
924 |
if (chWidth == Double.POSITIVE_INFINITY || chWidth == Double.NEGATIVE_INFINITY) { |
925 |
chWidth = fm.getMaxAdvance(); |
926 |
} |
927 |
} |
928 |
|
929 |
|
930 |
if ((style != STYLE_CLIP) && |
931 |
((style == STYLE_TRUNCATE && |
932 |
(widthPainted + r.getWidth() > w - (chWidth * 3)))) || |
933 |
(style == STYLE_WORDWRAP && |
934 |
(widthPainted + r.getWidth() > w))) { |
935 |
|
936 |
if (chWidth > 3) { |
937 |
double pixelsOff = (widthPainted + ( |
938 |
r.getWidth() + 5) |
939 |
) - w; |
940 |
|
941 |
double estCharsOver = pixelsOff / chWidth; |
942 |
|
943 |
if (style == STYLE_TRUNCATE) { |
944 |
int charsToPaint = Math.round(Math.round(Math.ceil((w - widthPainted) / chWidth))); |
945 |
/* System.err.println("estCharsOver = " + estCharsOver); |
946 |
System.err.println("Chars to paint " + charsToPaint + " chwidth = " + chWidth + " widthPainted " + widthPainted); |
947 |
System.err.println("Width painted + width of tag: " + (widthPainted + r.getWidth()) + " available: " + w); |
948 |
*/ |
949 |
|
950 |
int startPeriodsPos = pos + charsToPaint -3; |
951 |
if (startPeriodsPos >= chars.length) { |
952 |
startPeriodsPos = chars.length - 4; |
953 |
} |
954 |
length = (startPeriodsPos - pos); |
955 |
if (length < 0) length = 0; |
956 |
r = fm.getStringBounds(chars, pos, pos+length, g); |
957 |
// System.err.println("Truncated set to true at " + pos + " (" + chars[pos] + ")"); |
958 |
truncated = true; |
959 |
} else { |
960 |
//Word wrap mode |
961 |
goToNextRow = true; |
962 |
int lastChar = new Double(nextTag - |
963 |
estCharsOver).intValue(); |
964 |
//Unlike Swing's word wrap, which does not wrap on tag boundaries correctly, if we're out of space, |
965 |
//we're out of space |
966 |
brutalWrap = x == 0; |
967 |
for (int i = lastChar; i > pos; i--) { |
968 |
lastChar--; |
969 |
if (Character.isWhitespace(chars[i])) { |
970 |
length = (lastChar - pos) + 1; |
971 |
brutalWrap = false; |
972 |
break; |
973 |
} |
974 |
} |
975 |
if ((lastChar <= pos) && (length > estCharsOver) |
976 |
&& !brutalWrap) { |
977 |
x = origX; |
978 |
y += r.getHeight(); |
979 |
heightPainted += r.getHeight(); |
980 |
boolean boundsChanged = false; |
981 |
while (!done && Character.isWhitespace( |
982 |
chars[pos]) && (pos < nextTag)) { |
983 |
pos++; |
984 |
boundsChanged = true; |
985 |
done = pos == chars.length -1; |
986 |
} |
987 |
if (pos == nextTag) { |
988 |
lastWasWhitespace = true; |
989 |
} |
990 |
if (boundsChanged) { |
991 |
//recalculate the width we will add |
992 |
r = fm.getStringBounds(chars, pos, |
993 |
nextTag + 1, g); |
994 |
} |
995 |
goToNextRow = false; |
996 |
widthPainted = 0; |
997 |
if (chars[pos - 1 + length] == '<') { |
998 |
length --; |
999 |
} |
1000 |
} else if (brutalWrap) { |
1001 |
//wrap without checking word boundaries |
1002 |
length = (new Double( |
1003 |
(w - widthPainted) / chWidth)).intValue(); |
1004 |
if (pos + length > nextTag) { |
1005 |
length = (nextTag - pos); |
1006 |
} |
1007 |
goToNextRow = true; |
1008 |
} |
1009 |
} |
1010 |
} |
1011 |
} |
1012 |
if (!done) { |
1013 |
if (paint) { |
1014 |
g.drawChars(chars, pos, length, x, y); |
1015 |
} |
1016 |
|
1017 |
if (strikethrough || underline) { |
1018 |
LineMetrics lm = fm.getLineMetrics(chars, pos, |
1019 |
length - 1, g); |
1020 |
int lineWidth = new Double(x + r.getWidth()).intValue(); |
1021 |
if (paint) { |
1022 |
if (strikethrough) { |
1023 |
int stPos = Math.round(lm.getStrikethroughOffset()) + |
1024 |
g.getFont().getBaselineFor(chars[pos]) |
1025 |
+ 1; |
1026 |
//PENDING - worth supporting with g.setStroke()? A one pixel line is most likely |
1027 |
//good enough |
1028 |
|
1029 |
//int stThick = Math.round (lm.getStrikethroughThickness()); |
1030 |
g.drawLine(x, y + stPos, lineWidth, y + stPos); |
1031 |
} |
1032 |
if (underline) { |
1033 |
int stPos = Math.round( |
1034 |
lm.getUnderlineOffset()) + |
1035 |
g.getFont().getBaselineFor(chars[pos]) |
1036 |
+ 1; |
1037 |
//PENDING - worth supporting with g.setStroke()? A one pixel line is most likely |
1038 |
//good enough |
1039 |
|
1040 |
//int stThick = new Float (lm.getUnderlineThickness()).intValue(); |
1041 |
g.drawLine(x, y + stPos, lineWidth, y + stPos); |
1042 |
} |
1043 |
} |
1044 |
} |
1045 |
if (goToNextRow) { |
1046 |
//if we're in word wrap mode and need to go to the next |
1047 |
//line, reconfigure the x and y coordinates |
1048 |
x = origX; |
1049 |
y += r.getHeight(); |
1050 |
heightPainted += r.getHeight(); |
1051 |
widthPainted = 0; |
1052 |
pos += (length); |
1053 |
//skip any leading whitespace |
1054 |
while ((pos < chars.length) && |
1055 |
(Character.isWhitespace(chars[pos])) && |
1056 |
(chars[pos] != '<')) { |
1057 |
pos++; |
1058 |
} |
1059 |
lastWasWhitespace = true; |
1060 |
done |= pos >= chars.length; |
1061 |
} else { |
1062 |
x += r.getWidth(); |
1063 |
widthPainted += r.getWidth(); |
1064 |
lastWasWhitespace = Character.isWhitespace( |
1065 |
chars[nextTag]); |
1066 |
pos = nextTag + 1; |
1067 |
} |
1068 |
done |= nextTag == chars.length; |
1069 |
} |
1070 |
} |
1071 |
} |
1072 |
if (style != STYLE_WORDWRAP) { |
1073 |
return widthPainted; |
1074 |
} else { |
1075 |
return heightPainted + lastHeight; |
1076 |
} |
1077 |
} |
1078 |
|
1079 |
/** Parse a font color tag and return an appopriate java.awt.Color instance */ |
1080 |
private static Color findColor(final char[] ch, final int pos, |
1081 |
final int tagEnd) { |
1082 |
int colorPos = pos; |
1083 |
boolean useUIManager = false; |
1084 |
for (int i=pos; i < tagEnd; i ++) { |
1085 |
if (ch[i] == 'c') { |
1086 |
colorPos = i + 6; |
1087 |
if (ch[colorPos] == '\'' || ch[colorPos] == '"') { |
1088 |
colorPos++; |
1089 |
} |
1090 |
//skip the leading # character |
1091 |
if (ch[colorPos] == '#') { |
1092 |
colorPos++; |
1093 |
} else if (ch[colorPos] == '!') { |
1094 |
useUIManager = true; |
1095 |
colorPos++; |
1096 |
} |
1097 |
break; |
1098 |
} |
1099 |
} |
1100 |
if (colorPos == pos) { |
1101 |
String out = "Could not find color identifier in font declaration"; //NOI18N |
1102 |
throwBadHTML(out, pos, ch); |
1103 |
} |
1104 |
//Okay, we're now on the first character of the hex color definition |
1105 |
String s; |
1106 |
if (useUIManager) { |
1107 |
int end = ch.length-1; |
1108 |
for (int i=colorPos; i < ch.length; i++) { |
1109 |
if (ch[i] == '"' || ch[i] == '\'') { //NOI18N |
1110 |
end = i; |
1111 |
break; |
1112 |
} |
1113 |
} |
1114 |
s = new String(ch, colorPos, end-colorPos); |
1115 |
} else { |
1116 |
s = new String(ch, colorPos, 6); |
1117 |
} |
1118 |
Color result=null; |
1119 |
if (useUIManager) { |
1120 |
result = UIManager.getColor(s); |
1121 |
//Not all look and feels will provide standard colors; handle it gracefully |
1122 |
if (result == null) { |
1123 |
throwBadHTML( |
1124 |
"Could not resolve logical font declared in HTML: " + s, //NOI18N |
1125 |
pos, ch); |
1126 |
result = UIManager.getColor("textText"); //NOI18N |
1127 |
//Avoid NPE in headless situation? |
1128 |
if (result == null) { |
1129 |
result = Color.BLACK; |
1130 |
} |
1131 |
} |
1132 |
} else { |
1133 |
try { |
1134 |
int rgb = Integer.parseInt(s, 16); |
1135 |
result = new Color(rgb); |
1136 |
} catch (NumberFormatException nfe) { |
1137 |
throwBadHTML( |
1138 |
"Illegal hexadecimal color text: " + s + //NOI18N |
1139 |
" in HTML string", colorPos, ch); //NOI18N |
1140 |
} |
1141 |
} |
1142 |
if (result == null) { |
1143 |
throwBadHTML("Unresolvable html color: " + s //NOI18N |
1144 |
+ " in HTML string \n ", pos, ch); //NOI18N |
1145 |
} |
1146 |
return result; |
1147 |
} |
1148 |
|
1149 |
/** Find an entity at the passed character position in the passed array. |
1150 |
* If an entity is found, the trailing ; character will be substituted |
1151 |
* with the resulting character, and the position of that character |
1152 |
* in the array will be returned as the new position to render from, |
1153 |
* causing the renderer to skip the intervening characters */ |
1154 |
private static final int substEntity(char[] ch, int pos) { |
1155 |
//There are no 1 character entities, abort |
1156 |
if (pos >= ch.length-2) { |
1157 |
return -1; |
1158 |
} |
1159 |
//if it's numeric, parse out the number |
1160 |
if (ch[pos] == '#') { //NOI18N |
1161 |
return substNumericEntity(ch, pos+1); |
1162 |
} |
1163 |
//Okay, we've potentially got a named character entity. Try to find it. |
1164 |
boolean match; |
1165 |
for (int i=0; i < entities.length; i++) { |
1166 |
char[] c = (char[]) entities[i]; |
1167 |
match = true; |
1168 |
if (c.length < ch.length-pos) { |
1169 |
for (int j=0; j < c.length; j++) { |
1170 |
match &= c[j] == ch[j+pos]; |
1171 |
} |
1172 |
} else { |
1173 |
match = false; |
1174 |
} |
1175 |
if (match) { |
1176 |
//if it's a match, we still need the trailing ; |
1177 |
if (ch[pos+c.length] == ';') { //NOI18N |
1178 |
//substitute the character referenced by the entity |
1179 |
ch[pos+c.length] = entitySubstitutions[i]; |
1180 |
return pos+c.length; |
1181 |
} |
1182 |
} |
1183 |
} |
1184 |
return -1; |
1185 |
} |
1186 |
|
1187 |
/** Finds a character defined as a numeric entity (e.g. &#8222;) |
1188 |
* and replaces the trailing ; with the referenced character, returning |
1189 |
* the position of it so the renderer can continue from there. |
1190 |
*/ |
1191 |
private static final int substNumericEntity(char[] ch, int pos) { |
1192 |
for (int i=pos; i < ch.length; i++) { |
1193 |
if (ch[i] == ';') { |
1194 |
try { |
1195 |
ch[i] = (char) Integer.parseInt( |
1196 |
new String(ch, pos, i - pos)); |
1197 |
return i; |
1198 |
} catch (NumberFormatException nfe) { |
1199 |
throwBadHTML("Unparsable numeric entity: " + //NOI18N |
1200 |
new String(ch, pos, i - pos), pos, ch); //NOI18N |
1201 |
} |
1202 |
} |
1203 |
} |
1204 |
return -1; |
1205 |
} |
1206 |
|
1207 |
/** Throw an exception for unsupported or bad html, indicating where the problem is |
1208 |
* in the message */ |
1209 |
private static void throwBadHTML(String msg, int pos, char[] chars) { |
1210 |
char[] chh = new char[pos]; |
1211 |
Arrays.fill(chh, ' '); //NOI18N |
1212 |
chh[pos-1] = '^'; //NOI18N |
1213 |
String out = msg + "\n " + new String(chars) + "\n " |
1214 |
+ new String(chh) + "\n Full HTML string:" + new String(chars); //NOI18N |
1215 |
if (!strictHtml) { |
1216 |
if (ErrorManager.getDefault().isLoggable(ErrorManager.WARNING)) { |
1217 |
if (badStrings == null) { |
1218 |
badStrings = new HashSet(); |
1219 |
} |
1220 |
if (!badStrings.contains(msg)) { |
1221 |
//ErrorManager bug, issue 38372 - log messages containing |
1222 |
//newlines are truncated - so for now we iterate the |
1223 |
//string we've just constructed |
1224 |
StringTokenizer tk = new StringTokenizer(out, "\n", false); |
1225 |
while (tk.hasMoreTokens()) { |
1226 |
ErrorManager.getDefault().log(ErrorManager.WARNING, |
1227 |
tk.nextToken()); |
1228 |
} |
1229 |
badStrings.add(msg.intern()); |
1230 |
} |
1231 |
} |
1232 |
} else { |
1233 |
throw new IllegalArgumentException(out); |
1234 |
} |
1235 |
} |
1236 |
} |