1 /*
   2  * Copyright (c) 1997, 2014, 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 
  26 package javax.swing;
  27 
  28 import java.util.List;
  29 import java.util.ArrayList;
  30 import java.util.Collection;
  31 import java.util.Iterator;
  32 import javax.swing.plaf.*;
  33 import javax.accessibility.*;
  34 
  35 import java.awt.Component;
  36 import java.awt.Container;
  37 import java.awt.DefaultFocusTraversalPolicy;
  38 import java.awt.FocusTraversalPolicy;
  39 import java.awt.Window;
  40 import java.io.ObjectOutputStream;
  41 import java.io.ObjectInputStream;
  42 import java.io.IOException;
  43 import java.beans.PropertyVetoException;
  44 import java.util.Set;
  45 import java.util.TreeSet;
  46 /**
  47  * A container used to create a multiple-document interface or a virtual desktop.
  48  * You create <code>JInternalFrame</code> objects and add them to the
  49  * <code>JDesktopPane</code>. <code>JDesktopPane</code> extends
  50  * <code>JLayeredPane</code> to manage the potentially overlapping internal
  51  * frames. It also maintains a reference to an instance of
  52  * <code>DesktopManager</code> that is set by the UI
  53  * class for the current look and feel (L&amp;F).  Note that <code>JDesktopPane</code>
  54  * does not support borders.
  55  * <p>
  56  * This class is normally used as the parent of <code>JInternalFrames</code>
  57  * to provide a pluggable <code>DesktopManager</code> object to the
  58  * <code>JInternalFrames</code>. The <code>installUI</code> of the
  59  * L&amp;F specific implementation is responsible for setting the
  60  * <code>desktopManager</code> variable appropriately.
  61  * When the parent of a <code>JInternalFrame</code> is a <code>JDesktopPane</code>,
  62  * it should delegate most of its behavior to the <code>desktopManager</code>
  63  * (closing, resizing, etc).
  64  * <p>
  65  * For further documentation and examples see
  66  * <a href="http://docs.oracle.com/javase/tutorial/uiswing/components/internalframe.html">How to Use Internal Frames</a>,
  67  * a section in <em>The Java Tutorial</em>.
  68  * <p>
  69  * <strong>Warning:</strong> Swing is not thread safe. For more
  70  * information see <a
  71  * href="package-summary.html#threading">Swing's Threading
  72  * Policy</a>.
  73  * <p>
  74  * <strong>Warning:</strong>
  75  * Serialized objects of this class will not be compatible with
  76  * future Swing releases. The current serialization support is
  77  * appropriate for short term storage or RMI between applications running
  78  * the same version of Swing.  As of 1.4, support for long term storage
  79  * of all JavaBeans&trade;
  80  * has been added to the <code>java.beans</code> package.
  81  * Please see {@link java.beans.XMLEncoder}.
  82  *
  83  * @see JInternalFrame
  84  * @see JInternalFrame.JDesktopIcon
  85  * @see DesktopManager
  86  *
  87  * @author David Kloba
  88  */
  89 @SuppressWarnings("serial") // Same-version serialization only
  90 public class JDesktopPane extends JLayeredPane implements Accessible
  91 {
  92     /**
  93      * @see #getUIClassID
  94      * @see #readObject
  95      */
  96     private static final String uiClassID = "DesktopPaneUI";
  97 
  98     transient DesktopManager desktopManager;
  99 
 100     private transient JInternalFrame selectedFrame = null;
 101 
 102     /**
 103       * Indicates that the entire contents of the item being dragged
 104       * should appear inside the desktop pane.
 105       *
 106       * @see #OUTLINE_DRAG_MODE
 107       * @see #setDragMode
 108       */
 109     public static final int LIVE_DRAG_MODE = 0;
 110 
 111     /**
 112       * Indicates that an outline only of the item being dragged
 113       * should appear inside the desktop pane.
 114       *
 115       * @see #LIVE_DRAG_MODE
 116       * @see #setDragMode
 117       */
 118     public static final int OUTLINE_DRAG_MODE = 1;
 119 
 120     private int dragMode = LIVE_DRAG_MODE;
 121     private boolean dragModeSet = false;
 122     private transient List<JInternalFrame> framesCache;
 123     private boolean componentOrderCheckingEnabled = true;
 124     private boolean componentOrderChanged = false;
 125 
 126     /**
 127      * Creates a new <code>JDesktopPane</code>.
 128      */
 129     public JDesktopPane() {
 130         setUIProperty("opaque", Boolean.TRUE);
 131         setFocusCycleRoot(true);
 132 
 133         setFocusTraversalPolicy(new LayoutFocusTraversalPolicy() {
 134             public Component getDefaultComponent(Container c) {
 135                 JInternalFrame jifArray[] = getAllFrames();
 136                 Component comp = null;
 137                 for (JInternalFrame jif : jifArray) {
 138                     comp = jif.getFocusTraversalPolicy().getDefaultComponent(jif);
 139                     if (comp != null) {
 140                         break;
 141                     }
 142                 }
 143                 return comp;
 144             }
 145         });
 146         updateUI();
 147     }
 148 
 149     /**
 150      * Returns the L&amp;F object that renders this component.
 151      *
 152      * @return the <code>DesktopPaneUI</code> object that
 153      *   renders this component
 154      */
 155     public DesktopPaneUI getUI() {
 156         return (DesktopPaneUI)ui;
 157     }
 158 
 159     /**
 160      * Sets the L&amp;F object that renders this component.
 161      *
 162      * @param ui  the DesktopPaneUI L&amp;F object
 163      * @see UIDefaults#getUI
 164      * @beaninfo
 165      *        bound: true
 166      *       hidden: true
 167      *    attribute: visualUpdate true
 168      *  description: The UI object that implements the Component's LookAndFeel.
 169      */
 170     public void setUI(DesktopPaneUI ui) {
 171         super.setUI(ui);
 172     }
 173 
 174     /**
 175      * Sets the "dragging style" used by the desktop pane.
 176      * You may want to change to one mode or another for
 177      * performance or aesthetic reasons.
 178      *
 179      * @param dragMode the style of drag to use for items in the Desktop
 180      *
 181      * @see #LIVE_DRAG_MODE
 182      * @see #OUTLINE_DRAG_MODE
 183      *
 184      * @beaninfo
 185      *        bound: true
 186      *  description: Dragging style for internal frame children.
 187      *         enum: LIVE_DRAG_MODE JDesktopPane.LIVE_DRAG_MODE
 188      *               OUTLINE_DRAG_MODE JDesktopPane.OUTLINE_DRAG_MODE
 189      * @since 1.3
 190      */
 191     public void setDragMode(int dragMode) {
 192         int oldDragMode = this.dragMode;
 193         this.dragMode = dragMode;
 194         firePropertyChange("dragMode", oldDragMode, this.dragMode);
 195         dragModeSet = true;
 196      }
 197 
 198     /**
 199      * Gets the current "dragging style" used by the desktop pane.
 200      * @return either <code>Live_DRAG_MODE</code> or
 201      *   <code>OUTLINE_DRAG_MODE</code>
 202      * @see #setDragMode
 203      * @since 1.3
 204      */
 205      public int getDragMode() {
 206          return dragMode;
 207      }
 208 
 209     /**
 210      * Returns the <code>DesktopManger</code> that handles
 211      * desktop-specific UI actions.
 212      */
 213     public DesktopManager getDesktopManager() {
 214         return desktopManager;
 215     }
 216 
 217     /**
 218      * Sets the <code>DesktopManger</code> that will handle
 219      * desktop-specific UI actions. This may be overridden by
 220      * {@code LookAndFeel}.
 221      *
 222      * @param d the <code>DesktopManager</code> to use
 223      *
 224      * @beaninfo
 225      *        bound: true
 226      *  description: Desktop manager to handle the internal frames in the
 227      *               desktop pane.
 228      */
 229     public void setDesktopManager(DesktopManager d) {
 230         DesktopManager oldValue = desktopManager;
 231         desktopManager = d;
 232         firePropertyChange("desktopManager", oldValue, desktopManager);
 233     }
 234 
 235     /**
 236      * Notification from the <code>UIManager</code> that the L&amp;F has changed.
 237      * Replaces the current UI object with the latest version from the
 238      * <code>UIManager</code>.
 239      *
 240      * @see JComponent#updateUI
 241      */
 242     public void updateUI() {
 243         setUI((DesktopPaneUI)UIManager.getUI(this));
 244     }
 245 
 246 
 247     /**
 248      * Returns the name of the L&amp;F class that renders this component.
 249      *
 250      * @return the string "DesktopPaneUI"
 251      * @see JComponent#getUIClassID
 252      * @see UIDefaults#getUI
 253      */
 254     public String getUIClassID() {
 255         return uiClassID;
 256     }
 257 
 258     /**
 259      * Returns all <code>JInternalFrames</code> currently displayed in the
 260      * desktop. Returns iconified frames as well as expanded frames.
 261      *
 262      * @return an array of <code>JInternalFrame</code> objects
 263      */
 264     public JInternalFrame[] getAllFrames() {
 265         return getAllFrames(this).toArray(new JInternalFrame[0]);
 266     }
 267 
 268     private static Collection<JInternalFrame> getAllFrames(Container parent) {
 269         int i, count;
 270         Collection<JInternalFrame> results = new ArrayList<JInternalFrame>();
 271         count = parent.getComponentCount();
 272         for (i = 0; i < count; i++) {
 273             Component next = parent.getComponent(i);
 274             if (next instanceof JInternalFrame) {
 275                 results.add((JInternalFrame) next);
 276             } else if (next instanceof JInternalFrame.JDesktopIcon) {
 277                 JInternalFrame tmp = ((JInternalFrame.JDesktopIcon) next).getInternalFrame();
 278                 if (tmp != null) {
 279                     results.add(tmp);
 280                 }
 281             } else if (next instanceof Container) {
 282                 results.addAll(getAllFrames((Container) next));
 283             }
 284         }
 285         return results;
 286     }
 287 
 288     /** Returns the currently active <code>JInternalFrame</code>
 289       * in this <code>JDesktopPane</code>, or <code>null</code>
 290       * if no <code>JInternalFrame</code> is currently active.
 291       *
 292       * @return the currently active <code>JInternalFrame</code> or
 293       *   <code>null</code>
 294       * @since 1.3
 295       */
 296 
 297     public JInternalFrame getSelectedFrame() {
 298       return selectedFrame;
 299     }
 300 
 301     /** Sets the currently active <code>JInternalFrame</code>
 302      *  in this <code>JDesktopPane</code>. This method is used to bridge
 303      *  the package gap between JDesktopPane and the platform implementation
 304      *  code and should not be called directly. To visually select the frame
 305      *  the client must call JInternalFrame.setSelected(true) to activate
 306      *  the frame.
 307      *  @see JInternalFrame#setSelected(boolean)
 308      *
 309      * @param f the internal frame that's currently selected
 310      * @since 1.3
 311      */
 312 
 313     public void setSelectedFrame(JInternalFrame f) {
 314       selectedFrame = f;
 315     }
 316 
 317     /**
 318      * Returns all <code>JInternalFrames</code> currently displayed in the
 319      * specified layer of the desktop. Returns iconified frames as well
 320      * expanded frames.
 321      *
 322      * @param layer  an int specifying the desktop layer
 323      * @return an array of <code>JInternalFrame</code> objects
 324      * @see JLayeredPane
 325      */
 326     public JInternalFrame[] getAllFramesInLayer(int layer) {
 327         Collection<JInternalFrame> allFrames = getAllFrames(this);
 328         Iterator<JInternalFrame> iterator = allFrames.iterator();
 329         while (iterator.hasNext()) {
 330             if (iterator.next().getLayer() != layer) {
 331                 iterator.remove();
 332             }
 333         }
 334         return allFrames.toArray(new JInternalFrame[0]);
 335     }
 336 
 337     private List<JInternalFrame> getFrames() {
 338         Component c;
 339         Set<ComponentPosition> set = new TreeSet<ComponentPosition>();
 340         for (int i = 0; i < getComponentCount(); i++) {
 341             c = getComponent(i);
 342             if (c instanceof JInternalFrame) {
 343                 set.add(new ComponentPosition((JInternalFrame)c, getLayer(c),
 344                     i));
 345             }
 346             else if (c instanceof JInternalFrame.JDesktopIcon)  {
 347                 c = ((JInternalFrame.JDesktopIcon)c).getInternalFrame();
 348                 set.add(new ComponentPosition((JInternalFrame)c, getLayer(c),
 349                     i));
 350             }
 351         }
 352         List<JInternalFrame> frames = new ArrayList<JInternalFrame>(
 353                 set.size());
 354         for (ComponentPosition position : set) {
 355             frames.add(position.component);
 356         }
 357         return frames;
 358    }
 359 
 360     private static class ComponentPosition implements
 361         Comparable<ComponentPosition> {
 362         private final JInternalFrame component;
 363         private final int layer;
 364         private final int zOrder;
 365 
 366         ComponentPosition(JInternalFrame component, int layer, int zOrder) {
 367             this.component = component;
 368             this.layer = layer;
 369             this.zOrder = zOrder;
 370         }
 371 
 372         public int compareTo(ComponentPosition o) {
 373             int delta = o.layer - layer;
 374             if (delta == 0) {
 375                 return zOrder - o.zOrder;
 376             }
 377             return delta;
 378         }
 379     }
 380 
 381     private JInternalFrame getNextFrame(JInternalFrame f, boolean forward) {
 382         verifyFramesCache();
 383         if (f == null) {
 384             return getTopInternalFrame();
 385         }
 386         int i = framesCache.indexOf(f);
 387         if (i == -1 || framesCache.size() == 1) {
 388             /* error */
 389             return null;
 390         }
 391         if (forward) {
 392             // navigate to the next frame
 393             if (++i == framesCache.size()) {
 394                 /* wrap */
 395                 i = 0;
 396             }
 397         }
 398         else {
 399             // navigate to the previous frame
 400             if (--i == -1) {
 401                 /* wrap */
 402                 i = framesCache.size() - 1;
 403             }
 404         }
 405         return framesCache.get(i);
 406     }
 407 
 408     JInternalFrame getNextFrame(JInternalFrame f) {
 409         return getNextFrame(f, true);
 410     }
 411 
 412     private JInternalFrame getTopInternalFrame() {
 413         if (framesCache.size() == 0) {
 414             return null;
 415         }
 416         return framesCache.get(0);
 417     }
 418 
 419     private void updateFramesCache() {
 420         framesCache = getFrames();
 421     }
 422 
 423     private void verifyFramesCache() {
 424         // If framesCache is dirty, then recreate it.
 425         if (componentOrderChanged) {
 426             componentOrderChanged = false;
 427             updateFramesCache();
 428         }
 429     }
 430 
 431     /**
 432      * {@inheritDoc}
 433      */
 434     @Override
 435     public void remove(Component comp) {
 436         super.remove(comp);
 437         updateFramesCache();
 438     }
 439 
 440     /**
 441      * Selects the next <code>JInternalFrame</code> in this desktop pane.
 442      *
 443      * @param forward a boolean indicating which direction to select in;
 444      *        <code>true</code> for forward, <code>false</code> for
 445      *        backward
 446      * @return the JInternalFrame that was selected or <code>null</code>
 447      *         if nothing was selected
 448      * @since 1.6
 449      */
 450     public JInternalFrame selectFrame(boolean forward) {
 451         JInternalFrame selectedFrame = getSelectedFrame();
 452         JInternalFrame frameToSelect = getNextFrame(selectedFrame, forward);
 453         if (frameToSelect == null) {
 454             return null;
 455         }
 456         // Maintain navigation traversal order until an
 457         // external stack change, such as a click on a frame.
 458         setComponentOrderCheckingEnabled(false);
 459         if (forward && selectedFrame != null) {
 460             selectedFrame.moveToBack();  // For Windows MDI fidelity.
 461         }
 462         try { frameToSelect.setSelected(true);
 463         } catch (PropertyVetoException pve) {}
 464         setComponentOrderCheckingEnabled(true);
 465         return frameToSelect;
 466     }
 467 
 468     /*
 469      * Sets whether component order checking is enabled.
 470      * @param enable a boolean value, where <code>true</code> means
 471      * a change in component order will cause a change in the keyboard
 472      * navigation order.
 473      * @since 1.6
 474      */
 475     void setComponentOrderCheckingEnabled(boolean enable) {
 476         componentOrderCheckingEnabled = enable;
 477     }
 478 
 479     /**
 480      * {@inheritDoc}
 481      * @since 1.6
 482      */
 483     protected void addImpl(Component comp, Object constraints, int index) {
 484         super.addImpl(comp, constraints, index);
 485         if (componentOrderCheckingEnabled) {
 486             if (comp instanceof JInternalFrame ||
 487                 comp instanceof JInternalFrame.JDesktopIcon) {
 488                 componentOrderChanged = true;
 489             }
 490         }
 491     }
 492 
 493     /**
 494      * {@inheritDoc}
 495      * @since 1.6
 496      */
 497     public void remove(int index) {
 498         if (componentOrderCheckingEnabled) {
 499             Component comp = getComponent(index);
 500             if (comp instanceof JInternalFrame ||
 501                 comp instanceof JInternalFrame.JDesktopIcon) {
 502                 componentOrderChanged = true;
 503             }
 504         }
 505         super.remove(index);
 506     }
 507 
 508     /**
 509      * {@inheritDoc}
 510      * @since 1.6
 511      */
 512     public void removeAll() {
 513         if (componentOrderCheckingEnabled) {
 514             int count = getComponentCount();
 515             for (int i = 0; i < count; i++) {
 516                 Component comp = getComponent(i);
 517                 if (comp instanceof JInternalFrame ||
 518                     comp instanceof JInternalFrame.JDesktopIcon) {
 519                     componentOrderChanged = true;
 520                     break;
 521                 }
 522             }
 523         }
 524         super.removeAll();
 525     }
 526 
 527     /**
 528      * {@inheritDoc}
 529      * @since 1.6
 530      */
 531     public void setComponentZOrder(Component comp, int index) {
 532         super.setComponentZOrder(comp, index);
 533         if (componentOrderCheckingEnabled) {
 534             if (comp instanceof JInternalFrame ||
 535                 comp instanceof JInternalFrame.JDesktopIcon) {
 536                 componentOrderChanged = true;
 537             }
 538         }
 539     }
 540 
 541     /**
 542      * See readObject() and writeObject() in JComponent for more
 543      * information about serialization in Swing.
 544      */
 545     private void writeObject(ObjectOutputStream s) throws IOException {
 546         s.defaultWriteObject();
 547         if (getUIClassID().equals(uiClassID)) {
 548             byte count = JComponent.getWriteObjCounter(this);
 549             JComponent.setWriteObjCounter(this, --count);
 550             if (count == 0 && ui != null) {
 551                 ui.installUI(this);
 552             }
 553         }
 554     }
 555 
 556     void setUIProperty(String propertyName, Object value) {
 557         if (propertyName == "dragMode") {
 558             if (!dragModeSet) {
 559                 setDragMode(((Integer)value).intValue());
 560                 dragModeSet = false;
 561             }
 562         } else {
 563             super.setUIProperty(propertyName, value);
 564         }
 565     }
 566 
 567     /**
 568      * Returns a string representation of this <code>JDesktopPane</code>.
 569      * This method is intended to be used only for debugging purposes, and the
 570      * content and format of the returned string may vary between
 571      * implementations. The returned string may be empty but may not
 572      * be <code>null</code>.
 573      *
 574      * @return  a string representation of this <code>JDesktopPane</code>
 575      */
 576     protected String paramString() {
 577         String desktopManagerString = (desktopManager != null ?
 578                                        desktopManager.toString() : "");
 579 
 580         return super.paramString() +
 581         ",desktopManager=" + desktopManagerString;
 582     }
 583 
 584 /////////////////
 585 // Accessibility support
 586 ////////////////
 587 
 588     /**
 589      * Gets the <code>AccessibleContext</code> associated with this
 590      * <code>JDesktopPane</code>. For desktop panes, the
 591      * <code>AccessibleContext</code> takes the form of an
 592      * <code>AccessibleJDesktopPane</code>.
 593      * A new <code>AccessibleJDesktopPane</code> instance is created if necessary.
 594      *
 595      * @return an <code>AccessibleJDesktopPane</code> that serves as the
 596      *         <code>AccessibleContext</code> of this <code>JDesktopPane</code>
 597      */
 598     public AccessibleContext getAccessibleContext() {
 599         if (accessibleContext == null) {
 600             accessibleContext = new AccessibleJDesktopPane();
 601         }
 602         return accessibleContext;
 603     }
 604 
 605     /**
 606      * This class implements accessibility support for the
 607      * <code>JDesktopPane</code> class.  It provides an implementation of the
 608      * Java Accessibility API appropriate to desktop pane user-interface
 609      * elements.
 610      * <p>
 611      * <strong>Warning:</strong>
 612      * Serialized objects of this class will not be compatible with
 613      * future Swing releases. The current serialization support is
 614      * appropriate for short term storage or RMI between applications running
 615      * the same version of Swing.  As of 1.4, support for long term storage
 616      * of all JavaBeans&trade;
 617      * has been added to the <code>java.beans</code> package.
 618      * Please see {@link java.beans.XMLEncoder}.
 619      */
 620     @SuppressWarnings("serial") // Same-version serialization only
 621     protected class AccessibleJDesktopPane extends AccessibleJComponent {
 622 
 623         /**
 624          * Get the role of this object.
 625          *
 626          * @return an instance of AccessibleRole describing the role of the
 627          * object
 628          * @see AccessibleRole
 629          */
 630         public AccessibleRole getAccessibleRole() {
 631             return AccessibleRole.DESKTOP_PANE;
 632         }
 633     }
 634 }