1. /*
  2. * @(#)JEditorPane.java 1.125 04/07/23
  3. *
  4. * Copyright 2004 Sun Microsystems, Inc. All rights reserved.
  5. * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
  6. */
  7. package javax.swing;
  8. import java.awt.*;
  9. import java.awt.event.*;
  10. import java.net.*;
  11. import java.util.*;
  12. import java.io.*;
  13. import java.util.*;
  14. import javax.swing.plaf.*;
  15. import javax.swing.text.*;
  16. import javax.swing.event.*;
  17. import javax.swing.text.html.*;
  18. import javax.accessibility.*;
  19. /**
  20. * A text component to edit various kinds of content.
  21. * You can find how-to information and examples of using editor panes in
  22. * <a href="http://java.sun.com/docs/books/tutorial/uiswing/components/text.html">Using Text Components</a>,
  23. * a section in <em>The Java Tutorial.</em>
  24. *
  25. * <p>
  26. * This component uses implementations of the
  27. * <code>EditorKit</code> to accomplish its behavior. It effectively
  28. * morphs into the proper kind of text editor for the kind
  29. * of content it is given. The content type that editor is bound
  30. * to at any given time is determined by the <code>EditorKit</code> currently
  31. * installed. If the content is set to a new URL, its type is used
  32. * to determine the <code>EditorKit</code> that should be used to
  33. * load the content.
  34. * <p>
  35. * By default, the following types of content are known:
  36. * <dl>
  37. * <dt><b>text/plain</b>
  38. * <dd>Plain text, which is the default the type given isn't
  39. * recognized. The kit used in this case is an extension of
  40. * <code>DefaultEditorKit</code> that produces a wrapped plain text view.
  41. * <dt><b>text/html</b>
  42. * <dd>HTML text. The kit used in this case is the class
  43. * <code>javax.swing.text.html.HTMLEditorKit</code>
  44. * which provides HTML 3.2 support.
  45. * <dt><b>text/rtf</b>
  46. * <dd>RTF text. The kit used in this case is the class
  47. * <code>javax.swing.text.rtf.RTFEditorKit</code>
  48. * which provides a limited support of the Rich Text Format.
  49. * </dl>
  50. * <p>
  51. * There are several ways to load content into this component.
  52. * <ol>
  53. * <li>
  54. * The <a href="#setText">setText</a> method can be used to initialize
  55. * the component from a string. In this case the current
  56. * <code>EditorKit</code> will be used, and the content type will be
  57. * expected to be of this type.
  58. * <li>
  59. * The <a href="#read">read</a> method can be used to initialize the
  60. * component from a <code>Reader</code>. Note that if the content type is HTML,
  61. * relative references (e.g. for things like images) can't be resolved
  62. * unless the <base> tag is used or the <em>Base</em> property
  63. * on <code>HTMLDocument</code> is set.
  64. * In this case the current <code>EditorKit</code> will be used,
  65. * and the content type will be expected to be of this type.
  66. * <li>
  67. * The <a href="#setPage">setPage</a> method can be used to initialize
  68. * the component from a URL. In this case, the content type will be
  69. * determined from the URL, and the registered <code>EditorKit</code>
  70. * for that content type will be set.
  71. * </ol>
  72. * <p>
  73. * Some kinds of content may provide hyperlink support by generating
  74. * hyperlink events. The HTML <code>EditorKit</code> will generate
  75. * hyperlink events if the <code>JEditorPane</code> is <em>not editable</em>
  76. * (<code>JEditorPane.setEditable(false);</code> has been called).
  77. * If HTML frames are embedded in the document, the typical response would be
  78. * to change a portion of the current document. The following code
  79. * fragment is a possible hyperlink listener implementation, that treats
  80. * HTML frame events specially, and simply displays any other activated
  81. * hyperlinks.
  82. * <code><pre>
  83.   class Hyperactive implements HyperlinkListener {
  84.  
  85.   public void hyperlinkUpdate(HyperlinkEvent e) {
  86.   if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
  87.   JEditorPane pane = (JEditorPane) e.getSource();
  88.   if (e instanceof HTMLFrameHyperlinkEvent) {
  89.   HTMLFrameHyperlinkEvent evt = (HTMLFrameHyperlinkEvent)e;
  90.   HTMLDocument doc = (HTMLDocument)pane.getDocument();
  91.   doc.processHTMLFrameHyperlinkEvent(evt);
  92.   } else {
  93.   try {
  94.   pane.setPage(e.getURL());
  95.   } catch (Throwable t) {
  96.   t.printStackTrace();
  97.   }
  98.   }
  99.   }
  100.   }
  101.   }
  102. * </pre></code>
  103. * <p>
  104. * For information on customizing how <b>text/html</b> is rendered please see
  105. * {@link #W3C_LENGTH_UNITS} and {@link #HONOR_DISPLAY_PROPERTIES}
  106. * <p>
  107. * Culturally dependent information in some documents is handled through
  108. * a mechanism called character encoding. Character encoding is an
  109. * unambiguous mapping of the members of a character set (letters, ideographs,
  110. * digits, symbols, or control functions) to specific numeric code values. It
  111. * represents the way the file is stored. Example character encodings are
  112. * ISO-8859-1, ISO-8859-5, Shift-jis, Euc-jp, and UTF-8. When the file is
  113. * passed to an user agent (<code>JEditorPane</code>) it is converted to
  114. * the document character set (ISO-10646 aka Unicode).
  115. * <p>
  116. * There are multiple ways to get a character set mapping to happen
  117. * with <code>JEditorPane</code>.
  118. * <ol>
  119. * <li>
  120. * One way is to specify the character set as a parameter of the MIME
  121. * type. This will be established by a call to the
  122. * <a href="#setContentType">setContentType</a> method. If the content
  123. * is loaded by the <a href="#setPage">setPage</a> method the content
  124. * type will have been set according to the specification of the URL.
  125. * It the file is loaded directly, the content type would be expected to
  126. * have been set prior to loading.
  127. * <li>
  128. * Another way the character set can be specified is in the document itself.
  129. * This requires reading the document prior to determining the character set
  130. * that is desired. To handle this, it is expected that the
  131. * <code>EditorKit</code>.read operation throw a
  132. * <code>ChangedCharSetException</code> which will
  133. * be caught. The read is then restarted with a new Reader that uses
  134. * the character set specified in the <code>ChangedCharSetException</code>
  135. * (which is an <code>IOException</code>).
  136. * </ol>
  137. * <p>
  138. * <dt><b><font size=+1>Newlines</font></b>
  139. * <dd>
  140. * For a discussion on how newlines are handled, see
  141. * <a href="text/DefaultEditorKit.html">DefaultEditorKit</a>.
  142. * </dl>
  143. *
  144. * <p>
  145. * <strong>Warning:</strong>
  146. * Serialized objects of this class will not be compatible with
  147. * future Swing releases. The current serialization support is
  148. * appropriate for short term storage or RMI between applications running
  149. * the same version of Swing. As of 1.4, support for long term storage
  150. * of all JavaBeans<sup><font size="-2">TM</font></sup>
  151. * has been added to the <code>java.beans</code> package.
  152. * Please see {@link java.beans.XMLEncoder}.
  153. *
  154. * @beaninfo
  155. * attribute: isContainer false
  156. * description: A text component to edit various types of content.
  157. *
  158. * @author Timothy Prinzing
  159. * @version 1.125 07/23/04
  160. */
  161. public class JEditorPane extends JTextComponent {
  162. /**
  163. * Creates a new <code>JEditorPane</code>.
  164. * The document model is set to <code>null</code>.
  165. */
  166. public JEditorPane() {
  167. super();
  168. setFocusCycleRoot(true);
  169. setFocusTraversalPolicy(new LayoutFocusTraversalPolicy() {
  170. public Component getComponentAfter(Container focusCycleRoot,
  171. Component aComponent) {
  172. if (focusCycleRoot != JEditorPane.this ||
  173. (!isEditable() && getComponentCount() > 0)) {
  174. return super.getComponentAfter(focusCycleRoot,
  175. aComponent);
  176. } else {
  177. Container rootAncestor = getFocusCycleRootAncestor();
  178. return (rootAncestor != null)
  179. ? rootAncestor.getFocusTraversalPolicy().
  180. getComponentAfter(rootAncestor,
  181. JEditorPane.this)
  182. : null;
  183. }
  184. }
  185. public Component getComponentBefore(Container focusCycleRoot,
  186. Component aComponent) {
  187. if (focusCycleRoot != JEditorPane.this ||
  188. (!isEditable() && getComponentCount() > 0)) {
  189. return super.getComponentBefore(focusCycleRoot,
  190. aComponent);
  191. } else {
  192. Container rootAncestor = getFocusCycleRootAncestor();
  193. return (rootAncestor != null)
  194. ? rootAncestor.getFocusTraversalPolicy().
  195. getComponentBefore(rootAncestor,
  196. JEditorPane.this)
  197. : null;
  198. }
  199. }
  200. public Component getDefaultComponent(Container focusCycleRoot)
  201. {
  202. return (focusCycleRoot != JEditorPane.this ||
  203. (!isEditable() && getComponentCount() > 0))
  204. ? super.getDefaultComponent(focusCycleRoot)
  205. : null;
  206. }
  207. protected boolean accept(Component aComponent) {
  208. return (aComponent != JEditorPane.this)
  209. ? super.accept(aComponent)
  210. : false;
  211. }
  212. });
  213. LookAndFeel.installProperty(this,
  214. "focusTraversalKeysForward",
  215. JComponent.
  216. getManagingFocusForwardTraversalKeys());
  217. LookAndFeel.installProperty(this,
  218. "focusTraversalKeysBackward",
  219. JComponent.
  220. getManagingFocusBackwardTraversalKeys());
  221. }
  222. /**
  223. * Creates a <code>JEditorPane</code> based on a specified URL for input.
  224. *
  225. * @param initialPage the URL
  226. * @exception IOException if the URL is <code>null</code>
  227. * or cannot be accessed
  228. */
  229. public JEditorPane(URL initialPage) throws IOException {
  230. this();
  231. setPage(initialPage);
  232. }
  233. /**
  234. * Creates a <code>JEditorPane</code> based on a string containing
  235. * a URL specification.
  236. *
  237. * @param url the URL
  238. * @exception IOException if the URL is <code>null</code> or
  239. * cannot be accessed
  240. */
  241. public JEditorPane(String url) throws IOException {
  242. this();
  243. setPage(url);
  244. }
  245. /**
  246. * Creates a <code>JEditorPane</code> that has been initialized
  247. * to the given text. This is a convenience constructor that calls the
  248. * <code>setContentType</code> and <code>setText</code> methods.
  249. *
  250. * @param type mime type of the given text
  251. * @param text the text to initialize with; may be <code>null</code>
  252. * @exception NullPointerException if the <code>type</code> parameter
  253. * is <code>null</code>
  254. */
  255. public JEditorPane(String type, String text) {
  256. this();
  257. setContentType(type);
  258. setText(text);
  259. }
  260. /**
  261. * Adds a hyperlink listener for notification of any changes, for example
  262. * when a link is selected and entered.
  263. *
  264. * @param listener the listener
  265. */
  266. public synchronized void addHyperlinkListener(HyperlinkListener listener) {
  267. listenerList.add(HyperlinkListener.class, listener);
  268. }
  269. /**
  270. * Removes a hyperlink listener.
  271. *
  272. * @param listener the listener
  273. */
  274. public synchronized void removeHyperlinkListener(HyperlinkListener listener) {
  275. listenerList.remove(HyperlinkListener.class, listener);
  276. }
  277. /**
  278. * Returns an array of all the <code>HyperLinkListener</code>s added
  279. * to this JEditorPane with addHyperlinkListener().
  280. *
  281. * @return all of the <code>HyperLinkListener</code>s added or an empty
  282. * array if no listeners have been added
  283. * @since 1.4
  284. */
  285. public synchronized HyperlinkListener[] getHyperlinkListeners() {
  286. return (HyperlinkListener[])listenerList.getListeners(
  287. HyperlinkListener.class);
  288. }
  289. /**
  290. * Notifies all listeners that have registered interest for
  291. * notification on this event type. This is normally called
  292. * by the currently installed <code>EditorKit</code> if a content type
  293. * that supports hyperlinks is currently active and there
  294. * was activity with a link. The listener list is processed
  295. * last to first.
  296. *
  297. * @param e the event
  298. * @see EventListenerList
  299. */
  300. public void fireHyperlinkUpdate(HyperlinkEvent e) {
  301. // Guaranteed to return a non-null array
  302. Object[] listeners = listenerList.getListenerList();
  303. // Process the listeners last to first, notifying
  304. // those that are interested in this event
  305. for (int i = listeners.length-2; i>=0; i-=2) {
  306. if (listeners[i]==HyperlinkListener.class) {
  307. ((HyperlinkListener)listeners[i+1]).hyperlinkUpdate(e);
  308. }
  309. }
  310. }
  311. /**
  312. * Sets the current URL being displayed. The content type of the
  313. * pane is set, and if the editor kit for the pane is
  314. * non-<code>null</code>, then
  315. * a new default document is created and the URL is read into it.
  316. * If the URL contains and reference location, the location will
  317. * be scrolled to by calling the <code>scrollToReference</code>
  318. * method. If the desired URL is the one currently being displayed,
  319. * the document will not be reloaded. To force a document
  320. * reload it is necessary to clear the stream description property
  321. * of the document. The following code shows how this can be done:
  322. *
  323. * <pre>
  324. * Document doc = jEditorPane.getDocument();
  325. * doc.putProperty(Document.StreamDescriptionProperty, null);
  326. * </pre>
  327. *
  328. * If the desired URL is not the one currently being
  329. * displayed, the <code>getStream</code> method is called to
  330. * give subclasses control over the stream provided.
  331. * <p>
  332. * This may load either synchronously or asynchronously
  333. * depending upon the document returned by the <code>EditorKit</code>.
  334. * If the <code>Document</code> is of type
  335. * <code>AbstractDocument</code> and has a value returned by
  336. * <code>AbstractDocument.getAsynchronousLoadPriority</code>
  337. * that is greater than or equal to zero, the page will be
  338. * loaded on a separate thread using that priority.
  339. * <p>
  340. * If the document is loaded synchronously, it will be
  341. * filled in with the stream prior to being installed into
  342. * the editor with a call to <code>setDocument</code>, which
  343. * is bound and will fire a property change event. If an
  344. * <code>IOException</code> is thrown the partially loaded
  345. * document will
  346. * be discarded and neither the document or page property
  347. * change events will be fired. If the document is
  348. * successfully loaded and installed, a view will be
  349. * built for it by the UI which will then be scrolled if
  350. * necessary, and then the page property change event
  351. * will be fired.
  352. * <p>
  353. * If the document is loaded asynchronously, the document
  354. * will be installed into the editor immediately using a
  355. * call to <code>setDocument</code> which will fire a
  356. * document property change event, then a thread will be
  357. * created which will begin doing the actual loading.
  358. * In this case, the page property change event will not be
  359. * fired by the call to this method directly, but rather will be
  360. * fired when the thread doing the loading has finished.
  361. * It will also be fired on the event-dispatch thread.
  362. * Since the calling thread can not throw an <code>IOException</code>
  363. * in the event of failure on the other thread, the page
  364. * property change event will be fired when the other
  365. * thread is done whether the load was successful or not.
  366. *
  367. * @param page the URL of the page
  368. * @exception IOException for a <code>null</code> or invalid
  369. * page specification, or exception from the stream being read
  370. * @see #getPage
  371. * @beaninfo
  372. * description: the URL used to set content
  373. * bound: true
  374. * expert: true
  375. */
  376. public void setPage(URL page) throws IOException {
  377. if (page == null) {
  378. throw new IOException("invalid url");
  379. }
  380. URL loaded = getPage();
  381. // reset scrollbar
  382. if (!page.equals(loaded) && page.getRef() == null) {
  383. scrollRectToVisible(new Rectangle(0,0,1,1));
  384. }
  385. boolean reloaded = false;
  386. if ((loaded == null) || (! loaded.sameFile(page))) {
  387. // different url, load the new content
  388. InputStream in = getStream(page);
  389. if (kit != null) {
  390. Document doc = kit.createDefaultDocument();
  391. if (pageProperties != null) {
  392. // transfer properties discovered in stream to the
  393. // document property collection.
  394. for (Enumeration e = pageProperties.keys(); e.hasMoreElements() ;) {
  395. Object key = e.nextElement();
  396. doc.putProperty(key, pageProperties.get(key));
  397. }
  398. pageProperties.clear();
  399. }
  400. if (doc.getProperty(Document.StreamDescriptionProperty) == null) {
  401. doc.putProperty(Document.StreamDescriptionProperty, page);
  402. }
  403. // At this point, one could either load up the model with no
  404. // view notifications slowing it down (i.e. best synchronous
  405. // behavior) or set the model and start to feed it on a separate
  406. // thread (best asynchronous behavior).
  407. synchronized(this) {
  408. if (loading != null) {
  409. // we are loading asynchronously, so we need to cancel
  410. // the old stream.
  411. loading.cancel();
  412. loading = null;
  413. }
  414. }
  415. if (doc instanceof AbstractDocument) {
  416. AbstractDocument adoc = (AbstractDocument) doc;
  417. int p = adoc.getAsynchronousLoadPriority();
  418. if (p >= 0) {
  419. // load asynchronously
  420. setDocument(doc);
  421. synchronized(this) {
  422. loading = new PageStream(in);
  423. Thread pl = new PageLoader(doc, loading, p, loaded, page);
  424. pl.start();
  425. }
  426. return;
  427. }
  428. }
  429. read(in, doc);
  430. setDocument(doc);
  431. reloaded = true;
  432. }
  433. }
  434. final String reference = page.getRef();
  435. if (reference != null) {
  436. if (!reloaded) {
  437. scrollToReference(reference);
  438. }
  439. else {
  440. // Have to scroll after painted.
  441. SwingUtilities.invokeLater(new Runnable() {
  442. public void run() {
  443. scrollToReference(reference);
  444. }
  445. });
  446. }
  447. getDocument().putProperty(Document.StreamDescriptionProperty, page);
  448. }
  449. firePropertyChange("page", loaded, page);
  450. }
  451. /**
  452. * This method initializes from a stream. If the kit is
  453. * set to be of type <code>HTMLEditorKit</code>, and the
  454. * <code>desc</code> parameter is an <code>HTMLDocument</code>,
  455. * then it invokes the <code>HTMLEditorKit</code> to initiate
  456. * the read. Otherwise it calls the superclass
  457. * method which loads the model as plain text.
  458. *
  459. * @param in the stream from which to read
  460. * @param desc an object describing the stream
  461. * @exception IOException as thrown by the stream being
  462. * used to initialize
  463. * @see JTextComponent#read
  464. * @see #setDocument
  465. */
  466. public void read(InputStream in, Object desc) throws IOException {
  467. if (desc instanceof HTMLDocument &&
  468. kit instanceof HTMLEditorKit) {
  469. HTMLDocument hdoc = (HTMLDocument) desc;
  470. setDocument(hdoc);
  471. read(in, hdoc);
  472. } else {
  473. String charset = (String) getClientProperty("charset");
  474. Reader r = (charset != null) ? new InputStreamReader(in, charset) :
  475. new InputStreamReader(in);
  476. super.read(r, desc);
  477. }
  478. }
  479. /**
  480. * This method invokes the <code>EditorKit</code> to initiate a
  481. * read. In the case where a <code>ChangedCharSetException</code>
  482. * is thrown this exception will contain the new CharSet.
  483. * Therefore the <code>read</code> operation
  484. * is then restarted after building a new Reader with the new charset.
  485. *
  486. * @param in the inputstream to use
  487. * @param doc the document to load
  488. *
  489. */
  490. void read(InputStream in, Document doc) throws IOException {
  491. try {
  492. String charset = (String) getClientProperty("charset");
  493. Reader r = (charset != null) ? new InputStreamReader(in, charset) :
  494. new InputStreamReader(in);
  495. kit.read(r, doc, 0);
  496. } catch (BadLocationException e) {
  497. throw new IOException(e.getMessage());
  498. } catch (ChangedCharSetException e1) {
  499. String charSetSpec = e1.getCharSetSpec();
  500. if (e1.keyEqualsCharSet()) {
  501. putClientProperty("charset", charSetSpec);
  502. } else {
  503. setCharsetFromContentTypeParameters(charSetSpec);
  504. }
  505. in.close();
  506. URL url = (URL)doc.getProperty(Document.StreamDescriptionProperty);
  507. URLConnection conn = url.openConnection();
  508. in = conn.getInputStream();
  509. try {
  510. doc.remove(0, doc.getLength());
  511. } catch (BadLocationException e) {}
  512. doc.putProperty("IgnoreCharsetDirective", Boolean.valueOf(true));
  513. read(in, doc);
  514. }
  515. }
  516. /**
  517. * Thread to load a stream into the text document model.
  518. */
  519. class PageLoader extends Thread {
  520. /**
  521. * Construct an asynchronous page loader.
  522. */
  523. PageLoader(Document doc, InputStream in, int priority, URL old,
  524. URL page) {
  525. setPriority(priority);
  526. this.in = in;
  527. this.old = old;
  528. this.page = page;
  529. this.doc = doc;
  530. }
  531. /**
  532. * Try to load the document, then scroll the view
  533. * to the reference (if specified). When done, fire
  534. * a page property change event.
  535. */
  536. public void run() {
  537. try {
  538. read(in, doc);
  539. synchronized(JEditorPane.this) {
  540. loading = null;
  541. }
  542. URL page = (URL) doc.getProperty(Document.StreamDescriptionProperty);
  543. String reference = page.getRef();
  544. if (reference != null) {
  545. // scroll the page if necessary, but do it on the
  546. // event thread... that is the only guarantee that
  547. // modelToView can be safely called.
  548. Runnable callScrollToReference = new Runnable() {
  549. public void run() {
  550. URL u = (URL) getDocument().getProperty
  551. (Document.StreamDescriptionProperty);
  552. String ref = u.getRef();
  553. scrollToReference(ref);
  554. }
  555. };
  556. SwingUtilities.invokeLater(callScrollToReference);
  557. }
  558. } catch (IOException ioe) {
  559. UIManager.getLookAndFeel().provideErrorFeedback(JEditorPane.this);
  560. } finally {
  561. SwingUtilities.invokeLater(new Runnable() {
  562. public void run() {
  563. firePropertyChange("page", old, page);
  564. }
  565. });
  566. }
  567. }
  568. /**
  569. * The stream to load the document with
  570. */
  571. InputStream in;
  572. /**
  573. * URL of the old page that was replaced (for the property change event)
  574. */
  575. URL old;
  576. /**
  577. * URL of the page being loaded (for the property change event)
  578. */
  579. URL page;
  580. /**
  581. * The Document instance to load into. This is cached in case a
  582. * new Document is created between the time the thread this is created
  583. * and run.
  584. */
  585. Document doc;
  586. }
  587. static class PageStream extends FilterInputStream {
  588. boolean canceled;
  589. public PageStream(InputStream i) {
  590. super(i);
  591. canceled = false;
  592. }
  593. /**
  594. * Cancel the loading of the stream by throwing
  595. * an IOException on the next request.
  596. */
  597. public synchronized void cancel() {
  598. canceled = true;
  599. }
  600. protected synchronized void checkCanceled() throws IOException {
  601. if (canceled) {
  602. throw new IOException("page canceled");
  603. }
  604. }
  605. public int read() throws IOException {
  606. checkCanceled();
  607. return super.read();
  608. }
  609. public long skip(long n) throws IOException {
  610. checkCanceled();
  611. return super.skip(n);
  612. }
  613. public int available() throws IOException {
  614. checkCanceled();
  615. return super.available();
  616. }
  617. public void reset() throws IOException {
  618. checkCanceled();
  619. super.reset();
  620. }
  621. }
  622. /**
  623. * Fetches a stream for the given URL, which is about to
  624. * be loaded by the <code>setPage</code> method. By
  625. * default, this simply opens the URL and returns the
  626. * stream. This can be reimplemented to do useful things
  627. * like fetch the stream from a cache, monitor the progress
  628. * of the stream, etc.
  629. * <p>
  630. * This method is expected to have the the side effect of
  631. * establishing the content type, and therefore setting the
  632. * appropriate <code>EditorKit</code> to use for loading the stream.
  633. * <p>
  634. * If this the stream was an http connection, redirects
  635. * will be followed and the resulting URL will be set as
  636. * the <code>Document.StreamDescriptionProperty</code> so that relative
  637. * URL's can be properly resolved.
  638. *
  639. * @param page the URL of the page
  640. */
  641. protected InputStream getStream(URL page) throws IOException {
  642. URLConnection conn = page.openConnection();
  643. if (conn instanceof HttpURLConnection) {
  644. HttpURLConnection hconn = (HttpURLConnection) conn;
  645. hconn.setInstanceFollowRedirects(false);
  646. int response = hconn.getResponseCode();
  647. boolean redirect = (response >= 300 && response <= 399);
  648. /*
  649. * In the case of a redirect, we want to actually change the URL
  650. * that was input to the new, redirected URL
  651. */
  652. if (redirect) {
  653. String loc = conn.getHeaderField("Location");
  654. if (loc.startsWith("http", 0)) {
  655. page = new URL(loc);
  656. } else {
  657. page = new URL(page, loc);
  658. }
  659. return getStream(page);
  660. }
  661. }
  662. if (pageProperties == null) {
  663. pageProperties = new Hashtable();
  664. }
  665. String type = conn.getContentType();
  666. if (type != null) {
  667. setContentType(type);
  668. pageProperties.put("content-type", type);
  669. }
  670. pageProperties.put(Document.StreamDescriptionProperty, page);
  671. String enc = conn.getContentEncoding();
  672. if (enc != null) {
  673. pageProperties.put("content-encoding", enc);
  674. }
  675. InputStream in = conn.getInputStream();
  676. return in;
  677. }
  678. /**
  679. * Scrolls the view to the given reference location
  680. * (that is, the value returned by the <code>UL.getRef</code>
  681. * method for the URL being displayed). By default, this
  682. * method only knows how to locate a reference in an
  683. * HTMLDocument. The implementation calls the
  684. * <code>scrollRectToVisible</code> method to
  685. * accomplish the actual scrolling. If scrolling to a
  686. * reference location is needed for document types other
  687. * than HTML, this method should be reimplemented.
  688. * This method will have no effect if the component
  689. * is not visible.
  690. *
  691. * @param reference the named location to scroll to
  692. */
  693. public void scrollToReference(String reference) {
  694. Document d = getDocument();
  695. if (d instanceof HTMLDocument) {
  696. HTMLDocument doc = (HTMLDocument) d;
  697. HTMLDocument.Iterator iter = doc.getIterator(HTML.Tag.A);
  698. for (; iter.isValid(); iter.next()) {
  699. AttributeSet a = iter.getAttributes();
  700. String nm = (String) a.getAttribute(HTML.Attribute.NAME);
  701. if ((nm != null) && nm.equals(reference)) {
  702. // found a matching reference in the document.
  703. try {
  704. Rectangle r = modelToView(iter.getStartOffset());
  705. if (r != null) {
  706. // the view is visible, scroll it to the
  707. // center of the current visible area.
  708. Rectangle vis = getVisibleRect();
  709. //r.y -= (vis.height / 2);
  710. r.height = vis.height;
  711. scrollRectToVisible(r);
  712. }
  713. } catch (BadLocationException ble) {
  714. UIManager.getLookAndFeel().provideErrorFeedback(JEditorPane.this);
  715. }
  716. }
  717. }
  718. }
  719. }
  720. /**
  721. * Gets the current URL being displayed. If a URL was
  722. * not specified in the creation of the document, this
  723. * will return <code>null</code>, and relative URL's will not be
  724. * resolved.
  725. *
  726. * @return the URL, or <code>null</code> if none
  727. */
  728. public URL getPage() {
  729. return (URL) getDocument().getProperty(Document.StreamDescriptionProperty);
  730. }
  731. /**
  732. * Sets the current URL being displayed.
  733. *
  734. * @param url the URL for display
  735. * @exception IOException for a <code>null</code> or invalid URL
  736. * specification
  737. */
  738. public void setPage(String url) throws IOException {
  739. if (url == null) {
  740. throw new IOException("invalid url");
  741. }
  742. URL page = new URL(url);
  743. setPage(page);
  744. }
  745. /**
  746. * Gets the class ID for the UI.
  747. *
  748. * @return the string "EditorPaneUI"
  749. * @see JComponent#getUIClassID
  750. * @see UIDefaults#getUI
  751. */
  752. public String getUIClassID() {
  753. return uiClassID;
  754. }
  755. /**
  756. * Creates the default editor kit (<code>PlainEditorKit</code>) for when
  757. * the component is first created.
  758. *
  759. * @return the editor kit
  760. */
  761. protected EditorKit createDefaultEditorKit() {
  762. return new PlainEditorKit();
  763. }
  764. /**
  765. * Fetches the currently installed kit for handling content.
  766. * <code>createDefaultEditorKit</code> is called to set up a default
  767. * if necessary.
  768. *
  769. * @return the editor kit
  770. */
  771. public EditorKit getEditorKit() {
  772. if (kit == null) {
  773. kit = createDefaultEditorKit();
  774. }
  775. return kit;
  776. }
  777. /**
  778. * Gets the type of content that this editor
  779. * is currently set to deal with. This is
  780. * defined to be the type associated with the
  781. * currently installed <code>EditorKit</code>.
  782. *
  783. * @return the content type, <code>null</code> if no editor kit set
  784. */
  785. public final String getContentType() {
  786. return (kit != null) ? kit.getContentType() : null;
  787. }
  788. /**
  789. * Sets the type of content that this editor
  790. * handles. This calls <code>getEditorKitForContentType</code>,
  791. * and then <code>setEditorKit</code> if an editor kit can
  792. * be successfully located. This is mostly convenience method
  793. * that can be used as an alternative to calling
  794. * <code>setEditorKit</code> directly.
  795. * <p>
  796. * If there is a charset definition specified as a parameter
  797. * of the content type specification, it will be used when
  798. * loading input streams using the associated <code>EditorKit</code>.
  799. * For example if the type is specified as
  800. * <code>text/html; charset=EUC-JP</code> the content
  801. * will be loaded using the <code>EditorKit</code> registered for
  802. * <code>text/html</code> and the Reader provided to
  803. * the <code>EditorKit</code> to load unicode into the document will
  804. * use the <code>EUC-JP</code> charset for translating
  805. * to unicode. If the type is not recognized, the content
  806. * will be loaded using the <code>EditorKit</code> registered
  807. * for plain text, <code>text/plain</code>.
  808. *
  809. * @param type the non-<code>null</code> mime type for the content editing
  810. * support
  811. * @see #getContentType
  812. * @beaninfo
  813. * description: the type of content
  814. * @throws NullPointerException if the <code>type</code> parameter
  815. * is <code>null</code>
  816. */
  817. public final void setContentType(String type) {
  818. // The type could have optional info is part of it,
  819. // for example some charset info. We need to strip that
  820. // of and save it.
  821. int parm = type.indexOf(";");
  822. if (parm > -1) {
  823. // Save the paramList.
  824. String paramList = type.substring(parm);
  825. // update the content type string.
  826. type = type.substring(0, parm).trim();
  827. if (type.toLowerCase().startsWith("text/")) {
  828. setCharsetFromContentTypeParameters(paramList);
  829. }
  830. }
  831. if ((kit == null) || (! type.equals(kit.getContentType()))) {
  832. EditorKit k = getEditorKitForContentType(type);
  833. if (k != null) {
  834. setEditorKit(k);
  835. }
  836. }
  837. }
  838. /**
  839. * This method gets the charset information specified as part
  840. * of the content type in the http header information.
  841. */
  842. private void setCharsetFromContentTypeParameters(String paramlist) {
  843. String charset = null;
  844. try {
  845. // paramlist is handed to us with a leading ';', strip it.
  846. int semi = paramlist.indexOf(';');
  847. if (semi > -1 && semi < paramlist.length()-1) {
  848. paramlist = paramlist.substring(semi + 1);
  849. }
  850. if (paramlist.length() > 0) {
  851. // parse the paramlist into attr-value pairs & get the
  852. // charset pair's value
  853. HeaderParser hdrParser = new HeaderParser(paramlist);
  854. charset = hdrParser.findValue("charset");
  855. if (charset != null) {
  856. putClientProperty("charset", charset);
  857. }
  858. }
  859. }
  860. catch (IndexOutOfBoundsException e) {
  861. // malformed parameter list, use charset we have
  862. }
  863. catch (NullPointerException e) {
  864. // malformed parameter list, use charset we have
  865. }
  866. catch (Exception e) {
  867. // malformed parameter list, use charset we have; but complain
  868. System.err.println("JEditorPane.getCharsetFromContentTypeParameters failed on: " + paramlist);
  869. e.printStackTrace();
  870. }
  871. }
  872. /**
  873. * Sets the currently installed kit for handling
  874. * content. This is the bound property that
  875. * establishes the content type of the editor.
  876. * Any old kit is first deinstalled, then if kit is
  877. * non-<code>null</code>,
  878. * the new kit is installed, and a default document created for it.
  879. * A <code>PropertyChange</code> event ("editorKit") is always fired when
  880. * <code>setEditorKit</code> is called.
  881. * <p>
  882. * <em>NOTE: This has the side effect of changing the model,
  883. * because the <code>EditorKit</code> is the source of how a
  884. * particular type
  885. * of content is modeled. This method will cause <code>setDocument</code>
  886. * to be called on behalf of the caller to ensure integrity
  887. * of the internal state.</em>
  888. *
  889. * @param kit the desired editor behavior
  890. * @see #getEditorKit
  891. * @beaninfo
  892. * description: the currently installed kit for handling content
  893. * bound: true
  894. * expert: true
  895. */
  896. public void setEditorKit(EditorKit kit) {
  897. EditorKit old = this.kit;
  898. if (old != null) {
  899. old.deinstall(this);
  900. }
  901. this.kit = kit;
  902. if (this.kit != null) {
  903. this.kit.install(this);
  904. setDocument(this.kit.createDefaultDocument());
  905. }
  906. firePropertyChange("editorKit", old, kit);
  907. }
  908. /**
  909. * Fetches the editor kit to use for the given type
  910. * of content. This is called when a type is requested
  911. * that doesn't match the currently installed type.
  912. * If the component doesn't have an <code>EditorKit</code> registered
  913. * for the given type, it will try to create an
  914. * <code>EditorKit</code> from the default <code>EditorKit</code> registry.
  915. * If that fails, a <code>PlainEditorKit</code> is used on the
  916. * assumption that all text documents can be represented
  917. * as plain text.
  918. * <p>
  919. * This method can be reimplemented to use some
  920. * other kind of type registry. This can
  921. * be reimplemented to use the Java Activation
  922. * Framework, for example.
  923. *
  924. * @param type the non-</code>null</code> content type
  925. * @return the editor kit
  926. */
  927. public EditorKit getEditorKitForContentType(String type) {
  928. if (typeHandlers == null) {
  929. typeHandlers = new Hashtable(3);
  930. }
  931. EditorKit k = (EditorKit) typeHandlers.get(type);
  932. if (k == null) {
  933. k = createEditorKitForContentType(type);
  934. if (k != null) {
  935. setEditorKitForContentType(type, k);
  936. }
  937. }
  938. if (k == null) {
  939. k = createDefaultEditorKit();
  940. }
  941. return k;
  942. }
  943. /**
  944. * Directly sets the editor kit to use for the given type. A
  945. * look-and-feel implementation might use this in conjunction
  946. * with <code>createEditorKitForContentType</code> to install handlers for
  947. * content types with a look-and-feel bias.
  948. *
  949. * @param type the non-<code>null</code> content type
  950. * @param k the editor kit to be set
  951. */
  952. public void setEditorKitForContentType(String type, EditorKit k) {
  953. if (typeHandlers == null) {
  954. typeHandlers = new Hashtable(3);
  955. }
  956. typeHandlers.put(type, k);
  957. }
  958. /**
  959. * Replaces the currently selected content with new content
  960. * represented by the given string. If there is no selection
  961. * this amounts to an insert of the given text. If there
  962. * is no replacement text (i.e. the content string is empty
  963. * or <code>null</code>) this amounts to a removal of the
  964. * current selection. The replacement text will have the
  965. * attributes currently defined for input. If the component is not
  966. * editable, beep and return.
  967. * <p>
  968. * This method is thread safe, although most Swing methods
  969. * are not. Please see
  970. * <A HREF="http://java.sun.com/products/jfc/swingdoc-archive/threads.html">Threads
  971. * and Swing</A> for more information.
  972. *
  973. * @param content the content to replace the selection with. This
  974. * value can be <code>null</code>
  975. */
  976. public void replaceSelection(String content) {
  977. if (! isEditable()) {
  978. UIManager.getLookAndFeel().provideErrorFeedback(JEditorPane.this);
  979. return;
  980. }
  981. EditorKit kit = getEditorKit();
  982. if(kit instanceof StyledEditorKit) {
  983. try {
  984. Document doc = getDocument();
  985. Caret caret = getCaret();
  986. int p0 = Math.min(caret.getDot(), caret.getMark());
  987. int p1 = Math.max(caret.getDot(), caret.getMark());
  988. if (doc instanceof AbstractDocument) {
  989. ((AbstractDocument)doc).replace(p0, p1 - p0, content,
  990. ((StyledEditorKit)kit).getInputAttributes());
  991. }
  992. else {
  993. if (p0 != p1) {
  994. doc.remove(p0, p1 - p0);
  995. }
  996. if (content != null && content.length() > 0) {
  997. doc.insertString(p0, content, ((StyledEditorKit)kit).
  998. getInputAttributes());
  999. }
  1000. }
  1001. } catch (BadLocationException e) {
  1002. UIManager.getLookAndFeel().provideErrorFeedback(JEditorPane.this);
  1003. }
  1004. }
  1005. else {
  1006. super.replaceSelection(content);
  1007. }
  1008. }
  1009. /**
  1010. * Creates a handler for the given type from the default registry
  1011. * of editor kits. The registry is created if necessary. If the
  1012. * registered class has not yet been loaded, an attempt
  1013. * is made to dynamically load the prototype of the kit for the
  1014. * given type. If the type was registered with a <code>ClassLoader</code>,
  1015. * that <code>ClassLoader</code> will be used to load the prototype.
  1016. * If there was no registered <code>ClassLoader</code>,
  1017. * <code>Class.forName</code> will be used to load the prototype.
  1018. * <p>
  1019. * Once a prototype <code>EditorKit</code> instance is successfully
  1020. * located, it is cloned and the clone is returned.
  1021. *
  1022. * @param type the content type
  1023. * @return the editor kit, or <code>null</code> if there is nothing
  1024. * registered for the given type
  1025. */
  1026. public static EditorKit createEditorKitForContentType(String type) {
  1027. EditorKit k = null;
  1028. Hashtable kitRegistry = getKitRegisty();
  1029. k = (EditorKit) kitRegistry.get(type);
  1030. if (k == null) {
  1031. // try to dynamically load the support
  1032. String classname = (String) getKitTypeRegistry().get(type);
  1033. ClassLoader loader = (ClassLoader) getKitLoaderRegistry().get(type);
  1034. try {
  1035. Class c;
  1036. if (loader != null) {
  1037. c = loader.loadClass(classname);
  1038. } else {
  1039. // Will only happen if developer has invoked
  1040. // registerEditorKitForContentType(type, class, null).
  1041. c = Class.forName(classname, true, Thread.currentThread().
  1042. getContextClassLoader());
  1043. }
  1044. k = (EditorKit) c.newInstance();
  1045. kitRegistry.put(type, k);
  1046. } catch (Throwable e) {
  1047. k = null;
  1048. }
  1049. }
  1050. // create a copy of the prototype or null if there
  1051. // is no prototype.
  1052. if (k != null) {
  1053. return (EditorKit) k.clone();
  1054. }
  1055. return null;
  1056. }
  1057. /**
  1058. * Establishes the default bindings of <code>type</code> to
  1059. * <code>classname</code>.
  1060. * The class will be dynamically loaded later when actually
  1061. * needed, and can be safely changed before attempted uses
  1062. * to avoid loading unwanted classes. The prototype
  1063. * <code>EditorKit</code> will be loaded with <code>Class.forName</code>
  1064. * when registered with this method.
  1065. *
  1066. * @param type the non-<code>null</code> content type
  1067. * @param classname the class to load later
  1068. */
  1069. public static void registerEditorKitForContentType(String type, String classname) {
  1070. registerEditorKitForContentType(type, classname,Thread.currentThread().
  1071. getContextClassLoader());
  1072. }
  1073. /**
  1074. * Establishes the default bindings of <code>type</code> to
  1075. * <code>classname</code>.
  1076. * The class will be dynamically loaded later when actually
  1077. * needed using the given <code>ClassLoader</code>,
  1078. * and can be safely changed
  1079. * before attempted uses to avoid loading unwanted classes.
  1080. *
  1081. * @param type the non-</code>null</code> content type
  1082. * @param classname the class to load later
  1083. * @param loader the <code>ClassLoader</code> to use to load the name
  1084. */
  1085. public static void registerEditorKitForContentType(String type, String classname, ClassLoader loader) {
  1086. getKitTypeRegistry().put(type, classname);
  1087. getKitLoaderRegistry().put(type, loader);
  1088. getKitRegisty().remove(type);
  1089. }
  1090. /**
  1091. * Returns the currently registered <code>EditorKit</code>
  1092. * class name for the type <code>type</code>.
  1093. *
  1094. * @param type the non-<code>null</code> content type
  1095. *
  1096. * @since 1.3
  1097. */
  1098. public static String getEditorKitClassNameForContentType(String type) {
  1099. return (String)getKitTypeRegistry().get(type);
  1100. }
  1101. private static Hashtable getKitTypeRegistry() {
  1102. loadDefaultKitsIfNecessary();
  1103. return (Hashtable)SwingUtilities.appContextGet(kitTypeRegistryKey);
  1104. }
  1105. private static Hashtable getKitLoaderRegistry() {
  1106. loadDefaultKitsIfNecessary();
  1107. return (Hashtable)SwingUtilities.appContextGet(kitLoaderRegistryKey);
  1108. }
  1109. private static Hashtable getKitRegisty() {
  1110. Hashtable ht = (Hashtable)SwingUtilities.appContextGet(kitRegistryKey);
  1111. if (ht == null) {
  1112. ht = new Hashtable(3);
  1113. SwingUtilities.appContextPut(kitRegistryKey, ht);
  1114. }
  1115. return ht;
  1116. }
  1117. /**
  1118. * This is invoked every time the registries are accessed. Loading
  1119. * is done this way instead of via a static as the static is only
  1120. * called once when running in plugin resulting in the entries only
  1121. * appearing in the first applet.
  1122. */
  1123. private static void loadDefaultKitsIfNecessary() {
  1124. if (SwingUtilities.appContextGet(kitTypeRegistryKey) == null) {
  1125. Hashtable ht = new Hashtable();
  1126. SwingUtilities.appContextPut(kitTypeRegistryKey, ht);
  1127. ht = new Hashtable();
  1128. SwingUtilities.appContextPut(kitLoaderRegistryKey, ht);
  1129. registerEditorKitForContentType("text/plain",
  1130. "javax.swing.JEditorPane$PlainEditorKit");
  1131. registerEditorKitForContentType("text/html",
  1132. "javax.swing.text.html.HTMLEditorKit");
  1133. registerEditorKitForContentType("text/rtf",
  1134. "javax.swing.text.rtf.RTFEditorKit");
  1135. registerEditorKitForContentType("application/rtf",
  1136. "javax.swing.text.rtf.RTFEditorKit");
  1137. }
  1138. }
  1139. // --- java.awt.Component methods --------------------------
  1140. /**
  1141. * Returns the preferred size for the <code>JEditorPane</code>.
  1142. * The preferred size for <code>JEditorPane</code> is slightly altered
  1143. * from the preferred size of the superclass. If the size
  1144. * of the viewport has become smaller than the minimum size
  1145. * of the component, the scrollable definition for tracking
  1146. * width or height will turn to false. The default viewport
  1147. * layout will give the preferred size, and that is not desired
  1148. * in the case where the scrollable is tracking. In that case
  1149. * the <em>normal</em> preferred size is adjusted to the
  1150. * minimum size. This allows things like HTML tables to
  1151. * shrink down to their minimum size and then be laid out at
  1152. * their minimum size, refusing to shrink any further.
  1153. *
  1154. * @return a <code>Dimension</code> containing the preferred size
  1155. */
  1156. public Dimension getPreferredSize() {
  1157. Dimension d = super.getPreferredSize();
  1158. if (getParent() instanceof JViewport) {
  1159. JViewport port = (JViewport)getParent();
  1160. TextUI ui = getUI();
  1161. int prefWidth = d.width;
  1162. int prefHeight = d.height;
  1163. if (! getScrollableTracksViewportWidth()) {
  1164. int w = port.getWidth();
  1165. Dimension min = ui.getMinimumSize(this);
  1166. if (w != 0 && w < min.width) {
  1167. // Only adjust to min if we have a valid size
  1168. prefWidth = min.width;
  1169. }
  1170. }
  1171. if (! getScrollableTracksViewportHeight()) {
  1172. int h = port.getHeight();
  1173. Dimension min = ui.getMinimumSize(this);
  1174. if (h != 0 && h < min.height) {
  1175. // Only adjust to min if we have a valid size
  1176. prefHeight = min.height;
  1177. }
  1178. }
  1179. if (prefWidth != d.width || prefHeight != d.height) {
  1180. d = new Dimension(prefWidth, prefHeight);
  1181. }
  1182. }
  1183. return d;
  1184. }
  1185. // --- JTextComponent methods -----------------------------
  1186. /**
  1187. * Sets the text of this <code>TextComponent</code> to the specified
  1188. * content,
  1189. * which is expected to be in the format of the content type of
  1190. * this editor. For example, if the type is set to <code>text/html</code>
  1191. * the string should be specified in terms of HTML.
  1192. * <p>
  1193. * This is implemented to remove the contents of the current document,
  1194. * and replace them by parsing the given string using the current
  1195. * <code>EditorKit</code>. This gives the semantics of the
  1196. * superclass by not changing
  1197. * out the model, while supporting the content type currently set on
  1198. * this component. The assumption is that the previous content is
  1199. * relatively
  1200. * small, and that the previous content doesn't have side effects.
  1201. * Both of those assumptions can be violated and cause undesirable results.
  1202. * To avoid this, create a new document,
  1203. * <code>getEditorKit().createDefaultDocument()</code>, and replace the
  1204. * existing <code>Document</code> with the new one. You are then assured the
  1205. * previous <code>Document</code> won't have any lingering state.
  1206. * <ol>
  1207. * <li>
  1208. * Leaving the existing model in place means that the old view will be
  1209. * torn down, and a new view created, where replacing the document would
  1210. * avoid the tear down of the old view.
  1211. * <li>
  1212. * Some formats (such as HTML) can install things into the document that
  1213. * can influence future contents. HTML can have style information embedded
  1214. * that would influence the next content installed unexpectedly.
  1215. * </ol>
  1216. * <p>
  1217. * An alternative way to load this component with a string would be to
  1218. * create a StringReader and call the read method. In this case the model
  1219. * would be replaced after it was initialized with the contents of the
  1220. * string.
  1221. * <p>
  1222. * This method is thread safe, although most Swing methods
  1223. * are not. Please see
  1224. * <A HREF="http://java.sun.com/products/jfc/swingdoc-archive/threads.html">Threads
  1225. * and Swing</A> for more information.
  1226. *
  1227. * @param t the new text to be set; if <code>null</code> the old
  1228. * text will be deleted
  1229. * @see #getText
  1230. * @beaninfo
  1231. * description: the text of this component
  1232. */
  1233. public void setText(String t) {
  1234. try {
  1235. Document doc = getDocument();
  1236. doc.remove(0, doc.getLength());
  1237. if (t == null || t.equals("")) {
  1238. return;
  1239. }
  1240. Reader r = new StringReader(t);
  1241. EditorKit kit = getEditorKit();
  1242. kit.read(r, doc, 0);
  1243. } catch (IOException ioe) {
  1244. UIManager.getLookAndFeel().provideErrorFeedback(JEditorPane.this);
  1245. } catch (BadLocationException ble) {
  1246. UIManager.getLookAndFeel().provideErrorFeedback(JEditorPane.this);
  1247. }
  1248. }
  1249. /**
  1250. * Returns the text contained in this <code>TextComponent</code>
  1251. * in terms of the
  1252. * content type of this editor. If an exception is thrown while
  1253. * attempting to retrieve the text, <code>null</code> will be returned.
  1254. * This is implemented to call <code>JTextComponent.write</code> with
  1255. * a <code>StringWriter</code>.
  1256. *
  1257. * @return the text
  1258. * @see #setText
  1259. */
  1260. public String getText() {
  1261. String txt;
  1262. try {
  1263. StringWriter buf = new StringWriter();
  1264. write(buf);
  1265. txt = buf.toString();
  1266. } catch (IOException ioe) {
  1267. txt = null;
  1268. }
  1269. return txt;
  1270. }
  1271. // --- Scrollable ----------------------------------------
  1272. /**
  1273. * Returns true if a viewport should always force the width of this
  1274. * <code>Scrollable</code> to match the width of the viewport.
  1275. *
  1276. * @return true if a viewport should force the Scrollables width to
  1277. * match its own, false otherwise
  1278. */
  1279. public boolean getScrollableTracksViewportWidth() {
  1280. if (getParent() instanceof JViewport) {
  1281. JViewport port = (JViewport)getParent();
  1282. TextUI ui = getUI();
  1283. int w = port.getWidth();
  1284. Dimension min = ui.getMinimumSize(this);
  1285. Dimension max = ui.getMaximumSize(this);
  1286. if ((w >= min.width) && (w <= max.width)) {
  1287. return true;
  1288. }
  1289. }
  1290. return false;
  1291. }
  1292. /**
  1293. * Returns true if a viewport should always force the height of this
  1294. * <code>Scrollable</code> to match the height of the viewport.
  1295. *
  1296. * @return true if a viewport should force the
  1297. * <code>Scrollable</code>'s height to match its own,
  1298. * false otherwise
  1299. */
  1300. public boolean getScrollableTracksViewportHeight() {
  1301. if (getParent() instanceof JViewport) {
  1302. JViewport port = (JViewport)getParent();
  1303. TextUI ui = getUI();
  1304. int h = port.getHeight();
  1305. Dimension min = ui.getMinimumSize(this);
  1306. if (h >= min.height) {
  1307. Dimension max = ui.getMaximumSize(this);
  1308. if (h <= max.height) {
  1309. return true;
  1310. }
  1311. }
  1312. }
  1313. return false;
  1314. }
  1315. // --- Serialization ------------------------------------
  1316. /**
  1317. * See <code>readObject</code> and <code>writeObject</code> in
  1318. * <code>JComponent</code> for more
  1319. * information about serialization in Swing.
  1320. */
  1321. private void writeObject(ObjectOutputStream s) throws IOException {
  1322. s.defaultWriteObject();
  1323. if (getUIClassID().equals(uiClassID)) {
  1324. byte count = JComponent.getWriteObjCounter(this);
  1325. JComponent.setWriteObjCounter(this, --count);
  1326. if (count == 0 && ui != null) {
  1327. ui.installUI(this);
  1328. }
  1329. }
  1330. }
  1331. // --- variables ---------------------------------------
  1332. /**
  1333. * Stream currently loading asynchronously (potentially cancelable).
  1334. * Access to this variable should be synchronized.
  1335. */
  1336. PageStream loading;
  1337. /**
  1338. * Current content binding of the editor.
  1339. */
  1340. private EditorKit kit;
  1341. private Hashtable pageProperties;
  1342. /**
  1343. * Table of registered type handlers for this editor.
  1344. */
  1345. private Hashtable typeHandlers;
  1346. /*
  1347. * Private AppContext keys for this class's static variables.
  1348. */
  1349. private static final Object kitRegistryKey =
  1350. new StringBuffer("JEditorPane.kitRegistry");
  1351. private static final Object kitTypeRegistryKey =
  1352. new StringBuffer("JEditorPane.kitTypeRegistry");
  1353. private static final Object kitLoaderRegistryKey =
  1354. new StringBuffer("JEditorPane.kitLoaderRegistry");
  1355. /**
  1356. * @see #getUIClassID
  1357. * @see #readObject
  1358. */
  1359. private static final String uiClassID = "EditorPaneUI";
  1360. /**
  1361. * Key for a client property used to indicate whether
  1362. * <a href="http://www.w3.org/TR/CSS21/syndata.html#length-units">
  1363. * w3c compliant</a> length units are used for html rendering.
  1364. * <p>
  1365. * By default this is not enabled; to enable
  1366. * it set the client {@link putClientProperty property} with this name
  1367. * to <code>Boolean.TRUE</code>.
  1368. *
  1369. * @since 1.5
  1370. */
  1371. public static final String W3C_LENGTH_UNITS = "JEditorPane.w3cLengthUnits";
  1372. /**
  1373. * Key for a client property used to indicate whether
  1374. * the default font and foreground color from the component are
  1375. * used if a font or foreground color is not specified in the styled
  1376. * text.
  1377. * <p>
  1378. * The default varies based on the look and feel;
  1379. * to enable it set the client {@link putClientProperty property} with
  1380. * this name to <code>Boolean.TRUE</code>.
  1381. *
  1382. * @since 1.5
  1383. */
  1384. public static final String HONOR_DISPLAY_PROPERTIES = "JEditorPane.honorDisplayProperties";
  1385. /**
  1386. * Returns a string representation of this <code>JEditorPane</code>.
  1387. * This method
  1388. * is intended to be used only for debugging purposes, and the
  1389. * content and format of the returned string may vary between
  1390. * implementations. The returned string may be empty but may not
  1391. * be <code>null</code>.
  1392. *
  1393. * @return a string representation of this <code>JEditorPane</code>
  1394. */
  1395. protected String paramString() {
  1396. String kitString = (kit != null ?
  1397. kit.toString() : "");
  1398. String typeHandlersString = (typeHandlers != null ?
  1399. typeHandlers.toString() : "");
  1400. return super.paramString() +
  1401. ",kit=" + kitString +
  1402. ",typeHandlers=" + typeHandlersString;
  1403. }
  1404. /////////////////
  1405. // Accessibility support
  1406. ////////////////
  1407. /**
  1408. * Gets the AccessibleContext associated with this JEditorPane.
  1409. * For editor panes, the AccessibleContext takes the form of an
  1410. * AccessibleJEditorPane.
  1411. * A new AccessibleJEditorPane instance is created if necessary.
  1412. *
  1413. * @return an AccessibleJEditorPane that serves as the
  1414. * AccessibleContext of this JEditorPane
  1415. */
  1416. public AccessibleContext getAccessibleContext() {
  1417. if (accessibleContext == null) {
  1418. if (JEditorPane.this.getEditorKit() instanceof HTMLEditorKit) {
  1419. accessibleContext = new AccessibleJEditorPaneHTML();
  1420. } else {
  1421. accessibleContext = new AccessibleJEditorPane();
  1422. }
  1423. }
  1424. return accessibleContext;
  1425. }
  1426. /**
  1427. * This class implements accessibility support for the
  1428. * <code>JEditorPane</code> class. It provides an implementation of the
  1429. * Java Accessibility API appropriate to editor pane user-interface
  1430. * elements.
  1431. * <p>
  1432. * <strong>Warning:</strong>
  1433. * Serialized objects of this class will not be compatible with
  1434. * future Swing releases. The current serialization support is
  1435. * appropriate for short term storage or RMI between applications running
  1436. * the same version of Swing. As of 1.4, support for long term storage
  1437. * of all JavaBeans<sup><font size="-2">TM</font></sup>
  1438. * has been added to the <code>java.beans</code> package.
  1439. * Please see {@link java.beans.XMLEncoder}.
  1440. */
  1441. protected class AccessibleJEditorPane extends AccessibleJTextComponent {
  1442. /**
  1443. * Gets the accessibleDescription property of this object. If this
  1444. * property isn't set, returns the content type of this
  1445. * <code>JEditorPane</code> instead (e.g. "plain/text", "html/text").
  1446. *
  1447. * @return the localized description of the object; <code>null</code>
  1448. * if this object does not have a description
  1449. *
  1450. * @see #setAccessibleName
  1451. */
  1452. public String getAccessibleDescription() {
  1453. if (accessibleDescription != null) {
  1454. return accessibleDescription;
  1455. } else {
  1456. return JEditorPane.this.getContentType();
  1457. }
  1458. }
  1459. /**
  1460. * Gets the state set of this object.
  1461. *
  1462. * @return an instance of AccessibleStateSet describing the states
  1463. * of the object
  1464. * @see AccessibleStateSet
  1465. */
  1466. public AccessibleStateSet getAccessibleStateSet() {
  1467. AccessibleStateSet states = super.getAccessibleStateSet();
  1468. states.add(AccessibleState.MULTI_LINE);
  1469. return states;
  1470. }
  1471. }
  1472. /**
  1473. * This class provides support for <code>AccessibleHypertext</code>,
  1474. * and is used in instances where the <code>EditorKit</code>
  1475. * installed in this <code>JEditorPane</code> is an instance of
  1476. * <code>HTMLEditorKit</code>.
  1477. * <p>
  1478. * <strong>Warning:</strong>
  1479. * Serialized objects of this class will not be compatible with
  1480. * future Swing releases. The current serialization support is
  1481. * appropriate for short term storage or RMI between applications running
  1482. * the same version of Swing. As of 1.4, support for long term storage
  1483. * of all JavaBeans<sup><font size="-2">TM</font></sup>
  1484. * has been added to the <code>java.beans</code> package.
  1485. * Please see {@link java.beans.XMLEncoder}.
  1486. */
  1487. protected class AccessibleJEditorPaneHTML extends AccessibleJEditorPane {
  1488. private AccessibleContext accessibleContext;
  1489. public AccessibleText getAccessibleText() {
  1490. return new JEditorPaneAccessibleHypertextSupport();
  1491. }
  1492. protected AccessibleJEditorPaneHTML () {
  1493. HTMLEditorKit kit = (HTMLEditorKit)JEditorPane.this.getEditorKit();
  1494. accessibleContext = kit.getAccessibleContext();
  1495. }
  1496. /**
  1497. * Returns the number of accessible children of the object.
  1498. *
  1499. * @return the number of accessible children of the object.
  1500. */
  1501. public int getAccessibleChildrenCount() {
  1502. if (accessibleContext != null) {
  1503. return accessibleContext.getAccessibleChildrenCount();
  1504. } else {
  1505. return 0;
  1506. }
  1507. }
  1508. /**
  1509. * Returns the specified Accessible child of the object. The Accessible
  1510. * children of an Accessible object are zero-based, so the first child
  1511. * of an Accessible child is at index 0, the second child is at index 1,
  1512. * and so on.
  1513. *
  1514. * @param i zero-based index of child
  1515. * @return the Accessible child of the object
  1516. * @see #getAccessibleChildrenCount
  1517. */
  1518. public Accessible getAccessibleChild(int i) {
  1519. if (accessibleContext != null) {
  1520. return accessibleContext.getAccessibleChild(i);
  1521. } else {
  1522. return null;
  1523. }
  1524. }
  1525. /**
  1526. * Returns the Accessible child, if one exists, contained at the local
  1527. * coordinate Point.
  1528. *
  1529. * @param p The point relative to the coordinate system of this object.
  1530. * @return the Accessible, if it exists, at the specified location;
  1531. * otherwise null
  1532. */
  1533. public Accessible getAccessibleAt(Point p) {
  1534. if (accessibleContext != null && p != null) {
  1535. try {
  1536. AccessibleComponent acomp =
  1537. accessibleContext.getAccessibleComponent();
  1538. if (acomp != null) {
  1539. return acomp.getAccessibleAt(p);
  1540. } else {
  1541. return null;
  1542. }
  1543. } catch (IllegalComponentStateException e) {
  1544. return null;
  1545. }
  1546. } else {
  1547. return null;
  1548. }
  1549. }
  1550. }
  1551. /**
  1552. * What's returned by
  1553. * <code>AccessibleJEditorPaneHTML.getAccessibleText</code>.
  1554. *
  1555. * Provides support for <code>AccessibleHypertext</code> in case
  1556. * there is an HTML document being displayed in this
  1557. * <code>JEditorPane</code>.
  1558. *
  1559. */
  1560. protected class JEditorPaneAccessibleHypertextSupport
  1561. extends AccessibleJEditorPane implements AccessibleHypertext {
  1562. public class HTMLLink extends AccessibleHyperlink {
  1563. Element element;
  1564. public HTMLLink(Element e) {
  1565. element = e;
  1566. }
  1567. /**
  1568. * Since the document a link is associated with may have
  1569. * changed, this method returns whether this Link is valid
  1570. * anymore (with respect to the document it references).
  1571. *
  1572. * @return a flag indicating whether this link is still valid with
  1573. * respect to the AccessibleHypertext it belongs to
  1574. */
  1575. public boolean isValid() {
  1576. return JEditorPaneAccessibleHypertextSupport.this.linksValid;
  1577. }
  1578. /**
  1579. * Returns the number of accessible actions available in this Link
  1580. * If there are more than one, the first one is NOT considered the
  1581. * "default" action of this LINK object (e.g. in an HTML imagemap).
  1582. * In general, links will have only one AccessibleAction in them.
  1583. *
  1584. * @return the zero-based number of Actions in this object
  1585. */
  1586. public int getAccessibleActionCount() {
  1587. return 1;
  1588. }
  1589. /**
  1590. * Perform the specified Action on the object
  1591. *
  1592. * @param i zero-based index of actions
  1593. * @return true if the the action was performed; else false.
  1594. * @see #getAccessibleActionCount
  1595. */
  1596. public boolean doAccessibleAction(int i) {
  1597. if (i == 0 && isValid() == true) {
  1598. URL u = (URL) getAccessibleActionObject(i);
  1599. if (u != null) {
  1600. HyperlinkEvent linkEvent =
  1601. new HyperlinkEvent(JEditorPane.this, HyperlinkEvent.EventType.ACTIVATED, u);
  1602. JEditorPane.this.fireHyperlinkUpdate(linkEvent);
  1603. return true;
  1604. }
  1605. }
  1606. return false; // link invalid or i != 0
  1607. }
  1608. /**
  1609. * Return a String description of this particular
  1610. * link action. The string returned is the text
  1611. * within the document associated with the element
  1612. * which contains this link.
  1613. *
  1614. * @param i zero-based index of the actions
  1615. * @return a String description of the action
  1616. * @see #getAccessibleActionCount
  1617. */
  1618. public String getAccessibleActionDescription(int i) {
  1619. if (i == 0 && isValid() == true) {
  1620. Document d = JEditorPane.this.getDocument();
  1621. if (d != null) {
  1622. try {
  1623. return d.getText(getStartIndex(),
  1624. getEndIndex() - getStartIndex());
  1625. } catch (BadLocationException exception) {
  1626. return null;
  1627. }
  1628. }
  1629. }
  1630. return null;
  1631. }
  1632. /**
  1633. * Returns a URL object that represents the link.
  1634. *
  1635. * @param i zero-based index of the actions
  1636. * @return an URL representing the HTML link itself
  1637. * @see #getAccessibleActionCount
  1638. */
  1639. public Object getAccessibleActionObject(int i) {
  1640. if (i == 0 && isValid() == true) {
  1641. AttributeSet as = element.getAttributes();
  1642. AttributeSet anchor =
  1643. (AttributeSet) as.getAttribute(HTML.Tag.A);
  1644. String href = (anchor != null) ?
  1645. (String) anchor.getAttribute(HTML.Attribute.HREF) : null;
  1646. if (href != null) {
  1647. URL u;
  1648. try {
  1649. u = new URL(JEditorPane.this.getPage(), href);
  1650. } catch (MalformedURLException m) {
  1651. u = null;
  1652. }
  1653. return u;
  1654. }
  1655. }
  1656. return null; // link invalid or i != 0
  1657. }
  1658. /**
  1659. * Return an object that represents the link anchor,
  1660. * as appropriate for that link. E.g. from HTML:
  1661. * <a href="http://www.sun.com/access">Accessibility</a>
  1662. * this method would return a String containing the text:
  1663. * 'Accessibility'.
  1664. *
  1665. * Similarly, from this HTML:
  1666. * <a HREF="#top"><img src="top-hat.gif" alt="top hat"></a>
  1667. * this might return the object ImageIcon("top-hat.gif", "top hat");
  1668. *
  1669. * @param i zero-based index of the actions
  1670. * @return an Object representing the hypertext anchor
  1671. * @see #getAccessibleActionCount
  1672. */
  1673. public Object getAccessibleActionAnchor(int i) {
  1674. return getAccessibleActionDescription(i);
  1675. }
  1676. /**
  1677. * Get the index with the hypertext document at which this
  1678. * link begins
  1679. *
  1680. * @return index of start of link
  1681. */
  1682. public int getStartIndex() {
  1683. return element.getStartOffset();
  1684. }
  1685. /**
  1686. * Get the index with the hypertext document at which this
  1687. * link ends
  1688. *
  1689. * @return index of end of link
  1690. */
  1691. public int getEndIndex() {
  1692. return element.getEndOffset();
  1693. }
  1694. }
  1695. private class LinkVector extends Vector {
  1696. public int baseElementIndex(Element e) {
  1697. HTMLLink l;
  1698. for (int i = 0; i < elementCount; i++) {
  1699. l = (HTMLLink) elementAt(i);
  1700. if (l.element == e) {
  1701. return i;
  1702. }
  1703. }
  1704. return -1;
  1705. }
  1706. }
  1707. LinkVector hyperlinks;
  1708. boolean linksValid = false;
  1709. /**
  1710. * Build the private table mapping links to locations in the text
  1711. */
  1712. private void buildLinkTable() {
  1713. hyperlinks.removeAllElements();
  1714. Document d = JEditorPane.this.getDocument();
  1715. if (d != null) {
  1716. ElementIterator ei = new ElementIterator(d);
  1717. Element e;
  1718. AttributeSet as;
  1719. AttributeSet anchor;
  1720. String href;
  1721. while ((e = ei.next()) != null) {
  1722. if (e.isLeaf()) {
  1723. as = e.getAttributes();
  1724. anchor = (AttributeSet) as.getAttribute(HTML.Tag.A);
  1725. href = (anchor != null) ?
  1726. (String) anchor.getAttribute(HTML.Attribute.HREF) : null;
  1727. if (href != null) {
  1728. hyperlinks.addElement(new HTMLLink(e));
  1729. }
  1730. }
  1731. }
  1732. }
  1733. linksValid = true;
  1734. }
  1735. /**
  1736. * Make one of these puppies
  1737. */
  1738. public JEditorPaneAccessibleHypertextSupport() {
  1739. hyperlinks = new LinkVector();
  1740. Document d = JEditorPane.this.getDocument();
  1741. if (d != null) {
  1742. d.addDocumentListener(new DocumentListener() {
  1743. public void changedUpdate(DocumentEvent theEvent) {
  1744. linksValid = false;
  1745. }
  1746. public void insertUpdate(DocumentEvent theEvent) {
  1747. linksValid = false;
  1748. }
  1749. public void removeUpdate(DocumentEvent theEvent) {
  1750. linksValid = false;
  1751. }
  1752. });
  1753. }
  1754. }
  1755. /**
  1756. * Returns the number of links within this hypertext doc.
  1757. *
  1758. * @return number of links in this hypertext doc.
  1759. */
  1760. public int getLinkCount() {
  1761. if (linksValid == false) {
  1762. buildLinkTable();
  1763. }
  1764. return hyperlinks.size();
  1765. }
  1766. /**
  1767. * Returns the index into an array of hyperlinks that
  1768. * is associated with this character index, or -1 if there
  1769. * is no hyperlink associated with this index.
  1770. *
  1771. * @param charIndex index within the text
  1772. * @return index into the set of hyperlinks for this hypertext doc.
  1773. */
  1774. public int getLinkIndex(int charIndex) {
  1775. if (linksValid == false) {
  1776. buildLinkTable();
  1777. }
  1778. Element e = null;
  1779. Document doc = JEditorPane.this.getDocument();
  1780. if (doc != null) {
  1781. for (e = doc.getDefaultRootElement(); ! e.isLeaf(); ) {
  1782. int index = e.getElementIndex(charIndex);
  1783. e = e.getElement(index);
  1784. }
  1785. }
  1786. // don't need to verify that it's an HREF element; if
  1787. // not, then it won't be in the hyperlinks Vector, and
  1788. // so indexOf will return -1 in any case
  1789. return hyperlinks.baseElementIndex(e);
  1790. }
  1791. /**
  1792. * Returns the index into an array of hyperlinks that
  1793. * index. If there is no hyperlink at this index, it returns
  1794. * null.
  1795. *
  1796. * @param linkIndex into the set of hyperlinks for this hypertext doc.
  1797. * @return string representation of the hyperlink
  1798. */
  1799. public AccessibleHyperlink getLink(int linkIndex) {
  1800. if (linksValid == false) {
  1801. buildLinkTable();
  1802. }
  1803. if (linkIndex >= 0 && linkIndex < hyperlinks.size()) {
  1804. return (AccessibleHyperlink) hyperlinks.elementAt(linkIndex);
  1805. } else {
  1806. return null;
  1807. }
  1808. }
  1809. /**
  1810. * Returns the contiguous text within the document that
  1811. * is associated with this hyperlink.
  1812. *
  1813. * @param linkIndex into the set of hyperlinks for this hypertext doc.
  1814. * @return the contiguous text sharing the link at this index
  1815. */
  1816. public String getLinkText(int linkIndex) {
  1817. if (linksValid == false) {
  1818. buildLinkTable();
  1819. }
  1820. Element e = (Element) hyperlinks.elementAt(linkIndex);
  1821. if (e != null) {
  1822. Document d = JEditorPane.this.getDocument();
  1823. if (d != null) {
  1824. try {
  1825. return d.getText(e.getStartOffset(),
  1826. e.getEndOffset() - e.getStartOffset());
  1827. } catch (BadLocationException exception) {
  1828. return null;
  1829. }
  1830. }
  1831. }
  1832. return null;
  1833. }
  1834. }
  1835. static class PlainEditorKit extends DefaultEditorKit implements ViewFactory {
  1836. /**
  1837. * Fetches a factory that is suitable for producing
  1838. * views of any models that are produced by this
  1839. * kit. The default is to have the UI produce the
  1840. * factory, so this method has no implementation.
  1841. *
  1842. * @return the view factory
  1843. */
  1844. public ViewFactory getViewFactory() {
  1845. return this;
  1846. }
  1847. /**
  1848. * Creates a view from the given structural element of a
  1849. * document.
  1850. *
  1851. * @param elem the piece of the document to build a view of
  1852. * @return the view
  1853. * @see View
  1854. */
  1855. public View create(Element elem) {
  1856. Document doc = elem.getDocument();
  1857. Object i18nFlag
  1858. = doc.getProperty("i18n"/*AbstractDocument.I18NProperty*/);
  1859. if ((i18nFlag != null) && i18nFlag.equals(Boolean.TRUE)) {
  1860. // build a view that support bidi
  1861. return createI18N(elem);
  1862. } else {
  1863. return new WrappedPlainView(elem);
  1864. }
  1865. }
  1866. View createI18N(Element elem) {
  1867. String kind = elem.getName();
  1868. if (kind != null) {
  1869. if (kind.equals(AbstractDocument.ContentElementName)) {
  1870. return new PlainParagraph(elem);
  1871. } else if (kind.equals(AbstractDocument.ParagraphElementName)){
  1872. return new BoxView(elem, View.Y_AXIS);
  1873. }
  1874. }
  1875. return null;
  1876. }
  1877. /**
  1878. * Paragraph for representing plain-text lines that support
  1879. * bidirectional text.
  1880. */
  1881. static class PlainParagraph extends javax.swing.text.ParagraphView {
  1882. PlainParagraph(Element elem) {
  1883. super(elem);
  1884. layoutPool = new LogicalView(elem);
  1885. layoutPool.setParent(this);
  1886. }
  1887. protected void setPropertiesFromAttributes() {
  1888. Component c = getContainer();
  1889. if ((c != null)
  1890. && (! c.getComponentOrientation().isLeftToRight()))
  1891. {
  1892. setJustification(StyleConstants.ALIGN_RIGHT);
  1893. } else {
  1894. setJustification(StyleConstants.ALIGN_LEFT);
  1895. }
  1896. }
  1897. /**
  1898. * Fetch the constraining span to flow against for
  1899. * the given child index.
  1900. */
  1901. public int getFlowSpan(int index) {
  1902. Component c = getContainer();
  1903. if (c instanceof JTextArea) {
  1904. JTextArea area = (JTextArea) c;
  1905. if (! area.getLineWrap()) {
  1906. // no limit if unwrapped
  1907. return Integer.MAX_VALUE;
  1908. }
  1909. }
  1910. return super.getFlowSpan(index);
  1911. }
  1912. protected SizeRequirements calculateMinorAxisRequirements(int axis,
  1913. SizeRequirements r)
  1914. {
  1915. SizeRequirements req
  1916. = super.calculateMinorAxisRequirements(axis, r);
  1917. Component c = getContainer();
  1918. if (c instanceof JTextArea) {
  1919. JTextArea area = (JTextArea) c;
  1920. if (! area.getLineWrap()) {
  1921. // min is pref if unwrapped
  1922. req.minimum = req.preferred;
  1923. }
  1924. }
  1925. return req;
  1926. }
  1927. /**
  1928. * This class can be used to represent a logical view for
  1929. * a flow. It keeps the children updated to reflect the state
  1930. * of the model, gives the logical child views access to the
  1931. * view hierarchy, and calculates a preferred span. It doesn't
  1932. * do any rendering, layout, or model/view translation.
  1933. */
  1934. static class LogicalView extends CompositeView {
  1935. LogicalView(Element elem) {
  1936. super(elem);
  1937. }
  1938. protected int getViewIndexAtPosition(int pos) {
  1939. Element elem = getElement();
  1940. if (elem.getElementCount() > 0) {
  1941. return elem.getElementIndex(pos);
  1942. }
  1943. return 0;
  1944. }
  1945. protected boolean
  1946. updateChildren(DocumentEvent.ElementChange ec,
  1947. DocumentEvent e, ViewFactory f)
  1948. {
  1949. return false;
  1950. }
  1951. protected void loadChildren(ViewFactory f) {
  1952. Element elem = getElement();
  1953. if (elem.getElementCount() > 0) {
  1954. super.loadChildren(f);
  1955. } else {
  1956. View v = new GlyphView(elem);
  1957. append(v);
  1958. }
  1959. }
  1960. public float getPreferredSpan(int axis) {
  1961. if( getViewCount() != 1 )
  1962. throw new Error("One child view is assumed.");
  1963. View v = getView(0);
  1964. //((GlyphView)v).setGlyphPainter(null);
  1965. return v.getPreferredSpan(axis);
  1966. }
  1967. /**
  1968. * Forward the DocumentEvent to the given child view. This
  1969. * is implemented to reparent the child to the logical view
  1970. * (the children may have been parented by a row in the flow
  1971. * if they fit without breaking) and then execute the
  1972. * superclass behavior.
  1973. *
  1974. * @param v the child view to forward the event to.
  1975. * @param e the change information from the associated document
  1976. * @param a the current allocation of the view
  1977. * @param f the factory to use to rebuild if the view has
  1978. * children
  1979. * @see #forwardUpdate
  1980. * @since 1.3
  1981. */
  1982. protected void forwardUpdateToView(View v, DocumentEvent e,
  1983. Shape a, ViewFactory f) {
  1984. v.setParent(this);
  1985. super.forwardUpdateToView(v, e, a, f);
  1986. }
  1987. // The following methods don't do anything useful, they
  1988. // simply keep the class from being abstract.
  1989. public void paint(Graphics g, Shape allocation) {
  1990. }
  1991. protected boolean isBefore(int x, int y, Rectangle alloc) {
  1992. return false;
  1993. }
  1994. protected boolean isAfter(int x, int y, Rectangle alloc) {
  1995. return false;
  1996. }
  1997. protected View getViewAtPoint(int x, int y, Rectangle alloc) {
  1998. return null;
  1999. }
  2000. protected void childAllocation(int index, Rectangle a) {
  2001. }
  2002. }
  2003. }
  2004. }
  2005. /* This is useful for the nightmare of parsing multi-part HTTP/RFC822 headers
  2006. * sensibly:
  2007. * From a String like: 'timeout=15, max=5'
  2008. * create an array of Strings:
  2009. * { {"timeout", "15"},
  2010. * {"max", "5"}
  2011. * }
  2012. * From one like: 'Basic Realm="FuzzFace" Foo="Biz Bar Baz"'
  2013. * create one like (no quotes in literal):
  2014. * { {"basic", null},
  2015. * {"realm", "FuzzFace"}
  2016. * {"foo", "Biz Bar Baz"}
  2017. * }
  2018. * keys are converted to lower case, vals are left as is....
  2019. *
  2020. * author Dave Brown
  2021. */
  2022. static class HeaderParser {
  2023. /* table of key/val pairs - maxes out at 10!!!!*/
  2024. String raw;
  2025. String[][] tab;
  2026. public HeaderParser(String raw) {
  2027. this.raw = raw;
  2028. tab = new String[10][2];
  2029. parse();
  2030. }
  2031. private void parse() {
  2032. if (raw != null) {
  2033. raw = raw.trim();
  2034. char[] ca = raw.toCharArray();
  2035. int beg = 0, end = 0, i = 0;
  2036. boolean inKey = true;
  2037. boolean inQuote = false;
  2038. int len = ca.length;
  2039. while (end < len) {
  2040. char c = ca[end];
  2041. if (c == '=') { // end of a key
  2042. tab[i][0] = new String(ca, beg, end-beg).toLowerCase();
  2043. inKey = false;
  2044. end++;
  2045. beg = end;
  2046. } else if (c == '\"') {
  2047. if (inQuote) {
  2048. tab[i++][1]= new String(ca, beg, end-beg);
  2049. inQuote=false;
  2050. do {
  2051. end++;
  2052. } while (end < len && (ca[end] == ' ' || ca[end] == ','));
  2053. inKey=true;
  2054. beg=end;
  2055. } else {
  2056. inQuote=true;
  2057. end++;
  2058. beg=end;
  2059. }
  2060. } else if (c == ' ' || c == ',') { // end key/val, of whatever we're in
  2061. if (inQuote) {
  2062. end++;
  2063. continue;
  2064. } else if (inKey) {
  2065. tab[i++][0] = (new String(ca, beg, end-beg)).toLowerCase();
  2066. } else {
  2067. tab[i++][1] = (new String(ca, beg, end-beg));
  2068. }
  2069. while (end < len && (ca[end] == ' ' || ca[end] == ',')) {
  2070. end++;
  2071. }
  2072. inKey = true;
  2073. beg = end;
  2074. } else {
  2075. end++;
  2076. }
  2077. }
  2078. // get last key/val, if any
  2079. if (--end > beg) {
  2080. if (!inKey) {
  2081. if (ca[end] == '\"') {
  2082. tab[i++][1] = (new String(ca, beg, end-beg));
  2083. } else {
  2084. tab[i++][1] = (new String(ca, beg, end-beg+1));
  2085. }
  2086. } else {
  2087. tab[i][0] = (new String(ca, beg, end-beg+1)).toLowerCase();
  2088. }
  2089. } else if (end == beg) {
  2090. if (!inKey) {
  2091. if (ca[end] == '\"') {
  2092. tab[i++][1] = String.valueOf(ca[end-1]);
  2093. } else {
  2094. tab[i++][1] = String.valueOf(ca[end]);
  2095. }
  2096. } else {
  2097. tab[i][0] = String.valueOf(ca[end]).toLowerCase();
  2098. }
  2099. }
  2100. }
  2101. }
  2102. public String findKey(int i) {
  2103. if (i < 0 || i > 10)
  2104. return null;
  2105. return tab[i][0];
  2106. }
  2107. public String findValue(int i) {
  2108. if (i < 0 || i > 10)
  2109. return null;
  2110. return tab[i][1];
  2111. }
  2112. public String findValue(String key) {
  2113. return findValue(key, null);
  2114. }
  2115. public String findValue(String k, String Default) {
  2116. if (k == null)
  2117. return Default;
  2118. k = k.toLowerCase();
  2119. for (int i = 0; i < 10; ++i) {
  2120. if (tab[i][0] == null) {
  2121. return Default;
  2122. } else if (k.equals(tab[i][0])) {
  2123. return tab[i][1];
  2124. }
  2125. }
  2126. return Default;
  2127. }
  2128. public int findInt(String k, int Default) {
  2129. try {
  2130. return Integer.parseInt(findValue(k, String.valueOf(Default)));
  2131. } catch (Throwable t) {
  2132. return Default;
  2133. }
  2134. }
  2135. }
  2136. }