KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > wings > plaf > css > Utils


1 /*
2  * $Id: Utils.java,v 1.34 2005/05/27 12:51:28 blueshift Exp $
3  * Copyright 2000,2005 wingS development team.
4  *
5  * This file is part of wingS (http://www.j-wings.org).
6  *
7  * wingS is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU Lesser General Public License
9  * as published by the Free Software Foundation; either version 2.1
10  * of the License, or (at your option) any later version.
11  *
12  * Please see COPYING for the complete licence.
13  */

14 package org.wings.plaf.css;
15
16 import org.wings.*;
17 import org.wings.io.Device;
18 import org.wings.io.NullDevice;
19 import org.wings.plaf.CGManager;
20 import org.wings.script.ScriptListener;
21
22 import java.awt.*;
23 import java.io.BufferedReader JavaDoc;
24 import java.io.IOException JavaDoc;
25 import java.io.InputStream JavaDoc;
26 import java.io.InputStreamReader JavaDoc;
27 import java.util.HashMap JavaDoc;
28 import java.util.Iterator JavaDoc;
29 import java.util.Map JavaDoc;
30
31 /**
32  * Utils.java
33  *
34  * @author <a HREF="mailto:mreinsch@to.com">Michael Reinsch</a>
35  * @version $Revision: 1.34 $
36  */

