001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.gui.widgets;
003
004import java.io.IOException;
005import java.io.InputStream;
006import java.net.URL;
007import java.net.URLConnection;
008
009import javax.swing.JEditorPane;
010
011import org.openstreetmap.josm.tools.Utils;
012
013/**
014 * Subclass of {@link JEditorPane} that adds a "native" context menu (cut/copy/paste/select all)
015 * and effectively uses JOSM user agent when performing HTTP request in {@link #setPage(URL)} method.
016 * @since 5886
017 */
018public class JosmEditorPane extends JEditorPane {
019
020    /**
021     * Creates a new <code>JosmEditorPane</code>.
022     * The document model is set to <code>null</code>.
023     */
024    public JosmEditorPane() {
025        TextContextualPopupMenu.enableMenuFor(this);
026    }
027
028    /**
029     * Creates a <code>JosmEditorPane</code> based on a specified URL for input.
030     *
031     * @param initialPage the URL
032     * @exception IOException if the URL is <code>null</code> or cannot be accessed
033     */
034    public JosmEditorPane(URL initialPage) throws IOException {
035        this();
036        setPage(initialPage);
037    }
038
039    /**
040     * Creates a <code>JosmEditorPane</code> based on a string containing
041     * a URL specification.
042     *
043     * @param url the URL
044     * @exception IOException if the URL is <code>null</code> or cannot be accessed
045     */
046    public JosmEditorPane(String url) throws IOException {
047        this();
048        setPage(url);
049    }
050
051    /**
052     * Creates a <code>JosmEditorPane</code> that has been initialized
053     * to the given text.  This is a convenience constructor that calls the
054     * <code>setContentType</code> and <code>setText</code> methods.
055     *
056     * @param type mime type of the given text
057     * @param text the text to initialize with; may be <code>null</code>
058     * @exception NullPointerException if the <code>type</code> parameter
059     *      is <code>null</code>
060     */
061    public JosmEditorPane(String type, String text) {
062        this();
063        setContentType(type);
064        setText(text);
065    }
066
067    @Override
068    protected InputStream getStream(URL page) throws IOException {
069        URLConnection conn = Utils.setupURLConnection(page.openConnection());
070        InputStream result = conn.getInputStream();
071        String type = conn.getContentType();
072        if (type != null) {
073            setContentType(type);
074        }
075        return result;
076    }
077}