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