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