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