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     protected 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         SunToolkit.postEvent(context, new PeerEvent(this, () -> lostOwnershipNow(disposedContext),
 285                                                     PeerEvent.PRIORITY_EVENT));
 286     }
 287 
 288     protected void lostOwnershipNow(final AppContext disposedContext) {
 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     protected abstract void clearNativeContext();
 320 
 321     protected abstract void setContentsNative(Transferable contents);
 322 
 323     /**
 324      * @since 1.5
 325      */
 326     protected long[] getClipboardFormatsOpenClose() {
 327         try {
 328             openClipboard(null);
 329             return getClipboardFormats();
 330         } finally {
 331             closeClipboard();
 332         }
 333     }
 334 
 335     /**
 336      * Returns zero-length array (not null) if the number of available formats is zero.
 337      *
 338      * @throws IllegalStateException if formats could not be retrieved
 339      */
 340     protected abstract long[] getClipboardFormats();
 341 
 342     protected abstract byte[] getClipboardData(long format) throws IOException;
 343 
 344 
 345     private static Set formatArrayAsDataFlavorSet(long[] formats) {
 346         return (formats == null) ? null :
 347                 DataTransferer.getInstance().
 348                 getFlavorsForFormatsAsSet(formats, getDefaultFlavorTable());
 349     }
 350 
 351 
 352     public synchronized void addFlavorListener(FlavorListener listener) {
 353         if (listener == null) {
 354             return;
 355         }
 356         AppContext appContext = AppContext.getAppContext();
 357         EventListenerAggregate contextFlavorListeners = (EventListenerAggregate)
 358                 appContext.get(CLIPBOARD_FLAVOR_LISTENER_KEY);
 359         if (contextFlavorListeners == null) {
 360             contextFlavorListeners = new EventListenerAggregate(FlavorListener.class);
 361             appContext.put(CLIPBOARD_FLAVOR_LISTENER_KEY, contextFlavorListeners);
 362         }
 363         contextFlavorListeners.add(listener);
 364 
 365         if (numberOfFlavorListeners++ == 0) {
 366             long[] currentFormats = null;
 367             try {
 368                 openClipboard(null);
 369                 currentFormats = getClipboardFormats();
 370             } catch (IllegalStateException exc) {
 371             } finally {
 372                 closeClipboard();
 373             }
 374             currentDataFlavors = formatArrayAsDataFlavorSet(currentFormats);
 375 
 376             registerClipboardViewerChecked();
 377         }
 378     }
 379 
 380     public synchronized void removeFlavorListener(FlavorListener listener) {
 381         if (listener == null) {
 382             return;
 383         }
 384         AppContext appContext = AppContext.getAppContext();
 385         EventListenerAggregate contextFlavorListeners = (EventListenerAggregate)
 386                 appContext.get(CLIPBOARD_FLAVOR_LISTENER_KEY);
 387         if (contextFlavorListeners == null){
 388             //else we throw NullPointerException, but it is forbidden
 389             return;
 390         }
 391         if (contextFlavorListeners.remove(listener) &&
 392                 --numberOfFlavorListeners == 0) {
 393             unregisterClipboardViewerChecked();
 394             currentDataFlavors = null;
 395         }
 396     }
 397 
 398     public synchronized FlavorListener[] getFlavorListeners() {
 399         EventListenerAggregate contextFlavorListeners = (EventListenerAggregate)
 400                 AppContext.getAppContext().get(CLIPBOARD_FLAVOR_LISTENER_KEY);
 401         return contextFlavorListeners == null ? new FlavorListener[0] :
 402                 (FlavorListener[])contextFlavorListeners.getListenersCopy();
 403     }
 404 
 405     public boolean areFlavorListenersRegistered() {
 406         return (numberOfFlavorListeners > 0);
 407     }
 408 
 409     protected abstract void registerClipboardViewerChecked();
 410 
 411     protected abstract void unregisterClipboardViewerChecked();
 412 
 413     /**
 414      * Checks change of the <code>DataFlavor</code>s and, if necessary,
 415      * posts notifications on <code>FlavorEvent</code>s to the
 416      * AppContexts' EDTs.
 417      * The parameter <code>formats</code> is null iff we have just
 418      * failed to get formats available on the clipboard.
 419      *
 420      * @param formats data formats that have just been retrieved from
 421      *        this clipboard
 422      */
 423     public void checkChange(long[] formats) {
 424         Set prevDataFlavors = currentDataFlavors;
 425         currentDataFlavors = formatArrayAsDataFlavorSet(formats);
 426 
 427         if ((prevDataFlavors != null) && (currentDataFlavors != null) &&
 428                 prevDataFlavors.equals(currentDataFlavors)) {
 429             // we've been able to successfully get available on the clipboard
 430             // DataFlavors this and previous time and they are coincident;
 431             // don't notify
 432             return;
 433         }
 434 
 435         class SunFlavorChangeNotifier implements Runnable {
 436             private final FlavorListener flavorListener;
 437 
 438             SunFlavorChangeNotifier(FlavorListener flavorListener) {
 439                 this.flavorListener = flavorListener;
 440             }
 441 
 442             public void run() {
 443                 if (flavorListener != null) {
 444                     flavorListener.flavorsChanged(new FlavorEvent(SunClipboard.this));
 445                 }
 446             }
 447         };
 448 
 449         for (Iterator it = AppContext.getAppContexts().iterator(); it.hasNext();) {
 450             AppContext appContext = (AppContext)it.next();
 451             if (appContext == null || appContext.isDisposed()) {
 452                 continue;
 453             }
 454             EventListenerAggregate flavorListeners = (EventListenerAggregate)
 455                     appContext.get(CLIPBOARD_FLAVOR_LISTENER_KEY);
 456             if (flavorListeners != null) {
 457                 FlavorListener[] flavorListenerArray =
 458                         (FlavorListener[])flavorListeners.getListenersInternal();
 459                 for (int i = 0; i < flavorListenerArray.length; i++) {
 460                     SunToolkit.postEvent(appContext, new PeerEvent(this,
 461                             new SunFlavorChangeNotifier(flavorListenerArray[i]),
 462                             PeerEvent.PRIORITY_EVENT));
 463                 }
 464             }
 465         }
 466     }
 467 
 468     public static FlavorTable getDefaultFlavorTable() {
 469         return (FlavorTable) SystemFlavorMap.getDefaultFlavorMap();
 470     }
 471 }