1. /*
  2. * @(#)JEditorPane.java 1.77 01/11/29
  3. *
  4. * Copyright 2002 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. * This component uses implementations of the
  22. * EditorKit to accomplish its behavior. It effectively
  23. * morphs into the proper kind of text editor for the kind
  24. * of content it is given. The content type that editor is bound
  25. * to at any given time is determined by the EditorKit currently
  26. * installed. If the content is set to a new URL, its type is used
  27. * to determine the EditorKit that should be used to load the content.
  28. * <p>
  29. * By default, the following types of content are known:
  30. * <dl>
  31. * <dt><b>text/plain</b>
  32. * <dd>Plain text, which is the default the type given isn't
  33. * recognized. The kit used in this case is an extension of
  34. * DefaultEditorKit that produces a wrapped plain text view.
  35. * <dt><b>text/html</b>
  36. * <dd>HTML text. The kit used in this case is the class
  37. * <code>javax.swing.text.html.HTMLEditorKit</code>
  38. * which provides html 3.2 support.
  39. * <dt><b>text/rtf</b>
  40. * <dd>RTF text. The kit used in this case is the class
  41. * <code>javax.swing.text.rtf.RTFEditorKit</code>
  42. * which provides a limited support of the Rich Text Format.
  43. * </dl>
  44. * <p>
  45. * There are several ways to load content into this component.
  46. * <ol>
  47. * <li>
  48. * The <a href="#setText">setText</a> method can be used to initialize
  49. * the component from a string. In this case the current EditorKit
  50. * will be used, and the content type will be expected to be of this
  51. * type.
  52. * <li>
  53. * The <a href="#read">read</a> method can be used to initialize the
  54. * component from a Reader. Note that if the content type is html,
  55. * relative references (e.g. for things like images) can't be resolved
  56. * unless the <base> tag is used or the <em>Base</em> property
  57. * on HTMLDocument is set. In this case the current EditorKit
  58. * will be used, and the content type will be expected to be of this
  59. * type.
  60. * <li>
  61. * The <a href="#setPage">setPage</a> method can be used to initialize
  62. * the component from a URL. In this case, the content type will be
  63. * determined from the URL, and the registered EditorKit for that content
  64. * type will be set.
  65. * </ol>
  66. * <p>
  67. * For the keyboard keys used by this component in the standard Look and
  68. * Feel (L&F) renditions, see the
  69. * <a href="doc-files/Key-Index.html#JEditorPane">JEditorPane</a> key assignments.
  70. * <p>
  71. * Some kinds of content may provide hyperlink support by generating
  72. * hyperlink events. The html EditorKit will generate hyperlink events
  73. * if the JEditorPane is <em>not editable</em>
  74. * (i.e. <code>JEditorPane.setEditable(false);</code> has been called).
  75. * If html frames are embedded in the document, the typical response would be
  76. * to change a portion of the current document. The following code
  77. * fragment is a possible hyperlink listener implementation, that treats
  78. * html frame events specially, and simply displays any other activated
  79. * hyperlinks.
  80. * <code><pre>
  81. class Hyperactive implements HyperlinkListener {
  82. public void hyperlinkUpdate(HyperlinkEvent e) {
  83. if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
  84. JEditorPane pane = (JEditorPane) e.getSource();
  85. if (e instanceof HTMLFrameHyperlinkEvent) {
  86. HTMLFrameHyperlinkEvent evt = (HTMLFrameHyperlinkEvent)e;
  87. HTMLDocument doc = (HTMLDocument)pane.getDocument();
  88. doc.processHTMLFrameHyperlinkEvent(evt);
  89. } else {
  90. try {
  91. pane.setPage(e.getURL());
  92. } catch (Throwable t) {
  93. t.printStackTrace();
  94. }
  95. }
  96. }
  97. }
  98. }
  99. * </pre></code>
  100. * <p>
  101. * Culturally dependent information in some documents is handled through
  102. * a mechanism called character encoding. Character encoding is an
  103. * unambiguous mapping of the members of a character set (letters, ideographs,
  104. * digits, symbols, or control functions) to specific numeric code values. It
  105. * represents the way the file is stored. Example character encodings are
  106. * ISO-8859-1, ISO-8859-5, Shift-jis, Euc-jp, and UTF-8. When the file is
  107. * passed to an user agent (JEditorPane) it is converted to the document
  108. * character set (ISO-10646 aka Unicode).
  109. * <p>
  110. * There are multiple ways to get a character set mapping to happen
  111. * with JEditorPane.
  112. * <ol>
  113. * <li>
  114. * One way is to specify the character set as a parameter of the MIME
  115. * type. This will be established by a call to the
  116. * <a href="#setContentType">setContentType</a> method. If the content
  117. * is loaded by the <a href="#setPage">setPage</a> method the content
  118. * type will have been set according to the specification of the URL.
  119. * It the file is loaded directly, the content type would be expected to
  120. * have been set prior to loading.
  121. * <li>
  122. * Another way the character set can be specified is in the document itself.
  123. * This requires reading the document prior to determining the character set
  124. * that is desired. To handle this, it is expected that the
  125. * EditorKit.read operation throw a ChangedCharSetException which will
  126. * be caught. The read is then restarted with a new Reader that uses
  127. * the character set specified in the ChangedCharSetException (which is an
  128. * IOException).
  129. * </ol>
  130. * <p>
  131. * <strong>Warning:</strong>
  132. * Serialized objects of this class will not be compatible with
  133. * future Swing releases. The current serialization support is appropriate
  134. * for short term storage or RMI between applications running the same
  135. * version of Swing. A future release of Swing will provide support for
  136. * long term persistence.
  137. *
  138. * @beaninfo
  139. * attribute: isContainer false
  140. *
  141. * @author Timothy Prinzing
  142. * @version 1.77 11/29/01
  143. */
  144. public class JEditorPane extends JTextComponent {
  145. /**
  146. * Constructs a new JEditorPane. The document model is set to null.
  147. */
  148. public JEditorPane() {
  149. super();
  150. }
  151. /**
  152. * Creates a JEditorPane based on a specified URL for input.
  153. *
  154. * @param initialPage the URL
  155. * @exception IOException if the URL is null or cannot be accessed
  156. */
  157. public JEditorPane(URL initialPage) throws IOException {
  158. this();
  159. setPage(initialPage);
  160. }
  161. /**
  162. * Creates a JEditorPane based on a string containing a URL specification.
  163. *
  164. * @param url the URL
  165. * @exception IOException if the URL is null or cannot be accessed
  166. */
  167. public JEditorPane(String url) throws IOException {
  168. this();
  169. setPage(url);
  170. }
  171. /**
  172. * Creates a JEditorPane that has been initialized to the given
  173. * text. This is a convenience constructor that calls the
  174. * <code>setContentType</code> and <code>setText</code> methods.
  175. *
  176. * @param type mime type of the given text.
  177. * @param text the text to initialize with.
  178. */
  179. public JEditorPane(String type, String text) {
  180. this();
  181. setContentType(type);
  182. setText(text);
  183. }
  184. /**
  185. * Adds a hyperlink listener for notification of any changes, for example
  186. * when a link is selected and entered.
  187. *
  188. * @param listener the listener
  189. */
  190. public synchronized void addHyperlinkListener(HyperlinkListener listener) {
  191. listenerList.add(HyperlinkListener.class, listener);
  192. }
  193. /**
  194. * Removes a hyperlink listener.
  195. *
  196. * @param listener the listener
  197. */
  198. public synchronized void removeHyperlinkListener(HyperlinkListener listener) {
  199. listenerList.remove(HyperlinkListener.class, listener);
  200. }
  201. /**
  202. * Notifies all listeners that have registered interest for
  203. * notification on this event type. This is normally called
  204. * by the currently installed EditorKit if a content type
  205. * that supports hyperlinks is currently active and there
  206. * was activity with a link. The listener list is processed
  207. * last to first.
  208. *
  209. * @param e the event
  210. * @see EventListenerList
  211. */
  212. public void fireHyperlinkUpdate(HyperlinkEvent e) {
  213. // Guaranteed to return a non-null array
  214. Object[] listeners = listenerList.getListenerList();
  215. // Process the listeners last to first, notifying
  216. // those that are interested in this event
  217. for (int i = listeners.length-2; i>=0; i-=2) {
  218. if (listeners[i]==HyperlinkListener.class) {
  219. ((HyperlinkListener)listeners[i+1]).hyperlinkUpdate(e);
  220. }
  221. }
  222. }
  223. /**
  224. * Sets the current url being displayed. The content type of the
  225. * pane is set, and if the editor kit for the pane is non-null, then
  226. * a new default document is created and the URL is read into it.
  227. * If the url contains and reference location, the location will
  228. * be scrolled to by calling the <code>scrollToReference</code>
  229. * method. If the desired URL is not the one currently being
  230. * displayed, the <code>getStream</code> method is called to
  231. * give subclasses control over the stream provided.
  232. * <p>
  233. * This may load either synchronously or asynchronously
  234. * depending upon the document returned by the EditorKit.
  235. * If the Document is of type AbstractDocument and has
  236. * a value returned by
  237. * <code>AbstractDocument.getAsynchronousLoadPriority</code>
  238. * that is greater than or equal to zero, the page will be
  239. * loaded on a seperate thread using that priority.
  240. * <p>
  241. * If the document is loaded synchronously, it will be
  242. * filled in with the stream prior to being installed into
  243. * the editor with a call to <code>setDocument</code>, which
  244. * is bound and will fire a property change event. If an
  245. * IOException is thrown the partially loaded document will
  246. * be discarded and neither the document or page property
  247. * change events will be fired. If the document is
  248. * successfully loaded and installed, a view will be
  249. * built for it by the UI which will then be scrolled if
  250. * necessary, and then the page property change event
  251. * will be fired.
  252. * <p>
  253. * If the document is loaded asynchronously, the document
  254. * will be installed into the editor immediately using a
  255. * call to <code>setDocument</code> which will fire a
  256. * document property change event, then a thread will be
  257. * created which will begin doing the actual loading.
  258. * In this case, the page property change event will not be
  259. * fired by the call to this method directly, but rather will be
  260. * fired when the thread doing the loading has finished.
  261. * Since the calling thread can not throw an IOException in
  262. * the event of failure on the other thread, the page
  263. * property change event will be fired when the other
  264. * thread is done whether the load was successful or not.
  265. *
  266. * @param page the URL of the page
  267. * @exception IOException for a null or invalid page specification,
  268. * or exception from the stream being read.
  269. * @see #getPage
  270. * @beaninfo
  271. * description: the URL used to set content
  272. * bound: true
  273. * expert: true
  274. */
  275. public void setPage(URL page) throws IOException {
  276. if (page == null) {
  277. throw new IOException("invalid url");
  278. }
  279. URL loaded = getPage();
  280. // reset scrollbar
  281. scrollRectToVisible(new Rectangle(0,0,1,1));
  282. boolean reloaded = false;
  283. if ((loaded == null) || (! loaded.sameFile(page))) {
  284. // different url, load the new content
  285. InputStream in = getStream(page);
  286. if (kit != null) {
  287. Document doc = kit.createDefaultDocument();
  288. if (pageProperties != null) {
  289. // transfer properties discovered in stream to the
  290. // document property collection.
  291. for (Enumeration e = pageProperties.keys(); e.hasMoreElements() ;) {
  292. Object key = e.nextElement();
  293. doc.putProperty(key, pageProperties.get(key));
  294. }
  295. pageProperties.clear();
  296. }
  297. if (doc.getProperty(Document.StreamDescriptionProperty) == null) {
  298. doc.putProperty(Document.StreamDescriptionProperty, page);
  299. }
  300. // At this point, one could either load up the model with no
  301. // view notifications slowing it down (i.e. best synchronous
  302. // behavior) or set the model and start to feed it on a seperate
  303. // thread (best asynchronous behavior).
  304. if (doc instanceof AbstractDocument) {
  305. AbstractDocument adoc = (AbstractDocument) doc;
  306. int p = adoc.getAsynchronousLoadPriority();
  307. if (p >= 0) {
  308. // load asynchronously
  309. setDocument(doc);
  310. Thread pl = new PageLoader(in, p, loaded, page);
  311. pl.start();
  312. return;
  313. }
  314. }
  315. read(in, doc);
  316. setDocument(doc);
  317. reloaded = true;
  318. }
  319. }
  320. final String reference = page.getRef();
  321. if (reference != null) {
  322. if (!reloaded) {
  323. scrollToReference(reference);
  324. }
  325. else {
  326. // Have to scroll after painted.
  327. SwingUtilities.invokeLater(new Runnable() {
  328. public void run() {
  329. scrollToReference(reference);
  330. }
  331. });
  332. }
  333. }
  334. firePropertyChange("page", loaded, page);
  335. }
  336. /**
  337. * This method initializes from a stream. If
  338. * the kit is set to be of type HTMLEditorKit,
  339. * and the desc parameter is an HTMLDocument,
  340. * then it invokes the HTMLEditorKit to initiate
  341. * the read. Otherwise it calls the superclass
  342. * method which loads the model as plain text.
  343. *
  344. * @param in The stream to read from
  345. * @param desc An object describing the stream.
  346. * @exception IOException as thrown by the stream being
  347. * used to initialize.
  348. * @see JTextComponent#read
  349. * @see #setDocument
  350. */
  351. public void read(InputStream in, Object desc) throws IOException {
  352. if (desc instanceof HTMLDocument &&
  353. kit instanceof HTMLEditorKit) {
  354. HTMLDocument hdoc = (HTMLDocument) desc;
  355. setDocument(hdoc);
  356. read(in, hdoc);
  357. } else {
  358. super.read(new InputStreamReader(in, charSetName), desc);
  359. }
  360. }
  361. /**
  362. * This method invokes the editorKit to initiate a read. In the
  363. * case where a ChangedCharSetException is thrown this exception
  364. * will contain the new CharSet. Therefore the read() operation
  365. * is then restarted after building a new Reader with the new charset.
  366. *
  367. * @param the inputstream to use.
  368. * @param the document to load.
  369. *
  370. */
  371. void read(InputStream in, Document doc) throws IOException {
  372. try {
  373. kit.read(new InputStreamReader(in, charSetName), doc, 0);
  374. } catch (BadLocationException e) {
  375. throw new IOException(e.getMessage());
  376. } catch (ChangedCharSetException e1) {
  377. String charSetSpec = e1.getCharSetSpec();
  378. if (e1.keyEqualsCharSet()) {
  379. charSetName = charSetSpec;
  380. } else {
  381. setCharsetFromContentTypeParameters(charSetSpec);
  382. }
  383. in.close();
  384. URL url = (URL)doc.getProperty(Document.StreamDescriptionProperty);
  385. URLConnection conn = url.openConnection();
  386. in = conn.getInputStream();
  387. try {
  388. doc.remove(0, doc.getLength());
  389. } catch (BadLocationException e) {}
  390. doc.putProperty("IgnoreCharsetDirective", new Boolean(true));
  391. read(in, doc);
  392. }
  393. }
  394. /**
  395. * Thread to load a stream into the text document model.
  396. */
  397. class PageLoader extends Thread {
  398. /**
  399. * Construct an asynchronous page loader.
  400. */
  401. PageLoader(InputStream in, int priority, URL old, URL page) {
  402. setPriority(priority);
  403. this.in = in;
  404. this.old = old;
  405. this.page = page;
  406. }
  407. /**
  408. * Try to load the document, then scroll the view
  409. * to the reference (if specified). When done, fire
  410. * a page property change event.
  411. */
  412. public void run() {
  413. Document doc = getDocument();
  414. try {
  415. read(in, doc);
  416. URL page = (URL) doc.getProperty(Document.StreamDescriptionProperty);
  417. String reference = page.getRef();
  418. if (reference != null) {
  419. // scroll the page if necessary, but do it on the
  420. // event thread... that is the only guarantee that
  421. // modelToView can be safely called.
  422. Runnable callScrollToReference = new Runnable() {
  423. public void run() {
  424. URL u = (URL) getDocument().getProperty
  425. (Document.StreamDescriptionProperty);
  426. String ref = u.getRef();
  427. scrollToReference(ref);
  428. }
  429. };
  430. SwingUtilities.invokeLater(callScrollToReference);
  431. }
  432. } catch (IOException ioe) {
  433. getToolkit().beep();
  434. } finally {
  435. firePropertyChange("page", old, page);
  436. }
  437. }
  438. /**
  439. * The stream to load the document with
  440. */
  441. InputStream in;
  442. /**
  443. * URL of the old page that was replaced (for the property change event)
  444. */
  445. URL old;
  446. /**
  447. * URL of the page being loaded (for the property change event)
  448. */
  449. URL page;
  450. }
  451. /**
  452. * Fetch a stream for the given url, which is about to
  453. * be loaded by the <code>setPage</code> method. By
  454. * default, this simply opens the url and returns the
  455. * stream. This can be reimplemented to do useful things
  456. * like fetch the stream from a cache, monitor the progress
  457. * of the stream, etc.
  458. * <p>
  459. * This method is expected to have the the side effect of
  460. * establising the content type, and therefore setting the
  461. * appropriate EditorKit to use for loading the stream.
  462. */
  463. protected InputStream getStream(URL page) throws IOException {
  464. URLConnection conn = page.openConnection();
  465. if (conn instanceof HttpURLConnection) {
  466. HttpURLConnection hconn = (HttpURLConnection) conn;
  467. hconn.setFollowRedirects(false);
  468. int response = hconn.getResponseCode();
  469. boolean redirect = (response >= 300 && response <= 399);
  470. /*
  471. * In the case of a redirect, we want to actually change the URL
  472. * that was input to the new, redirected URL
  473. */
  474. if (redirect) {
  475. String loc = conn.getHeaderField("Location");
  476. if (loc.startsWith("http", 0)) {
  477. page = new URL(loc);
  478. } else {
  479. page = new URL(page, loc);
  480. }
  481. return getStream(page);
  482. }
  483. }
  484. if (pageProperties == null) {
  485. pageProperties = new Hashtable();
  486. }
  487. String type = conn.getContentType();
  488. if (type != null) {
  489. setContentType(type);
  490. pageProperties.put("content-type", type);
  491. }
  492. pageProperties.put(Document.StreamDescriptionProperty, page);
  493. String enc = conn.getContentEncoding();
  494. if (enc != null) {
  495. pageProperties.put("content-encoding", enc);
  496. }
  497. InputStream in = conn.getInputStream();
  498. return in;
  499. }
  500. /**
  501. * Scroll the view to the given reference location
  502. * (i.e. the value returned by the <code>UL.getRef</code>
  503. * method for the url being displayed). By default, this
  504. * method only knows how to locate a reference in an
  505. * HTMLDocument. The implementation calls the
  506. * <code>scrollRectToVisible</code> method to
  507. * accomplish the actual scrolling. If scrolling to a
  508. * reference location is needed for document types other
  509. * than html, this method should be reimplemented.
  510. * This method will have no effect if the component
  511. * is not visible.
  512. *
  513. * @param reference the named location to scroll to.
  514. */
  515. protected void scrollToReference(String reference) {
  516. Document d = getDocument();
  517. if (d instanceof HTMLDocument) {
  518. HTMLDocument doc = (HTMLDocument) d;
  519. HTMLDocument.Iterator iter = doc.getIterator(HTML.Tag.A);
  520. for (; iter.isValid(); iter.next()) {
  521. AttributeSet a = iter.getAttributes();
  522. String nm = (String) a.getAttribute(HTML.Attribute.NAME);
  523. if ((nm != null) && nm.equals(reference)) {
  524. // found a matching reference in the document.
  525. try {
  526. Rectangle r = modelToView(iter.getStartOffset());
  527. if (r != null) {
  528. // the view is visible, scroll it to the
  529. // center of the current visible area.
  530. Rectangle vis = getVisibleRect();
  531. r.y -= (vis.height / 2);
  532. r.height = vis.height;
  533. scrollRectToVisible(r);
  534. }
  535. } catch (BadLocationException ble) {
  536. getToolkit().beep();
  537. }
  538. }
  539. }
  540. }
  541. }
  542. /**
  543. * Gets the current url being displayed. If a URL was
  544. * not specified in the creation of the document, this
  545. * will return null, and relative URL's will not be
  546. * resolved.
  547. *
  548. * @return the URL
  549. */
  550. public URL getPage() {
  551. return (URL) getDocument().getProperty(Document.StreamDescriptionProperty);
  552. }
  553. /**
  554. * Sets the current url being displayed.
  555. *
  556. * @param url the URL for display
  557. * @exception IOException for a null or invalid URL specification
  558. */
  559. public void setPage(String url) throws IOException {
  560. if (url == null) {
  561. throw new IOException("invalid url");
  562. }
  563. URL page = new URL(url);
  564. setPage(page);
  565. }
  566. /**
  567. * Gets the class ID for the UI.
  568. *
  569. * @return the ID ("EditorPaneUI")
  570. * @see JComponent#getUIClassID
  571. * @see UIDefaults#getUI
  572. */
  573. public String getUIClassID() {
  574. return uiClassID;
  575. }
  576. /**
  577. * Creates the default editor kit (PlainEditorKit) for when
  578. * the component is first created.
  579. *
  580. * @return the editor kit
  581. */
  582. protected EditorKit createDefaultEditorKit() {
  583. return new PlainEditorKit();
  584. }
  585. /**
  586. * Fetches the currently installed kit for handling
  587. * content. createDefaultEditorKit() is called to set up a default
  588. * if necessary.
  589. *
  590. * @return the editor kit
  591. */
  592. public final EditorKit getEditorKit() {
  593. if (kit == null) {
  594. kit = createDefaultEditorKit();
  595. }
  596. return kit;
  597. }
  598. /**
  599. * Gets the type of content that this editor
  600. * is currently set to deal with. This is
  601. * defined to be the type associated with the
  602. * currently installed EditorKit.
  603. *
  604. * @return the content type, null if no editor kit set
  605. */
  606. public final String getContentType() {
  607. return (kit != null) ? kit.getContentType() : null;
  608. }
  609. /**
  610. * Sets the type of content that this editor
  611. * handles. This calls <code>getEditorKitForContentType</code>,
  612. * and then <code>setEditorKit</code> if an editor kit can
  613. * be successfully located. This is mostly convenience method
  614. * that can be used as an alternative to calling
  615. * <code>setEditorKit</code> directly.
  616. * <p>
  617. * If there is a charset definition specified as a parameter
  618. * of the content type specification, it will be used when
  619. * loading input streams using the associated EditorKit.
  620. * For example if the type is specified as
  621. * <code>text/html; charset=EUC-JP</code> the content
  622. * will be loaded using the EditorKit registered for
  623. * <code>text/html</code> and the Reader provided to
  624. * the EditorKit to load unicode into the document will
  625. * use the <code>EUC-JP</code> charset for translating
  626. * to unicode.
  627. *
  628. * @param type the non-null mime type for the content editing
  629. * support.
  630. * @see #getContentType
  631. * @beaninfo
  632. * description: the type of content
  633. */
  634. public final void setContentType(String type) {
  635. // The type could have optional info is part of it,
  636. // for example some charset info. We need to strip that
  637. // of and save it.
  638. int parm = type.indexOf(";");
  639. if (parm > -1) {
  640. // Save the paramList.
  641. String paramList = type.substring(parm);
  642. // update the content type string.
  643. type = type.substring(0, parm).trim();
  644. if (type.toLowerCase().startsWith("text/")) {
  645. setCharsetFromContentTypeParameters(paramList);
  646. }
  647. }
  648. if ((kit == null) || (! type.equals(kit.getContentType()))) {
  649. EditorKit k = getEditorKitForContentType(type);
  650. if (k != null) {
  651. setEditorKit(k);
  652. }
  653. }
  654. }
  655. /**
  656. * This method get's the charset information specified as part
  657. * of the content type in the http header information.
  658. */
  659. private void setCharsetFromContentTypeParameters(String paramlist) {
  660. String charset = null;
  661. try {
  662. // paramlist is handed to us with a leading ';', strip it.
  663. int semi = paramlist.indexOf(';');
  664. if (semi > -1 && semi < paramlist.length()-1) {
  665. paramlist = paramlist.substring(semi + 1);
  666. }
  667. if (paramlist.length() > 0) {
  668. // parse the paramlist into attr-value pairs & get the
  669. // charset pair's value
  670. HeaderParser hdrParser = new HeaderParser(paramlist);
  671. charset = hdrParser.findValue("charset");
  672. charSetName = charset;
  673. }
  674. }
  675. catch (IndexOutOfBoundsException e) {
  676. // malformed parameter list, use charset we have
  677. }
  678. catch (NullPointerException e) {
  679. // malformed parameter list, use charset we have
  680. }
  681. catch (Exception e) {
  682. // malformed parameter list, use charset we have; but complain
  683. System.err.println("JEditorPane.getCharsetFromContentTypeParameters failed on: " + paramlist);
  684. e.printStackTrace();
  685. }
  686. }
  687. /**
  688. * Sets the currently installed kit for handling
  689. * content. This is the bound property that
  690. * establishes the content type of the editor.
  691. * Any old kit is first deinstalled, then if kit is non-null,
  692. * the new kit is installed, and a default document created for it.
  693. * A PropertyChange event ("editorKit") is always fired when
  694. * setEditorKit() is called.
  695. * <p>
  696. * <em>NOTE: This has the side effect of changing the model,
  697. * because the EditorKit is the source of how a particular type
  698. * of content is modeled. This method will cause setDocument
  699. * to be called on behalf of the caller to insure integrity
  700. * of the internal state.</em>
  701. *
  702. * @param kit the desired editor behavior.
  703. * @see #getEditorKit
  704. * @beaninfo
  705. * description: the currently installed kit for handling content
  706. * bound: true
  707. * expert: true
  708. */
  709. public void setEditorKit(EditorKit kit) {
  710. EditorKit old = this.kit;
  711. if (old != null) {
  712. old.deinstall(this);
  713. }
  714. this.kit = kit;
  715. if (this.kit != null) {
  716. this.kit.install(this);
  717. setDocument(this.kit.createDefaultDocument());
  718. }
  719. firePropertyChange("editorKit", old, kit);
  720. }
  721. /**
  722. * Fetches the editor kit to use for the given type
  723. * of content. This is called when a type is requested
  724. * that doesn't match the currently installed type.
  725. * If the component doesn't have an EditorKit registered
  726. * for the given type, it will try to create an
  727. * EditorKit from the default EditorKit registry.
  728. * If that fails, a PlainEditorKit is used on the
  729. * assumption that all text documents can be represented
  730. * as plain text.
  731. * <p>
  732. * This method can be reimplemented to use some
  733. * other kind of type registry. This can
  734. * be reimplemented to use the Java Activation
  735. * Framework for example.
  736. *
  737. * @param type the non-null content type
  738. * @return the editor kit
  739. */
  740. public EditorKit getEditorKitForContentType(String type) {
  741. if (typeHandlers == null) {
  742. typeHandlers = new Hashtable(3);
  743. }
  744. EditorKit k = (EditorKit) typeHandlers.get(type);
  745. if (k == null) {
  746. k = createEditorKitForContentType(type);
  747. if (k != null) {
  748. setEditorKitForContentType(type, k);
  749. }
  750. }
  751. if (k == null) {
  752. k = createDefaultEditorKit();
  753. }
  754. return k;
  755. }
  756. /**
  757. * Directly set the editor kit to use for the given type. A
  758. * look-and-feel implementation might use this in conjunction
  759. * with createEditorKitForContentType to install handlers for
  760. * content types with a look-and-feel bias.
  761. *
  762. * @param type the non-null content type
  763. * @param k the editor kit to be set
  764. */
  765. public void setEditorKitForContentType(String type, EditorKit k) {
  766. if (typeHandlers == null) {
  767. typeHandlers = new Hashtable(3);
  768. }
  769. typeHandlers.put(type, k);
  770. }
  771. /**
  772. * Replaces the currently selected content with new content
  773. * represented by the given string. If there is no selection
  774. * this amounts to an insert of the given text. If there
  775. * is no replacement text this amounts to a removal of the
  776. * current selection. The replacement text will have the
  777. * attributes currently defined for input. If the document is not
  778. * editable, beep and return. Then if the document is null, do nothing.
  779. * If the content to insert is null or empty, ignore it.
  780. * <p>
  781. * This method is thread safe, although most Swing methods
  782. * are not. Please see
  783. * <A HREF="http://java.sun.com/products/jfc/swingdoc-archive/threads.html">Threads
  784. * and Swing</A> for more information.
  785. *
  786. * @param content the content to replace the selection with
  787. */
  788. public void replaceSelection(String content) {
  789. if (! isEditable()) {
  790. getToolkit().beep();
  791. return;
  792. }
  793. EditorKit kit = getEditorKit();
  794. if(kit instanceof StyledEditorKit) {
  795. try {
  796. Document doc = getDocument();
  797. Caret caret = getCaret();
  798. int p0 = Math.min(caret.getDot(), caret.getMark());
  799. int p1 = Math.max(caret.getDot(), caret.getMark());
  800. if (p0 != p1) {
  801. doc.remove(p0, p1 - p0);
  802. }
  803. if (content != null && content.length() > 0) {
  804. doc.insertString(p0, content, ((StyledEditorKit)kit).
  805. getInputAttributes());
  806. }
  807. } catch (BadLocationException e) {
  808. getToolkit().beep();
  809. }
  810. }
  811. else {
  812. super.replaceSelection(content);
  813. }
  814. }
  815. /**
  816. * Create a handler for the given type from the default registry
  817. * of editor kits. The registry is created if necessary. If the
  818. * registered class has not yet been loaded, an attempt
  819. * is made to dynamically load the prototype of the kit for the
  820. * given type. If the type was registered with a ClassLoader,
  821. * that ClassLoader will be used to load the prototype. If there
  822. * was no registered ClassLoader, Class.forName will be used to
  823. * load the prototype.
  824. * <p>
  825. * Once a prototype EditorKit instance is successfully located,
  826. * it is cloned and the clone is returned.
  827. *
  828. * @param type the content type
  829. * @return the editor kit, or null if there is nothing
  830. * registered for the given type.
  831. */
  832. public static EditorKit createEditorKitForContentType(String type) {
  833. EditorKit k = null;
  834. Hashtable kitRegistry =
  835. (Hashtable)SwingUtilities.appContextGet(kitRegistryKey);
  836. if (kitRegistry == null) {
  837. // nothing has been loaded yet.
  838. kitRegistry = new Hashtable();
  839. SwingUtilities.appContextPut(kitRegistryKey, kitRegistry);
  840. } else {
  841. k = (EditorKit) kitRegistry.get(type);
  842. }
  843. if (k == null) {
  844. // try to dynamically load the support
  845. String classname = (String) getKitTypeRegistry().get(type);
  846. ClassLoader loader = (ClassLoader) getKitLoaderRegistry().get(type);
  847. try {
  848. Class c;
  849. if (loader != null) {
  850. c = loader.loadClass(classname);
  851. } else {
  852. c = Class.forName(classname);
  853. }
  854. k = (EditorKit) c.newInstance();
  855. kitRegistry.put(type, k);
  856. } catch (Throwable e) {
  857. k = null;
  858. }
  859. }
  860. // create a copy of the prototype or null if there
  861. // is no prototype.
  862. if (k != null) {
  863. return (EditorKit) k.clone();
  864. }
  865. return null;
  866. }
  867. /**
  868. * Establishes the default bindings of type to name.
  869. * The class will be dynamically loaded later when actually
  870. * needed, and can be safely changed before attempted uses
  871. * to avoid loading unwanted classes. The prototype
  872. * EditorKit will be loaded with Class.forName when
  873. * registered with this method.
  874. *
  875. * @param type the non-null content type
  876. * @param classname the class to load later
  877. */
  878. public static void registerEditorKitForContentType(String type, String classname) {
  879. getKitLoaderRegistry().remove(type);
  880. getKitTypeRegistry().put(type, classname);
  881. }
  882. /**
  883. * Establishes the default bindings of type to name.
  884. * The class will be dynamically loaded later when actually
  885. * needed using the given ClassLoader, and can be safely changed
  886. * before attempted uses to avoid loading unwanted classes.
  887. *
  888. * @param type the non-null content type
  889. * @param classname the class to load later
  890. * @param loader the ClassLoader to use to load the name
  891. */
  892. public static void registerEditorKitForContentType(String type, String classname, ClassLoader loader) {
  893. getKitTypeRegistry().put(type, classname);
  894. getKitLoaderRegistry().put(type, loader);
  895. }
  896. private static Hashtable getKitTypeRegistry() {
  897. Hashtable kitTypeRegistry =
  898. (Hashtable)SwingUtilities.appContextGet(kitTypeRegistryKey);
  899. if (kitTypeRegistry == null) {
  900. kitTypeRegistry = new Hashtable();
  901. SwingUtilities.appContextPut(kitTypeRegistryKey, kitTypeRegistry);
  902. }
  903. return kitTypeRegistry;
  904. }
  905. private static Hashtable getKitLoaderRegistry() {
  906. Hashtable kitLoaderRegistry =
  907. (Hashtable)SwingUtilities.appContextGet(kitLoaderRegistryKey);
  908. if (kitLoaderRegistry == null) {
  909. kitLoaderRegistry = new Hashtable();
  910. SwingUtilities.appContextPut(kitLoaderRegistryKey, kitLoaderRegistry);
  911. }
  912. return kitLoaderRegistry;
  913. }
  914. // --- java.awt.Component methods --------------------------
  915. /**
  916. * The preferred size for JEditorPane is slightly altered
  917. * from the preferred size of the superclass. If the size
  918. * of the viewport has become smaller than the minimum size
  919. * of the component, the Scrollable definition for tracking
  920. * width or height will turn to false. The default viewport
  921. * layout will give the preferred size, and that is not desired
  922. * in the case where the scrollable is tracking. In that case
  923. * the <em>normal</em> preferred size is adjusted to the
  924. * minimum size. This allows things like html tables to
  925. * shrink down to their minimum size and then be laid out at
  926. * their minimum size, refusing to shrink any further.
  927. */
  928. public Dimension getPreferredSize() {
  929. Dimension d = super.getPreferredSize();
  930. if (getParent() instanceof JViewport) {
  931. JViewport port = (JViewport)getParent();
  932. TextUI ui = getUI();
  933. if (! getScrollableTracksViewportWidth()) {
  934. int w = port.getWidth();
  935. Dimension min = ui.getMinimumSize(this);
  936. Dimension max = ui.getMaximumSize(this);
  937. if (w < min.width) {
  938. d.width = min.width;
  939. }
  940. }
  941. if (! getScrollableTracksViewportHeight()) {
  942. int h = port.getHeight();
  943. Dimension min = ui.getMinimumSize(this);
  944. Dimension max = ui.getMaximumSize(this);
  945. if (h < min.height) {
  946. d.height = min.height;
  947. }
  948. }
  949. }
  950. return d;
  951. }
  952. // --- JComponent methods ---------------------------------
  953. /**
  954. * Turns off tab traversal once focus gained.
  955. *
  956. * @return true, to indicate that the focus is being managed
  957. */
  958. public boolean isManagingFocus() {
  959. return true;
  960. }
  961. /**
  962. * Make sure that TAB and Shift-TAB events get consumed, so that
  963. * awt doesn't attempt focus traversal.
  964. *
  965. */
  966. protected void processComponentKeyEvent(KeyEvent e) {
  967. super.processComponentKeyEvent(e);
  968. // tab consumption
  969. // We are actually consuming any TABs modified in any way, because
  970. // we don't want awt to get anything it can use for focus traversal.
  971. if (isManagingFocus()) {
  972. if ((e.getKeyCode() == KeyEvent.VK_TAB || e.getKeyChar() == '\t')) {
  973. e.consume();
  974. }
  975. }
  976. }
  977. // --- JTextComponent methods -----------------------------
  978. /**
  979. * Sets the text of this TextComponent to the specified content,
  980. * which is expected to be in the format of the content type of
  981. * this editor. For example, if the type is set to <code>text/html</code>
  982. * the string should be specified in terms of html.
  983. * <p>
  984. * This is implemented to remove the contents of the current document,
  985. * and replace them by parsing the given string using the current
  986. * EditorKit. This gives the semantics of the superclass by not changing
  987. * out the model, while supporting the content type currently set on
  988. * this component. The assumption is that the previous content is relatively
  989. * small, and that the previous content doesn't have side effects.
  990. * Both of those assumptions can be violated and cause undesirable results.
  991. * <ol>
  992. * <li>
  993. * Leaving the existing model in place means that the old view will be
  994. * torn down, and a new view created, where replacing the document would
  995. * avoid the tear down of the old view.
  996. * <li>
  997. * Some formats (such as html) can install things into the document that
  998. * can influence future contents. HTML can have style information embedded
  999. * that would influence the next content installed unexpectedly.
  1000. * </ol>
  1001. * <p>
  1002. * An alternative way to load this component with a string would be to
  1003. * create a StringReader and call the read method. In this case the model
  1004. * would be replaced after it was initialized with the contents of the string.
  1005. * <p>
  1006. * This method is thread safe, although most Swing methods
  1007. * are not. Please see
  1008. * <A HREF="http://java.sun.com/products/jfc/swingdoc-archive/threads.html">Threads
  1009. * and Swing</A> for more information.
  1010. *
  1011. * @param t the new text to be set
  1012. * @see #getText
  1013. * @beaninfo
  1014. * description: the text of this component
  1015. */
  1016. public void setText(String t) {
  1017. try {
  1018. Document doc = getDocument();
  1019. doc.remove(0, doc.getLength());
  1020. Reader r = new StringReader(t);
  1021. EditorKit kit = getEditorKit();
  1022. kit.read(r, doc, 0);
  1023. } catch (IOException ioe) {
  1024. getToolkit().beep();
  1025. } catch (BadLocationException ble) {
  1026. getToolkit().beep();
  1027. }
  1028. }
  1029. /**
  1030. * Returns the text contained in this TextComponent in terms of the
  1031. * content type of this editor. If an exception is thrown while
  1032. * attempting to retrieve the text, null will be returned. This
  1033. * is implemented to call <code>JTextComponent.write</code> with
  1034. * a <code>StringWriter</code>.
  1035. *
  1036. * @return the text
  1037. * @see #setText
  1038. */
  1039. public String getText() {
  1040. String txt;
  1041. try {
  1042. StringWriter buf = new StringWriter();
  1043. write(buf);
  1044. txt = buf.toString();
  1045. } catch (IOException ioe) {
  1046. txt = null;
  1047. }
  1048. return txt;
  1049. }
  1050. // --- Scrollable ----------------------------------------
  1051. /**
  1052. * Returns true if a viewport should always force the width of this
  1053. * Scrollable to match the width of the viewport.
  1054. *
  1055. * @return true if a viewport should force the Scrollables width to
  1056. * match its own.
  1057. */
  1058. public boolean getScrollableTracksViewportWidth() {
  1059. if (getParent() instanceof JViewport) {
  1060. JViewport port = (JViewport)getParent();
  1061. TextUI ui = getUI();
  1062. int w = port.getWidth();
  1063. Dimension min = ui.getMinimumSize(this);
  1064. Dimension max = ui.getMaximumSize(this);
  1065. if ((w >= min.width) && (w <= max.width)) {
  1066. return true;
  1067. }
  1068. }
  1069. return false;
  1070. }
  1071. /**
  1072. * Returns true if a viewport should always force the height of this
  1073. * Scrollable to match the height of the viewport.
  1074. *
  1075. * @return true if a viewport should force the Scrollables height to
  1076. * match its own.
  1077. */
  1078. public boolean getScrollableTracksViewportHeight() {
  1079. if (getParent() instanceof JViewport) {
  1080. JViewport port = (JViewport)getParent();
  1081. TextUI ui = getUI();
  1082. int h = port.getHeight();
  1083. Dimension min = ui.getMinimumSize(this);
  1084. Dimension max = ui.getMaximumSize(this);
  1085. if ((h >= min.height) && (h <= max.height)) {
  1086. return true;
  1087. }
  1088. }
  1089. return false;
  1090. }
  1091. // --- Serialization ------------------------------------
  1092. /**
  1093. * See readObject() and writeObject() in JComponent for more
  1094. * information about serialization in Swing.
  1095. */
  1096. private void writeObject(ObjectOutputStream s) throws IOException {
  1097. s.defaultWriteObject();
  1098. if ((ui != null) && (getUIClassID().equals(uiClassID))) {
  1099. ui.installUI(this);
  1100. }
  1101. }
  1102. // --- variables ---------------------------------------
  1103. /**
  1104. * Current content binding of the editor.
  1105. */
  1106. private EditorKit kit;
  1107. private Hashtable pageProperties;
  1108. /**
  1109. * Table of registered type handlers for this editor.
  1110. */
  1111. private Hashtable typeHandlers;
  1112. private String charSetName = "8859_1";
  1113. /*
  1114. * Private AppContext keys for this class's static variables.
  1115. */
  1116. private static final Object kitRegistryKey =
  1117. new StringBuffer("JEditorPane.kitRegistry");
  1118. private static final Object kitTypeRegistryKey =
  1119. new StringBuffer("JEditorPane.kitTypeRegistry");
  1120. private static final Object kitLoaderRegistryKey =
  1121. new StringBuffer("JEditorPane.kitLoaderRegistry");
  1122. /**
  1123. * @see #getUIClassID
  1124. * @see #readObject
  1125. */
  1126. private static final String uiClassID = "EditorPaneUI";
  1127. static {
  1128. // set the default bindings
  1129. registerEditorKitForContentType("text/plain", "javax.swing.JEditorPane$PlainEditorKit");
  1130. registerEditorKitForContentType("text/html", "javax.swing.text.html.HTMLEditorKit");
  1131. registerEditorKitForContentType("text/rtf", "javax.swing.text.rtf.RTFEditorKit");
  1132. registerEditorKitForContentType("application/rtf", "javax.swing.text.rtf.RTFEditorKit");
  1133. }
  1134. /**
  1135. * Returns a string representation of this JEditorPane. This method
  1136. * is intended to be used only for debugging purposes, and the
  1137. * content and format of the returned string may vary between
  1138. * implementations. The returned string may be empty but may not
  1139. * be <code>null</code>.
  1140. *
  1141. * @return a string representation of this JEditorPane.
  1142. */
  1143. protected String paramString() {
  1144. String charSetNameString = (charSetName != null ?
  1145. charSetName: "");
  1146. String kitString = (kit != null ?
  1147. kit.toString() : "");
  1148. String typeHandlersString = (typeHandlers != null ?
  1149. typeHandlers.toString() : "");
  1150. return super.paramString() +
  1151. ",charSetName=" + charSetNameString +
  1152. ",kit=" + kitString +
  1153. ",typeHandlers=" + typeHandlersString;
  1154. }
  1155. /////////////////
  1156. // Accessibility support
  1157. ////////////////
  1158. /**
  1159. * Get the AccessibleContext associated with this JEditorPane. A new
  1160. * context is created if necessary.
  1161. *
  1162. * @return the AccessibleContext of this JEditorPane
  1163. */
  1164. public AccessibleContext getAccessibleContext() {
  1165. if (accessibleContext == null) {
  1166. if (JEditorPane.this.getEditorKit() instanceof HTMLEditorKit) {
  1167. accessibleContext = new AccessibleJEditorPaneHTML();
  1168. } else {
  1169. accessibleContext = new AccessibleJEditorPane();
  1170. }
  1171. }
  1172. return accessibleContext;
  1173. }
  1174. /**
  1175. * The class used to obtain the accessible role for this object.
  1176. * <p>
  1177. * <strong>Warning:</strong>
  1178. * Serialized objects of this class will not be compatible with
  1179. * future Swing releases. The current serialization support is appropriate
  1180. * for short term storage or RMI between applications running the same
  1181. * version of Swing. A future release of Swing will provide support for
  1182. * long term persistence.
  1183. */
  1184. protected class AccessibleJEditorPane extends AccessibleJTextComponent {
  1185. /**
  1186. * Gets the accessibleDescription property of this object. If this
  1187. * property isn't set, return the content type of this JEditorPane
  1188. * instead (e.g. "plain/text", "html/text", etc.
  1189. *
  1190. * @return the localized description of the object; null if
  1191. * this object does not have a description
  1192. *
  1193. * @see #setAccessibleName
  1194. */
  1195. public String getAccessibleDescription() {
  1196. if (accessibleDescription != null) {
  1197. return accessibleDescription;
  1198. } else {
  1199. return JEditorPane.this.getContentType();
  1200. }
  1201. }
  1202. /**
  1203. * Gets the state set of this object.
  1204. *
  1205. * @return an instance of AccessibleStateSet describing the states
  1206. * of the object
  1207. * @see AccessibleStateSet
  1208. */
  1209. public AccessibleStateSet getAccessibleStateSet() {
  1210. AccessibleStateSet states = super.getAccessibleStateSet();
  1211. states.add(AccessibleState.MULTI_LINE);
  1212. return states;
  1213. }
  1214. }
  1215. /**
  1216. * This class provides support for AccessibleHypertext, and is used
  1217. * in instances where the EditorKit installed in this JEditorPane is
  1218. * an instance of HTMLEditorKit.
  1219. * <p>
  1220. * <strong>Warning:</strong>
  1221. * Serialized objects of this class will not be compatible with
  1222. * future Swing releases. The current serialization support is appropriate
  1223. * for short term storage or RMI between applications running the same
  1224. * version of Swing. A future release of Swing will provide support for
  1225. * baseline for serialized form of Swing objects.
  1226. */
  1227. protected class AccessibleJEditorPaneHTML extends AccessibleJEditorPane {
  1228. public AccessibleText getAccessibleText() {
  1229. return new JEditorPaneAccessibleHypertextSupport();
  1230. }
  1231. }
  1232. /**
  1233. * What's returned by AccessibleJEditorPaneHTML.getAccessibleText()
  1234. *
  1235. * Provides support for AccessibleHypertext in case there is an
  1236. * HTML document being displayed in this JEditorPane.
  1237. *
  1238. */
  1239. protected class JEditorPaneAccessibleHypertextSupport
  1240. extends AccessibleJEditorPane implements AccessibleHypertext {
  1241. public class HTMLLink extends AccessibleHyperlink {
  1242. Element element;
  1243. public HTMLLink(Element e) {
  1244. element = e;
  1245. }
  1246. /**
  1247. * Since the document a link is associated with may have
  1248. * changed, this method returns whether this Link is valid
  1249. * anymore (with respect to the document it references).
  1250. *
  1251. * @return a flag indicating whether this link is still valid with
  1252. * respect to the AccessibleHypertext it belongs to
  1253. */
  1254. public boolean isValid() {
  1255. return JEditorPaneAccessibleHypertextSupport.this.linksValid;
  1256. }
  1257. /**
  1258. * Returns the number of accessible actions available in this Link
  1259. * If there are more than one, the first one is NOT considered the
  1260. * "default" action of this LINK object (e.g. in an HTML imagemap).
  1261. * In general, links will have only one AccessibleAction in them.
  1262. *
  1263. * @return the zero-based number of Actions in this object
  1264. */
  1265. public int getAccessibleActionCount() {
  1266. return 1;
  1267. }
  1268. /**
  1269. * Perform the specified Action on the object
  1270. *
  1271. * @param i zero-based index of actions
  1272. * @return true if the the action was performed; else false.
  1273. * @see #getAccessibleActionCount
  1274. */
  1275. public boolean doAccessibleAction(int i) {
  1276. if (i == 0 && isValid() == true) {
  1277. URL u = (URL) getAccessibleActionObject(i);
  1278. if (u != null) {
  1279. HyperlinkEvent linkEvent =
  1280. new HyperlinkEvent(JEditorPane.this, HyperlinkEvent.EventType.ACTIVATED, u);
  1281. JEditorPane.this.fireHyperlinkUpdate(linkEvent);
  1282. return true;
  1283. }
  1284. }
  1285. return false; // link invalid or i != 0
  1286. }
  1287. /**
  1288. * Return a String description of this particular
  1289. * link action. The string returned is the text
  1290. * within the document associated with the element
  1291. * which contains this link.
  1292. *
  1293. * @param i zero-based index of the actions
  1294. * @return a String description of the action
  1295. * @see #getAccessibleActionCount
  1296. */
  1297. public String getAccessibleActionDescription(int i) {
  1298. if (i == 0 && isValid() == true) {
  1299. Document d = JEditorPane.this.getDocument();
  1300. if (d != null) {
  1301. try {
  1302. return d.getText(getStartIndex(),
  1303. getEndIndex() - getStartIndex());
  1304. } catch (BadLocationException exception) {
  1305. return null;
  1306. }
  1307. }
  1308. }
  1309. return null;
  1310. }
  1311. /**
  1312. * Returns a URL object that represents the link.
  1313. *
  1314. * @param i zero-based index of the actions
  1315. * @return an URL representing the HTML link itself
  1316. * @see #getAccessibleActionCount
  1317. */
  1318. public Object getAccessibleActionObject(int i) {
  1319. if (i == 0 && isValid() == true) {
  1320. AttributeSet as = element.getAttributes();
  1321. AttributeSet anchor =
  1322. (AttributeSet) as.getAttribute(HTML.Tag.A);
  1323. String href = (anchor != null) ?
  1324. (String) anchor.getAttribute(HTML.Attribute.HREF) : null;
  1325. if (href != null) {
  1326. URL u;
  1327. try {
  1328. u = new URL(JEditorPane.this.getPage(), href);
  1329. } catch (MalformedURLException m) {
  1330. u = null;
  1331. }
  1332. return u;
  1333. }
  1334. }
  1335. return null; // link invalid or i != 0
  1336. }
  1337. /**
  1338. * Return an object that represents the link anchor,
  1339. * as appropriate for that link. E.g. from HTML:
  1340. * <a href="http://www.sun.com/access">Accessibility</a>
  1341. * this method would return a String containing the text:
  1342. * 'Accessibility'.
  1343. *
  1344. * Similarly, from this HTML:
  1345. * <a HREF="#top"><img src="top-hat.gif" alt="top hat"></a>
  1346. * this might return the object ImageIcon("top-hat.gif", "top hat");
  1347. *
  1348. * @param i zero-based index of the actions
  1349. * @return an Object representing the hypertext anchor
  1350. * @see #getAccessibleActionCount
  1351. */
  1352. public Object getAccessibleActionAnchor(int i) {
  1353. return getAccessibleActionDescription(i);
  1354. }
  1355. /**
  1356. * Get the index with the hypertext document at which this
  1357. * link begins
  1358. *
  1359. * @return index of start of link
  1360. */
  1361. public int getStartIndex() {
  1362. return element.getStartOffset();
  1363. }
  1364. /**
  1365. * Get the index with the hypertext document at which this
  1366. * link ends
  1367. *
  1368. * @return index of end of link
  1369. */
  1370. public int getEndIndex() {
  1371. return element.getEndOffset();
  1372. }
  1373. }
  1374. private class LinkVector extends Vector {
  1375. public int baseElementIndex(Element e) {
  1376. HTMLLink l;
  1377. for (int i = 0; i < elementCount; i++) {
  1378. l = (HTMLLink) elementAt(i);
  1379. if (l.element == e) {
  1380. return i;
  1381. }
  1382. }
  1383. return -1;
  1384. }
  1385. }
  1386. LinkVector hyperlinks;
  1387. boolean linksValid = false;
  1388. /**
  1389. * Build the private table mapping links to locations in the text
  1390. */
  1391. private void buildLinkTable() {
  1392. hyperlinks.removeAllElements();
  1393. Document d = JEditorPane.this.getDocument();
  1394. if (d != null) {
  1395. ElementIterator ei = new ElementIterator(d);
  1396. Element e;
  1397. AttributeSet as;
  1398. AttributeSet anchor;
  1399. String href;
  1400. while ((e = ei.next()) != null) {
  1401. if (e.isLeaf()) {
  1402. as = e.getAttributes();
  1403. anchor = (AttributeSet) as.getAttribute(HTML.Tag.A);
  1404. href = (anchor != null) ?
  1405. (String) anchor.getAttribute(HTML.Attribute.HREF) : null;
  1406. if (href != null) {
  1407. hyperlinks.addElement(new HTMLLink(e));
  1408. }
  1409. }
  1410. }
  1411. }
  1412. linksValid = true;
  1413. }
  1414. /**
  1415. * Make one of these puppies
  1416. */
  1417. public JEditorPaneAccessibleHypertextSupport() {
  1418. hyperlinks = new LinkVector();
  1419. Document d = JEditorPane.this.getDocument();
  1420. if (d != null) {
  1421. d.addDocumentListener(new DocumentListener() {
  1422. public void changedUpdate(DocumentEvent theEvent) {
  1423. linksValid = false;
  1424. }
  1425. public void insertUpdate(DocumentEvent theEvent) {
  1426. linksValid = false;
  1427. }
  1428. public void removeUpdate(DocumentEvent theEvent) {
  1429. linksValid = false;
  1430. }
  1431. });
  1432. }
  1433. }
  1434. /**
  1435. * Returns the number of links within this hypertext doc.
  1436. *
  1437. * @return number of links in this hypertext doc.
  1438. */
  1439. public int getLinkCount() {
  1440. if (linksValid == false) {
  1441. buildLinkTable();
  1442. }
  1443. return hyperlinks.size();
  1444. }
  1445. /**
  1446. * Returns the index into an array of hyperlinks that
  1447. * is associated with this character index, or -1 if there
  1448. * is no hyperlink associated with this index.
  1449. *
  1450. * @param character index within the text
  1451. * @return index into the set of hyperlinks for this hypertext doc.
  1452. */
  1453. public int getLinkIndex(int charIndex) {
  1454. if (linksValid == false) {
  1455. buildLinkTable();
  1456. }
  1457. Element e = null;
  1458. Document doc = JEditorPane.this.getDocument();
  1459. if (doc != null) {
  1460. for (e = doc.getDefaultRootElement(); ! e.isLeaf(); ) {
  1461. int index = e.getElementIndex(charIndex);
  1462. e = e.getElement(index);
  1463. }
  1464. }
  1465. // don't need to verify that it's an HREF element; if
  1466. // not, then it won't be in the hyperlinks Vector, and
  1467. // so indexOf will return -1 in any case
  1468. return hyperlinks.baseElementIndex(e);
  1469. }
  1470. /**
  1471. * Returns the index into an array of hyperlinks that
  1472. * index. If there is no hyperlink at this index, it returns
  1473. * null.
  1474. *
  1475. * @param index into the set of hyperlinks for this hypertext doc.
  1476. * @return string representation of the hyperlink
  1477. */
  1478. public AccessibleHyperlink getLink(int linkIndex) {
  1479. if (linksValid == false) {
  1480. buildLinkTable();
  1481. }
  1482. if (linkIndex >= 0 && linkIndex < hyperlinks.size()) {
  1483. return (AccessibleHyperlink) hyperlinks.elementAt(linkIndex);
  1484. } else {
  1485. return null;
  1486. }
  1487. }
  1488. /**
  1489. * Returns the contiguous text within the document that
  1490. * is associated with this hyperlink.
  1491. *
  1492. * @param index into the set of hyperlinks for this hypertext doc.
  1493. * @return the contiguous text sharing the link at this index
  1494. */
  1495. public String getLinkText(int linkIndex) {
  1496. if (linksValid == false) {
  1497. buildLinkTable();
  1498. }
  1499. Element e = (Element) hyperlinks.elementAt(linkIndex);
  1500. if (e != null) {
  1501. Document d = JEditorPane.this.getDocument();
  1502. if (d != null) {
  1503. try {
  1504. return d.getText(e.getStartOffset(),
  1505. e.getEndOffset() - e.getStartOffset());
  1506. } catch (BadLocationException exception) {
  1507. return null;
  1508. }
  1509. }
  1510. }
  1511. return null;
  1512. }
  1513. }
  1514. static class PlainEditorKit extends DefaultEditorKit implements ViewFactory {
  1515. /**
  1516. * Creates a copy of the editor kit. This
  1517. * allows an implementation to serve as a prototype
  1518. * for others, so that they can be quickly created.
  1519. *
  1520. * @return the copy
  1521. */
  1522. public Object clone() {
  1523. return new PlainEditorKit();
  1524. }
  1525. /**
  1526. * Fetches a factory that is suitable for producing
  1527. * views of any models that are produced by this
  1528. * kit. The default is to have the UI produce the
  1529. * factory, so this method has no implementation.
  1530. *
  1531. * @return the view factory
  1532. */
  1533. public ViewFactory getViewFactory() {
  1534. return this;
  1535. }
  1536. /**
  1537. * Creates a view from the given structural element of a
  1538. * document.
  1539. *
  1540. * @param elem the piece of the document to build a view of
  1541. * @return the view
  1542. * @see View
  1543. */
  1544. public View create(Element elem) {
  1545. return new WrappedPlainView(elem);
  1546. }
  1547. }
  1548. }
  1549. /* This is useful for the nightmare of parsing multi-part HTTP/RFC822 headers
  1550. * sensibly:
  1551. * From a String like: 'timeout=15, max=5'
  1552. * create an array of Strings:
  1553. * { {"timeout", "15"},
  1554. * {"max", "5"}
  1555. * }
  1556. * From one like: 'Basic Realm="FuzzFace" Foo="Biz Bar Baz"'
  1557. * create one like (no quotes in literal):
  1558. * { {"basic", null},
  1559. * {"realm", "FuzzFace"}
  1560. * {"foo", "Biz Bar Baz"}
  1561. * }
  1562. * keys are converted to lower case, vals are left as is....
  1563. *
  1564. * author Dave Brown
  1565. */
  1566. class HeaderParser {
  1567. /* table of key/val pairs - maxes out at 10!!!!*/
  1568. String raw;
  1569. String[][] tab;
  1570. public HeaderParser(String raw) {
  1571. this.raw = raw;
  1572. tab = new String[10][2];
  1573. parse();
  1574. }
  1575. private void parse() {
  1576. if (raw != null) {
  1577. raw = raw.trim();
  1578. char[] ca = raw.toCharArray();
  1579. int beg = 0, end = 0, i = 0;
  1580. boolean inKey = true;
  1581. boolean inQuote = false;
  1582. int len = ca.length;
  1583. while (end < len) {
  1584. char c = ca[end];
  1585. if (c == '=') { // end of a key
  1586. tab[i][0] = new String(ca, beg, end-beg).toLowerCase();
  1587. inKey = false;
  1588. end++;
  1589. beg = end;
  1590. } else if (c == '\"') {
  1591. if (inQuote) {
  1592. tab[i++][1]= new String(ca, beg, end-beg);
  1593. inQuote=false;
  1594. do {
  1595. end++;
  1596. } while (end < len && (ca[end] == ' ' || ca[end] == ','));
  1597. inKey=true;
  1598. beg=end;
  1599. } else {
  1600. inQuote=true;
  1601. end++;
  1602. beg=end;
  1603. }
  1604. } else if (c == ' ' || c == ',') { // end key/val, of whatever we're in
  1605. if (inQuote) {
  1606. end++;
  1607. continue;
  1608. } else if (inKey) {
  1609. tab[i++][0] = (new String(ca, beg, end-beg)).toLowerCase();
  1610. } else {
  1611. tab[i++][1] = (new String(ca, beg, end-beg));
  1612. }
  1613. while (end < len && (ca[end] == ' ' || ca[end] == ',')) {
  1614. end++;
  1615. }
  1616. inKey = true;
  1617. beg = end;
  1618. } else {
  1619. end++;
  1620. }
  1621. }
  1622. // get last key/val, if any
  1623. if (--end > beg) {
  1624. if (!inKey) {
  1625. if (ca[end] == '\"') {
  1626. tab[i++][1] = (new String(ca, beg, end-beg));
  1627. } else {
  1628. tab[i++][1] = (new String(ca, beg, end-beg+1));
  1629. }
  1630. } else {
  1631. tab[i][0] = (new String(ca, beg, end-beg+1)).toLowerCase();
  1632. }
  1633. } else if (end == beg) {
  1634. if (!inKey) {
  1635. if (ca[end] == '\"') {
  1636. tab[i++][1] = String.valueOf(ca[end-1]);
  1637. } else {
  1638. tab[i++][1] = String.valueOf(ca[end]);
  1639. }
  1640. } else {
  1641. tab[i][0] = String.valueOf(ca[end]).toLowerCase();
  1642. }
  1643. }
  1644. }
  1645. }
  1646. public String findKey(int i) {
  1647. if (i < 0 || i > 10)
  1648. return null;
  1649. return tab[i][0];
  1650. }
  1651. public String findValue(int i) {
  1652. if (i < 0 || i > 10)
  1653. return null;
  1654. return tab[i][1];
  1655. }
  1656. public String findValue(String key) {
  1657. return findValue(key, null);
  1658. }
  1659. public String findValue(String k, String Default) {
  1660. if (k == null)
  1661. return Default;
  1662. k.toLowerCase();
  1663. for (int i = 0; i < 10; ++i) {
  1664. if (tab[i][0] == null) {
  1665. return Default;
  1666. } else if (k.equals(tab[i][0])) {
  1667. return tab[i][1];
  1668. }
  1669. }
  1670. return Default;
  1671. }
  1672. public int findInt(String k, int Default) {
  1673. try {
  1674. return Integer.parseInt(findValue(k, String.valueOf(Default)));
  1675. } catch (Throwable t) {
  1676. return Default;
  1677. }
  1678. }
  1679. }