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