37 public final class Utils {
38     /**
39      * Print debug information in generated HTML
40      */

41     public static boolean PRINT_DEBUG = true;
42
43     protected final static char[] hexDigits = {
44         '0', '1', '2', '3', '4', '5',
45         '6', '7', '8', '9', 'a', 'b',
46         'c', 'd', 'e', 'f'};
47
48     protected Utils() {
49     }
50
51     /**
52      * Renders a container using its Layout manager or fallback just one after another.
53      */

54     public static void renderContainer(Device d, SContainer c)
55             throws IOException JavaDoc {
56         SLayoutManager layout = c.getLayout();
57
58         if (layout == null) {
59             // lookup the default Layout Behaviour
60
final CGManager manager = c.getSession().getCGManager();
61             Object JavaDoc value;
62             value = manager.getObject("SContainer.defaultLayoutBehaviour", String JavaDoc.class);
63             if (value != null && value instanceof String JavaDoc) {
64                 if ("classic".equals(((String JavaDoc) value).toLowerCase())) {
65                     layout = new SBoxLayout(SBoxLayout.VERTICAL);
66                 } else if ("standard".equals(((String JavaDoc) value).toLowerCase())) {
67                     layout = new SFlowLayout(SFlowLayout.LEFT);
68                 } else if ("none".equals(((String JavaDoc) value).toLowerCase())) {
69                     // just write out the components one after another
70
for (int i = 0; i < c.getComponentCount(); i++) {
71                         c.getComponent(i).write(d);
72                     }
73                     return;
74                 } else { // fallback
75
layout = new SFlowLayout(SFlowLayout.LEFT);
76                 }
77             } else {
78                 // Swing default LayoutManager is FlowLayout
79
layout = new SFlowLayout(SFlowLayout.LEFT);
80             }
81             c.setLayout(layout);
82         }
83         layout.write(d);
84     }
85
86     public static void writeEvents(Device d, SComponent c)
87             throws IOException JavaDoc {
88         ScriptListener[] listeners = c.getScriptListeners();
89         if (listeners.length > 0) {
90             Map JavaDoc eventScripts = new HashMap JavaDoc();
91             for (int i = 0; i < listeners.length; i++) {
92                 final ScriptListener script = listeners[i];
93                 final String JavaDoc event = script.getEvent();
94                 String JavaDoc eventScriptCode = script.getCode();
95
96                 if (event == null
97                         || event.length() == 0
98                         || eventScriptCode == null
99                         || eventScriptCode.length() == 0) {
100                     continue;
101                 }
102
103                 if (eventScripts.containsKey(event)) {
104                     String JavaDoc savedEventScriptCode = (String JavaDoc) eventScripts.get(event);
105                     eventScriptCode = savedEventScriptCode
106                             + (savedEventScriptCode.trim().endsWith(";") ? "" : ";")
107                             + eventScriptCode;
108                 }
109                 eventScripts.put(event, eventScriptCode);
110             }
111
112             Iterator JavaDoc it = eventScripts.keySet().iterator();
113             while (it.hasNext()) {
114                 String JavaDoc event = (String JavaDoc) it.next();
115                 String JavaDoc code = (String JavaDoc) eventScripts.get(event);
116                 d.print(" ");
117                 d.print(event);
118                 d.print("=\"");
119                 d.print(code);
120                 d.print("\"");
121             }
122         }
123     }
124
125     /*
126       static String event(SComponent component, String lowLevelEventId) {
127       if (component.getSession().getEventInvalidation() && component.getParentFrame() != null) {
128       if (!(component instanceof LowLevelEventListener) || ((LowLevelEventListener)component).checkEpoch())
129       return (component.getParentFrame().getEventEpoch()
130       + SConstants.UID_DIVIDER
131       + lowLevelEventId);
132       }
133       return lowLevelEventId;
134       }
135     */

136
137     /**
138      * Encodes a low level event id for using it in a request parameter. Every
139      * {@link LowLevelEventListener} should encode its LowLevelEventId before
140      * using it in a request parameter. This encoding adds consistency checking
141      * for outtimed requests ("Back Button")
142      */

143     public static String JavaDoc event(SComponent component) {
144         return component.getEncodedLowLevelEventId();
145         //return event(component, component.getLowLevelEventId());
146
}
147
148     /**
149      * HTML allows 4 values for align property of a div element.
150      *
151      * @param d Output
152      * @param align Please refer {@link SConstants}
153      * @throws IOException
154      */

155     public static void printDivHorizontalAlignment(Device d, int align) throws IOException JavaDoc {
156         printTableHorizontalAlignment(d, align);
157     }
158
159     /**
160      * Horizontal alignment for TABLE cells. i.e. <code>align="center"</code>
161      */

162     private static void printTableHorizontalAlignment(Device d, int align)
163             throws IOException JavaDoc {
164         if (align == SConstants.NO_ALIGN || align == SConstants.LEFT) {
165             d.print(" align=\"left\"");
166         } else if (align == SConstants.CENTER) {
167             d.print(" align=\"center\"");
168         } else if (align == SConstants.RIGHT) {
169             d.print(" align=\"right\"");
170         } else if (align == SConstants.JUSTIFY) {
171             d.print(" align=\"justify\"");
172         }
173     }
174
175     /**
176      * Vertical alignment for TABLE cells. i.e. <code>valign="top"</code>
177      */

178     private static void printTableVerticalAlignment(Device d, int align)
179             throws IOException JavaDoc {
180         if (align == SConstants.NO_ALIGN || align == SConstants.CENTER) {
181         } else if (align == SConstants.TOP) {
182             d.print(" valign=\"top\"");
183         } else if (align == SConstants.BOTTOM) {
184             d.print(" valign=\"bottom\"");
185         } else if (align == SConstants.BASELINE) {
186             d.print(" valign=\"baseline\"");
187         }
188     }
189
190     public static void printTableCellAlignment(Device d, SComponent c)
191             throws IOException JavaDoc {
192         if (c != null) {
193             printTableHorizontalAlignment(d, c.getHorizontalAlignment());
194             printTableVerticalAlignment(d, c.getVerticalAlignment());
195         }
196     }
197
198     public static String JavaDoc toColorString(int rgb) {
199         char[] buf = new char[6];
200         int digits = 6;
201         do {
202             buf[--digits] = hexDigits[rgb & 15];
203             rgb >>>= 4;
204         } while (digits != 0);
205
206         return new String JavaDoc(buf);
207     }
208
209     public static String JavaDoc toColorString(java.awt.Color JavaDoc c) {
210         return toColorString(c.getRGB());
211     }
212
213     /**
214      * Writes out the following CSS attributes as CSS inline style
215      * <ul>
216      * <li>Background/Foreground color</li>
217      * <li>Font size,style,weight,family</li>
218      * <li>Preferred Dimension height and width</li>
219      * </ul>. Sample: <code> style="width:100%; color:#ff0000;"</code>
220      *
221      * @param d Output device
222      * @param component Component having CSS attributes
223      * @throws IOException
224      * @deprecated Use #generateCSSComponentInlineStyle
225      */

226     public static void printCSSInlineStyleAttributes(Device d, SComponent component) throws IOException JavaDoc {
227         if (component == null)
228             return;
229         StringBuffer JavaDoc styleString = generateCSSComponentInlineStyle(component);
230
231         Utils.optAttribute(d, "style", styleString.toString());
232     }
233
234     public static StringBuffer JavaDoc generateCSSComponentInlineStyle(SComponent component) {
235         StringBuffer JavaDoc styleString = new StringBuffer JavaDoc();
236         if (component != null) {
237             final Color fgColor = component.getForeground();
238             final Color bgcolor = component.getBackground();
239             final SFont font = component.getFont();
240             final SDimension dim = component.getPreferredSize();
241
242             if (bgcolor != null)
243                 styleString.append("background-color:#").append(toColorString(bgcolor)).append(";");
244
245             if (fgColor != null) {
246                 styleString.append("color:#").append(toColorString(fgColor)).append(";");
247             }
248
249             if (font != null) {
250                 int style = font.getStyle();
251                 styleString.append("font-size:").append(font.getSize()).append("pt;");
252                 styleString.append("font-style:").append((style & Font.ITALIC) > 0 ? "italic;" : "normal;");
253                 styleString.append("font-weight:").append((style & Font.BOLD) > 0 ? "bold;" : "normal;");
254                 styleString.append("font-family:").append(font.getFace()).append(";");
255             }
256
257             if (dim != null) {
258                 if (dim.isWidthDefined()) styleString.append("width:").append(dim.getWidth()).append(";");
259                 if (dim.isHeightDefined()) styleString.append("height:").append(dim.getHeight()).append(";");
260             }
261         }
262         return styleString;
263     }
264
265     /**
266      * Prints a HTML style attribute with widht/height of passed SDimension.
267      * <p>Sample: <code> style="widht:100%;"</code>
268      *
269      * @param device Device to print to
270      * @param preferredSize Preferred sitze. May be null or contain null attributes
271      * @deprecated Consolidate CSS Inline Styles Strings !!!
272      */

273     public static void printCSSInlinePreferredSize(Device device, SDimension preferredSize) throws IOException JavaDoc {
274         if (preferredSize != null && (preferredSize.isWidthDefined() || preferredSize.isHeightDefined())) {
275             device.print(" style=\"");
276             device.print(generateCSSInlinePreferredSize(preferredSize));
277             device.print("\"");
278         }
279     }
280
281     /**
282      * Generates a CSS Inline Style string for the passed SDimension.
283      * <p>Sample: <code>width:100%;heigth=15px"</code>
284      *
285      * @param preferredSize Preferred sitze. May be null or contain null attributes
286      * @return Style string. Sample: <code>width:100%;heigth=15px"</code>
287      */

288     public static StringBuffer JavaDoc generateCSSInlinePreferredSize(SDimension preferredSize) {
289         StringBuffer JavaDoc styleString = new StringBuffer JavaDoc();
290         if (preferredSize != null && (preferredSize.isWidthDefined() || preferredSize.isHeightDefined())) {
291             if (preferredSize.isWidthDefined())
292                 styleString.append("width:").append(preferredSize.getWidth()).append(";");
293             if (preferredSize.isHeightDefined())
294                 styleString.append("height:").append(preferredSize.getHeight()).append(";");
295         }
296         return styleString;
297     }
298
299     public static StringBuffer JavaDoc generateCSSInlineBorder(int borderSize) {
300         StringBuffer JavaDoc styleString = new StringBuffer JavaDoc();
301         if (borderSize > 0)
302             styleString.append("border:").append(borderSize).append("px solid black;");
303         else
304             ; //styleString.append("border:none;"); Not necessary. Default
305
return styleString;
306     }
307
308     /**
309      * Prints a HTML style attribute with widht/height of 100%.
310      * <p>Sample: <code> style="width:100%;"</code>
311      *
312      * @param device Device to print to
313      */

314     public static void printCSSInlineFullSize(Device device, SDimension preferredSize) throws IOException JavaDoc {
315         if (preferredSize != null && (preferredSize.isWidthDefined() || preferredSize.isHeightDefined())) {
316             device.print(" style=\"width:100%;height:100%\"");
317         }
318     }
319
320     /**
321      * writes an {X|HT}ML quoted string according to RFC 1866.
322      * '"', '<', '>', '&' become '&quot;', '&lt;', '&gt;', '&amp;'
323      */

324     // not optimized yet
325
private static void quote(Device d, String JavaDoc s, boolean quoteNewline) throws IOException JavaDoc {
326         if (s == null) return;
327         char[] chars = s.toCharArray();
328         char c;
329         int last = 0;
330         for (int pos = 0; pos < chars.length; ++pos) {
331             c = chars[pos];
332             // write special characters as code ..
333
if (c < 32 || c > 127) {
334                 d.print(chars, last, (pos - last));
335                 if (c == '\n' && quoteNewline) {
336                     d.print("<br>");
337                 } else {
338                     d.print("&#");
339                     d.print((int) c);
340                     d.print(";");
341                 } // end of if ()
342
last = pos + 1;
343             } else
344                 switch (c) {
345                     case '&':
346                         d.print(chars, last, (pos - last));
347                         d.print("&amp;");
348                         last = pos + 1;
349                         break;
350                     case '"':
351                         d.print(chars, last, (pos - last));
352                         d.print("&quot;");
353                         last = pos + 1;
354                         break;
355                     case '<':
356                         d.print(chars, last, (pos - last));
357                         d.print("&lt;");
358                         last = pos + 1;
359                         break;
360                     case '>':
361                         d.print(chars, last, (pos - last));
362                         d.print("&gt;");
363                         last = pos + 1;
364                         break;
365                         /*
366                          * watchout: we cannot replace _space_ by &nbsp;
367                          * since non-breakable-space is a different
368                          * character: isolatin-char 160, not 32.
369                          * This will result in a confusion in forms:
370                          * - the user enters space, presses submit
371                          * - the form content is written to the Device by wingS,
372                          * space is replaced by &nbsp;
373                          * - the next time the form is submitted, we get
374                          * isolatin-char 160, _not_ space.
375                          * (at least Konqueror behaves this correct; mozilla does not)
376                          * Henner
377                          */

378                 }
379         }
380         d.print(chars, last, chars.length - last);
381     }
382
383     public static void writeRaw(Device d, String JavaDoc s) throws IOException JavaDoc {
384         if (s == null) return;
385         d.print(s);
386     }
387
388     /**
389      * writes the given String to the device. The string is quoted, i.e.
390      * for all special characters in *ML, their appropriate entity is
391      * returned.
392      * If the String starts with '<html>', the content is regarded being
393      * HTML-code and is written as is (without the <html> tag).
394      */

395     public static void write(Device d, String JavaDoc s) throws IOException JavaDoc {
396         if (s == null) return;
397         if ((s.length() > 5) && (s.startsWith("<html>"))) {
398             writeRaw(d, s.substring(6));
399         } else {
400             quote(d, s, false);
401         }
402     }
403
404     /**
405      * Prints an optional attribute. If the String value has a content
406      * (value != null && value.length > 0), the attrib is added otherwise
407      * it is left out
408      */

409     public static void optAttribute(Device d, String JavaDoc attr, String JavaDoc value)
410             throws IOException JavaDoc {
411         if (value != null && value.trim().length() > 0) {
412             d.print(" ").print(attr).print("=\"");
413             quote(d, value, true);
414             d.print("\"");
415         }
416     }
417
418     /**
419      * Prints an optional attribute. If the String value has a content
420      * (value != null && value.length > 0), the attrib is added otherwise
421      * it is left out
422      */

423     public static void optAttribute(Device d, String JavaDoc attr, Color value)
424             throws IOException JavaDoc {
425         if (value != null) {
426             d.print(" ");
427             d.print(attr);
428             d.print("=\"");
429             write(d, value);
430             d.print("\"");
431         }
432     }
433
434     /**
435      * Prints an optional, renderable attribute.
436      */

437     public static void optAttribute(Device d, String JavaDoc attr, Renderable r)
438             throws IOException JavaDoc {
439         if (r != null) {
440             d.print(" ");
441             d.print(attr);
442             d.print("=\"");
443             r.write(d);
444             d.print("\"");
445         }
446     }
447
448     /**
449      * Prints an optional attribute. If the integer value is greater than 0,
450      * the attrib is added otherwise it is left out
451      */

452     public static void optAttribute(Device d, String JavaDoc attr, int value)
453             throws IOException JavaDoc {
454         if (value > 0) {
455             d.print(" ");
456             d.print(attr);
457             d.print("=\"");
458             d.print(String.valueOf(value));
459             d.print("\"");
460         }
461     }
462
463     /**
464      * Prints an optional attribute. If the dimension value not equals <i>null</i>
465      * the attrib is added otherwise it is left out
466      */

467     public static void optAttribute(Device d, String JavaDoc attr, SDimension value)
468             throws IOException JavaDoc {
469         if (value != null) {
470             d.print(" ");
471             d.print(attr);
472             d.print("=\"");
473             write(d, value.toString());
474             d.print("\"");
475         }
476     }
477
478     /**
479      * writes the given java.awt.Color to the device. Speed optimized;
480      * character conversion avoided.
481      */

482     public static void write(Device d, Color c) throws IOException JavaDoc {
483         d.print("#");
484         int rgb = (c == null) ? 0 : c.getRGB();
485         int mask = 0xf00000;
486         for (int bitPos = 20; bitPos >= 0; bitPos -= 4) {
487             d.print(hexDigits[(rgb & mask) >>> bitPos]);
488             mask >>>= 4;
489         }
490     }
491
492     /**
493      * writes anything Renderable
494      */

495     public static void write(Device d, Renderable r) throws IOException JavaDoc {
496         if (r == null) return;
497         r.write(d);
498     }
499
500     /*
501      * testing purposes.
502      */

503     public static void main(String JavaDoc argv[]) throws Exception JavaDoc {
504         Color c = new Color(255, 254, 7);
505         Device d = new org.wings.io.StringBufferDevice();
506         write(d, c);
507         quote(d, "\nThis is a <abc> string \"; foo & sons\nmoin", true);
508         d.print(String.valueOf(-42));
509         d.print(String.valueOf(Integer.MIN_VALUE));
510
511         write(d, "hello test&nbsp;\n");
512         write(d, "<html>hallo test&nbsp;\n");
513
514         d = new org.wings.io.NullDevice();
515         long start = System.currentTimeMillis();
516         for (int i = 0; i < 1000000; ++i) {
517             quote(d, "this is a little & foo", true);
518         }
519         System.err.println("took: " + (System.currentTimeMillis() - start)
520                 + "ms");
521     }
522
523     /**
524      * Helper method for CGs to print out debug information in output stream.
525      * If {@link #PRINT_DEBUG} prints the passed string and returns the current {@link Device}.
526      * In other case omits ouput and returns a {@link NullDevice}
527      *
528      * @param d The original device
529      * @return The original device or a {@link NullDevice}
530      */

531     public static Device printDebug(Device d, String JavaDoc s) throws IOException JavaDoc {
532         if (PRINT_DEBUG)
533             return d.print(s);
534         else
535             return NullDevice.DEFAULT;
536     }
537
538     /**
539      * Prints a hierarchical idented newline if debug mode is enabled.
540      * {@link #printNewline(org.wings.io.Device, org.wings.SComponent)}
541      */

542     public static Device printDebugNewline(Device d, SComponent currentComponent) throws IOException JavaDoc {
543         if (PRINT_DEBUG)
544             return printNewline(d, currentComponent);
545         else
546             return d;
547     }
548
549     /**
550      * Prints a hierarchical idented newline. For each surrounding container of the passed component one ident level.
551      */

552     public static Device printNewline(Device d, SComponent currentComponent) throws IOException JavaDoc {
553         if (currentComponent == null || PRINT_DEBUG == false) // special we save every ms handling for holger ;-)
554
return d;
555         d.print("\n");
556         while (currentComponent.getParent() != null && currentComponent.getParent().getParent() != null) {
557             d.print("\t");
558             currentComponent = currentComponent.getParent();
559         }
560         return d;
561     }
562
563     /**
564      * loads a script from disk through the classloader.
565      *
566      * @param path the path where the script can be found
567      * @return the script as a String
568      */

569     public static String JavaDoc loadScript(String JavaDoc path) {
570         InputStream JavaDoc in = null;
571         BufferedReader JavaDoc reader = null;
572
573         try {
574             in = Utils.class.getClassLoader().getResourceAsStream(path);
575             reader = new BufferedReader JavaDoc(new InputStreamReader JavaDoc(in));
576             StringBuffer JavaDoc buffer = new StringBuffer JavaDoc();
577             String JavaDoc line;
578             while ((line = reader.readLine()) != null) {
579                 buffer.append(line).append("\n");
580             }
581             buffer.append("\n");
582
583             return buffer.toString();
584         } catch (Exception JavaDoc e) {
585             e.printStackTrace();
586             return "";
587         } finally {
588             try {
589                 in.close();
590             } catch (Exception JavaDoc ign) {
591             }
592             try {
593                 reader.close();
594             } catch (Exception JavaDoc ign1) {
595             }
596         }
597     }
598
599     /**
600      * prints a String. Substitutes spaces with nbsp's
601      * @param text
602      * @return
603      */

604     public static String JavaDoc nonBreakingSpaces(String JavaDoc text) {
605         return text.replace(' ', '\u00A0');
606     }
607
608 }
609
Popular Tags