1 /*
   2  * Copyright (c) 1999, 2006, 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 sun.awt.datatransfer;
  27 
  28 import java.awt.EventQueue;
  29 
  30 import java.awt.datatransfer.Clipboard;
  31 import java.awt.datatransfer.FlavorTable;
  32 import java.awt.datatransfer.SystemFlavorMap;
  33 import java.awt.datatransfer.Transferable;
  34 import java.awt.datatransfer.ClipboardOwner;
  35 import java.awt.datatransfer.DataFlavor;
  36 import java.awt.datatransfer.FlavorListener;
  37 import java.awt.datatransfer.FlavorEvent;
  38 import java.awt.datatransfer.UnsupportedFlavorException;
  39 
  40 import java.beans.PropertyChangeEvent;
  41 import java.beans.PropertyChangeListener;
  42 
  43 import java.util.Iterator;
  44 import java.util.Set;
  45 import java.util.HashSet;
  46 
  47 import java.io.IOException;
  48 
  49 import sun.awt.AppContext;
  50 import sun.awt.PeerEvent;
  51 import sun.awt.SunToolkit;
  52 import sun.awt.EventListenerAggregate;
  53 
  54 
  55 /**
  56  * Serves as a common, helper superclass for the Win32 and X11 system
  57  * Clipboards.
  58  *
  59  * @author Danila Sinopalnikov
  60  * @author Alexander Gerasimov
  61  *
  62  * @since 1.3
  63  */
  64 public abstract class SunClipboard extends Clipboard
  65     implements PropertyChangeListener {
  66 
  67     public static final FlavorTable flavorMap =
  68         (FlavorTable)SystemFlavorMap.getDefaultFlavorMap();
  69 
  70     private AppContext contentsContext = null;
  71 
  72     private final Object CLIPBOARD_FLAVOR_LISTENER_KEY;
  73 
  74     /**
  75      * A number of <code>FlavorListener</code>s currently registered
  76      * on this clipboard across all <code>AppContext</code>s.
  77      */
  78     private volatile int numberOfFlavorListeners = 0;
  79 
  80     /**
  81      * A set of <code>DataFlavor</code>s that is available on
  82      * this clipboard. It is used for tracking changes
  83      * of <code>DataFlavor</code>s available on this clipboard.
  84      */
  85     private volatile Set currentDataFlavors;
  86 
  87 
  88     public SunClipboard(String name) {
  89         super(name);
  90         CLIPBOARD_FLAVOR_LISTENER_KEY = new StringBuffer(name + "_CLIPBOARD_FLAVOR_LISTENER_KEY");
  91     }
  92 
  93     public synchronized void setContents(Transferable contents,
  94                                          ClipboardOwner owner) {
  95         // 4378007 : Toolkit.getSystemClipboard().setContents(null, null)
  96         // should throw NPE
  97         if (contents == null) {
  98             throw new NullPointerException("contents");
  99         }
 100 
 101         initContext();
 102 
 103         final ClipboardOwner oldOwner = this.owner;
 104         final Transferable oldContents = this.contents;
 105 
 106         try {
 107             this.owner = owner;
 108             this.contents = new TransferableProxy(contents, true);
 109 
 110             setContentsNative(contents);
 111         } finally {
 112             if (oldOwner != null && oldOwner != owner) {
 113                 EventQueue.invokeLater(new Runnable() {
 114                     public void run() {
 115                         oldOwner.lostOwnership(SunClipboard.this, oldContents);
 116                     }
 117                 });
 118             }
 119         }
 120     }
 121 
 122     private synchronized void initContext() {
 123         final AppContext context = AppContext.getAppContext();
 124 
 125         if (contentsContext != context) {
 126             // Need to synchronize on the AppContext to guarantee that it cannot
 127             // be disposed after the check, but before the listener is added.
 128             synchronized (context) {
 129                 if (context.isDisposed()) {
 130                     throw new IllegalStateException("Can't set contents from disposed AppContext");
 131                 }
 132                 context.addPropertyChangeListener
 133                     (AppContext.DISPOSED_PROPERTY_NAME, this);
 134             }
 135             if (contentsContext != null) {
 136                 contentsContext.removePropertyChangeListener
 137                     (AppContext.DISPOSED_PROPERTY_NAME, this);
 138             }
 139             contentsContext = context;
 140         }
 141     }
 142 
 143     public synchronized Transferable getContents(Object requestor) {
 144         if (contents != null) {
 145             return contents;
 146         }
 147         return new ClipboardTransferable(this);
 148     }
 149 
 150 
 151     /**
 152      * @return the contents of this clipboard if it has been set from the same
 153      *         AppContext as it is currently retrieved or null otherwise
 154      * @since 1.5
 155      */
 156     private synchronized Transferable getContextContents() {
 157         AppContext context = AppContext.getAppContext();
 158         return (context == contentsContext) ? contents : null;
 159     }
 160 
 161 
 162     /**
 163      * @see java.awt.Clipboard#getAvailableDataFlavors
 164      * @since 1.5
 165      */
 166     public DataFlavor[] getAvailableDataFlavors() {
 167         Transferable cntnts = getContextContents();
 168         if (cntnts != null) {
 169             return cntnts.getTransferDataFlavors();
 170         }
 171 
 172         long[] formats = getClipboardFormatsOpenClose();
 173 
 174         return DataTransferer.getInstance().
 175             getFlavorsForFormatsAsArray(formats, flavorMap);
 176     }
 177 
 178     /**
 179      * @see java.awt.Clipboard#isDataFlavorAvailable
 180      * @since 1.5
 181      */
 182     public boolean isDataFlavorAvailable(DataFlavor flavor) {
 183         if (flavor == null) {
 184             throw new NullPointerException("flavor");
 185         }
 186 
 187         Transferable cntnts = getContextContents();
 188         if (cntnts != null) {
 189             return cntnts.isDataFlavorSupported(flavor);
 190         }
 191 
 192         long[] formats = getClipboardFormatsOpenClose();
 193 
 194         return formatArrayAsDataFlavorSet(formats).contains(flavor);
 195     }
 196 
 197     /**
 198      * @see java.awt.Clipboard#getData
 199      * @since 1.5
 200      */
 201     public Object getData(DataFlavor flavor)
 202         throws UnsupportedFlavorException, IOException {
 203         if (flavor == null) {
 204             throw new NullPointerException("flavor");
 205         }
 206 
 207         Transferable cntnts = getContextContents();
 208         if (cntnts != null) {
 209             return cntnts.getTransferData(flavor);
 210         }
 211 
 212         long format = 0;
 213         byte[] data = null;
 214         Transferable localeTransferable = null;
 215 
 216         try {
 217             openClipboard(null);
 218 
 219             long[] formats = getClipboardFormats();
 220             Long lFormat = DataTransferer.getInstance().
 221                     getFlavorsForFormats(formats, flavorMap).get(flavor);
 222 
 223             if (lFormat == null) {
 224                 throw new UnsupportedFlavorException(flavor);
 225             }
 226 
 227             format = lFormat.longValue();
 228             data = getClipboardData(format);
 229 
 230             if (DataTransferer.getInstance().isLocaleDependentTextFormat(format)) {
 231                 localeTransferable = createLocaleTransferable(formats);
 232             }
 233 
 234         } finally {
 235             closeClipboard();
 236         }
 237 
 238         return DataTransferer.getInstance().
 239                 translateBytes(data, flavor, format, localeTransferable);
 240     }
 241 
 242     /**
 243      * The clipboard must be opened.
 244      *
 245      * @since 1.5
 246      */
 247     protected Transferable createLocaleTransferable(long[] formats) throws IOException {
 248         return null;
 249     }
 250 
 251     /**
 252      * @throws IllegalStateException if the clipboard has not been opened
 253      */
 254     public void openClipboard(SunClipboard newOwner) {}
 255     public void closeClipboard() {}
 256 
 257     public abstract long getID();
 258 
 259     public void propertyChange(PropertyChangeEvent evt) {
 260         if (AppContext.DISPOSED_PROPERTY_NAME.equals(evt.getPropertyName()) &&
 261             Boolean.TRUE.equals(evt.getNewValue())) {
 262             final AppContext disposedContext = (AppContext)evt.getSource();
 263             lostOwnershipLater(disposedContext);
 264         }
 265     }
 266 
 267     protected void lostOwnershipImpl() {
 268         lostOwnershipLater(null);
 269     }
 270 
 271     /**
 272      * Clears the clipboard state (contents, owner and contents context) and
 273      * notifies the current owner that ownership is lost. Does nothing if the
 274      * argument is not <code>null</code> and is not equal to the current
 275      * contents context.
 276      *
 277      * @param disposedContext the AppContext that is disposed or
 278      *        <code>null</code> if the ownership is lost because another
 279      *        application acquired ownership.
 280      */
 281     protected void lostOwnershipLater(final AppContext disposedContext) {
 282         final AppContext context = this.contentsContext;
 283         if (context == null) {
 284             return;
 285         }
 286 
 287         final Runnable runnable = new Runnable() {
 288                 public void run() {
 289                     final SunClipboard sunClipboard = SunClipboard.this;
 290                     ClipboardOwner owner = null;
 291                     Transferable contents = null;
 292 
 293                     synchronized (sunClipboard) {
 294                         final AppContext context = sunClipboard.contentsContext;
 295 
 296                         if (context == null) {
 297                             return;
 298                         }
 299 
 300                         if (disposedContext == null || context == disposedContext) {
 301                             owner = sunClipboard.owner;
 302                             contents = sunClipboard.contents;
 303                             sunClipboard.contentsContext = null;
 304                             sunClipboard.owner = null;
 305                             sunClipboard.contents = null;
 306                             sunClipboard.clearNativeContext();
 307                             context.removePropertyChangeListener
 308                                 (AppContext.DISPOSED_PROPERTY_NAME, sunClipboard);
 309                         } else {
 310                             return;
 311                         }
 312                     }
 313                     if (owner != null) {
 314                         owner.lostOwnership(sunClipboard, contents);
 315                     }
 316                 }
 317             };
 318 
 319         SunToolkit.postEvent(context, new PeerEvent(this, runnable,
 320                                                     PeerEvent.PRIORITY_EVENT));
 321     }
 322 
 323     protected abstract void clearNativeContext();
 324 
 325     protected abstract void setContentsNative(Transferable contents);
 326 
 327     /**
 328      * @since 1.5
 329      */
 330     protected long[] getClipboardFormatsOpenClose() {
 331         try {
 332             openClipboard(null);
 333             return getClipboardFormats();
 334         } finally {
 335             closeClipboard();
 336         }
 337     }
 338 
 339     /**
 340      * Returns zero-length array (not null) if the number of available formats is zero.
 341      *
 342      * @throws IllegalStateException if formats could not be retrieved
 343      */
 344     protected abstract long[] getClipboardFormats();
 345 
 346     protected abstract byte[] getClipboardData(long format) throws IOException;
 347 
 348 
 349     private static Set formatArrayAsDataFlavorSet(long[] formats) {
 350         return (formats == null) ? null :
 351                 DataTransferer.getInstance().
 352                 getFlavorsForFormatsAsSet(formats, flavorMap);
 353     }
 354 
 355 
 356     public synchronized void addFlavorListener(FlavorListener listener) {
 357         if (listener == null) {
 358             return;
 359         }
 360         AppContext appContext = AppContext.getAppContext();
 361         EventListenerAggregate contextFlavorListeners = (EventListenerAggregate)
 362                 appContext.get(CLIPBOARD_FLAVOR_LISTENER_KEY);
 363         if (contextFlavorListeners == null) {
 364             contextFlavorListeners = new EventListenerAggregate(FlavorListener.class);
 365             appContext.put(CLIPBOARD_FLAVOR_LISTENER_KEY, contextFlavorListeners);
 366         }
 367         contextFlavorListeners.add(listener);
 368 
 369         if (numberOfFlavorListeners++ == 0) {
 370             long[] currentFormats = null;
 371             try {
 372                 openClipboard(null);
 373                 currentFormats = getClipboardFormats();
 374             } catch (IllegalStateException exc) {
 375             } finally {
 376                 closeClipboard();
 377             }
 378             currentDataFlavors = formatArrayAsDataFlavorSet(currentFormats);
 379 
 380             registerClipboardViewerChecked();
 381         }
 382     }
 383 
 384     public synchronized void removeFlavorListener(FlavorListener listener) {
 385         if (listener == null) {
 386             return;
 387         }
 388         AppContext appContext = AppContext.getAppContext();
 389         EventListenerAggregate contextFlavorListeners = (EventListenerAggregate)
 390                 appContext.get(CLIPBOARD_FLAVOR_LISTENER_KEY);
 391         if (contextFlavorListeners == null){
 392             //else we throw NullPointerException, but it is forbidden
 393             return;
 394         }
 395         if (contextFlavorListeners.remove(listener) &&
 396                 --numberOfFlavorListeners == 0) {
 397             unregisterClipboardViewerChecked();
 398             currentDataFlavors = null;
 399         }
 400     }
 401 
 402     public synchronized FlavorListener[] getFlavorListeners() {
 403         EventListenerAggregate contextFlavorListeners = (EventListenerAggregate)
 404                 AppContext.getAppContext().get(CLIPBOARD_FLAVOR_LISTENER_KEY);
 405         return contextFlavorListeners == null ? new FlavorListener[0] :
 406                 (FlavorListener[])contextFlavorListeners.getListenersCopy();
 407     }
 408 
 409     public boolean areFlavorListenersRegistered() {
 410         return (numberOfFlavorListeners > 0);
 411     }
 412 
 413     protected abstract void registerClipboardViewerChecked();
 414 
 415     protected abstract void unregisterClipboardViewerChecked();
 416 
 417     /**
 418      * Checks change of the <code>DataFlavor</code>s and, if necessary,
 419      * posts notifications on <code>FlavorEvent</code>s to the
 420      * AppContexts' EDTs.
 421      * The parameter <code>formats</code> is null iff we have just
 422      * failed to get formats available on the clipboard.
 423      *
 424      * @param formats data formats that have just been retrieved from
 425      *        this clipboard
 426      */
 427     public void checkChange(long[] formats) {
 428         Set prevDataFlavors = currentDataFlavors;
 429         currentDataFlavors = formatArrayAsDataFlavorSet(formats);
 430 
 431         if ((prevDataFlavors != null) && (currentDataFlavors != null) &&
 432                 prevDataFlavors.equals(currentDataFlavors)) {
 433             // we've been able to successfully get available on the clipboard
 434             // DataFlavors this and previous time and they are coincident;
 435             // don't notify
 436             return;
 437         }
 438 
 439         class SunFlavorChangeNotifier implements Runnable {
 440             private final FlavorListener flavorListener;
 441 
 442             SunFlavorChangeNotifier(FlavorListener flavorListener) {
 443                 this.flavorListener = flavorListener;
 444             }
 445 
 446             public void run() {
 447                 if (flavorListener != null) {
 448                     flavorListener.flavorsChanged(new FlavorEvent(SunClipboard.this));
 449                 }
 450             }
 451         };
 452 
 453         for (Iterator it = AppContext.getAppContexts().iterator(); it.hasNext();) {
 454             AppContext appContext = (AppContext)it.next();
 455             if (appContext == null || appContext.isDisposed()) {
 456                 continue;
 457             }
 458             EventListenerAggregate flavorListeners = (EventListenerAggregate)
 459                     appContext.get(CLIPBOARD_FLAVOR_LISTENER_KEY);
 460             if (flavorListeners != null) {
 461                 FlavorListener[] flavorListenerArray =
 462                         (FlavorListener[])flavorListeners.getListenersInternal();
 463                 for (int i = 0; i < flavorListenerArray.length; i++) {
 464                     SunToolkit.postEvent(appContext, new PeerEvent(this,
 465                             new SunFlavorChangeNotifier(flavorListenerArray[i]),
 466                             PeerEvent.PRIORITY_EVENT));
 467                 }
 468             }
 469         }
 470     }
 471 
 472 }