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 @SuppressWarnings("deprecation") 1201 Object tmp = c.newInstance(); 1202 k = (EditorKit) tmp; 1203 kitRegistry.put(type, k); 1204 } catch (Throwable e) { 1205 k = null; 1206 } 1207 } 1208 1209 // create a copy of the prototype or null if there 1210 // is no prototype. 1211 if (k != null) { 1212 return (EditorKit) k.clone(); 1213 } 1214 return null; 1215 } 1216 1217 /** 1218 * Establishes the default bindings of <code>type</code> to 1219 * <code>classname</code>. 1220 * The class will be dynamically loaded later when actually 1221 * needed, and can be safely changed before attempted uses 1222 * to avoid loading unwanted classes. The prototype 1223 * <code>EditorKit</code> will be loaded with <code>Class.forName</code> 1224 * when registered with this method. 1225 * 1226 * @param type the non-<code>null</code> content type 1227 * @param classname the class to load later 1228 */ 1229 public static void registerEditorKitForContentType(String type, String classname) { 1230 registerEditorKitForContentType(type, classname,Thread.currentThread(). 1231 getContextClassLoader()); 1232 } 1233 1234 /** 1235 * Establishes the default bindings of <code>type</code> to 1236 * <code>classname</code>. 1237 * The class will be dynamically loaded later when actually 1238 * needed using the given <code>ClassLoader</code>, 1239 * and can be safely changed 1240 * before attempted uses to avoid loading unwanted classes. 1241 * 1242 * @param type the non-<code>null</code> content type 1243 * @param classname the class to load later 1244 * @param loader the <code>ClassLoader</code> to use to load the name 1245 */ 1246 public static void registerEditorKitForContentType(String type, String classname, ClassLoader loader) { 1247 getKitTypeRegistry().put(type, classname); 1248 getKitLoaderRegistry().put(type, loader); 1249 getKitRegisty().remove(type); 1250 } 1251 1252 /** 1253 * Returns the currently registered {@code EditorKit} class name for the 1254 * type {@code type}. 1255 * 1256 * @param type the non-{@code null} content type 1257 * @return a {@code String} containing the {@code EditorKit} class name 1258 * for {@code type} 1259 * @since 1.3 1260 */ 1261 public static String getEditorKitClassNameForContentType(String type) { 1262 return getKitTypeRegistry().get(type); 1263 } 1264 1265 private static Hashtable<String, String> getKitTypeRegistry() { 1266 loadDefaultKitsIfNecessary(); 1267 @SuppressWarnings("unchecked") 1268 Hashtable<String, String> tmp = 1269 (Hashtable)SwingUtilities.appContextGet(kitTypeRegistryKey); 1270 return tmp; 1271 } 1272 1273 private static Hashtable<String, ClassLoader> getKitLoaderRegistry() { 1274 loadDefaultKitsIfNecessary(); 1275 @SuppressWarnings("unchecked") 1276 Hashtable<String, ClassLoader> tmp = 1277 (Hashtable)SwingUtilities.appContextGet(kitLoaderRegistryKey); 1278 return tmp; 1279 } 1280 1281 private static Hashtable<String, EditorKit> getKitRegisty() { 1282 @SuppressWarnings("unchecked") 1283 Hashtable<String, EditorKit> ht = 1284 (Hashtable)SwingUtilities.appContextGet(kitRegistryKey); 1285 if (ht == null) { 1286 ht = new Hashtable<>(3); 1287 SwingUtilities.appContextPut(kitRegistryKey, ht); 1288 } 1289 return ht; 1290 } 1291 1292 /** 1293 * This is invoked every time the registries are accessed. Loading 1294 * is done this way instead of via a static as the static is only 1295 * called once when running in plugin resulting in the entries only 1296 * appearing in the first applet. 1297 */ 1298 private static void loadDefaultKitsIfNecessary() { 1299 if (SwingUtilities.appContextGet(kitTypeRegistryKey) == null) { 1300 synchronized(defaultEditorKitMap) { 1301 if (defaultEditorKitMap.size() == 0) { 1302 defaultEditorKitMap.put("text/plain", 1303 "javax.swing.JEditorPane$PlainEditorKit"); 1304 defaultEditorKitMap.put("text/html", 1305 "javax.swing.text.html.HTMLEditorKit"); 1306 defaultEditorKitMap.put("text/rtf", 1307 "javax.swing.text.rtf.RTFEditorKit"); 1308 defaultEditorKitMap.put("application/rtf", 1309 "javax.swing.text.rtf.RTFEditorKit"); 1310 } 1311 } 1312 Hashtable<Object, Object> ht = new Hashtable<>(); 1313 SwingUtilities.appContextPut(kitTypeRegistryKey, ht); 1314 ht = new Hashtable<>(); 1315 SwingUtilities.appContextPut(kitLoaderRegistryKey, ht); 1316 for (String key : defaultEditorKitMap.keySet()) { 1317 registerEditorKitForContentType(key,defaultEditorKitMap.get(key)); 1318 } 1319 1320 } 1321 } 1322 1323 // --- java.awt.Component methods -------------------------- 1324 1325 /** 1326 * Returns the preferred size for the <code>JEditorPane</code>. 1327 * The preferred size for <code>JEditorPane</code> is slightly altered 1328 * from the preferred size of the superclass. If the size 1329 * of the viewport has become smaller than the minimum size 1330 * of the component, the scrollable definition for tracking 1331 * width or height will turn to false. The default viewport 1332 * layout will give the preferred size, and that is not desired 1333 * in the case where the scrollable is tracking. In that case 1334 * the <em>normal</em> preferred size is adjusted to the 1335 * minimum size. This allows things like HTML tables to 1336 * shrink down to their minimum size and then be laid out at 1337 * their minimum size, refusing to shrink any further. 1338 * 1339 * @return a <code>Dimension</code> containing the preferred size 1340 */ 1341 public Dimension getPreferredSize() { 1342 Dimension d = super.getPreferredSize(); 1343 Container parent = SwingUtilities.getUnwrappedParent(this); 1344 if (parent instanceof JViewport) { 1345 JViewport port = (JViewport) parent; 1346 TextUI ui = getUI(); 1347 int prefWidth = d.width; 1348 int prefHeight = d.height; 1349 if (! getScrollableTracksViewportWidth()) { 1350 int w = port.getWidth(); 1351 Dimension min = ui.getMinimumSize(this); 1352 if (w != 0 && w < min.width) { 1353 // Only adjust to min if we have a valid size 1354 prefWidth = min.width; 1355 } 1356 } 1357 if (! getScrollableTracksViewportHeight()) { 1358 int h = port.getHeight(); 1359 Dimension min = ui.getMinimumSize(this); 1360 if (h != 0 && h < min.height) { 1361 // Only adjust to min if we have a valid size 1362 prefHeight = min.height; 1363 } 1364 } 1365 if (prefWidth != d.width || prefHeight != d.height) { 1366 d = new Dimension(prefWidth, prefHeight); 1367 } 1368 } 1369 return d; 1370 } 1371 1372 // --- JTextComponent methods ----------------------------- 1373 1374 /** 1375 * Sets the text of this <code>TextComponent</code> to the specified 1376 * content, 1377 * which is expected to be in the format of the content type of 1378 * this editor. For example, if the type is set to <code>text/html</code> 1379 * the string should be specified in terms of HTML. 1380 * <p> 1381 * This is implemented to remove the contents of the current document, 1382 * and replace them by parsing the given string using the current 1383 * <code>EditorKit</code>. This gives the semantics of the 1384 * superclass by not changing 1385 * out the model, while supporting the content type currently set on 1386 * this component. The assumption is that the previous content is 1387 * relatively 1388 * small, and that the previous content doesn't have side effects. 1389 * Both of those assumptions can be violated and cause undesirable results. 1390 * To avoid this, create a new document, 1391 * <code>getEditorKit().createDefaultDocument()</code>, and replace the 1392 * existing <code>Document</code> with the new one. You are then assured the 1393 * previous <code>Document</code> won't have any lingering state. 1394 * <ol> 1395 * <li> 1396 * Leaving the existing model in place means that the old view will be 1397 * torn down, and a new view created, where replacing the document would 1398 * avoid the tear down of the old view. 1399 * <li> 1400 * Some formats (such as HTML) can install things into the document that 1401 * can influence future contents. HTML can have style information embedded 1402 * that would influence the next content installed unexpectedly. 1403 * </ol> 1404 * <p> 1405 * An alternative way to load this component with a string would be to 1406 * create a StringReader and call the read method. In this case the model 1407 * would be replaced after it was initialized with the contents of the 1408 * string. 1409 * 1410 * @param t the new text to be set; if <code>null</code> the old 1411 * text will be deleted 1412 * @see #getText 1413 */ 1414 @BeanProperty(bound = false, description 1415 = "the text of this component") 1416 public void setText(String t) { 1417 try { 1418 Document doc = getDocument(); 1419 doc.remove(0, doc.getLength()); 1420 if (t == null || t.equals("")) { 1421 return; 1422 } 1423 Reader r = new StringReader(t); 1424 EditorKit kit = getEditorKit(); 1425 kit.read(r, doc, 0); 1426 } catch (IOException ioe) { 1427 UIManager.getLookAndFeel().provideErrorFeedback(JEditorPane.this); 1428 } catch (BadLocationException ble) { 1429 UIManager.getLookAndFeel().provideErrorFeedback(JEditorPane.this); 1430 } 1431 } 1432 1433 /** 1434 * Returns the text contained in this <code>TextComponent</code> 1435 * in terms of the 1436 * content type of this editor. If an exception is thrown while 1437 * attempting to retrieve the text, <code>null</code> will be returned. 1438 * This is implemented to call <code>JTextComponent.write</code> with 1439 * a <code>StringWriter</code>. 1440 * 1441 * @return the text 1442 * @see #setText 1443 */ 1444 public String getText() { 1445 String txt; 1446 try { 1447 StringWriter buf = new StringWriter(); 1448 write(buf); 1449 txt = buf.toString(); 1450 } catch (IOException ioe) { 1451 txt = null; 1452 } 1453 return txt; 1454 } 1455 1456 // --- Scrollable ---------------------------------------- 1457 1458 /** 1459 * Returns true if a viewport should always force the width of this 1460 * <code>Scrollable</code> to match the width of the viewport. 1461 * 1462 * @return true if a viewport should force the Scrollables width to 1463 * match its own, false otherwise 1464 */ 1465 @BeanProperty(bound = false) 1466 public boolean getScrollableTracksViewportWidth() { 1467 Container parent = SwingUtilities.getUnwrappedParent(this); 1468 if (parent instanceof JViewport) { 1469 JViewport port = (JViewport) parent; 1470 TextUI ui = getUI(); 1471 int w = port.getWidth(); 1472 Dimension min = ui.getMinimumSize(this); 1473 Dimension max = ui.getMaximumSize(this); 1474 if ((w >= min.width) && (w <= max.width)) { 1475 return true; 1476 } 1477 } 1478 return false; 1479 } 1480 1481 /** 1482 * Returns true if a viewport should always force the height of this 1483 * <code>Scrollable</code> to match the height of the viewport. 1484 * 1485 * @return true if a viewport should force the 1486 * <code>Scrollable</code>'s height to match its own, 1487 * false otherwise 1488 */ 1489 @BeanProperty(bound = false) 1490 public boolean getScrollableTracksViewportHeight() { 1491 Container parent = SwingUtilities.getUnwrappedParent(this); 1492 if (parent instanceof JViewport) { 1493 JViewport port = (JViewport) parent; 1494 TextUI ui = getUI(); 1495 int h = port.getHeight(); 1496 Dimension min = ui.getMinimumSize(this); 1497 if (h >= min.height) { 1498 Dimension max = ui.getMaximumSize(this); 1499 if (h <= max.height) { 1500 return true; 1501 } 1502 } 1503 } 1504 return false; 1505 } 1506 1507 // --- Serialization ------------------------------------ 1508 1509 /** 1510 * See <code>readObject</code> and <code>writeObject</code> in 1511 * <code>JComponent</code> for more 1512 * information about serialization in Swing. 1513 */ 1514 private void writeObject(ObjectOutputStream s) throws IOException { 1515 s.defaultWriteObject(); 1516 if (getUIClassID().equals(uiClassID)) { 1517 byte count = JComponent.getWriteObjCounter(this); 1518 JComponent.setWriteObjCounter(this, --count); 1519 if (count == 0 && ui != null) { 1520 ui.installUI(this); 1521 } 1522 } 1523 } 1524 1525 // --- variables --------------------------------------- 1526 1527 private SwingWorker<URL, Object> pageLoader; 1528 1529 /** 1530 * Current content binding of the editor. 1531 */ 1532 private EditorKit kit; 1533 private boolean isUserSetEditorKit; 1534 1535 private Hashtable<String, Object> pageProperties; 1536 1537 /** Should be kept in sync with javax.swing.text.html.FormView counterpart. */ 1538 static final String PostDataProperty = "javax.swing.JEditorPane.postdata"; 1539 1540 /** 1541 * Table of registered type handlers for this editor. 1542 */ 1543 private Hashtable<String, EditorKit> typeHandlers; 1544 1545 /* 1546 * Private AppContext keys for this class's static variables. 1547 */ 1548 private static final Object kitRegistryKey = 1549 new StringBuffer("JEditorPane.kitRegistry"); 1550 private static final Object kitTypeRegistryKey = 1551 new StringBuffer("JEditorPane.kitTypeRegistry"); 1552 private static final Object kitLoaderRegistryKey = 1553 new StringBuffer("JEditorPane.kitLoaderRegistry"); 1554 1555 /** 1556 * @see #getUIClassID 1557 * @see #readObject 1558 */ 1559 private static final String uiClassID = "EditorPaneUI"; 1560 1561 1562 /** 1563 * Key for a client property used to indicate whether 1564 * <a href="http://www.w3.org/TR/CSS21/syndata.html#length-units"> 1565 * w3c compliant</a> length units are used for html rendering. 1566 * <p> 1567 * By default this is not enabled; to enable 1568 * it set the client {@link #putClientProperty property} with this name 1569 * to <code>Boolean.TRUE</code>. 1570 * 1571 * @since 1.5 1572 */ 1573 public static final String W3C_LENGTH_UNITS = "JEditorPane.w3cLengthUnits"; 1574 1575 /** 1576 * Key for a client property used to indicate whether 1577 * the default font and foreground color from the component are 1578 * used if a font or foreground color is not specified in the styled 1579 * text. 1580 * <p> 1581 * The default varies based on the look and feel; 1582 * to enable it set the client {@link #putClientProperty property} with 1583 * this name to <code>Boolean.TRUE</code>. 1584 * 1585 * @since 1.5 1586 */ 1587 public static final String HONOR_DISPLAY_PROPERTIES = "JEditorPane.honorDisplayProperties"; 1588 1589 static final Map<String, String> defaultEditorKitMap = new HashMap<String, String>(0); 1590 1591 /** 1592 * Returns a string representation of this <code>JEditorPane</code>. 1593 * This method 1594 * is intended to be used only for debugging purposes, and the 1595 * content and format of the returned string may vary between 1596 * implementations. The returned string may be empty but may not 1597 * be <code>null</code>. 1598 * 1599 * @return a string representation of this <code>JEditorPane</code> 1600 */ 1601 protected String paramString() { 1602 String kitString = (kit != null ? 1603 kit.toString() : ""); 1604 String typeHandlersString = (typeHandlers != null ? 1605 typeHandlers.toString() : ""); 1606 1607 return super.paramString() + 1608 ",kit=" + kitString + 1609 ",typeHandlers=" + typeHandlersString; 1610 } 1611 1612 1613 ///////////////// 1614 // Accessibility support 1615 //////////////// 1616 1617 1618 /** 1619 * Gets the AccessibleContext associated with this JEditorPane. 1620 * For editor panes, the AccessibleContext takes the form of an 1621 * AccessibleJEditorPane. 1622 * A new AccessibleJEditorPane instance is created if necessary. 1623 * 1624 * @return an AccessibleJEditorPane that serves as the 1625 * AccessibleContext of this JEditorPane 1626 */ 1627 @BeanProperty(bound = false) 1628 public AccessibleContext getAccessibleContext() { 1629 if (getEditorKit() instanceof HTMLEditorKit) { 1630 if (accessibleContext == null || accessibleContext.getClass() != 1631 AccessibleJEditorPaneHTML.class) { 1632 accessibleContext = new AccessibleJEditorPaneHTML(); 1633 } 1634 } else if (accessibleContext == null || accessibleContext.getClass() != 1635 AccessibleJEditorPane.class) { 1636 accessibleContext = new AccessibleJEditorPane(); 1637 } 1638 return accessibleContext; 1639 } 1640 1641 /** 1642 * This class implements accessibility support for the 1643 * <code>JEditorPane</code> class. It provides an implementation of the 1644 * Java Accessibility API appropriate to editor pane user-interface 1645 * elements. 1646 * <p> 1647 * <strong>Warning:</strong> 1648 * Serialized objects of this class will not be compatible with 1649 * future Swing releases. The current serialization support is 1650 * appropriate for short term storage or RMI between applications running 1651 * the same version of Swing. As of 1.4, support for long term storage 1652 * of all JavaBeans™ 1653 * has been added to the <code>java.beans</code> package. 1654 * Please see {@link java.beans.XMLEncoder}. 1655 */ 1656 @SuppressWarnings("serial") // Same-version serialization only 1657 protected class AccessibleJEditorPane extends AccessibleJTextComponent { 1658 1659 /** 1660 * Gets the accessibleDescription property of this object. If this 1661 * property isn't set, returns the content type of this 1662 * <code>JEditorPane</code> instead (e.g. "plain/text", "html/text"). 1663 * 1664 * @return the localized description of the object; <code>null</code> 1665 * if this object does not have a description 1666 * 1667 * @see #setAccessibleName 1668 */ 1669 public String getAccessibleDescription() { 1670 String description = accessibleDescription; 1671 1672 // fallback to client property 1673 if (description == null) { 1674 description = (String)getClientProperty(AccessibleContext.ACCESSIBLE_DESCRIPTION_PROPERTY); 1675 } 1676 if (description == null) { 1677 description = JEditorPane.this.getContentType(); 1678 } 1679 return description; 1680 } 1681 1682 /** 1683 * Gets the state set of this object. 1684 * 1685 * @return an instance of AccessibleStateSet describing the states 1686 * of the object 1687 * @see AccessibleStateSet 1688 */ 1689 public AccessibleStateSet getAccessibleStateSet() { 1690 AccessibleStateSet states = super.getAccessibleStateSet(); 1691 states.add(AccessibleState.MULTI_LINE); 1692 return states; 1693 } 1694 } 1695 1696 /** 1697 * This class provides support for <code>AccessibleHypertext</code>, 1698 * and is used in instances where the <code>EditorKit</code> 1699 * installed in this <code>JEditorPane</code> is an instance of 1700 * <code>HTMLEditorKit</code>. 1701 * <p> 1702 * <strong>Warning:</strong> 1703 * Serialized objects of this class will not be compatible with 1704 * future Swing releases. The current serialization support is 1705 * appropriate for short term storage or RMI between applications running 1706 * the same version of Swing. As of 1.4, support for long term storage 1707 * of all JavaBeans™ 1708 * has been added to the <code>java.beans</code> package. 1709 * Please see {@link java.beans.XMLEncoder}. 1710 */ 1711 @SuppressWarnings("serial") // Same-version serialization only 1712 protected class AccessibleJEditorPaneHTML extends AccessibleJEditorPane { 1713 1714 private AccessibleContext accessibleContext; 1715 1716 /** 1717 * Returns the accessible text. 1718 * @return the accessible text 1719 */ 1720 public AccessibleText getAccessibleText() { 1721 return new JEditorPaneAccessibleHypertextSupport(); 1722 } 1723 1724 /** 1725 * Constructs an {@code AccessibleJEditorPaneHTML}. 1726 */ 1727 protected AccessibleJEditorPaneHTML () { 1728 HTMLEditorKit kit = (HTMLEditorKit)JEditorPane.this.getEditorKit(); 1729 accessibleContext = kit.getAccessibleContext(); 1730 } 1731 1732 /** 1733 * Returns the number of accessible children of the object. 1734 * 1735 * @return the number of accessible children of the object. 1736 */ 1737 public int getAccessibleChildrenCount() { 1738 if (accessibleContext != null) { 1739 return accessibleContext.getAccessibleChildrenCount(); 1740 } else { 1741 return 0; 1742 } 1743 } 1744 1745 /** 1746 * Returns the specified Accessible child of the object. The Accessible 1747 * children of an Accessible object are zero-based, so the first child 1748 * of an Accessible child is at index 0, the second child is at index 1, 1749 * and so on. 1750 * 1751 * @param i zero-based index of child 1752 * @return the Accessible child of the object 1753 * @see #getAccessibleChildrenCount 1754 */ 1755 public Accessible getAccessibleChild(int i) { 1756 if (accessibleContext != null) { 1757 return accessibleContext.getAccessibleChild(i); 1758 } else { 1759 return null; 1760 } 1761 } 1762 1763 /** 1764 * Returns the Accessible child, if one exists, contained at the local 1765 * coordinate Point. 1766 * 1767 * @param p The point relative to the coordinate system of this object. 1768 * @return the Accessible, if it exists, at the specified location; 1769 * otherwise null 1770 */ 1771 public Accessible getAccessibleAt(Point p) { 1772 if (accessibleContext != null && p != null) { 1773 try { 1774 AccessibleComponent acomp = 1775 accessibleContext.getAccessibleComponent(); 1776 if (acomp != null) { 1777 return acomp.getAccessibleAt(p); 1778 } else { 1779 return null; 1780 } 1781 } catch (IllegalComponentStateException e) { 1782 return null; 1783 } 1784 } else { 1785 return null; 1786 } 1787 } 1788 } 1789 1790 /** 1791 * What's returned by 1792 * <code>AccessibleJEditorPaneHTML.getAccessibleText</code>. 1793 * 1794 * Provides support for <code>AccessibleHypertext</code> in case 1795 * there is an HTML document being displayed in this 1796 * <code>JEditorPane</code>. 1797 * 1798 */ 1799 protected class JEditorPaneAccessibleHypertextSupport 1800 extends AccessibleJEditorPane implements AccessibleHypertext { 1801 1802 /** 1803 * An HTML link. 1804 */ 1805 public class HTMLLink extends AccessibleHyperlink { 1806 Element element; 1807 1808 /** 1809 * Constructs a {@code HTMLLink}. 1810 * @param e the element 1811 */ 1812 public HTMLLink(Element e) { 1813 element = e; 1814 } 1815 1816 /** 1817 * Since the document a link is associated with may have 1818 * changed, this method returns whether this Link is valid 1819 * anymore (with respect to the document it references). 1820 * 1821 * @return a flag indicating whether this link is still valid with 1822 * respect to the AccessibleHypertext it belongs to 1823 */ 1824 public boolean isValid() { 1825 return JEditorPaneAccessibleHypertextSupport.this.linksValid; 1826 } 1827 1828 /** 1829 * Returns the number of accessible actions available in this Link 1830 * If there are more than one, the first one is NOT considered the 1831 * "default" action of this LINK object (e.g. in an HTML imagemap). 1832 * In general, links will have only one AccessibleAction in them. 1833 * 1834 * @return the zero-based number of Actions in this object 1835 */ 1836 public int getAccessibleActionCount() { 1837 return 1; 1838 } 1839 1840 /** 1841 * Perform the specified Action on the object 1842 * 1843 * @param i zero-based index of actions 1844 * @return true if the action was performed; else false. 1845 * @see #getAccessibleActionCount 1846 */ 1847 public boolean doAccessibleAction(int i) { 1848 if (i == 0 && isValid() == true) { 1849 URL u = (URL) getAccessibleActionObject(i); 1850 if (u != null) { 1851 HyperlinkEvent linkEvent = 1852 new HyperlinkEvent(JEditorPane.this, HyperlinkEvent.EventType.ACTIVATED, u); 1853 JEditorPane.this.fireHyperlinkUpdate(linkEvent); 1854 return true; 1855 } 1856 } 1857 return false; // link invalid or i != 0 1858 } 1859 1860 /** 1861 * Return a String description of this particular 1862 * link action. The string returned is the text 1863 * within the document associated with the element 1864 * which contains this link. 1865 * 1866 * @param i zero-based index of the actions 1867 * @return a String description of the action 1868 * @see #getAccessibleActionCount 1869 */ 1870 public String getAccessibleActionDescription(int i) { 1871 if (i == 0 && isValid() == true) { 1872 Document d = JEditorPane.this.getDocument(); 1873 if (d != null) { 1874 try { 1875 return d.getText(getStartIndex(), 1876 getEndIndex() - getStartIndex()); 1877 } catch (BadLocationException exception) { 1878 return null; 1879 } 1880 } 1881 } 1882 return null; 1883 } 1884 1885 /** 1886 * Returns a URL object that represents the link. 1887 * 1888 * @param i zero-based index of the actions 1889 * @return an URL representing the HTML link itself 1890 * @see #getAccessibleActionCount 1891 */ 1892 public Object getAccessibleActionObject(int i) { 1893 if (i == 0 && isValid() == true) { 1894 AttributeSet as = element.getAttributes(); 1895 AttributeSet anchor = 1896 (AttributeSet) as.getAttribute(HTML.Tag.A); 1897 String href = (anchor != null) ? 1898 (String) anchor.getAttribute(HTML.Attribute.HREF) : null; 1899 if (href != null) { 1900 URL u; 1901 try { 1902 u = new URL(JEditorPane.this.getPage(), href); 1903 } catch (MalformedURLException m) { 1904 u = null; 1905 } 1906 return u; 1907 } 1908 } 1909 return null; // link invalid or i != 0 1910 } 1911 1912 /** 1913 * Return an object that represents the link anchor, 1914 * as appropriate for that link. E.g. from HTML: 1915 * <a href="http://www.sun.com/access">Accessibility</a> 1916 * this method would return a String containing the text: 1917 * 'Accessibility'. 1918 * 1919 * Similarly, from this HTML: 1920 * <a HREF="#top"><img src="top-hat.gif" alt="top hat"></a> 1921 * this might return the object ImageIcon("top-hat.gif", "top hat"); 1922 * 1923 * @param i zero-based index of the actions 1924 * @return an Object representing the hypertext anchor 1925 * @see #getAccessibleActionCount 1926 */ 1927 public Object getAccessibleActionAnchor(int i) { 1928 return getAccessibleActionDescription(i); 1929 } 1930 1931 1932 /** 1933 * Get the index with the hypertext document at which this 1934 * link begins 1935 * 1936 * @return index of start of link 1937 */ 1938 public int getStartIndex() { 1939 return element.getStartOffset(); 1940 } 1941 1942 /** 1943 * Get the index with the hypertext document at which this 1944 * link ends 1945 * 1946 * @return index of end of link 1947 */ 1948 public int getEndIndex() { 1949 return element.getEndOffset(); 1950 } 1951 } 1952 1953 private class LinkVector extends Vector<HTMLLink> { 1954 public int baseElementIndex(Element e) { 1955 HTMLLink l; 1956 for (int i = 0; i < elementCount; i++) { 1957 l = elementAt(i); 1958 if (l.element == e) { 1959 return i; 1960 } 1961 } 1962 return -1; 1963 } 1964 } 1965 1966 LinkVector hyperlinks; 1967 boolean linksValid = false; 1968 1969 /** 1970 * Build the private table mapping links to locations in the text 1971 */ 1972 private void buildLinkTable() { 1973 hyperlinks.removeAllElements(); 1974 Document d = JEditorPane.this.getDocument(); 1975 if (d != null) { 1976 ElementIterator ei = new ElementIterator(d); 1977 Element e; 1978 AttributeSet as; 1979 AttributeSet anchor; 1980 String href; 1981 while ((e = ei.next()) != null) { 1982 if (e.isLeaf()) { 1983 as = e.getAttributes(); 1984 anchor = (AttributeSet) as.getAttribute(HTML.Tag.A); 1985 href = (anchor != null) ? 1986 (String) anchor.getAttribute(HTML.Attribute.HREF) : null; 1987 if (href != null) { 1988 hyperlinks.addElement(new HTMLLink(e)); 1989 } 1990 } 1991 } 1992 } 1993 linksValid = true; 1994 } 1995 1996 /** 1997 * Make one of these puppies 1998 */ 1999 public JEditorPaneAccessibleHypertextSupport() { 2000 hyperlinks = new LinkVector(); 2001 Document d = JEditorPane.this.getDocument(); 2002 if (d != null) { 2003 d.addDocumentListener(new DocumentListener() { 2004 public void changedUpdate(DocumentEvent theEvent) { 2005 linksValid = false; 2006 } 2007 public void insertUpdate(DocumentEvent theEvent) { 2008 linksValid = false; 2009 } 2010 public void removeUpdate(DocumentEvent theEvent) { 2011 linksValid = false; 2012 } 2013 }); 2014 } 2015 } 2016 2017 /** 2018 * Returns the number of links within this hypertext doc. 2019 * 2020 * @return number of links in this hypertext doc. 2021 */ 2022 public int getLinkCount() { 2023 if (linksValid == false) { 2024 buildLinkTable(); 2025 } 2026 return hyperlinks.size(); 2027 } 2028 2029 /** 2030 * Returns the index into an array of hyperlinks that 2031 * is associated with this character index, or -1 if there 2032 * is no hyperlink associated with this index. 2033 * 2034 * @param charIndex index within the text 2035 * @return index into the set of hyperlinks for this hypertext doc. 2036 */ 2037 public int getLinkIndex(int charIndex) { 2038 if (linksValid == false) { 2039 buildLinkTable(); 2040 } 2041 Element e = null; 2042 Document doc = JEditorPane.this.getDocument(); 2043 if (doc != null) { 2044 for (e = doc.getDefaultRootElement(); ! e.isLeaf(); ) { 2045 int index = e.getElementIndex(charIndex); 2046 e = e.getElement(index); 2047 } 2048 } 2049 2050 // don't need to verify that it's an HREF element; if 2051 // not, then it won't be in the hyperlinks Vector, and 2052 // so indexOf will return -1 in any case 2053 return hyperlinks.baseElementIndex(e); 2054 } 2055 2056 /** 2057 * Returns the index into an array of hyperlinks that 2058 * index. If there is no hyperlink at this index, it returns 2059 * null. 2060 * 2061 * @param linkIndex into the set of hyperlinks for this hypertext doc. 2062 * @return string representation of the hyperlink 2063 */ 2064 public AccessibleHyperlink getLink(int linkIndex) { 2065 if (linksValid == false) { 2066 buildLinkTable(); 2067 } 2068 if (linkIndex >= 0 && linkIndex < hyperlinks.size()) { 2069 return hyperlinks.elementAt(linkIndex); 2070 } else { 2071 return null; 2072 } 2073 } 2074 2075 /** 2076 * Returns the contiguous text within the document that 2077 * is associated with this hyperlink. 2078 * 2079 * @param linkIndex into the set of hyperlinks for this hypertext doc. 2080 * @return the contiguous text sharing the link at this index 2081 */ 2082 public String getLinkText(int linkIndex) { 2083 if (linksValid == false) { 2084 buildLinkTable(); 2085 } 2086 Element e = (Element) hyperlinks.elementAt(linkIndex); 2087 if (e != null) { 2088 Document d = JEditorPane.this.getDocument(); 2089 if (d != null) { 2090 try { 2091 return d.getText(e.getStartOffset(), 2092 e.getEndOffset() - e.getStartOffset()); 2093 } catch (BadLocationException exception) { 2094 return null; 2095 } 2096 } 2097 } 2098 return null; 2099 } 2100 } 2101 2102 static class PlainEditorKit extends DefaultEditorKit implements ViewFactory { 2103 2104 /** 2105 * Fetches a factory that is suitable for producing 2106 * views of any models that are produced by this 2107 * kit. The default is to have the UI produce the 2108 * factory, so this method has no implementation. 2109 * 2110 * @return the view factory 2111 */ 2112 public ViewFactory getViewFactory() { 2113 return this; 2114 } 2115 2116 /** 2117 * Creates a view from the given structural element of a 2118 * document. 2119 * 2120 * @param elem the piece of the document to build a view of 2121 * @return the view 2122 * @see View 2123 */ 2124 public View create(Element elem) { 2125 Document doc = elem.getDocument(); 2126 Object i18nFlag 2127 = doc.getProperty("i18n"/*AbstractDocument.I18NProperty*/); 2128 if ((i18nFlag != null) && i18nFlag.equals(Boolean.TRUE)) { 2129 // build a view that support bidi 2130 return createI18N(elem); 2131 } else { 2132 return new WrappedPlainView(elem); 2133 } 2134 } 2135 2136 View createI18N(Element elem) { 2137 String kind = elem.getName(); 2138 if (kind != null) { 2139 if (kind.equals(AbstractDocument.ContentElementName)) { 2140 return new PlainParagraph(elem); 2141 } else if (kind.equals(AbstractDocument.ParagraphElementName)){ 2142 return new BoxView(elem, View.Y_AXIS); 2143 } 2144 } 2145 return null; 2146 } 2147 2148 /** 2149 * Paragraph for representing plain-text lines that support 2150 * bidirectional text. 2151 */ 2152 static class PlainParagraph extends javax.swing.text.ParagraphView { 2153 2154 PlainParagraph(Element elem) { 2155 super(elem); 2156 layoutPool = new LogicalView(elem); 2157 layoutPool.setParent(this); 2158 } 2159 2160 protected void setPropertiesFromAttributes() { 2161 Component c = getContainer(); 2162 if ((c != null) 2163 && (! c.getComponentOrientation().isLeftToRight())) 2164 { 2165 setJustification(StyleConstants.ALIGN_RIGHT); 2166 } else { 2167 setJustification(StyleConstants.ALIGN_LEFT); 2168 } 2169 } 2170 2171 /** 2172 * Fetch the constraining span to flow against for 2173 * the given child index. 2174 */ 2175 public int getFlowSpan(int index) { 2176 Component c = getContainer(); 2177 if (c instanceof JTextArea) { 2178 JTextArea area = (JTextArea) c; 2179 if (! area.getLineWrap()) { 2180 // no limit if unwrapped 2181 return Integer.MAX_VALUE; 2182 } 2183 } 2184 return super.getFlowSpan(index); 2185 } 2186 2187 protected SizeRequirements calculateMinorAxisRequirements(int axis, 2188 SizeRequirements r) 2189 { 2190 SizeRequirements req 2191 = super.calculateMinorAxisRequirements(axis, r); 2192 Component c = getContainer(); 2193 if (c instanceof JTextArea) { 2194 JTextArea area = (JTextArea) c; 2195 if (! area.getLineWrap()) { 2196 // min is pref if unwrapped 2197 req.minimum = req.preferred; 2198 } 2199 } 2200 return req; 2201 } 2202 2203 /** 2204 * This class can be used to represent a logical view for 2205 * a flow. It keeps the children updated to reflect the state 2206 * of the model, gives the logical child views access to the 2207 * view hierarchy, and calculates a preferred span. It doesn't 2208 * do any rendering, layout, or model/view translation. 2209 */ 2210 static class LogicalView extends CompositeView { 2211 2212 LogicalView(Element elem) { 2213 super(elem); 2214 } 2215 2216 protected int getViewIndexAtPosition(int pos) { 2217 Element elem = getElement(); 2218 if (elem.getElementCount() > 0) { 2219 return elem.getElementIndex(pos); 2220 } 2221 return 0; 2222 } 2223 2224 protected boolean 2225 updateChildren(DocumentEvent.ElementChange ec, 2226 DocumentEvent e, ViewFactory f) 2227 { 2228 return false; 2229 } 2230 2231 protected void loadChildren(ViewFactory f) { 2232 Element elem = getElement(); 2233 if (elem.getElementCount() > 0) { 2234 super.loadChildren(f); 2235 } else { 2236 View v = new GlyphView(elem); 2237 append(v); 2238 } 2239 } 2240 2241 public float getPreferredSpan(int axis) { 2242 if( getViewCount() != 1 ) 2243 throw new Error("One child view is assumed."); 2244 2245 View v = getView(0); 2246 //((GlyphView)v).setGlyphPainter(null); 2247 return v.getPreferredSpan(axis); 2248 } 2249 2250 /** 2251 * Forward the DocumentEvent to the given child view. This 2252 * is implemented to reparent the child to the logical view 2253 * (the children may have been parented by a row in the flow 2254 * if they fit without breaking) and then execute the 2255 * superclass behavior. 2256 * 2257 * @param v the child view to forward the event to. 2258 * @param e the change information from the associated document 2259 * @param a the current allocation of the view 2260 * @param f the factory to use to rebuild if the view has 2261 * children 2262 * @see #forwardUpdate 2263 * @since 1.3 2264 */ 2265 protected void forwardUpdateToView(View v, DocumentEvent e, 2266 Shape a, ViewFactory f) { 2267 v.setParent(this); 2268 super.forwardUpdateToView(v, e, a, f); 2269 } 2270 2271 // The following methods don't do anything useful, they 2272 // simply keep the class from being abstract. 2273 2274 public void paint(Graphics g, Shape allocation) { 2275 } 2276 2277 protected boolean isBefore(int x, int y, Rectangle alloc) { 2278 return false; 2279 } 2280 2281 protected boolean isAfter(int x, int y, Rectangle alloc) { 2282 return false; 2283 } 2284 2285 protected View getViewAtPoint(int x, int y, Rectangle alloc) { 2286 return null; 2287 } 2288 2289 protected void childAllocation(int index, Rectangle a) { 2290 } 2291 } 2292 } 2293 } 2294 2295 /* This is useful for the nightmare of parsing multi-part HTTP/RFC822 headers 2296 * sensibly: 2297 * From a String like: 'timeout=15, max=5' 2298 * create an array of Strings: 2299 * { {"timeout", "15"}, 2300 * {"max", "5"} 2301 * } 2302 * From one like: 'Basic Realm="FuzzFace" Foo="Biz Bar Baz"' 2303 * create one like (no quotes in literal): 2304 * { {"basic", null}, 2305 * {"realm", "FuzzFace"} 2306 * {"foo", "Biz Bar Baz"} 2307 * } 2308 * keys are converted to lower case, vals are left as is.... 2309 * 2310 * author Dave Brown 2311 */ 2312 2313 2314 static class HeaderParser { 2315 2316 /* table of key/val pairs - maxes out at 10!!!!*/ 2317 String raw; 2318 String[][] tab; 2319 2320 public HeaderParser(String raw) { 2321 this.raw = raw; 2322 tab = new String[10][2]; 2323 parse(); 2324 } 2325 2326 private void parse() { 2327 2328 if (raw != null) { 2329 raw = raw.trim(); 2330 char[] ca = raw.toCharArray(); 2331 int beg = 0, end = 0, i = 0; 2332 boolean inKey = true; 2333 boolean inQuote = false; 2334 int len = ca.length; 2335 while (end < len) { 2336 char c = ca[end]; 2337 if (c == '=') { // end of a key 2338 tab[i][0] = new String(ca, beg, end-beg).toLowerCase(); 2339 inKey = false; 2340 end++; 2341 beg = end; 2342 } else if (c == '\"') { 2343 if (inQuote) { 2344 tab[i++][1]= new String(ca, beg, end-beg); 2345 inQuote=false; 2346 do { 2347 end++; 2348 } while (end < len && (ca[end] == ' ' || ca[end] == ',')); 2349 inKey=true; 2350 beg=end; 2351 } else { 2352 inQuote=true; 2353 end++; 2354 beg=end; 2355 } 2356 } else if (c == ' ' || c == ',') { // end key/val, of whatever we're in 2357 if (inQuote) { 2358 end++; 2359 continue; 2360 } else if (inKey) { 2361 tab[i++][0] = (new String(ca, beg, end-beg)).toLowerCase(); 2362 } else { 2363 tab[i++][1] = (new String(ca, beg, end-beg)); 2364 } 2365 while (end < len && (ca[end] == ' ' || ca[end] == ',')) { 2366 end++; 2367 } 2368 inKey = true; 2369 beg = end; 2370 } else { 2371 end++; 2372 } 2373 } 2374 // get last key/val, if any 2375 if (--end > beg) { 2376 if (!inKey) { 2377 if (ca[end] == '\"') { 2378 tab[i++][1] = (new String(ca, beg, end-beg)); 2379 } else { 2380 tab[i++][1] = (new String(ca, beg, end-beg+1)); 2381 } 2382 } else { 2383 tab[i][0] = (new String(ca, beg, end-beg+1)).toLowerCase(); 2384 } 2385 } else if (end == beg) { 2386 if (!inKey) { 2387 if (ca[end] == '\"') { 2388 tab[i++][1] = String.valueOf(ca[end-1]); 2389 } else { 2390 tab[i++][1] = String.valueOf(ca[end]); 2391 } 2392 } else { 2393 tab[i][0] = String.valueOf(ca[end]).toLowerCase(); 2394 } 2395 } 2396 } 2397 2398 } 2399 2400 public String findKey(int i) { 2401 if (i < 0 || i > 10) 2402 return null; 2403 return tab[i][0]; 2404 } 2405 2406 public String findValue(int i) { 2407 if (i < 0 || i > 10) 2408 return null; 2409 return tab[i][1]; 2410 } 2411 2412 public String findValue(String key) { 2413 return findValue(key, null); 2414 } 2415 2416 public String findValue(String k, String Default) { 2417 if (k == null) 2418 return Default; 2419 k = k.toLowerCase(); 2420 for (int i = 0; i < 10; ++i) { 2421 if (tab[i][0] == null) { 2422 return Default; 2423 } else if (k.equals(tab[i][0])) { 2424 return tab[i][1]; 2425 } 2426 } 2427 return Default; 2428 } 2429 2430 public int findInt(String k, int Default) { 2431 try { 2432 return Integer.parseInt(findValue(k, String.valueOf(Default))); 2433 } catch (Throwable t) { 2434 return Default; 2435 } 2436 } 2437 } 2438 2439 }