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