1278 lines · 41.6 KB · Java
RawDownload
/* * Copyright (c) 1995, 2008, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation.  Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package sun.applet; import java.util.*;import java.io.*;import java.awt.*;import java.awt.event.*;import java.awt.print.*;import javax.print.attribute.*;import java.applet.*;import java.net.URL;import java.net.MalformedURLException;import java.net.SocketPermission;import sun.misc.Ref;import java.security.AccessController;import java.security.PrivilegedAction;import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;import sun.awt.SunToolkit;import sun.awt.AppContext;import java.lang.ref.WeakReference; /** * A frame to show the applet tag in. */class TextFrame extends Frame {     /**     * Create the tag frame.     */    TextFrame(int x, int y, String title, String text) {        setTitle(title);        TextArea txt = new TextArea(20, 60);        txt.setText(text);        txt.setEditable(false);         add("Center", txt);         Panel p = new Panel();        add("South", p);        Button b = new Button(amh.getMessage("button.dismiss", "Dismiss"));        p.add(b);         class ActionEventListener implements ActionListener {            public void actionPerformed(ActionEvent evt) {                dispose();            }        }        b.addActionListener(new ActionEventListener());         pack();        move(x, y);        setVisible(true);         WindowListener windowEventListener = new WindowAdapter() {             public void windowClosing(WindowEvent evt) {                dispose();            }        };         addWindowListener(windowEventListener);    }    private static AppletMessageHandler amh = new AppletMessageHandler("textframe"); } /** * Lets us construct one using unix-style one shot behaviors */ class StdAppletViewerFactory implements AppletViewerFactory{    public AppletViewer createAppletViewer(int x, int y,                                           URL doc, Hashtable atts) {        return new AppletViewer(x, y, doc, atts, System.out, this);    }     public MenuBar getBaseMenuBar() {        return new MenuBar();    }     public boolean isStandalone() {        return true;    }} /** * The applet viewer makes it possible to run a Java applet without using a browser. * For details on the syntax that <B>appletviewer</B> supports, see * <a href="../../../docs/tooldocs/appletviewertags.html">AppletViewer Tags</a>. * (The document named appletviewertags.html in the JDK's docs/tooldocs directory, *  once the JDK docs have been installed.) */public class AppletViewer extends Frame implements AppletContext,                                                   Printable {     /**     * Some constants...     */    private static String defaultSaveFile = "Applet.ser";     /**     * The panel in which the applet is being displayed.     */    AppletViewerPanel panel;     /**     * The status line.     */    Label label;     /**     * output status messages to this stream     */     PrintStream statusMsgStream;     /**     * For cloning     */    AppletViewerFactory factory;      private final class UserActionListener implements ActionListener {        public void actionPerformed(ActionEvent evt) {            processUserAction(evt);        }    }     /**     * Create the applet viewer     */    public AppletViewer(int x, int y, URL doc, Hashtable atts,                        PrintStream statusMsgStream, AppletViewerFactory factory) {        this.factory = factory;        this.statusMsgStream = statusMsgStream;        setTitle(amh.getMessage("tool.title", atts.get("code")));         MenuBar mb = factory.getBaseMenuBar();         Menu m = new Menu(amh.getMessage("menu.applet"));         addMenuItem(m, "menuitem.restart");        addMenuItem(m, "menuitem.reload");        addMenuItem(m, "menuitem.stop");        addMenuItem(m, "menuitem.save");        addMenuItem(m, "menuitem.start");        addMenuItem(m, "menuitem.clone");        m.add(new MenuItem("-"));        addMenuItem(m, "menuitem.tag");        addMenuItem(m, "menuitem.info");        addMenuItem(m, "menuitem.edit").disable();        addMenuItem(m, "menuitem.encoding");        m.add(new MenuItem("-"));        addMenuItem(m, "menuitem.print");        m.add(new MenuItem("-"));        addMenuItem(m, "menuitem.props");        m.add(new MenuItem("-"));        addMenuItem(m, "menuitem.close");        if (factory.isStandalone()) {            addMenuItem(m, "menuitem.quit");        }         mb.add(m);         setMenuBar(mb);         add("Center", panel = new AppletViewerPanel(doc, atts));        add("South", label = new Label(amh.getMessage("label.hello")));        panel.init();        appletPanels.addElement(panel);         pack();        move(x, y);        setVisible(true);         WindowListener windowEventListener = new WindowAdapter() {             public void windowClosing(WindowEvent evt) {                appletClose();            }             public void windowIconified(WindowEvent evt) {                appletStop();            }             public void windowDeiconified(WindowEvent evt) {                appletStart();            }        };         class AppletEventListener implements AppletListener        {            final Frame frame;             public AppletEventListener(Frame frame)            {                this.frame = frame;            }             public void appletStateChanged(AppletEvent evt)            {                AppletPanel src = (AppletPanel)evt.getSource();                 switch (evt.getID()) {                    case AppletPanel.APPLET_RESIZE: {                        if(src != null) {                            resize(preferredSize());                            validate();                        }                        break;                    }                    case AppletPanel.APPLET_LOADING_COMPLETED: {                        Applet a = src.getApplet(); // sun.applet.AppletPanel                         // Fixed #4754451: Applet can have methods running on main                        // thread event queue.                        //                        // The cause of this bug is that the frame of the applet                        // is created in main thread group. Thus, when certain                        // AWT/Swing events are generated, the events will be                        // dispatched through the wrong event dispatch thread.                        //                        // To fix this, we rearrange the AppContext with the frame,                        // so the proper event queue will be looked up.                        //                        // Swing also maintains a Frame list for the AppContext,                        // so we will have to rearrange it as well.                        //                        if (a != null)                            AppletPanel.changeFrameAppContext(frame, SunToolkit.targetToAppContext(a));                        else                            AppletPanel.changeFrameAppContext(frame, AppContext.getAppContext());                         break;                    }                }            }        };         addWindowListener(windowEventListener);        panel.addAppletListener(new AppletEventListener(this));         // Start the applet        showStatus(amh.getMessage("status.start"));        initEventQueue();    }     // XXX 99/9/10 probably should be "private"    public MenuItem addMenuItem(Menu m, String s) {        MenuItem mItem = new MenuItem(amh.getMessage(s));        mItem.addActionListener(new UserActionListener());        return m.add(mItem);    }     /**     * Send the initial set of events to the appletviewer event queue.     * On start-up the current behaviour is to load the applet and call     * Applet.init() and Applet.start().     */    private void initEventQueue() {        // appletviewer.send.event is an undocumented and unsupported system        // property which is used exclusively for testing purposes.        String eventList = System.getProperty("appletviewer.send.event");         if (eventList == null) {            // Add the standard events onto the event queue.            panel.sendEvent(AppletPanel.APPLET_LOAD);            panel.sendEvent(AppletPanel.APPLET_INIT);            panel.sendEvent(AppletPanel.APPLET_START);        } else {            // We're testing AppletViewer.  Force the specified set of events            // onto the event queue, wait for the events to be processed, and            // exit.             // The list of events that will be executed is provided as a            // ","-separated list.  No error-checking will be done on the list.            String [] events = splitSeparator(",", eventList);             for (int i = 0; i < events.length; i++) {                System.out.println("Adding event to queue: " + events[i]);                if (events[i].equals("dispose"))                    panel.sendEvent(AppletPanel.APPLET_DISPOSE);                else if (events[i].equals("load"))                    panel.sendEvent(AppletPanel.APPLET_LOAD);                else if (events[i].equals("init"))                    panel.sendEvent(AppletPanel.APPLET_INIT);                else if (events[i].equals("start"))                    panel.sendEvent(AppletPanel.APPLET_START);                else if (events[i].equals("stop"))                    panel.sendEvent(AppletPanel.APPLET_STOP);                else if (events[i].equals("destroy"))                    panel.sendEvent(AppletPanel.APPLET_DESTROY);                else if (events[i].equals("quit"))                    panel.sendEvent(AppletPanel.APPLET_QUIT);                else if (events[i].equals("error"))                    panel.sendEvent(AppletPanel.APPLET_ERROR);                else                    // non-fatal error if we get an unrecognized event                    System.out.println("Unrecognized event name: " + events[i]);            }             while (!panel.emptyEventQueue()) ;            appletSystemExit();        }    }     /**     * Split a string based on the presence of a specified separator.  Returns     * an array of arbitrary length.  The end of each element in the array is     * indicated by the separator of the end of the string.  If there is a     * separator immediately before the end of the string, the final element     * will be empty.  None of the strings will contain the separator.  Useful     * when separating strings such as "foo/bar/bas" using separator "/".     *     * @param sep  The separator.     * @param s    The string to split.     * @return     An array of strings.  Each string in the array is determined     *             by the location of the provided sep in the original string,     *             s.  Whitespace not stripped.     */    private String [] splitSeparator(String sep, String s) {        Vector v = new Vector();        int tokenStart = 0;        int tokenEnd   = 0;         while ((tokenEnd = s.indexOf(sep, tokenStart)) != -1) {            v.addElement(s.substring(tokenStart, tokenEnd));            tokenStart = tokenEnd+1;        }        // Add the final element.        v.addElement(s.substring(tokenStart));         String [] retVal = new String[v.size()];        v.copyInto(retVal);        return retVal;    }     /*     * Methods for java.applet.AppletContext     */     private static Map audioClips = new HashMap();     /**     * Get an audio clip.     */    public AudioClip getAudioClip(URL url) {        checkConnect(url);        synchronized (audioClips) {            AudioClip clip = (AudioClip)audioClips.get(url);            if (clip == null) {                audioClips.put(url, clip = new AppletAudioClip(url));            }            return clip;        }    }     private static Map imageRefs = new HashMap();     /**     * Get an image.     */    public Image getImage(URL url) {        return getCachedImage(url);    }     static Image getCachedImage(URL url) {        // System.getSecurityManager().checkConnection(url.getHost(), url.getPort());        return (Image)getCachedImageRef(url).get();    }     /**     * Get an image ref.     */    static Ref getCachedImageRef(URL url) {        synchronized (imageRefs) {            AppletImageRef ref = (AppletImageRef)imageRefs.get(url);            if (ref == null) {                ref = new AppletImageRef(url);                imageRefs.put(url, ref);            }            return ref;        }    }     /**     * Flush the image cache.     */    static void flushImageCache() {        imageRefs.clear();    }     static Vector appletPanels = new Vector();     /**     * Get an applet by name.     */    public Applet getApplet(String name) {        AppletSecurity security = (AppletSecurity)System.getSecurityManager();        name = name.toLowerCase();        SocketPermission panelSp =            new SocketPermission(panel.getCodeBase().getHost(), "connect");        for (Enumeration e = appletPanels.elements() ; e.hasMoreElements() ;) {            AppletPanel p = (AppletPanel)e.nextElement();            String param = p.getParameter("name");            if (param != null) {                param = param.toLowerCase();            }            if (name.equals(param) &&                p.getDocumentBase().equals(panel.getDocumentBase())) {                 SocketPermission sp =                    new SocketPermission(p.getCodeBase().getHost(), "connect");                 if (panelSp.implies(sp)) {                    return p.applet;                }            }        }        return null;    }     /**     * Return an enumeration of all the accessible     * applets on this page.     */    public Enumeration getApplets() {        AppletSecurity security = (AppletSecurity)System.getSecurityManager();        Vector v = new Vector();        SocketPermission panelSp =            new SocketPermission(panel.getCodeBase().getHost(), "connect");         for (Enumeration e = appletPanels.elements() ; e.hasMoreElements() ;) {            AppletPanel p = (AppletPanel)e.nextElement();            if (p.getDocumentBase().equals(panel.getDocumentBase())) {                 SocketPermission sp =                    new SocketPermission(p.getCodeBase().getHost(), "connect");                if (panelSp.implies(sp)) {                    v.addElement(p.applet);                }            }        }        return v.elements();    }     /**     * Ignore.     */    public void showDocument(URL url) {    }     /**     * Ignore.     */    public void showDocument(URL url, String target) {    }     /**     * Show status.     */    public void showStatus(String status) {        label.setText(status);    }     public void setStream(String key, InputStream stream)throws IOException{        // We do nothing.    }     public InputStream getStream(String key){        // We do nothing.        return null;    } 

Lines 1–500 of 1278.