1. /*
  2. * @(#)StyleSheet.java 1.77 03/01/23
  3. *
  4. * Copyright 2003 Sun Microsystems, Inc. All rights reserved.
  5. * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
  6. */
  7. package javax.swing.text.html;
  8. import java.util.*;
  9. import java.awt.*;
  10. import java.io.*;
  11. import java.net.*;
  12. import javax.swing.Icon;
  13. import javax.swing.ImageIcon;
  14. import javax.swing.border.*;
  15. import javax.swing.event.ChangeListener;
  16. import javax.swing.text.*;
  17. /**
  18. * Support for defining the visual characteristics of
  19. * HTML views being rendered. The StyleSheet is used to
  20. * translate the HTML model into visual characteristics.
  21. * This enables views to be customized by a look-and-feel,
  22. * multiple views over the same model can be rendered
  23. * differently, etc. This can be thought of as a CSS
  24. * rule repository. The key for CSS attributes is an
  25. * object of type CSS.Attribute. The type of the value
  26. * is up to the StyleSheet implementation, but the
  27. * <code>toString</code> method is required
  28. * to return a string representation of CSS value.
  29. * <p>
  30. * The primary entry point for HTML View implementations
  31. * to get their attributes is the
  32. * <a href="#getViewAttributes">getViewAttributes</a>
  33. * method. This should be implemented to establish the
  34. * desired policy used to associate attributes with the view.
  35. * Each HTMLEditorKit (i.e. and therefore each associated
  36. * JEditorPane) can have its own StyleSheet, but by default one
  37. * sheet will be shared by all of the HTMLEditorKit instances.
  38. * HTMLDocument instance can also have a StyleSheet, which
  39. * holds the document-specific CSS specifications.
  40. * <p>
  41. * In order for Views to store less state and therefore be
  42. * more lightweight, the StyleSheet can act as a factory for
  43. * painters that handle some of the rendering tasks. This allows
  44. * implementations to determine what they want to cache
  45. * and have the sharing potentially at the level that a
  46. * selector is common to multiple views. Since the StyleSheet
  47. * may be used by views over multiple documents and typically
  48. * the HTML attributes don't effect the selector being used,
  49. * the potential for sharing is significant.
  50. * <p>
  51. * The rules are stored as named styles, and other information
  52. * is stored to translate the context of an element to a
  53. * rule quickly. The following code fragment will display
  54. * the named styles, and therefore the CSS rules contained.
  55. * <code><pre>
  56. *  
  57. *   import java.util.*;
  58. *   import javax.swing.text.*;
  59. *   import javax.swing.text.html.*;
  60. *  
  61. *   public class ShowStyles {
  62. *  
  63. *   public static void main(String[] args) {
  64. *   HTMLEditorKit kit = new HTMLEditorKit();
  65. *   HTMLDocument doc = (HTMLDocument) kit.createDefaultDocument();
  66. *   StyleSheet styles = doc.getStyleSheet();
  67. *  
  68. *   Enumeration rules = styles.getStyleNames();
  69. *   while (rules.hasMoreElements()) {
  70. *   String name = (String) rules.nextElement();
  71. *   Style rule = styles.getStyle(name);
  72. *   System.out.println(rule.toString());
  73. *   }
  74. *   System.exit(0);
  75. *   }
  76. *   }
  77. *  
  78. * </pre></code>
  79. * <p>
  80. * The semantics for when a CSS style should overide visual attributes
  81. * defined by an element are not well defined. For example, the html
  82. * <code><body bgcolor=red></code> makes the body have a red
  83. * background. But if the html file also contains the CSS rule
  84. * <code>body { background: blue }</code> it becomes less clear as to
  85. * what color the background of the body should be. The current
  86. * implemention gives visual attributes defined in the element the
  87. * highest precedence, that is they are always checked before any styles.
  88. * Therefore, in the previous example the background would have a
  89. * red color as the body element defines the background color to be red.
  90. * <p>
  91. * As already mentioned this supports CSS. We don't support the full CSS
  92. * spec. Refer to the javadoc of the CSS class to see what properties
  93. * we support. The two major CSS parsing related
  94. * concepts we do not currently
  95. * support are pseudo selectors, such as <code>A:link { color: red }</code>,
  96. * and the <code>important</code> modifier.
  97. * <p>
  98. * <font color="red">Note: This implementation is currently
  99. * incomplete. It can be replaced with alternative implementations
  100. * that are complete. Future versions of this class will provide
  101. * better CSS support.</font>
  102. *
  103. * @author Timothy Prinzing
  104. * @author Sunita Mani
  105. * @author Sara Swanson
  106. * @author Jill Nakata
  107. * @version 1.77 01/23/03
  108. */
  109. public class StyleSheet extends StyleContext {
  110. // As the javadoc states, this class maintains a mapping between
  111. // a CSS selector (such as p.bar) and a Style.
  112. // This consists of a number of parts:
  113. // . Each selector is broken down into its constituent simple selectors,
  114. // and stored in an inverted graph, for example:
  115. // p { color: red } ol p { font-size: 10pt } ul p { font-size: 12pt }
  116. // results in the graph:
  117. // root
  118. // |
  119. // p
  120. // / \
  121. // ol ul
  122. // each node (an instance of SelectorMapping) has an associated
  123. // specificity and potentially a Style.
  124. // . Every rule that is asked for (either by way of getRule(String) or
  125. // getRule(HTML.Tag, Element)) results in a unique instance of
  126. // ResolvedStyle. ResolvedStyles contain the AttributeSets from the
  127. // SelectorMapping.
  128. // . When a new rule is created it is inserted into the graph, and
  129. // the AttributeSets of each ResolvedStyles are updated appropriately.
  130. // . This class creates special AttributeSets, LargeConversionSet and
  131. // SmallConversionSet, that maintain a mapping between StyleConstants
  132. // and CSS so that developers that wish to use the StyleConstants
  133. // methods can do so.
  134. // . When one of the AttributeSets is mutated by way of a
  135. // StyleConstants key, all the associated CSS keys are removed. This is
  136. // done so that the two representations don't get out of sync. For
  137. // example, if the developer adds StyleConsants.BOLD, FALSE to an
  138. // AttributeSet that contains HTML.Tag.B, the HTML.Tag.B entry will
  139. // be removed.
  140. /**
  141. * Construct a StyleSheet
  142. */
  143. public StyleSheet() {
  144. super();
  145. selectorMapping = new SelectorMapping(0);
  146. resolvedStyles = new Hashtable();
  147. if (css == null) {
  148. css = new CSS();
  149. }
  150. }
  151. /**
  152. * Fetches the style to use to render the given type
  153. * of HTML tag. The element given is representing
  154. * the tag and can be used to determine the nesting
  155. * for situations where the attributes will differ
  156. * if nesting inside of elements.
  157. *
  158. * @param t the type to translate to visual attributes
  159. * @param e the element representing the tag; the element
  160. * can be used to determine the nesting for situations where
  161. * the attributes will differ if nested inside of other
  162. * elements
  163. * @return the set of CSS attributes to use to render
  164. * the tag
  165. */
  166. public Style getRule(HTML.Tag t, Element e) {
  167. SearchBuffer sb = SearchBuffer.obtainSearchBuffer();
  168. try {
  169. // Build an array of all the parent elements.
  170. Vector searchContext = sb.getVector();
  171. for (Element p = e; p != null; p = p.getParentElement()) {
  172. searchContext.addElement(p);
  173. }
  174. // Build a fully qualified selector.
  175. int n = searchContext.size();
  176. StringBuffer cacheLookup = sb.getStringBuffer();
  177. AttributeSet attr;
  178. String eName;
  179. Object name;
  180. // >= 1 as the HTML.Tag for the 0th element is passed in.
  181. for (int counter = n - 1; counter >= 1; counter--) {
  182. e = (Element)searchContext.elementAt(counter);
  183. attr = e.getAttributes();
  184. name = attr.getAttribute(StyleConstants.NameAttribute);
  185. eName = name.toString();
  186. cacheLookup.append(eName);
  187. if (attr != null) {
  188. if (attr.isDefined(HTML.Attribute.ID)) {
  189. cacheLookup.append('#');
  190. cacheLookup.append(attr.getAttribute
  191. (HTML.Attribute.ID));
  192. }
  193. else if (attr.isDefined(HTML.Attribute.CLASS)) {
  194. cacheLookup.append('.');
  195. cacheLookup.append(attr.getAttribute
  196. (HTML.Attribute.CLASS));
  197. }
  198. }
  199. cacheLookup.append(' ');
  200. }
  201. cacheLookup.append(t.toString());
  202. e = (Element)searchContext.elementAt(0);
  203. attr = e.getAttributes();
  204. if (e.isLeaf()) {
  205. // For leafs, we use the second tier attributes.
  206. Object testAttr = attr.getAttribute(t);
  207. if (testAttr instanceof AttributeSet) {
  208. attr = (AttributeSet)testAttr;
  209. }
  210. else {
  211. attr = null;
  212. }
  213. }
  214. if (attr != null) {
  215. if (attr.isDefined(HTML.Attribute.ID)) {
  216. cacheLookup.append('#');
  217. cacheLookup.append(attr.getAttribute(HTML.Attribute.ID));
  218. }
  219. else if (attr.isDefined(HTML.Attribute.CLASS)) {
  220. cacheLookup.append('.');
  221. cacheLookup.append(attr.getAttribute
  222. (HTML.Attribute.CLASS));
  223. }
  224. }
  225. Style style = getResolvedStyle(cacheLookup.toString(),
  226. searchContext, t);
  227. return style;
  228. }
  229. finally {
  230. SearchBuffer.releaseSearchBuffer(sb);
  231. }
  232. }
  233. /**
  234. * Fetches the rule that best matches the selector given
  235. * in string form. Where <code>selector</code> is a space separated
  236. * String of the element names. For example, <code>selector</code>
  237. * might be 'html body tr td''<p>
  238. * The attributes of the returned Style will change
  239. * as rules are added and removed. That is if you to ask for a rule
  240. * with a selector "table p" and a new rule was added with a selector
  241. * of "p" the returned Style would include the new attributes from
  242. * the rule "p".
  243. */
  244. public Style getRule(String selector) {
  245. selector = cleanSelectorString(selector);
  246. if (selector != null) {
  247. Style style = getResolvedStyle(selector);
  248. return style;
  249. }
  250. return null;
  251. }
  252. /**
  253. * Adds a set of rules to the sheet. The rules are expected to
  254. * be in valid CSS format. Typically this would be called as
  255. * a result of parsing a <style> tag.
  256. */
  257. public void addRule(String rule) {
  258. if (rule != null) {
  259. CssParser parser = new CssParser();
  260. try {
  261. parser.parse(getBase(), new StringReader(rule), false, false);
  262. } catch (IOException ioe) { }
  263. }
  264. }
  265. /**
  266. * Translates a CSS declaration to an AttributeSet that represents
  267. * the CSS declaration. Typically this would be called as a
  268. * result of encountering an HTML style attribute.
  269. */
  270. public AttributeSet getDeclaration(String decl) {
  271. if (decl == null) {
  272. return SimpleAttributeSet.EMPTY;
  273. }
  274. CssParser parser = new CssParser();
  275. return parser.parseDeclaration(decl);
  276. }
  277. /**
  278. * Loads a set of rules that have been specified in terms of
  279. * CSS1 grammar. If there are collisions with existing rules,
  280. * the newly specified rule will win.
  281. *
  282. * @param in the stream to read the CSS grammar from
  283. * @param ref the reference URL. This value represents the
  284. * location of the stream and may be null. All relative
  285. * URLs specified in the stream will be based upon this
  286. * parameter.
  287. */
  288. public void loadRules(Reader in, URL ref) throws IOException {
  289. CssParser parser = new CssParser();
  290. parser.parse(ref, in, false, false);
  291. }
  292. /**
  293. * Fetches a set of attributes to use in the view for
  294. * displaying. This is basically a set of attributes that
  295. * can be used for View.getAttributes.
  296. */
  297. public AttributeSet getViewAttributes(View v) {
  298. return new ViewAttributeSet(v);
  299. }
  300. /**
  301. * Removes a named style previously added to the document.
  302. *
  303. * @param nm the name of the style to remove
  304. */
  305. public void removeStyle(String nm) {
  306. Style aStyle = getStyle(nm);
  307. if (aStyle != null) {
  308. String selector = cleanSelectorString(nm);
  309. String[] selectors = getSimpleSelectors(selector);
  310. synchronized(this) {
  311. SelectorMapping mapping = getRootSelectorMapping();
  312. for (int i = selectors.length - 1; i >= 0; i--) {
  313. mapping = mapping.getChildSelectorMapping(selectors[i],
  314. true);
  315. }
  316. Style rule = mapping.getStyle();
  317. if (rule != null) {
  318. mapping.setStyle(null);
  319. if (resolvedStyles.size() > 0) {
  320. Enumeration values = resolvedStyles.elements();
  321. while (values.hasMoreElements()) {
  322. ResolvedStyle style = (ResolvedStyle)values.
  323. nextElement();
  324. style.removeStyle(rule);
  325. }
  326. }
  327. }
  328. }
  329. }
  330. super.removeStyle(nm);
  331. }
  332. /**
  333. * Adds the rules from the StyleSheet <code>ss</code> to those of
  334. * the receiver. <code>ss's</code> rules will override the rules of
  335. * any previously added style sheets. An added StyleSheet will never
  336. * override the rules of the receiving style sheet.
  337. *
  338. * @since 1.3
  339. */
  340. public void addStyleSheet(StyleSheet ss) {
  341. synchronized(this) {
  342. if (linkedStyleSheets == null) {
  343. linkedStyleSheets = new Vector();
  344. }
  345. if (!linkedStyleSheets.contains(ss)) {
  346. linkedStyleSheets.insertElementAt(ss, 0);
  347. linkStyleSheetAt(ss, 0);
  348. }
  349. }
  350. }
  351. /**
  352. * Removes the StyleSheet <code>ss</code> from those of the receiver.
  353. *
  354. * @since 1.3
  355. */
  356. public void removeStyleSheet(StyleSheet ss) {
  357. synchronized(this) {
  358. if (linkedStyleSheets != null) {
  359. int index = linkedStyleSheets.indexOf(ss);
  360. if (index != -1) {
  361. linkedStyleSheets.removeElementAt(index);
  362. unlinkStyleSheet(ss, index);
  363. if (index == 0 && linkedStyleSheets.size() == 0) {
  364. linkedStyleSheets = null;
  365. }
  366. }
  367. }
  368. }
  369. }
  370. //
  371. // The following is used to import style sheets.
  372. //
  373. /**
  374. * Returns an array of the linked StyleSheets. Will return null
  375. * if there are no linked StyleSheets.
  376. *
  377. * @since 1.3
  378. */
  379. public StyleSheet[] getStyleSheets() {
  380. StyleSheet[] retValue;
  381. synchronized(this) {
  382. if (linkedStyleSheets != null) {
  383. retValue = new StyleSheet[linkedStyleSheets.size()];
  384. linkedStyleSheets.copyInto(retValue);
  385. }
  386. else {
  387. retValue = null;
  388. }
  389. }
  390. return retValue;
  391. }
  392. /**
  393. * Imports a style sheet from <code>url</code>. The resulting rules
  394. * are directly added to the receiver. If you do not want the rules
  395. * to become part of the receiver, create a new StyleSheet and use
  396. * addStyleSheet to link it in.
  397. *
  398. * @since 1.3
  399. */
  400. public void importStyleSheet(URL url) {
  401. try {
  402. InputStream is;
  403. is = url.openStream();
  404. Reader r = new BufferedReader(new InputStreamReader(is));
  405. CssParser parser = new CssParser();
  406. parser.parse(url, r, false, true);
  407. r.close();
  408. is.close();
  409. } catch (Throwable e) {
  410. // on error we simply have no styles... the html
  411. // will look mighty wrong but still function.
  412. }
  413. }
  414. /**
  415. * Sets the base. All import statements that are relative, will be
  416. * relative to <code>base</code>.
  417. *
  418. * @since 1.3
  419. */
  420. public void setBase(URL base) {
  421. this.base = base;
  422. }
  423. /**
  424. * Returns the base.
  425. *
  426. * @since 1.3
  427. */
  428. public URL getBase() {
  429. return base;
  430. }
  431. /**
  432. * Adds a CSS attribute to the given set.
  433. *
  434. * @since 1.3
  435. */
  436. public void addCSSAttribute(MutableAttributeSet attr, CSS.Attribute key,
  437. String value) {
  438. css.addInternalCSSValue(attr, key, value);
  439. }
  440. /**
  441. * Adds a CSS attribute to the given set.
  442. *
  443. * @since 1.3
  444. */
  445. public boolean addCSSAttributeFromHTML(MutableAttributeSet attr,
  446. CSS.Attribute key, String value) {
  447. Object iValue = css.getCssValue(key, value);
  448. if (iValue != null) {
  449. attr.addAttribute(key, iValue);
  450. return true;
  451. }
  452. return false;
  453. }
  454. // ---- Conversion functionality ---------------------------------
  455. /**
  456. * Converts a set of HTML attributes to an equivalent
  457. * set of CSS attributes.
  458. *
  459. * @param htmlAttrSet AttributeSet containing the HTML attributes.
  460. */
  461. public AttributeSet translateHTMLToCSS(AttributeSet htmlAttrSet) {
  462. AttributeSet cssAttrSet = css.translateHTMLToCSS(htmlAttrSet);
  463. MutableAttributeSet cssStyleSet = addStyle(null, null);
  464. cssStyleSet.addAttributes(cssAttrSet);
  465. return cssStyleSet;
  466. }
  467. /**
  468. * Adds an attribute to the given set, and returns
  469. * the new representative set. This is reimplemented to
  470. * convert StyleConstant attributes to CSS prior to forwarding
  471. * to the superclass behavior. The StyleConstants attribute
  472. * has no corresponding CSS entry, the StyleConstants attribute
  473. * is stored (but will likely be unused).
  474. *
  475. * @param old the old attribute set
  476. * @param key the non-null attribute key
  477. * @param value the attribute value
  478. * @return the updated attribute set
  479. * @see MutableAttributeSet#addAttribute
  480. */
  481. public AttributeSet addAttribute(AttributeSet old, Object key,
  482. Object value) {
  483. if (css == null) {
  484. // supers constructor will call this before returning,
  485. // and we need to make sure CSS is non null.
  486. css = new CSS();
  487. }
  488. if (key instanceof StyleConstants) {
  489. HTML.Tag tag = HTML.getTagForStyleConstantsKey(
  490. (StyleConstants)key);
  491. if (tag != null && old.isDefined(tag)) {
  492. old = removeAttribute(old, tag);
  493. }
  494. Object cssValue = css.styleConstantsValueToCSSValue
  495. ((StyleConstants)key, value);
  496. if (cssValue != null) {
  497. Object cssKey = css.styleConstantsKeyToCSSKey
  498. ((StyleConstants)key);
  499. if (cssKey != null) {
  500. return super.addAttribute(old, cssKey, cssValue);
  501. }
  502. }
  503. }
  504. return super.addAttribute(old, key, value);
  505. }
  506. /**
  507. * Adds a set of attributes to the element. If any of these attributes
  508. * are StyleConstants attributes, they will be converted to CSS prior
  509. * to forwarding to the superclass behavior.
  510. *
  511. * @param old the old attribute set
  512. * @param attr the attributes to add
  513. * @return the updated attribute set
  514. * @see MutableAttributeSet#addAttribute
  515. */
  516. public AttributeSet addAttributes(AttributeSet old, AttributeSet attr) {
  517. if (!(attr instanceof HTMLDocument.TaggedAttributeSet)) {
  518. old = removeHTMLTags(old, attr);
  519. }
  520. return super.addAttributes(old, convertAttributeSet(attr));
  521. }
  522. /**
  523. * Removes an attribute from the set. If the attribute is a StyleConstants
  524. * attribute, the request will be converted to a CSS attribute prior to
  525. * forwarding to the superclass behavior.
  526. *
  527. * @param old the old set of attributes
  528. * @param key the non-null attribute name
  529. * @return the updated attribute set
  530. * @see MutableAttributeSet#removeAttribute
  531. */
  532. public AttributeSet removeAttribute(AttributeSet old, Object key) {
  533. if (key instanceof StyleConstants) {
  534. HTML.Tag tag = HTML.getTagForStyleConstantsKey(
  535. (StyleConstants)key);
  536. if (tag != null) {
  537. old = super.removeAttribute(old, tag);
  538. }
  539. Object cssKey = css.styleConstantsKeyToCSSKey((StyleConstants)key);
  540. if (cssKey != null) {
  541. return super.removeAttribute(old, cssKey);
  542. }
  543. }
  544. return super.removeAttribute(old, key);
  545. }
  546. /**
  547. * Removes a set of attributes for the element. If any of the attributes
  548. * is a StyleConstants attribute, the request will be converted to a CSS
  549. * attribute prior to forwarding to the superclass behavior.
  550. *
  551. * @param old the old attribute set
  552. * @param names the attribute names
  553. * @return the updated attribute set
  554. * @see MutableAttributeSet#removeAttributes
  555. */
  556. public AttributeSet removeAttributes(AttributeSet old, Enumeration names) {
  557. // PENDING: Should really be doing something similar to
  558. // removeHTMLTags here, but it is rather expensive to have to
  559. // clone names
  560. return super.removeAttributes(old, names);
  561. }
  562. /**
  563. * Removes a set of attributes. If any of the attributes
  564. * is a StyleConstants attribute, the request will be converted to a CSS
  565. * attribute prior to forwarding to the superclass behavior.
  566. *
  567. * @param old the old attribute set
  568. * @param attrs the attributes
  569. * @return the updated attribute set
  570. * @see MutableAttributeSet#removeAttributes
  571. */
  572. public AttributeSet removeAttributes(AttributeSet old, AttributeSet attrs) {
  573. if (old != attrs) {
  574. old = removeHTMLTags(old, attrs);
  575. }
  576. return super.removeAttributes(old, convertAttributeSet(attrs));
  577. }
  578. /**
  579. * Creates a compact set of attributes that might be shared.
  580. * This is a hook for subclasses that want to alter the
  581. * behavior of SmallAttributeSet. This can be reimplemented
  582. * to return an AttributeSet that provides some sort of
  583. * attribute conversion.
  584. *
  585. * @param a The set of attributes to be represented in the
  586. * the compact form.
  587. */
  588. protected SmallAttributeSet createSmallAttributeSet(AttributeSet a) {
  589. return new SmallConversionSet(a);
  590. }
  591. /**
  592. * Creates a large set of attributes that should trade off
  593. * space for time. This set will not be shared. This is
  594. * a hook for subclasses that want to alter the behavior
  595. * of the larger attribute storage format (which is
  596. * SimpleAttributeSet by default). This can be reimplemented
  597. * to return a MutableAttributeSet that provides some sort of
  598. * attribute conversion.
  599. *
  600. * @param a The set of attributes to be represented in the
  601. * the larger form.
  602. */
  603. protected MutableAttributeSet createLargeAttributeSet(AttributeSet a) {
  604. return new LargeConversionSet(a);
  605. }
  606. /**
  607. * For any StyleConstants key in attr that has an associated HTML.Tag,
  608. * it is removed from old. The resulting AttributeSet is then returned.
  609. */
  610. private AttributeSet removeHTMLTags(AttributeSet old, AttributeSet attr) {
  611. if (!(attr instanceof LargeConversionSet) &&
  612. !(attr instanceof SmallConversionSet)) {
  613. Enumeration names = attr.getAttributeNames();
  614. while (names.hasMoreElements()) {
  615. Object key = names.nextElement();
  616. if (key instanceof StyleConstants) {
  617. HTML.Tag tag = HTML.getTagForStyleConstantsKey(
  618. (StyleConstants)key);
  619. if (tag != null && old.isDefined(tag)) {
  620. old = super.removeAttribute(old, tag);
  621. }
  622. }
  623. }
  624. }
  625. return old;
  626. }
  627. /**
  628. * Converts a set of attributes (if necessary) so that
  629. * any attributes that were specified as StyleConstants
  630. * attributes and have a CSS mapping, will be converted
  631. * to CSS attributes.
  632. */
  633. AttributeSet convertAttributeSet(AttributeSet a) {
  634. if ((a instanceof LargeConversionSet) ||
  635. (a instanceof SmallConversionSet)) {
  636. // known to be converted.
  637. return a;
  638. }
  639. // in most cases, there are no StyleConstants attributes
  640. // so we iterate the collection of keys to avoid creating
  641. // a new set.
  642. Enumeration names = a.getAttributeNames();
  643. while (names.hasMoreElements()) {
  644. Object name = names.nextElement();
  645. if (name instanceof StyleConstants) {
  646. // we really need to do a conversion, iterate again
  647. // building a new set.
  648. MutableAttributeSet converted = new LargeConversionSet();
  649. Enumeration keys = a.getAttributeNames();
  650. while (keys.hasMoreElements()) {
  651. Object key = keys.nextElement();
  652. Object cssValue = null;
  653. if (key instanceof StyleConstants) {
  654. // convert the StyleConstants attribute if possible
  655. Object cssKey = css.styleConstantsKeyToCSSKey
  656. ((StyleConstants)key);
  657. if (cssKey != null) {
  658. Object value = a.getAttribute(key);
  659. cssValue = css.styleConstantsValueToCSSValue
  660. ((StyleConstants)key, value);
  661. if (cssValue != null) {
  662. converted.addAttribute(cssKey, cssValue);
  663. }
  664. }
  665. }
  666. if (cssValue == null) {
  667. converted.addAttribute(key, a.getAttribute(key));
  668. }
  669. }
  670. return converted;
  671. }
  672. }
  673. return a;
  674. }
  675. /**
  676. * Large set of attributes that does conversion of requests
  677. * for attributes of type StyleConstants.
  678. */
  679. class LargeConversionSet extends SimpleAttributeSet {
  680. /**
  681. * Creates a new attribute set based on a supplied set of attributes.
  682. *
  683. * @param source the set of attributes
  684. */
  685. public LargeConversionSet(AttributeSet source) {
  686. super(source);
  687. }
  688. public LargeConversionSet() {
  689. super();
  690. }
  691. /**
  692. * Checks whether a given attribute is defined.
  693. *
  694. * @param key the attribute key
  695. * @return true if the attribute is defined
  696. * @see AttributeSet#isDefined
  697. */
  698. public boolean isDefined(Object key) {
  699. if (key instanceof StyleConstants) {
  700. Object cssKey = css.styleConstantsKeyToCSSKey
  701. ((StyleConstants)key);
  702. if (cssKey != null) {
  703. return super.isDefined(cssKey);
  704. }
  705. }
  706. return super.isDefined(key);
  707. }
  708. /**
  709. * Gets the value of an attribute.
  710. *
  711. * @param key the attribute name
  712. * @return the attribute value
  713. * @see AttributeSet#getAttribute
  714. */
  715. public Object getAttribute(Object key) {
  716. if (key instanceof StyleConstants) {
  717. Object cssKey = css.styleConstantsKeyToCSSKey
  718. ((StyleConstants)key);
  719. if (cssKey != null) {
  720. Object value = super.getAttribute(cssKey);
  721. if (value != null) {
  722. return css.cssValueToStyleConstantsValue
  723. ((StyleConstants)key, value);
  724. }
  725. }
  726. }
  727. return super.getAttribute(key);
  728. }
  729. }
  730. /**
  731. * Small set of attributes that does conversion of requests
  732. * for attributes of type StyleConstants.
  733. */
  734. class SmallConversionSet extends SmallAttributeSet {
  735. /**
  736. * Creates a new attribute set based on a supplied set of attributes.
  737. *
  738. * @param source the set of attributes
  739. */
  740. public SmallConversionSet(AttributeSet attrs) {
  741. super(attrs);
  742. }
  743. /**
  744. * Checks whether a given attribute is defined.
  745. *
  746. * @param key the attribute key
  747. * @return true if the attribute is defined
  748. * @see AttributeSet#isDefined
  749. */
  750. public boolean isDefined(Object key) {
  751. if (key instanceof StyleConstants) {
  752. Object cssKey = css.styleConstantsKeyToCSSKey
  753. ((StyleConstants)key);
  754. if (cssKey != null) {
  755. return super.isDefined(cssKey);
  756. }
  757. }
  758. return super.isDefined(key);
  759. }
  760. /**
  761. * Gets the value of an attribute.
  762. *
  763. * @param key the attribute name
  764. * @return the attribute value
  765. * @see AttributeSet#getAttribute
  766. */
  767. public Object getAttribute(Object key) {
  768. if (key instanceof StyleConstants) {
  769. Object cssKey = css.styleConstantsKeyToCSSKey
  770. ((StyleConstants)key);
  771. if (cssKey != null) {
  772. Object value = super.getAttribute(cssKey);
  773. if (value != null) {
  774. return css.cssValueToStyleConstantsValue
  775. ((StyleConstants)key, value);
  776. }
  777. }
  778. }
  779. return super.getAttribute(key);
  780. }
  781. }
  782. // ---- Resource handling ----------------------------------------
  783. /**
  784. * Fetches the font to use for the given set of attributes.
  785. */
  786. public Font getFont(AttributeSet a) {
  787. return css.getFont(this, a, 12);
  788. }
  789. /**
  790. * Takes a set of attributes and turn it into a foreground color
  791. * specification. This might be used to specify things
  792. * like brighter, more hue, etc.
  793. *
  794. * @param a the set of attributes
  795. * @return the color
  796. */
  797. public Color getForeground(AttributeSet a) {
  798. Color c = css.getColor(a, CSS.Attribute.COLOR);
  799. if (c == null) {
  800. return Color.black;
  801. }
  802. return c;
  803. }
  804. /**
  805. * Takes a set of attributes and turn it into a background color
  806. * specification. This might be used to specify things
  807. * like brighter, more hue, etc.
  808. *
  809. * @param a the set of attributes
  810. * @return the color
  811. */
  812. public Color getBackground(AttributeSet a) {
  813. return css.getColor(a, CSS.Attribute.BACKGROUND_COLOR);
  814. }
  815. /**
  816. * Fetches the box formatter to use for the given set
  817. * of CSS attributes.
  818. */
  819. public BoxPainter getBoxPainter(AttributeSet a) {
  820. return new BoxPainter(a, css, this);
  821. }
  822. /**
  823. * Fetches the list formatter to use for the given set
  824. * of CSS attributes.
  825. */
  826. public ListPainter getListPainter(AttributeSet a) {
  827. return new ListPainter(a, this);
  828. }
  829. /**
  830. * Sets the base font size, with valid values between 1 and 7.
  831. */
  832. public void setBaseFontSize(int sz) {
  833. css.setBaseFontSize(sz);
  834. }
  835. /**
  836. * Sets the base font size from the passed in String. The string
  837. * can either identify a specific font size, with legal values between
  838. * 1 and 7, or identifiy a relative font size such as +1 or -2.
  839. */
  840. public void setBaseFontSize(String size) {
  841. css.setBaseFontSize(size);
  842. }
  843. public static int getIndexOfSize(float pt) {
  844. return CSS.getIndexOfSize(pt);
  845. }
  846. /**
  847. * Returns the point size, given a size index.
  848. */
  849. public float getPointSize(int index) {
  850. return css.getPointSize(index);
  851. }
  852. /**
  853. * Given a string such as "+2", "-2", or "2",
  854. * returns a point size value.
  855. */
  856. public float getPointSize(String size) {
  857. return css.getPointSize(size);
  858. }
  859. /**
  860. * Converts a color string such as "RED" or "#NNNNNN" to a Color.
  861. * Note: This will only convert the HTML3.2 color strings
  862. * or a string of length 7;
  863. * otherwise, it will return null.
  864. */
  865. public Color stringToColor(String string) {
  866. return CSS.stringToColor(string);
  867. }
  868. /**
  869. * Returns the ImageIcon to draw in the background for
  870. * <code>attr</code>.
  871. */
  872. ImageIcon getBackgroundImage(AttributeSet attr) {
  873. Object value = attr.getAttribute(CSS.Attribute.BACKGROUND_IMAGE);
  874. if (value != null) {
  875. return ((CSS.BackgroundImage)value).getImage(getBase());
  876. }
  877. return null;
  878. }
  879. /**
  880. * Adds a rule into the StyleSheet.
  881. *
  882. * @param selector the selector to use for the rule.
  883. * This will be a set of simple selectors, and must
  884. * be a length of 1 or greater.
  885. * @param declaration the set of CSS attributes that
  886. * make up the rule.
  887. */
  888. void addRule(String[] selector, AttributeSet declaration,
  889. boolean isLinked) {
  890. int n = selector.length;
  891. StringBuffer sb = new StringBuffer();
  892. sb.append(selector[0]);
  893. for (int counter = 1; counter < n; counter++) {
  894. sb.append(' ');
  895. sb.append(selector[counter]);
  896. }
  897. String selectorName = sb.toString();
  898. Style rule = getStyle(selectorName);
  899. if (rule == null) {
  900. // Notice how the rule is first created, and it not part of
  901. // the synchronized block. It is done like this as creating
  902. // a new rule will fire a ChangeEvent. We do not want to be
  903. // holding the lock when calling to other objects, it can
  904. // result in deadlock.
  905. Style altRule = addStyle(selectorName, null);
  906. synchronized(this) {
  907. SelectorMapping mapping = getRootSelectorMapping();
  908. for (int i = n - 1; i >= 0; i--) {
  909. mapping = mapping.getChildSelectorMapping
  910. (selector[i], true);
  911. }
  912. rule = mapping.getStyle();
  913. if (rule == null) {
  914. rule = altRule;
  915. mapping.setStyle(rule);
  916. refreshResolvedRules(selectorName, selector, rule,
  917. mapping.getSpecificity());
  918. }
  919. }
  920. }
  921. if (isLinked) {
  922. rule = getLinkedStyle(rule);
  923. }
  924. rule.addAttributes(declaration);
  925. }
  926. //
  927. // The following gaggle of methods is used in maintaing the rules from
  928. // the sheet.
  929. //
  930. /**
  931. * Updates the attributes of the rules to reference any related
  932. * rules in <code>ss</code>.
  933. */
  934. private synchronized void linkStyleSheetAt(StyleSheet ss, int index) {
  935. if (resolvedStyles.size() > 0) {
  936. Enumeration values = resolvedStyles.elements();
  937. while (values.hasMoreElements()) {
  938. ResolvedStyle rule = (ResolvedStyle)values.nextElement();
  939. rule.insertExtendedStyleAt(ss.getRule(rule.getName()),
  940. index);
  941. }
  942. }
  943. }
  944. /**
  945. * Removes references to the rules in <code>ss</code>.
  946. * <code>index</code> gives the index the StyleSheet was at, that is
  947. * how many StyleSheets had been added before it.
  948. */
  949. private synchronized void unlinkStyleSheet(StyleSheet ss, int index) {
  950. if (resolvedStyles.size() > 0) {
  951. Enumeration values = resolvedStyles.elements();
  952. while (values.hasMoreElements()) {
  953. ResolvedStyle rule = (ResolvedStyle)values.nextElement();
  954. rule.removeExtendedStyleAt(index);
  955. }
  956. }
  957. }
  958. /**
  959. * Returns the simple selectors that comprise selector.
  960. */
  961. /* protected */
  962. String[] getSimpleSelectors(String selector) {
  963. selector = cleanSelectorString(selector);
  964. SearchBuffer sb = SearchBuffer.obtainSearchBuffer();
  965. Vector selectors = sb.getVector();
  966. int lastIndex = 0;
  967. int length = selector.length();
  968. while (lastIndex != -1) {
  969. int newIndex = selector.indexOf(' ', lastIndex);
  970. if (newIndex != -1) {
  971. selectors.addElement(selector.substring(lastIndex, newIndex));
  972. if (++newIndex == length) {
  973. lastIndex = -1;
  974. }
  975. else {
  976. lastIndex = newIndex;
  977. }
  978. }
  979. else {
  980. selectors.addElement(selector.substring(lastIndex));
  981. lastIndex = -1;
  982. }
  983. }
  984. String[] retValue = new String[selectors.size()];
  985. selectors.copyInto(retValue);
  986. SearchBuffer.releaseSearchBuffer(sb);
  987. return retValue;
  988. }
  989. /**
  990. * Returns a string that only has one space between simple selectors,
  991. * which may be the passed in String.
  992. */
  993. /*protected*/ String cleanSelectorString(String selector) {
  994. boolean lastWasSpace = true;
  995. for (int counter = 0, maxCounter = selector.length();
  996. counter < maxCounter; counter++) {
  997. switch(selector.charAt(counter)) {
  998. case ' ':
  999. if (lastWasSpace) {
  1000. return _cleanSelectorString(selector);
  1001. }
  1002. lastWasSpace = true;
  1003. break;
  1004. case '\n':
  1005. case '\r':
  1006. case '\t':
  1007. return _cleanSelectorString(selector);
  1008. default:
  1009. lastWasSpace = false;
  1010. }
  1011. }
  1012. if (lastWasSpace) {
  1013. return _cleanSelectorString(selector);
  1014. }
  1015. // It was fine.
  1016. return selector;
  1017. }
  1018. /**
  1019. * Returns a new String that contains only one space between non
  1020. * white space characters.
  1021. */
  1022. private String _cleanSelectorString(String selector) {
  1023. SearchBuffer sb = SearchBuffer.obtainSearchBuffer();
  1024. StringBuffer buff = sb.getStringBuffer();
  1025. boolean lastWasSpace = true;
  1026. int lastIndex = 0;
  1027. char[] chars = selector.toCharArray();
  1028. int numChars = chars.length;
  1029. String retValue = null;
  1030. try {
  1031. for (int counter = 0; counter < numChars; counter++) {
  1032. switch(chars[counter]) {
  1033. case ' ':
  1034. if (!lastWasSpace) {
  1035. lastWasSpace = true;
  1036. if (lastIndex < counter) {
  1037. buff.append(chars, lastIndex,
  1038. 1 + counter - lastIndex);
  1039. }
  1040. }
  1041. lastIndex = counter + 1;
  1042. break;
  1043. case '\n':
  1044. case '\r':
  1045. case '\t':
  1046. if (!lastWasSpace) {
  1047. lastWasSpace = true;
  1048. if (lastIndex < counter) {
  1049. buff.append(chars, lastIndex,
  1050. counter - lastIndex);
  1051. buff.append(' ');
  1052. }
  1053. }
  1054. lastIndex = counter + 1;
  1055. break;
  1056. default:
  1057. lastWasSpace = false;
  1058. break;
  1059. }
  1060. }
  1061. if (lastWasSpace && buff.length() > 0) {
  1062. // Remove last space.
  1063. buff.setLength(buff.length() - 1);
  1064. }
  1065. else if (lastIndex < numChars) {
  1066. buff.append(chars, lastIndex, numChars - lastIndex);
  1067. }
  1068. retValue = buff.toString();
  1069. }
  1070. finally {
  1071. SearchBuffer.releaseSearchBuffer(sb);
  1072. }
  1073. return retValue;
  1074. }
  1075. /**
  1076. * Returns the root selector mapping that all selectors are relative
  1077. * to. This is an inverted graph of the selectors.
  1078. */
  1079. private SelectorMapping getRootSelectorMapping() {
  1080. return selectorMapping;
  1081. }
  1082. /**
  1083. * Returns the specificity of the passed in String. It assumes the
  1084. * passed in string doesn't contain junk, that is each selector is
  1085. * separated by a space and each selector at most contains one . or one
  1086. * #. A simple selector has a weight of 1, an id selector has a weight
  1087. * of 100, and a class selector has a weight of 10000.
  1088. */
  1089. /*protected*/ static int getSpecificity(String selector) {
  1090. int specificity = 0;
  1091. boolean lastWasSpace = true;
  1092. for (int counter = 0, maxCounter = selector.length();
  1093. counter < maxCounter; counter++) {
  1094. switch(selector.charAt(counter)) {
  1095. case '.':
  1096. specificity += 100;
  1097. break;
  1098. case '#':
  1099. specificity += 10000;
  1100. break;
  1101. case ' ':
  1102. lastWasSpace = true;
  1103. break;
  1104. default:
  1105. if (lastWasSpace) {
  1106. lastWasSpace = false;
  1107. specificity += 1;
  1108. }
  1109. }
  1110. }
  1111. return specificity;
  1112. }
  1113. /**
  1114. * Returns the style that linked attributes should be added to. This
  1115. * will create the style if necessary.
  1116. */
  1117. private Style getLinkedStyle(Style localStyle) {
  1118. // NOTE: This is not synchronized, and the caller of this does
  1119. // not synchronize. There is the chance for one of the callers to
  1120. // overwrite the existing resolved parent, but it is quite rare.
  1121. // The reason this is left like this is because setResolveParent
  1122. // will fire a ChangeEvent. It is really, REALLY bad for us to
  1123. // hold a lock when calling outside of us, it may cause a deadlock.
  1124. Style retStyle = (Style)localStyle.getResolveParent();
  1125. if (retStyle == null) {
  1126. retStyle = addStyle(null, null);
  1127. localStyle.setResolveParent(retStyle);
  1128. }
  1129. return retStyle;
  1130. }
  1131. /**
  1132. * Returns the resolved style for <code>selector</code>. This will
  1133. * create the resolved style, if necessary.
  1134. */
  1135. private synchronized Style getResolvedStyle(String selector,
  1136. Vector elements,
  1137. HTML.Tag t) {
  1138. Style retStyle = (Style)resolvedStyles.get(selector);
  1139. if (retStyle == null) {
  1140. retStyle = createResolvedStyle(selector, elements, t);
  1141. }
  1142. return retStyle;
  1143. }
  1144. /**
  1145. * Returns the resolved style for <code>selector</code>. This will
  1146. * create the resolved style, if necessary.
  1147. */
  1148. private synchronized Style getResolvedStyle(String selector) {
  1149. Style retStyle = (Style)resolvedStyles.get(selector);
  1150. if (retStyle == null) {
  1151. retStyle = createResolvedStyle(selector);
  1152. }
  1153. return retStyle;
  1154. }
  1155. /**
  1156. * Adds <code>mapping</code> to <code>elements</code>. It is added
  1157. * such that <code>elements</code> will remain ordered by
  1158. * specificity.
  1159. */
  1160. private void addSortedStyle(SelectorMapping mapping, Vector elements) {
  1161. int size = elements.size();
  1162. if (size > 0) {
  1163. int specificity = mapping.getSpecificity();
  1164. for (int counter = 0; counter < size; counter++) {
  1165. if (specificity >= ((SelectorMapping)elements.elementAt
  1166. (counter)).getSpecificity()) {
  1167. elements.insertElementAt(mapping, counter);
  1168. return;
  1169. }
  1170. }
  1171. }
  1172. elements.addElement(mapping);
  1173. }
  1174. /**
  1175. * Adds <code>parentMapping</code> to <code>styles</code>, and
  1176. * recursively calls this method if <code>parentMapping</code> has
  1177. * any child mappings for any of the Elements in <code>elements</code>.
  1178. */
  1179. private synchronized void getStyles(SelectorMapping parentMapping,
  1180. Vector styles,
  1181. String[] tags, String[] ids, String[] classes,
  1182. int index, int numElements,
  1183. Hashtable alreadyChecked) {
  1184. // Avoid desending the same mapping twice.
  1185. if (alreadyChecked.contains(parentMapping)) {
  1186. return;
  1187. }
  1188. alreadyChecked.put(parentMapping, parentMapping);
  1189. Style style = parentMapping.getStyle();
  1190. if (style != null) {
  1191. addSortedStyle(parentMapping, styles);
  1192. }
  1193. for (int counter = index; counter < numElements; counter++) {
  1194. String tagString = tags[counter];
  1195. if (tagString != null) {
  1196. SelectorMapping childMapping = parentMapping.
  1197. getChildSelectorMapping(tagString, false);
  1198. if (childMapping != null) {
  1199. getStyles(childMapping, styles, tags, ids, classes,
  1200. counter + 1, numElements, alreadyChecked);
  1201. }
  1202. if (classes[counter] != null) {
  1203. String className = classes[counter];
  1204. childMapping = parentMapping.getChildSelectorMapping(
  1205. tagString + "." + className, false);
  1206. if (childMapping != null) {
  1207. getStyles(childMapping, styles, tags, ids, classes,
  1208. counter + 1, numElements, alreadyChecked);
  1209. }
  1210. childMapping = parentMapping.getChildSelectorMapping(
  1211. "." + className, false);
  1212. if (childMapping != null) {
  1213. getStyles(childMapping, styles, tags, ids, classes,
  1214. counter + 1, numElements, alreadyChecked);
  1215. }
  1216. }
  1217. if (ids[counter] != null) {
  1218. String idName = ids[counter];
  1219. childMapping = parentMapping.getChildSelectorMapping(
  1220. tagString + "#" + idName, false);
  1221. if (childMapping != null) {
  1222. getStyles(childMapping, styles, tags, ids, classes,
  1223. counter + 1, numElements, alreadyChecked);
  1224. }
  1225. childMapping = parentMapping.getChildSelectorMapping(
  1226. "#" + idName, false);
  1227. if (childMapping != null) {
  1228. getStyles(childMapping, styles, tags, ids, classes,
  1229. counter + 1, numElements, alreadyChecked);
  1230. }
  1231. }
  1232. }
  1233. }
  1234. }
  1235. /**
  1236. * Creates and returns a Style containing all the rules that match
  1237. * <code>selector</code>.
  1238. */
  1239. private synchronized Style createResolvedStyle(String selector,
  1240. String[] tags,
  1241. String[] ids, String[] classes) {
  1242. SearchBuffer sb = SearchBuffer.obtainSearchBuffer();
  1243. Vector tempVector = sb.getVector();
  1244. Hashtable tempHashtable = sb.getHashtable();
  1245. // Determine all the Styles that are appropriate, placing them
  1246. // in tempVector
  1247. try {
  1248. SelectorMapping mapping = getRootSelectorMapping();
  1249. int numElements = tags.length;
  1250. String tagString = tags[0];
  1251. SelectorMapping childMapping = mapping.getChildSelectorMapping(
  1252. tagString, false);
  1253. if (childMapping != null) {
  1254. getStyles(childMapping, tempVector, tags, ids, classes, 1,
  1255. numElements, tempHashtable);
  1256. }
  1257. if (classes[0] != null) {
  1258. String className = classes[0];
  1259. childMapping = mapping.getChildSelectorMapping(
  1260. tagString + "." + className, false);
  1261. if (childMapping != null) {
  1262. getStyles(childMapping, tempVector, tags, ids, classes, 1,
  1263. numElements, tempHashtable);
  1264. }
  1265. childMapping = mapping.getChildSelectorMapping(
  1266. "." + className, false);
  1267. if (childMapping != null) {
  1268. getStyles(childMapping, tempVector, tags, ids, classes,
  1269. 1, numElements, tempHashtable);
  1270. }
  1271. }
  1272. if (ids[0] != null) {
  1273. String idName = ids[0];
  1274. childMapping = mapping.getChildSelectorMapping(
  1275. tagString + "#" + idName, false);
  1276. if (childMapping != null) {
  1277. getStyles(childMapping, tempVector, tags, ids, classes,
  1278. 1, numElements, tempHashtable);
  1279. }
  1280. childMapping = mapping.getChildSelectorMapping(
  1281. "#" + idName, false);
  1282. if (childMapping != null) {
  1283. getStyles(childMapping, tempVector, tags, ids, classes,
  1284. 1, numElements, tempHashtable);
  1285. }
  1286. }
  1287. // Create a new Style that will delegate to all the matching
  1288. // Styles.
  1289. int numLinkedSS = (linkedStyleSheets != null) ?
  1290. linkedStyleSheets.size() : 0;
  1291. int numStyles = tempVector.size();
  1292. AttributeSet[] attrs = new AttributeSet[numStyles + numLinkedSS];
  1293. for (int counter = 0; counter < numStyles; counter++) {
  1294. attrs[counter] = ((SelectorMapping)tempVector.
  1295. elementAt(counter)).getStyle();
  1296. }
  1297. // Get the AttributeSet from linked style sheets.
  1298. for (int counter = 0; counter < numLinkedSS; counter++) {
  1299. AttributeSet attr = ((StyleSheet)linkedStyleSheets.
  1300. elementAt(counter)).getRule(selector);
  1301. if (attr == null) {
  1302. attrs[counter + numStyles] = SimpleAttributeSet.EMPTY;
  1303. }
  1304. else {
  1305. attrs[counter + numStyles] = attr;
  1306. }
  1307. }
  1308. ResolvedStyle retStyle = new ResolvedStyle(selector, attrs,
  1309. numStyles);
  1310. resolvedStyles.put(selector, retStyle);
  1311. return retStyle;
  1312. }
  1313. finally {
  1314. SearchBuffer.releaseSearchBuffer(sb);
  1315. }
  1316. }
  1317. /**
  1318. * Creates and returns a Style containing all the rules that
  1319. * matches <code>selector</code>.
  1320. *
  1321. * @param elements a Vector of all the Elements
  1322. * the style is being asked for. The
  1323. * first Element is the deepest Element, with the last Element
  1324. * representing the root.
  1325. * @param t the Tag to use for
  1326. * the first Element in <code>elements</code>
  1327. */
  1328. private Style createResolvedStyle(String selector, Vector elements,
  1329. HTML.Tag t) {
  1330. int numElements = elements.size();
  1331. // Build three arrays, one for tags, one for class's, and one for
  1332. // id's
  1333. String tags[] = new String[numElements];
  1334. String ids[] = new String[numElements];
  1335. String classes[] = new String[numElements];
  1336. for (int counter = 0; counter < numElements; counter++) {
  1337. Element e = (Element)elements.elementAt(counter);
  1338. AttributeSet attr = e.getAttributes();
  1339. if (counter == 0 && e.isLeaf()) {
  1340. // For leafs, we use the second tier attributes.
  1341. Object testAttr = attr.getAttribute(t);
  1342. if (testAttr instanceof AttributeSet) {
  1343. attr = (AttributeSet)testAttr;
  1344. }
  1345. else {
  1346. attr = null;
  1347. }
  1348. }
  1349. if (attr != null) {
  1350. HTML.Tag tag = (HTML.Tag)attr.getAttribute(StyleConstants.
  1351. NameAttribute);
  1352. if (tag != null) {
  1353. tags[counter] = tag.toString();
  1354. }
  1355. else {
  1356. tags[counter] = null;
  1357. }
  1358. if (attr.isDefined(HTML.Attribute.CLASS)) {
  1359. classes[counter] = attr.getAttribute
  1360. (HTML.Attribute.CLASS).toString();
  1361. }
  1362. else {
  1363. classes[counter] = null;
  1364. }
  1365. if (attr.isDefined(HTML.Attribute.ID)) {
  1366. ids[counter] = attr.getAttribute(HTML.Attribute.ID).
  1367. toString();
  1368. }
  1369. else {
  1370. ids[counter] = null;
  1371. }
  1372. }
  1373. else {
  1374. tags[counter] = ids[counter] = classes[counter] = null;
  1375. }
  1376. }
  1377. tags[0] = t.toString();
  1378. return createResolvedStyle(selector, tags, ids, classes);
  1379. }
  1380. /**
  1381. * Creates and returns a Style containing all the rules that match
  1382. * <code>selector</code>. It is assumed that each simple selector
  1383. * in <code>selector</code> is separated by a space.
  1384. */
  1385. private Style createResolvedStyle(String selector) {
  1386. SearchBuffer sb = SearchBuffer.obtainSearchBuffer();
  1387. // Will contain the tags, ids, and classes, in that order.
  1388. Vector elements = sb.getVector();
  1389. try {
  1390. boolean done;
  1391. int dotIndex = 0;
  1392. int spaceIndex = 0;
  1393. int poundIndex = 0;
  1394. int lastIndex = 0;
  1395. int length = selector.length();
  1396. while (lastIndex < length) {
  1397. if (dotIndex == lastIndex) {
  1398. dotIndex = selector.indexOf('.', lastIndex);
  1399. }
  1400. if (poundIndex == lastIndex) {
  1401. poundIndex = selector.indexOf('#', lastIndex);
  1402. }
  1403. spaceIndex = selector.indexOf(' ', lastIndex);
  1404. if (spaceIndex == -1) {
  1405. spaceIndex = length;
  1406. }
  1407. if (dotIndex != -1 && poundIndex != -1 &&
  1408. dotIndex < spaceIndex && poundIndex < spaceIndex) {
  1409. if (poundIndex < dotIndex) {
  1410. // #.
  1411. if (lastIndex == poundIndex) {
  1412. elements.addElement("");
  1413. }
  1414. else {
  1415. elements.addElement(selector.substring(lastIndex,
  1416. poundIndex));
  1417. }
  1418. if ((dotIndex + 1) < spaceIndex) {
  1419. elements.addElement(selector.substring
  1420. (dotIndex + 1, spaceIndex));
  1421. }
  1422. else {
  1423. elements.addElement(null);
  1424. }
  1425. if ((poundIndex + 1) == dotIndex) {
  1426. elements.addElement(null);
  1427. }
  1428. else {
  1429. elements.addElement(selector.substring
  1430. (poundIndex + 1, dotIndex));
  1431. }
  1432. }
  1433. else if(poundIndex < spaceIndex) {
  1434. // .#
  1435. if (lastIndex == dotIndex) {
  1436. elements.addElement("");
  1437. }
  1438. else {
  1439. elements.addElement(selector.substring(lastIndex,
  1440. dotIndex));
  1441. }
  1442. if ((dotIndex + 1) < poundIndex) {
  1443. elements.addElement(selector.substring
  1444. (dotIndex + 1, poundIndex));
  1445. }
  1446. else {
  1447. elements.addElement(null);
  1448. }
  1449. if ((poundIndex + 1) == spaceIndex) {
  1450. elements.addElement(null);
  1451. }
  1452. else {
  1453. elements.addElement(selector.substring
  1454. (poundIndex + 1, spaceIndex));
  1455. }
  1456. }
  1457. dotIndex = poundIndex = spaceIndex + 1;
  1458. }
  1459. else if (dotIndex != -1 && dotIndex < spaceIndex) {
  1460. // .
  1461. if (dotIndex == lastIndex) {
  1462. elements.addElement("");
  1463. }
  1464. else {
  1465. elements.addElement(selector.substring(lastIndex,
  1466. dotIndex));
  1467. }
  1468. if ((dotIndex + 1) == spaceIndex) {
  1469. elements.addElement(null);
  1470. }
  1471. else {
  1472. elements.addElement(selector.substring(dotIndex + 1,
  1473. spaceIndex));
  1474. }
  1475. elements.addElement(null);
  1476. dotIndex = spaceIndex + 1;
  1477. }
  1478. else if (poundIndex != -1 && poundIndex < spaceIndex) {
  1479. // #
  1480. if (poundIndex == lastIndex) {
  1481. elements.addElement("");
  1482. }
  1483. else {
  1484. elements.addElement(selector.substring(lastIndex,
  1485. poundIndex));
  1486. }
  1487. elements.addElement(null);
  1488. if ((poundIndex + 1) == spaceIndex) {
  1489. elements.addElement(null);
  1490. }
  1491. else {
  1492. elements.addElement(selector.substring(poundIndex + 1,
  1493. spaceIndex));
  1494. }
  1495. poundIndex = spaceIndex + 1;
  1496. }
  1497. else {
  1498. // id
  1499. elements.addElement(selector.substring(lastIndex,
  1500. spaceIndex));
  1501. elements.addElement(null);
  1502. elements.addElement(null);
  1503. }
  1504. lastIndex = spaceIndex + 1;
  1505. }
  1506. // Create the tag, id, and class arrays.
  1507. int total = elements.size();
  1508. int numTags = total / 3;
  1509. String[] tags = new String[numTags];
  1510. String[] ids = new String[numTags];
  1511. String[] classes = new String[numTags];
  1512. for (int index = 0, eIndex = total - 3; index < numTags;
  1513. index++, eIndex -= 3) {
  1514. tags[index] = (String)elements.elementAt(eIndex);
  1515. ids[index] = (String)elements.elementAt(eIndex + 1);
  1516. classes[index] = (String)elements.elementAt(eIndex + 2);
  1517. }
  1518. return createResolvedStyle(selector, tags, ids, classes);
  1519. }
  1520. finally {
  1521. SearchBuffer.releaseSearchBuffer(sb);
  1522. }
  1523. }
  1524. /**
  1525. * Should be invoked when a new rule is added that did not previously
  1526. * exist. Goes through and refreshes the necessary resolved
  1527. * rules.
  1528. */
  1529. private synchronized void refreshResolvedRules(String selectorName,
  1530. String[] selector,
  1531. Style newStyle,
  1532. int specificity) {
  1533. if (resolvedStyles.size() > 0) {
  1534. Enumeration values = resolvedStyles.elements();
  1535. while (values.hasMoreElements()) {
  1536. ResolvedStyle style = (ResolvedStyle)values.nextElement();
  1537. if (style.matches(selectorName)) {
  1538. style.insertStyle(newStyle, specificity);
  1539. }
  1540. }
  1541. }
  1542. }
  1543. /**
  1544. * A temporary class used to hold a Vector, a StringBuffer and a
  1545. * Hashtable. This is used to avoid allocing a lot of garbage when
  1546. * searching for rules. Use the static method obtainSearchBuffer and
  1547. * releaseSearchBuffer to get a SearchBuffer, and release it when
  1548. * done.
  1549. */
  1550. private static class SearchBuffer {
  1551. /** A stack containing instances of SearchBuffer. Used in getting
  1552. * rules. */
  1553. static Stack searchBuffers = new Stack();
  1554. // A set of temporary variables that can be used in whatever way.
  1555. Vector vector = null;
  1556. StringBuffer stringBuffer = null;
  1557. Hashtable hashtable = null;
  1558. /**
  1559. * Returns an instance of SearchBuffer. Be sure and issue
  1560. * a releaseSearchBuffer when done with it.
  1561. */
  1562. static SearchBuffer obtainSearchBuffer() {
  1563. SearchBuffer sb;
  1564. try {
  1565. sb = (SearchBuffer)searchBuffers.pop();
  1566. } catch (EmptyStackException ese) {
  1567. sb = new SearchBuffer();
  1568. }
  1569. return sb;
  1570. }
  1571. /**
  1572. * Adds <code>sb</code> to the stack of SearchBuffers that can
  1573. * be used.
  1574. */
  1575. static void releaseSearchBuffer(SearchBuffer sb) {
  1576. sb.empty();
  1577. searchBuffers.push(sb);
  1578. }
  1579. StringBuffer getStringBuffer() {
  1580. if (stringBuffer == null) {
  1581. stringBuffer = new StringBuffer();
  1582. }
  1583. return stringBuffer;
  1584. }
  1585. Vector getVector() {
  1586. if (vector == null) {
  1587. vector = new Vector();
  1588. }
  1589. return vector;
  1590. }
  1591. Hashtable getHashtable() {
  1592. if (hashtable == null) {
  1593. hashtable = new Hashtable();
  1594. }
  1595. return hashtable;
  1596. }
  1597. void empty() {
  1598. if (stringBuffer != null) {
  1599. stringBuffer.setLength(0);
  1600. }
  1601. if (vector != null) {
  1602. vector.removeAllElements();
  1603. }
  1604. if (hashtable != null) {
  1605. hashtable.clear();
  1606. }
  1607. }
  1608. }
  1609. static final Border noBorder = new EmptyBorder(0,0,0,0);
  1610. /**
  1611. * Class to carry out some of the duties of
  1612. * CSS formatting. Implementations of this
  1613. * class enable views to present the CSS formatting
  1614. * while not knowing anything about how the CSS values
  1615. * are being cached.
  1616. * <p>
  1617. * As a delegate of Views, this object is responsible for
  1618. * the insets of a View and making sure the background
  1619. * is maintained according to the CSS attributes.
  1620. */
  1621. public static class BoxPainter implements Serializable {
  1622. BoxPainter(AttributeSet a, CSS css, StyleSheet ss) {
  1623. this.ss = ss;
  1624. this.css = css;
  1625. border = getBorder(a);
  1626. binsets = border.getBorderInsets(null);
  1627. topMargin = getLength(CSS.Attribute.MARGIN_TOP, a);
  1628. bottomMargin = getLength(CSS.Attribute.MARGIN_BOTTOM, a);
  1629. leftMargin = getLength(CSS.Attribute.MARGIN_LEFT, a);
  1630. rightMargin = getLength(CSS.Attribute.MARGIN_RIGHT, a);
  1631. bg = ss.getBackground(a);
  1632. if (ss.getBackgroundImage(a) != null) {
  1633. bgPainter = new BackgroundImagePainter(a, css, ss);
  1634. }
  1635. }
  1636. /**
  1637. * Fetches a border to render for the given attributes.
  1638. * PENDING(prinz) This is pretty badly hacked at the
  1639. * moment.
  1640. */
  1641. Border getBorder(AttributeSet a) {
  1642. Border b = noBorder;
  1643. Object o = a.getAttribute(CSS.Attribute.BORDER_STYLE);
  1644. if (o != null) {
  1645. String bstyle = o.toString();
  1646. int bw = (int) getLength(CSS.Attribute.BORDER_TOP_WIDTH, a);
  1647. if (bw > 0) {
  1648. if (bstyle.equals("inset")) {
  1649. Color c = getBorderColor(a);
  1650. b = new BevelBorder(BevelBorder.LOWERED, c.brighter(), c.darker());
  1651. } else if (bstyle.equals("outset")) {
  1652. Color c = getBorderColor(a);
  1653. b = new BevelBorder(BevelBorder.RAISED, c.brighter(), c.darker());
  1654. } else if (bstyle.equals("solid")) {
  1655. Color c = getBorderColor(a);
  1656. b = new LineBorder(c);
  1657. }
  1658. }
  1659. }
  1660. return b;
  1661. }
  1662. /**
  1663. * Fetches the color to use for borders. This will either be
  1664. * the value specified by the border-color attribute (which
  1665. * is not inherited), or it will default to the color attribute
  1666. * (which is inherited).
  1667. */
  1668. Color getBorderColor(AttributeSet a) {
  1669. Color color = css.getColor(a, CSS.Attribute.BORDER_COLOR);
  1670. if (color == null) {
  1671. color = css.getColor(a, CSS.Attribute.COLOR);
  1672. if (color == null) {
  1673. return Color.black;
  1674. }
  1675. }
  1676. return color;
  1677. }
  1678. /**
  1679. * Fetches the inset needed on a given side to
  1680. * account for the margin, border, and padding.
  1681. *
  1682. * @param side The size of the box to fetch the
  1683. * inset for. This can be View.TOP,
  1684. * View.LEFT, View.BOTTOM, or View.RIGHT.
  1685. * @param v the view making the request. This is
  1686. * used to get the AttributeSet, and may be used to
  1687. * resolve percentage arguments.
  1688. * @exception IllegalArgumentException for an invalid direction
  1689. */
  1690. public float getInset(int side, View v) {
  1691. AttributeSet a = v.getAttributes();
  1692. float inset = 0;
  1693. switch(side) {
  1694. case View.LEFT:
  1695. inset += leftMargin;
  1696. inset += binsets.left;
  1697. inset += getLength(CSS.Attribute.PADDING_LEFT, a);
  1698. break;
  1699. case View.RIGHT:
  1700. inset += rightMargin;
  1701. inset += binsets.right;
  1702. inset += getLength(CSS.Attribute.PADDING_RIGHT, a);
  1703. break;
  1704. case View.TOP:
  1705. inset += topMargin;
  1706. inset += binsets.top;
  1707. inset += getLength(CSS.Attribute.PADDING_TOP, a);
  1708. break;
  1709. case View.BOTTOM:
  1710. inset += bottomMargin;
  1711. inset += binsets.bottom;
  1712. inset += getLength(CSS.Attribute.PADDING_BOTTOM, a);
  1713. break;
  1714. default:
  1715. throw new IllegalArgumentException("Invalid side: " + side);
  1716. }
  1717. return inset;
  1718. }
  1719. /**
  1720. * Paints the CSS box according to the attributes
  1721. * given. This should paint the border, padding,
  1722. * and background.
  1723. *
  1724. * @param g the rendering surface.
  1725. * @param x the x coordinate of the allocated area to
  1726. * render into.
  1727. * @param y the y coordinate of the allocated area to
  1728. * render into.
  1729. * @param w the width of the allocated area to render into.
  1730. * @param h the height of the allocated area to render into.
  1731. * @param v the view making the request. This is
  1732. * used to get the AttributeSet, and may be used to
  1733. * resolve percentage arguments.
  1734. */
  1735. public void paint(Graphics g, float x, float y, float w, float h, View v) {
  1736. // PENDING(prinz) implement real rendering... which would
  1737. // do full set of border and background capabilities.
  1738. // remove margin
  1739. x += leftMargin;
  1740. y += topMargin;
  1741. w -= leftMargin + rightMargin;
  1742. h -= topMargin + bottomMargin;
  1743. if (bg != null) {
  1744. g.setColor(bg);
  1745. g.fillRect((int) x, (int) y, (int) w, (int) h);
  1746. }
  1747. if (bgPainter != null) {
  1748. bgPainter.paint(g, x, y, w, h, v);
  1749. }
  1750. border.paintBorder(null, g, (int) x, (int) y, (int) w, (int) h);
  1751. }
  1752. float getLength(CSS.Attribute key, AttributeSet a) {
  1753. return css.getLength(a, key);
  1754. }
  1755. float topMargin;
  1756. float bottomMargin;
  1757. float leftMargin;
  1758. float rightMargin;
  1759. // Bitmask, used to indicate what margins are relative:
  1760. // bit 0 for top, 1 for bottom, 2 for left and 3 for right.
  1761. short marginFlags;
  1762. Border border;
  1763. Insets binsets;
  1764. CSS css;
  1765. StyleSheet ss;
  1766. Color bg;
  1767. BackgroundImagePainter bgPainter;
  1768. }
  1769. /**
  1770. * Class to carry out some of the duties of CSS list
  1771. * formatting. Implementations of this
  1772. * class enable views to present the CSS formatting
  1773. * while not knowing anything about how the CSS values
  1774. * are being cached.
  1775. */
  1776. public static class ListPainter implements Serializable {
  1777. ListPainter(AttributeSet attr, StyleSheet ss) {
  1778. /* Get the image to use as a list bullet */
  1779. String imgstr = (String)attr.getAttribute(CSS.Attribute.
  1780. LIST_STYLE_IMAGE);
  1781. type = null;
  1782. if (imgstr != null && !imgstr.equals("none")) {
  1783. String tmpstr = null;
  1784. try {
  1785. StringTokenizer st = new StringTokenizer(imgstr, "()");
  1786. if (st.hasMoreTokens())
  1787. tmpstr = st.nextToken();
  1788. if (st.hasMoreTokens())
  1789. tmpstr = st.nextToken();
  1790. URL u = new URL(tmpstr);
  1791. img = new ImageIcon(u);
  1792. } catch (MalformedURLException e) {
  1793. if (tmpstr != null && ss != null && ss.getBase() != null) {
  1794. try {
  1795. URL u = new URL(ss.getBase(), tmpstr);
  1796. img = new ImageIcon(u);
  1797. } catch (MalformedURLException murle) {
  1798. img = null;
  1799. }
  1800. }
  1801. else {
  1802. img = null;
  1803. }
  1804. }
  1805. }
  1806. /* Get the type of bullet to use in the list */
  1807. if (img == null) {
  1808. type = (CSS.Value)attr.getAttribute(CSS.Attribute.
  1809. LIST_STYLE_TYPE);
  1810. }
  1811. start = 1;
  1812. paintRect = new Rectangle();
  1813. }
  1814. /**
  1815. * Returns a string that represents the value
  1816. * of the HTML.Attribute.TYPE attribute.
  1817. * If this attributes is not defined, then
  1818. * then the type defaults to "disc" unless
  1819. * the tag is on Ordered list. In the case
  1820. * of the latter, the default type is "decimal".
  1821. */
  1822. private CSS.Value getChildType(View childView) {
  1823. CSS.Value childtype = (CSS.Value)childView.getAttributes().
  1824. getAttribute(CSS.Attribute.LIST_STYLE_TYPE);
  1825. if (childtype == null) {
  1826. if (type == null) {
  1827. // Parent view.
  1828. View v = childView.getParent();
  1829. HTMLDocument doc = (HTMLDocument)v.getDocument();
  1830. if (doc.matchNameAttribute(v.getElement().getAttributes(),
  1831. HTML.Tag.OL)) {
  1832. childtype = CSS.Value.DECIMAL;
  1833. } else {
  1834. childtype = CSS.Value.DISC;
  1835. }
  1836. } else {
  1837. childtype = type;
  1838. }
  1839. }
  1840. return childtype;
  1841. }
  1842. /**
  1843. * Obtains the starting index from <code>parent</code>.
  1844. */
  1845. private void getStart(View parent) {
  1846. checkedForStart = true;
  1847. Element element = parent.getElement();
  1848. if (element != null) {
  1849. AttributeSet attr = element.getAttributes();
  1850. Object startValue;
  1851. if (attr != null && attr.isDefined(HTML.Attribute.START) &&
  1852. (startValue = attr.getAttribute
  1853. (HTML.Attribute.START)) != null &&
  1854. (startValue instanceof String)) {
  1855. try {
  1856. start = Integer.parseInt((String)startValue);
  1857. }
  1858. catch (NumberFormatException nfe) {}
  1859. }
  1860. }
  1861. }
  1862. /**
  1863. * Returns an integer that should be used to render the child at
  1864. * <code>childIndex</code> with. The retValue will usually be
  1865. * <code>childIndex</code> + 1, unless <code>parentView</code>
  1866. * has some Views that do not represent LI's, or one of the views
  1867. * has a HTML.Attribute.START specified.
  1868. */
  1869. private int getRenderIndex(View parentView, int childIndex) {
  1870. if (!checkedForStart) {
  1871. getStart(parentView);
  1872. }
  1873. int retIndex = childIndex;
  1874. for (int counter = childIndex; counter >= 0; counter--) {
  1875. AttributeSet as = parentView.getElement().getElement(counter).
  1876. getAttributes();
  1877. if (as.getAttribute(StyleConstants.NameAttribute) !=
  1878. HTML.Tag.LI) {
  1879. retIndex--;
  1880. }
  1881. else {
  1882. Object value = as.getAttribute(HTML.Attribute.VALUE);
  1883. if (value != null &&
  1884. (value instanceof String)) {
  1885. try {
  1886. int iValue = Integer.parseInt((String)value);
  1887. return retIndex - counter + iValue;
  1888. }
  1889. catch (NumberFormatException nfe) {}
  1890. }
  1891. }
  1892. }
  1893. return retIndex + start;
  1894. }
  1895. /**
  1896. * Paints the CSS list decoration according to the
  1897. * attributes given.
  1898. *
  1899. * @param g the rendering surface.
  1900. * @param x the x coordinate of the list item allocation
  1901. * @param y the y coordinate of the list item allocation
  1902. * @param w the width of the list item allocation
  1903. * @param h the height of the list item allocation
  1904. * @param v the allocated area to paint into.
  1905. * @param item which list item is being painted. This
  1906. * is a number greater than or equal to 0.
  1907. */
  1908. public void paint(Graphics g, float x, float y, float w, float h, View v, int item) {
  1909. View cv = v.getView(item);
  1910. Object name = cv.getElement().getAttributes().getAttribute
  1911. (StyleConstants.NameAttribute);
  1912. // Only draw something if the View is a list item. This won't
  1913. // be the case for comments.
  1914. if (!(name instanceof HTML.Tag) ||
  1915. name != HTML.Tag.LI) {
  1916. return;
  1917. }
  1918. // How the list indicator is aligned is not specified, it is
  1919. // left up to the UA. IE and NS differ on this behavior.
  1920. // This is closer to NS where we align to the first line of text.
  1921. // If the child is not text we draw the indicator at the
  1922. // origin (0).
  1923. float align = 0;
  1924. if (cv.getViewCount() > 0) {
  1925. View pView = cv.getView(0);
  1926. Object cName = pView.getElement().getAttributes().
  1927. getAttribute(StyleConstants.NameAttribute);
  1928. if ((cName == HTML.Tag.P || cName == HTML.Tag.IMPLIED) &&
  1929. pView.getViewCount() > 0) {
  1930. paintRect.setBounds((int)x, (int)y, (int)w, (int)h);
  1931. Shape shape = cv.getChildAllocation(0, paintRect);
  1932. if (shape != null && (shape = pView.getView(0).
  1933. getChildAllocation(0, shape)) != null) {
  1934. Rectangle rect = (shape instanceof Rectangle) ?
  1935. (Rectangle)shape : shape.getBounds();
  1936. align = pView.getView(0).getAlignment(View.Y_AXIS);
  1937. y = rect.y;
  1938. h = rect.height;
  1939. }
  1940. }
  1941. }
  1942. if (img != null) {
  1943. drawIcon(g, (int) x, (int) y, (int) h, align,
  1944. v.getContainer());
  1945. return;
  1946. }
  1947. CSS.Value childtype = getChildType(cv);
  1948. Font font = ((StyledDocument)cv.getDocument()).
  1949. getFont(cv.getAttributes());
  1950. if (font != null) {
  1951. g.setFont(font);
  1952. }
  1953. if (childtype == CSS.Value.SQUARE || childtype == CSS.Value.CIRCLE
  1954. || childtype == CSS.Value.DISC) {
  1955. drawShape(g, childtype, (int) x, (int) y, (int) h, align);
  1956. } else if (childtype == CSS.Value.CIRCLE) {
  1957. drawShape(g, childtype, (int) x, (int) y, (int) h, align);
  1958. } else if (childtype == CSS.Value.DECIMAL) {
  1959. drawLetter(g, '1', (int) x, (int) y, (int) h, align,
  1960. getRenderIndex(v, item));
  1961. } else if (childtype == CSS.Value.LOWER_ALPHA) {
  1962. drawLetter(g, 'a', (int) x, (int) y, (int) h, align,
  1963. getRenderIndex(v, item));
  1964. } else if (childtype == CSS.Value.UPPER_ALPHA) {
  1965. drawLetter(g, 'A', (int) x, (int) y, (int) h, align,
  1966. getRenderIndex(v, item));
  1967. } else if (childtype == CSS.Value.LOWER_ROMAN) {
  1968. drawLetter(g, 'i', (int) x, (int) y, (int) h, align,
  1969. getRenderIndex(v, item));
  1970. } else if (childtype == CSS.Value.UPPER_ROMAN) {
  1971. drawLetter(g, 'I', (int) x, (int) y, (int) h, align,
  1972. getRenderIndex(v, item));
  1973. }
  1974. }
  1975. /**
  1976. * Draws the bullet icon specified by the list-style-image argument.
  1977. *
  1978. * @param g the graphics context
  1979. * @param ax x coordinate to place the bullet
  1980. * @param ay y coordinate to place the bullet
  1981. * @param ah height of the container the bullet is placed in
  1982. * @param align preferred alignment factor for the child view
  1983. */
  1984. void drawIcon(Graphics g, int ax, int ay, int ah,
  1985. float align, Component c) {
  1986. // Align to bottom of icon.
  1987. g.setColor(Color.black);
  1988. int x = ax - img.getIconWidth() - bulletgap;
  1989. int y = Math.max(ay, ay + (int)(align * ah) -img.getIconHeight());
  1990. img.paintIcon(c, g, x, y);
  1991. }
  1992. /**
  1993. * Draws the graphical bullet item specified by the type argument.
  1994. *
  1995. * @param g the graphics context
  1996. * @param type type of bullet to draw (circle, square, disc)
  1997. * @param ax x coordinate to place the bullet
  1998. * @param ay y coordinate to place the bullet
  1999. * @param ah height of the container the bullet is placed in
  2000. * @param align preferred alignment factor for the child view
  2001. */
  2002. void drawShape(Graphics g, CSS.Value type, int ax, int ay, int ah,
  2003. float align) {
  2004. // Align to bottom of shape.
  2005. g.setColor(Color.black);
  2006. int x = ax - bulletgap - 8;
  2007. int y = Math.max(ay, ay + (int)(align * ah) - 8);
  2008. if (type == CSS.Value.SQUARE) {
  2009. g.drawRect(x, y, 8, 8);
  2010. } else if (type == CSS.Value.CIRCLE) {
  2011. g.drawOval(x, y, 8, 8);
  2012. } else {
  2013. g.fillOval(x, y, 8, 8);
  2014. }
  2015. }
  2016. /**
  2017. * Draws the letter or number for an ordered list.
  2018. *
  2019. * @param g the graphics context
  2020. * @param letter type of ordered list to draw
  2021. * @param ax x coordinate to place the bullet
  2022. * @param ay y coordinate to place the bullet
  2023. * @param ah height of the container the bullet is placed in
  2024. * @param index position of the list item in the list
  2025. */
  2026. void drawLetter(Graphics g, char letter, int ax, int ay, int ah,
  2027. float align, int index) {
  2028. g.setColor(Color.black);
  2029. String str = formatItemNum(index, letter) + ".";
  2030. FontMetrics fm = g.getFontMetrics();
  2031. int stringwidth = fm.stringWidth(str);
  2032. int x = ax - stringwidth - bulletgap;
  2033. int y = Math.max(ay + fm.getAscent(), ay + (int)(ah * align));
  2034. g.drawString(str, x, y);
  2035. }
  2036. /**
  2037. * Converts the item number into the ordered list number
  2038. * (i.e. 1 2 3, i ii iii, a b c, etc.
  2039. *
  2040. * @param itemNum number to format
  2041. * @param type type of ordered list
  2042. */
  2043. String formatItemNum(int itemNum, char type) {
  2044. String numStyle = "1";
  2045. boolean uppercase = false;
  2046. String formattedNum;
  2047. switch (type) {
  2048. case '1':
  2049. default:
  2050. formattedNum = String.valueOf(itemNum);
  2051. break;
  2052. case 'A':
  2053. uppercase = true;
  2054. // fall through
  2055. case 'a':
  2056. formattedNum = formatAlphaNumerals(itemNum);
  2057. break;
  2058. case 'I':
  2059. uppercase = true;
  2060. // fall through
  2061. case 'i':
  2062. formattedNum = formatRomanNumerals(itemNum);
  2063. }
  2064. if (uppercase) {
  2065. formattedNum = formattedNum.toUpperCase();
  2066. }
  2067. return formattedNum;
  2068. }
  2069. /**
  2070. * Converts the item number into an alphabetic character
  2071. *
  2072. * @param itemNum number to format
  2073. */
  2074. String formatAlphaNumerals(int itemNum) {
  2075. String result = "";
  2076. if (itemNum > 26) {
  2077. result = formatAlphaNumerals(itemNum / 26) +
  2078. formatAlphaNumerals(itemNum % 26);
  2079. } else {
  2080. // -1 because item is 1 based.
  2081. result = String.valueOf((char)('a' + itemNum - 1));
  2082. }
  2083. return result;
  2084. }
  2085. /* list of roman numerals */
  2086. static final char romanChars[][] = {
  2087. {'i', 'v'},
  2088. {'x', 'l' },
  2089. {'c', 'd' },
  2090. {'m', '?' },
  2091. };
  2092. /**
  2093. * Converts the item number into a roman numeral
  2094. *
  2095. * @param num number to format
  2096. */
  2097. String formatRomanNumerals(int num) {
  2098. return formatRomanNumerals(0, num);
  2099. }
  2100. /**
  2101. * Converts the item number into a roman numeral
  2102. *
  2103. * @param num number to format
  2104. */
  2105. String formatRomanNumerals(int level, int num) {
  2106. if (num < 10) {
  2107. return formatRomanDigit(level, num);
  2108. } else {
  2109. return formatRomanNumerals(level + 1, num / 10) +
  2110. formatRomanDigit(level, num % 10);
  2111. }
  2112. }
  2113. /**
  2114. * Converts the item number into a roman numeral
  2115. *
  2116. * @param level position
  2117. * @param num digit to format
  2118. */
  2119. String formatRomanDigit(int level, int digit) {
  2120. String result = "";
  2121. if (digit == 9) {
  2122. result = result + romanChars[level][0];
  2123. result = result + romanChars[level + 1][0];
  2124. return result;
  2125. } else if (digit == 4) {
  2126. result = result + romanChars[level][0];
  2127. result = result + romanChars[level][1];
  2128. return result;
  2129. } else if (digit >= 5) {
  2130. result = result + romanChars[level][1];
  2131. digit -= 5;
  2132. }
  2133. for (int i = 0; i < digit; i++) {
  2134. result = result + romanChars[level][0];
  2135. }
  2136. return result;
  2137. }
  2138. private Rectangle paintRect;
  2139. private boolean checkedForStart;
  2140. private int start;
  2141. private CSS.Value type;
  2142. URL imageurl;
  2143. Icon img = null;
  2144. private int bulletgap = 5;
  2145. }
  2146. /**
  2147. * Paints the background image.
  2148. */
  2149. static class BackgroundImagePainter implements Serializable {
  2150. ImageIcon backgroundImage;
  2151. float hPosition;
  2152. float vPosition;
  2153. // bit mask: 0 for repeat x, 1 for repeat y, 2 for horiz relative,
  2154. // 3 for vert relative
  2155. short flags;
  2156. // These are used when painting, updatePaintCoordinates updates them.
  2157. private int paintX;
  2158. private int paintY;
  2159. private int paintMaxX;
  2160. private int paintMaxY;
  2161. BackgroundImagePainter(AttributeSet a, CSS css, StyleSheet ss) {
  2162. backgroundImage = ss.getBackgroundImage(a);
  2163. // Determine the position.
  2164. CSS.BackgroundPosition pos = (CSS.BackgroundPosition)a.getAttribute
  2165. (CSS.Attribute.BACKGROUND_POSITION);
  2166. if (pos != null) {
  2167. hPosition = pos.getHorizontalPosition();
  2168. vPosition = pos.getVerticalPosition();
  2169. if (pos.isHorizontalPositionRelativeToSize()) {
  2170. flags |= 4;
  2171. }
  2172. else if (pos.isHorizontalPositionRelativeToSize()) {
  2173. hPosition *= css.getFontSize(a, 12);
  2174. }
  2175. if (pos.isVerticalPositionRelativeToSize()) {
  2176. flags |= 8;
  2177. }
  2178. else if (pos.isVerticalPositionRelativeToFontSize()) {
  2179. vPosition *= css.getFontSize(a, 12);
  2180. }
  2181. }
  2182. // Determine any repeating values.
  2183. CSS.Value repeats = (CSS.Value)a.getAttribute(CSS.Attribute.
  2184. BACKGROUND_REPEAT);
  2185. if (repeats == null || repeats == CSS.Value.BACKGROUND_REPEAT) {
  2186. flags |= 3;
  2187. }
  2188. else if (repeats == CSS.Value.BACKGROUND_REPEAT_X) {
  2189. flags |= 1;
  2190. }
  2191. else if (repeats == CSS.Value.BACKGROUND_REPEAT_Y) {
  2192. flags |= 2;
  2193. }
  2194. }
  2195. void paint(Graphics g, float x, float y, float w, float h, View v) {
  2196. Rectangle clip = g.getClipRect();
  2197. if (clip != null) {
  2198. // Constrain the clip so that images don't draw outside the
  2199. // legal bounds.
  2200. g.clipRect((int)x, (int)y, (int)w, (int)h);
  2201. }
  2202. if ((flags & 3) == 0) {
  2203. // no repeating
  2204. int width = backgroundImage.getIconWidth();
  2205. int height = backgroundImage.getIconWidth();
  2206. if ((flags & 4) == 4) {
  2207. paintX = (int)(x + w * hPosition -
  2208. (float)width * hPosition);
  2209. }
  2210. else {
  2211. paintX = (int)x + (int)hPosition;
  2212. }
  2213. if ((flags & 8) == 8) {
  2214. paintY = (int)(y + h * vPosition -
  2215. (float)height * vPosition);
  2216. }
  2217. else {
  2218. paintY = (int)y + (int)vPosition;
  2219. }
  2220. if (clip == null ||
  2221. !((paintX + width <= clip.x) ||
  2222. (paintY + height <= clip.y) ||
  2223. (paintX >= clip.x + clip.width) ||
  2224. (paintY >= clip.y + clip.height))) {
  2225. backgroundImage.paintIcon(null, g, paintX, paintY);
  2226. }
  2227. }
  2228. else {
  2229. int width = backgroundImage.getIconWidth();
  2230. int height = backgroundImage.getIconHeight();
  2231. if (width > 0 && height > 0) {
  2232. paintX = (int)x;
  2233. paintY = (int)y;
  2234. paintMaxX = (int)(x + w);
  2235. paintMaxY = (int)(y + h);
  2236. if (updatePaintCoordinates(clip, width, height)) {
  2237. while (paintX < paintMaxX) {
  2238. int ySpot = paintY;
  2239. while (ySpot < paintMaxY) {
  2240. backgroundImage.paintIcon(null, g, paintX,
  2241. ySpot);
  2242. ySpot += height;
  2243. }
  2244. paintX += width;
  2245. }
  2246. }
  2247. }
  2248. }
  2249. if (clip != null) {
  2250. // Reset clip.
  2251. g.setClip(clip.x, clip.y, clip.width, clip.height);
  2252. }
  2253. }
  2254. private boolean updatePaintCoordinates
  2255. (Rectangle clip, int width, int height){
  2256. if ((flags & 3) == 1) {
  2257. paintMaxY = paintY + 1;
  2258. }
  2259. else if ((flags & 3) == 2) {
  2260. paintMaxX = paintX + 1;
  2261. }
  2262. if (clip != null) {
  2263. if ((flags & 3) == 1 && ((paintY + height <= clip.y) ||
  2264. (paintY > clip.y + clip.height))) {
  2265. // not visible.
  2266. return false;
  2267. }
  2268. if ((flags & 3) == 2 && ((paintX + width <= clip.x) ||
  2269. (paintX > clip.x + clip.width))) {
  2270. // not visible.
  2271. return false;
  2272. }
  2273. if ((flags & 1) == 1) {
  2274. if ((clip.x + clip.width) < paintMaxX) {
  2275. if ((clip.x + clip.width - paintX) % width == 0) {
  2276. paintMaxX = clip.x + clip.width;
  2277. }
  2278. else {
  2279. paintMaxX = ((clip.x + clip.width - paintX) /
  2280. width + 1) * width + paintX;
  2281. }
  2282. }
  2283. if (clip.x > paintX) {
  2284. paintX = (clip.x - paintX) / width * width + paintX;
  2285. }
  2286. }
  2287. if ((flags & 2) == 2) {
  2288. if ((clip.y + clip.height) < paintMaxY) {
  2289. if ((clip.y + clip.height - paintY) % height == 0) {
  2290. paintMaxY = clip.y + clip.height;
  2291. }
  2292. else {
  2293. paintMaxY = ((clip.y + clip.height - paintY) /
  2294. height + 1) * height + paintY;
  2295. }
  2296. }
  2297. if (clip.y > paintY) {
  2298. paintY = (clip.y - paintY) / height * height + paintY;
  2299. }
  2300. }
  2301. }
  2302. // Valid
  2303. return true;
  2304. }
  2305. }
  2306. /**
  2307. * A subclass of MuxingAttributeSet that translates between
  2308. * CSS and HTML and StyleConstants. The AttributeSets used are
  2309. * the CSS rules that match the Views Elements.
  2310. */
  2311. class ViewAttributeSet extends MuxingAttributeSet {
  2312. ViewAttributeSet(View v) {
  2313. host = v;
  2314. // PENDING(prinz) fix this up to be a more realistic
  2315. // implementation.
  2316. Document doc = v.getDocument();
  2317. SearchBuffer sb = SearchBuffer.obtainSearchBuffer();
  2318. Vector muxList = sb.getVector();
  2319. try {
  2320. if (doc instanceof HTMLDocument) {
  2321. StyleSheet styles = StyleSheet.this;
  2322. Element elem = v.getElement();
  2323. AttributeSet a = elem.getAttributes();
  2324. AttributeSet htmlAttr = styles.translateHTMLToCSS(a);
  2325. if (htmlAttr.getAttributeCount() != 0) {
  2326. muxList.addElement(htmlAttr);
  2327. }
  2328. if (elem.isLeaf()) {
  2329. Enumeration keys = a.getAttributeNames();
  2330. while (keys.hasMoreElements()) {
  2331. Object key = keys.nextElement();
  2332. if (key instanceof HTML.Tag) {
  2333. if ((HTML.Tag)key == HTML.Tag.A) {
  2334. Object o = a.getAttribute((HTML.Tag)key);
  2335. /**
  2336. In the case of an A tag, the css rules
  2337. apply only for tags that have their
  2338. href attribute defined and not for
  2339. anchors that only have their name attributes
  2340. defined, i.e anchors that function as
  2341. destinations. Hence we do not add the
  2342. attributes for that latter kind of
  2343. anchors. When CSS2 support is added,
  2344. it will be possible to specificity this
  2345. kind of conditional behaviour in the
  2346. stylesheet.
  2347. **/
  2348. if (o != null && o instanceof AttributeSet) {
  2349. AttributeSet attr = (AttributeSet)o;
  2350. if (attr.getAttribute(HTML.Attribute.HREF) == null) {
  2351. continue;
  2352. }
  2353. }
  2354. }
  2355. AttributeSet cssRule = styles.getRule((HTML.Tag) key, elem);
  2356. if (cssRule != null) {
  2357. muxList.addElement(cssRule);
  2358. }
  2359. }
  2360. }
  2361. } else {
  2362. HTML.Tag t = (HTML.Tag) a.getAttribute
  2363. (StyleConstants.NameAttribute);
  2364. AttributeSet cssRule = styles.getRule(t, elem);
  2365. if (cssRule != null) {
  2366. muxList.addElement(cssRule);
  2367. }
  2368. }
  2369. }
  2370. AttributeSet[] attrs = new AttributeSet[muxList.size()];
  2371. muxList.copyInto(attrs);
  2372. setAttributes(attrs);
  2373. }
  2374. finally {
  2375. SearchBuffer.releaseSearchBuffer(sb);
  2376. }
  2377. }
  2378. // --- AttributeSet methods ----------------------------
  2379. /**
  2380. * Checks whether a given attribute is defined.
  2381. * This will convert the key over to CSS if the
  2382. * key is a StyleConstants key that has a CSS
  2383. * mapping.
  2384. *
  2385. * @param key the attribute key
  2386. * @return true if the attribute is defined
  2387. * @see AttributeSet#isDefined
  2388. */
  2389. public boolean isDefined(Object key) {
  2390. if (key instanceof StyleConstants) {
  2391. Object cssKey = css.styleConstantsKeyToCSSKey
  2392. ((StyleConstants)key);
  2393. if (cssKey != null) {
  2394. key = cssKey;
  2395. }
  2396. }
  2397. return super.isDefined(key);
  2398. }
  2399. /**
  2400. * Gets the value of an attribute. If the requested
  2401. * attribute is a StyleConstants attribute that has
  2402. * a CSS mapping, the request will be converted.
  2403. *
  2404. * @param key the attribute name
  2405. * @return the attribute value
  2406. * @see AttributeSet#getAttribute
  2407. */
  2408. public Object getAttribute(Object key) {
  2409. if (key instanceof StyleConstants) {
  2410. Object cssKey = css.styleConstantsKeyToCSSKey
  2411. ((StyleConstants)key);
  2412. if (cssKey != null) {
  2413. Object value = doGetAttribute(cssKey);
  2414. if (value instanceof CSS.CssValue) {
  2415. return ((CSS.CssValue)value).toStyleConstants
  2416. ((StyleConstants)key, host);
  2417. }
  2418. }
  2419. }
  2420. return doGetAttribute(key);
  2421. }
  2422. Object doGetAttribute(Object key) {
  2423. Object retValue = super.getAttribute(key);
  2424. if (retValue != null) {
  2425. return retValue;
  2426. }
  2427. // didn't find it... try parent if it's a css attribute
  2428. // that is inherited.
  2429. if (key instanceof CSS.Attribute) {
  2430. CSS.Attribute css = (CSS.Attribute) key;
  2431. if (css.isInherited()) {
  2432. AttributeSet parent = getResolveParent();
  2433. if (parent != null)
  2434. return parent.getAttribute(key);
  2435. }
  2436. }
  2437. return null;
  2438. }
  2439. /**
  2440. * If not overriden, the resolving parent defaults to
  2441. * the parent element.
  2442. *
  2443. * @return the attributes from the parent
  2444. * @see AttributeSet#getResolveParent
  2445. */
  2446. public AttributeSet getResolveParent() {
  2447. if (host == null) {
  2448. return null;
  2449. }
  2450. View parent = host.getParent();
  2451. return (parent != null) ? parent.getAttributes() : null;
  2452. }
  2453. /** View created for. */
  2454. View host;
  2455. }
  2456. /**
  2457. * A subclass of MuxingAttributeSet that implements Style. Currently
  2458. * the MutableAttributeSet methods are unimplemented, that is they
  2459. * do nothing.
  2460. */
  2461. // PENDING(sky): Decide what to do with this. Either make it
  2462. // contain a SimpleAttributeSet that modify methods are delegated to,
  2463. // or change getRule to return an AttributeSet and then don't make this
  2464. // implement Style.
  2465. static class ResolvedStyle extends MuxingAttributeSet implements
  2466. Serializable, Style {
  2467. ResolvedStyle(String name, AttributeSet[] attrs, int extendedIndex) {
  2468. super(attrs);
  2469. this.name = name;
  2470. this.extendedIndex = extendedIndex;
  2471. }
  2472. /**
  2473. * Inserts a Style into the receiver so that the styles the
  2474. * receiver represents are still ordered by specificity.
  2475. * <code>style</code> will be added before any extended styles, that
  2476. * is before extendedIndex.
  2477. */
  2478. synchronized void insertStyle(Style style, int specificity) {
  2479. AttributeSet[] attrs = getAttributes();
  2480. int maxCounter = attrs.length;
  2481. int counter = 0;
  2482. for (;counter < extendedIndex; counter++) {
  2483. if (specificity > getSpecificity(((Style)attrs[counter]).
  2484. getName())) {
  2485. break;
  2486. }
  2487. }
  2488. insertAttributeSetAt(style, counter);
  2489. extendedIndex++;
  2490. }
  2491. /**
  2492. * Removes a previously added style. This will do nothing if
  2493. * <code>style</code> is not referenced by the receiver.
  2494. */
  2495. synchronized void removeStyle(Style style) {
  2496. AttributeSet[] attrs = getAttributes();
  2497. for (int counter = attrs.length - 1; counter >= 0; counter--) {
  2498. if (attrs[counter] == style) {
  2499. removeAttributeSetAt(counter);
  2500. if (counter < extendedIndex) {
  2501. extendedIndex--;
  2502. }
  2503. break;
  2504. }
  2505. }
  2506. }
  2507. /**
  2508. * Adds <code>s</code> as one of the Attributesets to look up
  2509. * attributes in.
  2510. */
  2511. synchronized void insertExtendedStyleAt(Style attr, int index) {
  2512. insertAttributeSetAt(attr, extendedIndex + index);
  2513. }
  2514. /**
  2515. * Adds <code>s</code> as one of the AttributeSets to look up
  2516. * attributes in. It will be the AttributeSet last checked.
  2517. */
  2518. synchronized void addExtendedStyle(Style attr) {
  2519. insertAttributeSetAt(attr, getAttributes().length);
  2520. }
  2521. /**
  2522. * Removes the style at <code>index</code> +
  2523. * <code>extendedIndex</code>.
  2524. */
  2525. synchronized void removeExtendedStyleAt(int index) {
  2526. removeAttributeSetAt(extendedIndex + index);
  2527. }
  2528. /**
  2529. * Returns true if the receiver matches <code>selector</code>, where
  2530. * a match is defined by the CSS rule matching.
  2531. * Each simple selector must be separated by a single space.
  2532. */
  2533. protected boolean matches(String selector) {
  2534. int sLast = selector.length();
  2535. if (sLast == 0) {
  2536. return false;
  2537. }
  2538. int thisLast = name.length();
  2539. int sCurrent = selector.lastIndexOf(' ');
  2540. int thisCurrent = name.lastIndexOf(' ');
  2541. if (sCurrent >= 0) {
  2542. sCurrent++;
  2543. }
  2544. if (thisCurrent >= 0) {
  2545. thisCurrent++;
  2546. }
  2547. if (!matches(selector, sCurrent, sLast, thisCurrent, thisLast)) {
  2548. return false;
  2549. }
  2550. while (sCurrent != -1) {
  2551. sLast = sCurrent - 1;
  2552. sCurrent = selector.lastIndexOf(' ', sLast - 1);
  2553. if (sCurrent >= 0) {
  2554. sCurrent++;
  2555. }
  2556. boolean match = false;
  2557. while (!match && thisCurrent != -1) {
  2558. thisLast = thisCurrent - 1;
  2559. thisCurrent = name.lastIndexOf(' ', thisLast - 1);
  2560. if (thisCurrent >= 0) {
  2561. thisCurrent++;
  2562. }
  2563. match = matches(selector, sCurrent, sLast, thisCurrent,
  2564. thisLast);
  2565. }
  2566. if (!match) {
  2567. return false;
  2568. }
  2569. }
  2570. return true;
  2571. }
  2572. /**
  2573. * Returns true if the substring of the receiver, in the range
  2574. * thisCurrent, thisLast matches the substring of selector in
  2575. * the ranme sCurrent to sLast based on CSS selector matching.
  2576. */
  2577. boolean matches(String selector, int sCurrent, int sLast,
  2578. int thisCurrent, int thisLast) {
  2579. sCurrent = Math.max(sCurrent, 0);
  2580. thisCurrent = Math.max(thisCurrent, 0);
  2581. int thisDotIndex = boundedIndexOf(name, '.', thisCurrent,
  2582. thisLast);
  2583. int thisPoundIndex = boundedIndexOf(name, '#', thisCurrent,
  2584. thisLast);
  2585. int sDotIndex = boundedIndexOf(selector, '.', sCurrent, sLast);
  2586. int sPoundIndex = boundedIndexOf(selector, '#', sCurrent, sLast);
  2587. if (sDotIndex != -1) {
  2588. // Selector has a '.', which indicates name must match it,
  2589. // or if the '.' starts the selector than name must have
  2590. // the same class (doesn't matter what element name).
  2591. if (thisDotIndex == -1) {
  2592. return false;
  2593. }
  2594. if (sCurrent == sDotIndex) {
  2595. if ((thisLast - thisDotIndex) != (sLast - sDotIndex) ||
  2596. !selector.regionMatches(sCurrent, name, thisDotIndex,
  2597. (thisLast - thisDotIndex))) {
  2598. return false;
  2599. }
  2600. }
  2601. else {
  2602. // Has to fully match.
  2603. if ((sLast - sCurrent) != (thisLast - thisCurrent) ||
  2604. !selector.regionMatches(sCurrent, name, thisCurrent,
  2605. (thisLast - thisCurrent))) {
  2606. return false;
  2607. }
  2608. }
  2609. return true;
  2610. }
  2611. if (sPoundIndex != -1) {
  2612. // Selector has a '#', which indicates name must match it,
  2613. // or if the '#' starts the selector than name must have
  2614. // the same id (doesn't matter what element name).
  2615. if (thisPoundIndex == -1) {
  2616. return false;
  2617. }
  2618. if (sCurrent == sPoundIndex) {
  2619. if ((thisLast - thisPoundIndex) !=(sLast - sPoundIndex) ||
  2620. !selector.regionMatches(sCurrent, name, thisPoundIndex,
  2621. (thisLast - thisPoundIndex))) {
  2622. return false;
  2623. }
  2624. }
  2625. else {
  2626. // Has to fully match.
  2627. if ((sLast - sCurrent) != (thisLast - thisCurrent) ||
  2628. !selector.regionMatches(sCurrent, name, thisCurrent,
  2629. (thisLast - thisCurrent))) {
  2630. return false;
  2631. }
  2632. }
  2633. return true;
  2634. }
  2635. if (thisDotIndex != -1) {
  2636. // Reciever references a class, just check element name.
  2637. return (((thisDotIndex - thisCurrent) == (sLast - sCurrent)) &&
  2638. selector.regionMatches(sCurrent, name, thisCurrent,
  2639. thisDotIndex - thisCurrent));
  2640. }
  2641. if (thisPoundIndex != -1) {
  2642. // Reciever references an id, just check element name.
  2643. return (((thisPoundIndex - thisCurrent) ==(sLast - sCurrent))&&
  2644. selector.regionMatches(sCurrent, name, thisCurrent,
  2645. thisPoundIndex - thisCurrent));
  2646. }
  2647. // Fail through, no classes or ides, just check string.
  2648. return (((thisLast - thisCurrent) == (sLast - sCurrent)) &&
  2649. selector.regionMatches(sCurrent, name, thisCurrent,
  2650. thisLast - thisCurrent));
  2651. }
  2652. /**
  2653. * Similiar to String.indexOf, but allows an upper bound
  2654. * (this is slower in that it will still check string starting at
  2655. * start.
  2656. */
  2657. int boundedIndexOf(String string, char search, int start,
  2658. int end) {
  2659. int retValue = string.indexOf(search, start);
  2660. if (retValue >= end) {
  2661. return -1;
  2662. }
  2663. return retValue;
  2664. }
  2665. public void addAttribute(Object name, Object value) {}
  2666. public void addAttributes(AttributeSet attributes) {}
  2667. public void removeAttribute(Object name) {}
  2668. public void removeAttributes(Enumeration names) {}
  2669. public void removeAttributes(AttributeSet attributes) {}
  2670. public void setResolveParent(AttributeSet parent) {}
  2671. public String getName() {return name;}
  2672. public void addChangeListener(ChangeListener l) {}
  2673. public void removeChangeListener(ChangeListener l) {}
  2674. public ChangeListener[] getChangeListeners() {
  2675. return new ChangeListener[0];
  2676. }
  2677. /** The name of the Style, which is the selector.
  2678. * This will NEVER change!
  2679. */
  2680. String name;
  2681. /** Start index of styles coming from other StyleSheets. */
  2682. private int extendedIndex;
  2683. }
  2684. /**
  2685. * SelectorMapping contains a specifitiy, as an integer, and an associated
  2686. * Style. It can also reference children <code>SelectorMapping</code>s,
  2687. * so that it behaves like a tree.
  2688. * <p>
  2689. * This is not thread safe, it is assumed the caller will take the
  2690. * necessary precations if this is to be used in a threaded environment.
  2691. */
  2692. static class SelectorMapping implements Serializable {
  2693. public SelectorMapping(int specificity) {
  2694. this.specificity = specificity;
  2695. }
  2696. /**
  2697. * Returns the specificity this mapping represents.
  2698. */
  2699. public int getSpecificity() {
  2700. return specificity;
  2701. }
  2702. /**
  2703. * Sets the Style associated with this mapping.
  2704. */
  2705. public void setStyle(Style style) {
  2706. this.style = style;
  2707. }
  2708. /**
  2709. * Returns the Style associated with this mapping.
  2710. */
  2711. public Style getStyle() {
  2712. return style;
  2713. }
  2714. /**
  2715. * Returns the child mapping identified by the simple selector
  2716. * <code>selector</code>. If a child mapping does not exist for
  2717. *<code>selector</code>, and <code>create</code> is true, a new
  2718. * one will be created.
  2719. */
  2720. public SelectorMapping getChildSelectorMapping(String selector,
  2721. boolean create) {
  2722. SelectorMapping retValue = null;
  2723. if (children != null) {
  2724. retValue = (SelectorMapping)children.get(selector);
  2725. }
  2726. else if (create) {
  2727. children = new HashMap(7);
  2728. }
  2729. if (retValue == null && create) {
  2730. int specificity = getChildSpecificity(selector);
  2731. retValue = createChildSelectorMapping(specificity);
  2732. children.put(selector, retValue);
  2733. }
  2734. return retValue;
  2735. }
  2736. /**
  2737. * Creates a child <code>SelectorMapping</code> with the specified
  2738. * <code>specificity</code>.
  2739. */
  2740. protected SelectorMapping createChildSelectorMapping(int specificity) {
  2741. return new SelectorMapping(specificity);
  2742. }
  2743. /**
  2744. * Returns the specificity for the child selector
  2745. * <code>selector</code>.
  2746. */
  2747. protected int getChildSpecificity(String selector) {
  2748. // class (.) 100
  2749. // id (#) 10000
  2750. char firstChar = selector.charAt(0);
  2751. int specificity = getSpecificity();
  2752. if (firstChar == '.') {
  2753. specificity += 100;
  2754. }
  2755. else if (firstChar == '#') {
  2756. specificity += 10000;
  2757. }
  2758. else {
  2759. specificity += 1;
  2760. if (selector.indexOf('.') != -1) {
  2761. specificity += 100;
  2762. }
  2763. if (selector.indexOf('#') != -1) {
  2764. specificity += 10000;
  2765. }
  2766. }
  2767. return specificity;
  2768. }
  2769. /**
  2770. * The specificity for this selector.
  2771. */
  2772. private int specificity;
  2773. /**
  2774. * Style for this selector.
  2775. */
  2776. private Style style;
  2777. /**
  2778. * Any sub selectors. Key will be String, and value will be
  2779. * another SelectorMapping.
  2780. */
  2781. private HashMap children;
  2782. }
  2783. // ---- Variables ---------------------------------------------
  2784. final static int DEFAULT_FONT_SIZE = 3;
  2785. private CSS css;
  2786. /**
  2787. * An inverted graph of the selectors.
  2788. */
  2789. private SelectorMapping selectorMapping;
  2790. /** Maps from selector (as a string) to Style that includes all
  2791. * relevant styles. */
  2792. private Hashtable resolvedStyles;
  2793. /** Vector of StyleSheets that the rules are to reference.
  2794. */
  2795. private Vector linkedStyleSheets;
  2796. /** Where the style sheet was found. Used for relative imports. */
  2797. private URL base;
  2798. /**
  2799. * Default parser for CSS specifications that get loaded into
  2800. * the StyleSheet.<p>
  2801. * This class is NOT thread safe, do not ask it to parse while it is
  2802. * in the middle of parsing.
  2803. */
  2804. class CssParser implements CSSParser.CSSParserCallback {
  2805. /**
  2806. * Parses the passed in CSS declaration into an AttributeSet.
  2807. */
  2808. public AttributeSet parseDeclaration(String string) {
  2809. try {
  2810. return parseDeclaration(new StringReader(string));
  2811. } catch (IOException ioe) {}
  2812. return null;
  2813. }
  2814. /**
  2815. * Parses the passed in CSS declaration into an AttributeSet.
  2816. */
  2817. public AttributeSet parseDeclaration(Reader r) throws IOException {
  2818. parse(base, r, true, false);
  2819. return declaration.copyAttributes();
  2820. }
  2821. /**
  2822. * Parse the given CSS stream
  2823. */
  2824. public void parse(URL base, Reader r, boolean parseDeclaration,
  2825. boolean isLink) throws IOException {
  2826. this.base = base;
  2827. this.isLink = isLink;
  2828. this.parsingDeclaration = parseDeclaration;
  2829. declaration.removeAttributes(declaration);
  2830. selectorTokens.removeAllElements();
  2831. selectors.removeAllElements();
  2832. propertyName = null;
  2833. parser.parse(r, this, parseDeclaration);
  2834. }
  2835. //
  2836. // CSSParserCallback methods, public to implement the interface.
  2837. //
  2838. /**
  2839. * Invoked when a valid @import is encountered, will call
  2840. * <code>importStyleSheet</code> if a
  2841. * <code>MalformedURLException</code> is not thrown in creating
  2842. * the URL.
  2843. */
  2844. public void handleImport(String importString) {
  2845. URL url = CSS.getURL(base, importString);
  2846. if (url != null) {
  2847. importStyleSheet(url);
  2848. }
  2849. }
  2850. /**
  2851. * A selector has been encountered.
  2852. */
  2853. public void handleSelector(String selector) {
  2854. selector = selector.toLowerCase();
  2855. int length = selector.length();
  2856. if (selector.endsWith(",")) {
  2857. if (length > 1) {
  2858. selector = selector.substring(0, length - 1);
  2859. selectorTokens.addElement(selector);
  2860. }
  2861. addSelector();
  2862. }
  2863. else if (length > 0) {
  2864. selectorTokens.addElement(selector);
  2865. }
  2866. }
  2867. /**
  2868. * Invoked when the start of a rule is encountered.
  2869. */
  2870. public void startRule() {
  2871. if (selectorTokens.size() > 0) {
  2872. addSelector();
  2873. }
  2874. propertyName = null;
  2875. }
  2876. /**
  2877. * Invoked when a property name is encountered.
  2878. */
  2879. public void handleProperty(String property) {
  2880. propertyName = property;
  2881. }
  2882. /**
  2883. * Invoked when a property value is encountered.
  2884. */
  2885. public void handleValue(String value) {
  2886. if (propertyName != null) {
  2887. CSS.Attribute cssKey = CSS.getAttribute(propertyName);
  2888. if (cssKey != null) {
  2889. // There is currently no mechanism to determine real
  2890. // base that style sheet was loaded from. For the time
  2891. // being, this maps for LIST_STYLE_IMAGE, which appear
  2892. // to be the only one that currently matters. A more
  2893. // general mechanism is definately needed.
  2894. if (cssKey == CSS.Attribute.LIST_STYLE_IMAGE) {
  2895. if (value != null && !value.equals("none")) {
  2896. URL url = CSS.getURL(base, value);
  2897. if (url != null) {
  2898. value = url.toString();
  2899. }
  2900. }
  2901. }
  2902. addCSSAttribute(declaration, cssKey, value);
  2903. }
  2904. propertyName = null;
  2905. }
  2906. }
  2907. /**
  2908. * Invoked when the end of a rule is encountered.
  2909. */
  2910. public void endRule() {
  2911. int n = selectors.size();
  2912. for (int i = 0; i < n; i++) {
  2913. String[] selector = (String[]) selectors.elementAt(i);
  2914. if (selector.length > 0) {
  2915. StyleSheet.this.addRule(selector, declaration, isLink);
  2916. }
  2917. }
  2918. declaration.removeAttributes(declaration);
  2919. selectors.removeAllElements();
  2920. }
  2921. private void addSelector() {
  2922. String[] selector = new String[selectorTokens.size()];
  2923. selectorTokens.copyInto(selector);
  2924. selectors.addElement(selector);
  2925. selectorTokens.removeAllElements();
  2926. }
  2927. Vector selectors = new Vector();
  2928. Vector selectorTokens = new Vector();
  2929. /** Name of the current property. */
  2930. String propertyName;
  2931. MutableAttributeSet declaration = new SimpleAttributeSet();
  2932. /** True if parsing a declaration, that is the Reader will not
  2933. * contain a selector. */
  2934. boolean parsingDeclaration;
  2935. /** True if the attributes are coming from a linked/imported style. */
  2936. boolean isLink;
  2937. /** Where the CSS stylesheet lives. */
  2938. URL base;
  2939. CSSParser parser = new CSSParser();
  2940. }
  2941. }