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