Skip to content

Instantly share code, notes, and snippets.

@eirikbakke
Created September 18, 2015 18:03
Show Gist options
  • Save eirikbakke/e8022f9f8d26c28eecd7 to your computer and use it in GitHub Desktop.
Save eirikbakke/e8022f9f8d26c28eecd7 to your computer and use it in GitHub Desktop.
package com.sieuferd.harness;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.SystemFlavorMap;
import java.awt.datatransfer.Transferable;
import java.io.InputStream;
public final class FlavorMapBugExhibit {
public static final boolean ENABLE_WORKAROUND = false;
private FlavorMapBugExhibit() { }
/* To test, open Microsoft Excel for Mac 2011, select a few cells, and invoke "Copy" to copy the
cells to the clipboard. Then run this class. When ENABLE_WORKAROUND is false, an
UnsupportedFlavorException will be thrown. The bug does not exist on Windows (tested with
Excel 2013). */
public static void main(String args[]) throws Exception {
DataFlavor dataFlavor = registerExcelDataFlavor();
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
Transferable transferable = clipboard.getContents(null);
try (InputStream is = (InputStream) transferable.getTransferData(dataFlavor)) {
// Should print 208, 207.
System.out.println(is.read());
System.out.println(is.read());
}
}
private static DataFlavor registerExcelDataFlavor() throws Exception {
// See http://lists.apple.com/archives/java-dev/2010/Oct/msg00026.html .
final boolean isMacOS = System.getProperty("os.name").contains("Mac OS X");
final String nat = isMacOS
// Tested with Excel for Mac 2011.
? "CorePasteboardFlavorType 0x454D4253"
// Tested with Excel for Windows 2013.
: "Biff8";
DataFlavor result = new DataFlavor("application/vnd.ms-excel", "Excel BIFF8");
SystemFlavorMap map = (SystemFlavorMap) SystemFlavorMap.getDefaultFlavorMap();
map.addUnencodedNativeForFlavor(result, nat);
map.addFlavorForUnencodedNative(nat, result);
if (isMacOS && ENABLE_WORKAROUND) {
// Workaround for the exhibited bug.
/* Force calling of DataTransferer.getFormatForNativeAsLong, which is necessary for getting
indexForFormat to return a valid index when CClipboard.getClipboardFormats in
macosx/native/sun/awt/CClipboard.m calls it. */
sun.awt.datatransfer.DataTransferer.getInstance().getFormatsForFlavor(result, map);
}
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment