繁体   English   中英

从Firefox复制并在Ubuntu中使用Java读取时,剪贴板内容会混乱

[英]Clipboard content is messed up when copied from Firefox and read using Java in Ubuntu

背景

我正在尝试使用Java获取HTML数据风格的剪贴板数据。 因此我将它们从浏览器复制到剪贴板中。 然后我使用java.awt.datatransfer.Clipboard来获取它们。

这在Windows系统中正常工作。 但在Ubuntu中存在一些奇怪的问题。 最糟糕的是从Firefox浏览器将数据复制到剪贴板。

再现行为的示例

Java代码:

import java.io.*;

import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;

public class WorkingWithClipboadData {

 static void doSomethingWithBytesFromClipboard(byte[] dataBytes, String paramCharset, int number) throws Exception {

  String fileName = "Result " + number + " " + paramCharset + ".txt";

  OutputStream fileOut = new FileOutputStream(fileName);
  fileOut.write(dataBytes, 0, dataBytes.length);
  fileOut.close();

 }

 public static void main(String[] args) throws Exception {

  Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();

  int count = 0;

  for (DataFlavor dataFlavor : clipboard.getAvailableDataFlavors()) {

System.out.println(dataFlavor);

   String mimeType = dataFlavor.getHumanPresentableName();
   if ("text/html".equalsIgnoreCase(mimeType)) {
    String paramClass = dataFlavor.getParameter("class");
    if ("java.io.InputStream".equals(paramClass)) {
     String paramCharset = dataFlavor.getParameter("charset");
     if (paramCharset != null  && paramCharset.startsWith("UTF")) {

System.out.println("============================================");
System.out.println(paramCharset);
System.out.println("============================================");

      InputStream inputStream = (InputStream)clipboard.getData(dataFlavor);

      ByteArrayOutputStream data = new ByteArrayOutputStream();

      byte[] buffer = new byte[1024];
      int length = -1;
      while ((length = inputStream.read(buffer)) != -1) {
       data.write(buffer, 0, length);
      }
      data.flush();
      inputStream.close();

      byte[] dataBytes = data.toByteArray();
      data.close();

      doSomethingWithBytesFromClipboard(dataBytes, paramCharset, ++count);

     }
    }
   }
  }
 }

}

问题描述

我正在做的是,在Firefox中打开URL https://en.wikipedia.org/wiki/Germanic_umlaut 然后我在那里选择“letters:ä”并将其复制到剪贴板中。 然后我运行我的Java程序。 之后,生成的文件(仅其中一些作为示例)如下所示:

axel@arichter:~/Dokumente/JAVA/poi/poi-3.17$ xxd "./Result 1 UTF-16.txt" 
00000000: feff fffd fffd 006c 0000 0065 0000 0074  .......l...e...t
00000010: 0000 0074 0000 0065 0000 0072 0000 0073  ...t...e...r...s
00000020: 0000 003a 0000 0020 0000 003c 0000 0069  ...:... ...<...i
00000030: 0000 003e 0000 fffd 0000 003c 0000 002f  ...>.......<.../
00000040: 0000 0069 0000 003e 0000                 ...i...>..

好的,开始时的FEFF看起来像UTF-16BE字节顺序标记。 但是什么是FFFD 为什么单个字母之间有0000字节? l UTF-16编码仅为006C 似乎所有字母都以32位编码。 但这对UTF-16是错误的。 并且所有非ASCII字符都使用FFFD 0000编码,因此丢失。

axel@arichter:~/Dokumente/JAVA/poi/poi-3.17$ xxd "./Result 4 UTF-8.txt" 
00000000: efbf bdef bfbd 6c00 6500 7400 7400 6500  ......l.e.t.t.e.
00000010: 7200 7300 3a00 2000 3c00 6900 3e00 efbf  r.s.:. .<.i.>...
00000020: bd00 3c00 2f00 6900 3e00                 ..<./.i.>.

这里EFBF BDEF BFBD看起来不像任何已知的字节顺序标记。 并且所有字母似乎都以16位编码,这是UTF-8所需位的两倍。 所以使用的位似乎总是需要的双重计数。 参见上面的UTF-16示例。 并且所有非ASCII字母都被编码为EFBFBD ,因此也丢失了。

axel@arichter:~/Dokumente/JAVA/poi/poi-3.17$ xxd "./Result 7 UTF-16BE.txt" 
00000000: fffd fffd 006c 0000 0065 0000 0074 0000  .....l...e...t..
00000010: 0074 0000 0065 0000 0072 0000 0073 0000  .t...e...r...s..
00000020: 003a 0000 0020 0000 003c 0000 0069 0000  .:... ...<...i..
00000030: 003e 0000 fffd 0000 003c 0000 002f 0000  .>.......<.../..
00000040: 0069 0000 003e 0000                      .i...>..

与上面的例子相同。 所有字母都使用32位编码。 除了使用代理对的补充字符外, UTF-16只能使用16位。 所有非ASCII字母都用FFFD 0000编码,因此丢失。

axel@arichter:~/Dokumente/JAVA/poi/poi-3.17$ xxd "./Result 10 UTF-16LE.txt" 
00000000: fdff fdff 6c00 0000 6500 0000 7400 0000  ....l...e...t...
00000010: 7400 0000 6500 0000 7200 0000 7300 0000  t...e...r...s...
00000020: 3a00 0000 2000 0000 3c00 0000 6900 0000  :... ...<...i...
00000030: 3e00 0000 fdff 0000 3c00 0000 2f00 0000  >.......<.../...
00000040: 6900 0000 3e00 0000                      i...>...

只是为了完成。 与上面相同的图片。

所以结论是Ubuntu剪贴板在从Firefox复制到它之后完全搞砸了。 至少对于HTML数据风格以及使用Java读取剪贴板时。

其他浏览器使用

当我使用Chromium浏览器作为数据源做同样的事情时,问题就会变小。

所以我在Chromium打开网址https://en.wikipedia.org/wiki/Germanic_umlaut 然后我在那里选择“letters:ä”并将其复制到剪贴板中。 然后我运行我的Java程序。

结果如下:

axel@arichter:~/Dokumente/JAVA/poi/poi-3.17$ xxd "./Result 1 UTF-16.txt" 
00000000: feff 003c 006d 0065 0074 0061 0020 0068  ...<.m.e.t.a. .h
...
00000800: 0061 006c 003b 0022 003e 00e4 003c 002f  .a.l.;.".>...<./
00000810: 0069 003e 0000                           .i.>..

Chromium在剪贴板中的HTML数据风格中选择了更多的HTML。 但编码看起来很合适。 还在为没有ASCII ä = 00E4 但是也有一个小问题,最后还有额外的字节0000 ,不应该存在。 UTF-16还有2个额外的00字节。

axel@arichter:~/Dokumente/JAVA/poi/poi-3.17$ xxd "./Result 4 UTF-8.txt" 
00000000: 3c6d 6574 6120 6874 7470 2d65 7175 6976  <meta http-equiv
...
000003f0: 696f 6e2d 636f 6c6f 723a 2069 6e69 7469  ion-color: initi
00000400: 616c 3b22 3ec3 a43c 2f69 3e00            al;">..</i>.

与上述相同。 编码看起来适合UTF-8 但是这里还有一个额外的00字节,不应该存在。

环境

DISTRIB_ID=Ubuntu
DISTRIB_RELEASE=16.04
DISTRIB_CODENAME=xenial
DISTRIB_DESCRIPTION="Ubuntu 16.04.4 LTS"


Mozilla Firefox 61.0.1 (64-Bit)


java version "1.8.0_101"
Java(TM) SE Runtime Environment (build 1.8.0_101-b13)
Java HotSpot(TM) 64-Bit Server VM (build 25.101-b13, mixed mode)

问题

我在代码中做错了吗?

有人可以建议如何避免剪贴板中的混乱内容? 由于非ASCII字符丢失,至少从Firefox复制时,我认为我们不能修复此内容。

这是一个已知的问题吗? 有人可以确认相同的行为吗? 如果是这样,Firefox中是否已经有关于此的错误报告?

或者这是一个只有在Java代码读取剪贴板内容时才会出现的问题? 似乎好像。 因为如果我从Firefox复制内容并将其粘贴到Libreoffice Writer中,则Unicode会正确显示。 如果我然后将内容从Writer复制到剪贴板并使用我的Java程序读取它,那么UTF编码是正确的,除了最后的额外00字节。 因此,从Writer复制的剪贴板内容的行为类似于从Chromium浏览器复制的内容。


新的见解

字节0xFFFD似乎是Unicode字符'REPLACEMENT CHARACTER'(U + FFFD)。 所以0xFDFF是这个的小端表示, 0xEFBFBD是这个的UTF-8编码。 因此,所有结果似乎都是错误解码和重新编码Unicode的结果。

好像来自Firefox的剪贴板内容是带有BOM UTF-16LE 但是Java将其作为UTF-8 因此,2字节的BOM变为两个混乱的字符,用0xEFBFBD替换,每个额外的0x00序列成为它们自己的NUL字符,所有不正确的UTF-8字节序列的字节序列变成混乱的字符,用0xEFBFBD替换。 然后这个伪UTF-8将被重新编码。 现在垃圾完成了。

例:

具有BOM的UTF-16LE中的序列aɛaüa将是0xFFFE 6100 5B02 6100 FC00 6100

这被视为UTF-8(0xEFBFBD =不是一个正确的UTF-8字节序列)= 0xEFBFBD 0xEFBFBD a NUL [ STX a NUL 0xEFBFBD NUL a NUL

重新编码为UTF-16LE的伪ASCII将为: 0xFDFF FDFF 6100 0000 5B00 0200 6100 0000 FDFF 0000 6100 0000

重新编码为UTF-8的伪ASCII将为0xEFBF BDEF BFBD 6100 5B02 6100 EFBF BD00 6100

这正是发生的事情。

其他例子:

 = 0x00C2 = UTF-16LE中的C200 =伪UTF-8中的0xEFBFBD00

= 0x80C2 = UTF-16LE中的C280 =伪UTF-8中的0xC280

所以我认为Firefox不应该归咎于此,而是UbuntuJava的运行时环境。 因为从Firefox到Writer的复制/粘贴在Ubuntu中工作,我认为Java的运行时环境无法正确处理Ubuntu剪贴板中的Firefox数据风格。


新见解:

我比较了我的Windows 10和我的Ubuntuflavormap.properties文件,并且有所不同。 Ubuntu中, text/html的本机名称是UTF8_STRING而在Windows它是HTML Format 所以我认为这可能是问题所在。 所以我添加了这条线

HTML\\ Format=text/html;charset=utf-8;eoln="\\n";terminators=0

到我在Ubuntu flavormap.properties文件。

之后:

Map<DataFlavor,String> nativesForFlavors = SystemFlavorMap.getDefaultFlavorMap().getNativesForFlavors(
   new DataFlavor[]{
   new DataFlavor("text/html;charset=UTF-16LE")
   });

System.out.println(nativesForFlavors);

版画

{java.awt.datatransfer.DataFlavor[mimetype=text/html;representationclass=java.io.InputStream;charset=UTF-16LE]=HTML Format}

但是,当Java读取时,Ubuntu剪贴板内容的结果没有变化。

看了这个之后,看起来这是Java的长期存在的错误这里甚至更老的报道)。

看起来X11 Java组件看起来希望剪贴板数据始终采用UTF-8编码,Firefox使用UTF-16编码数据。 由于Java的假设,它通过强制将UTF-16解析为UTF-8来破坏文本。 我试过但找不到绕过这个问题的好方法。 “text / html”的“text”部分似乎向Java表明从剪贴板接收的字节应始终首先解释为文本,然后以各种方式提供。 我找不到任何直接从X11访问预转换字节数组的方法。

由于到目前为止还没有一个有价值的答案,似乎我们需要一个丑陋的解决方法来使用Java来使用Ubuntu系统剪贴板。 非常可惜。 O tempora,o mores。 我们生活在Windows使用Unicode编码比使用Ubuntu Linux更好的时候。

我们所知道的内容已在答案中说明。 所以我们有一个正确的编码text/plain结果,但是混乱的text/html结果。 我们知道text/html结果是如何搞砸的。

所以我们可以做的是“修复”错误的编码HTML,首先用正确的替换字符替换所有混乱的字符。 然后我们可以用正确编码的纯文本中的正确字符替换替换字符。 当然,这只能用于HTML的部分,它是可见文本而不是属性。 因为属性内容当然不在纯文本中。

解决方法:

import java.io.*;

import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;

import java.nio.charset.Charset;

public class WorkingWithClipboadDataBytesUTF8 {

 static byte[] repairUTF8HTMLDataBytes(byte[] plainDataBytes, byte[] htmlDataBytes) throws Exception {

  //get all the not ASCII characters from plainDataBytes
  //we need them for replacement later
  String plain = new String(plainDataBytes, Charset.forName("UTF-8"));
  char[] chars = plain.toCharArray();
  StringBuffer unicodeChars = new StringBuffer();
  for (int i = 0; i < chars.length; i++) {
   if (chars[i] > 127) unicodeChars.append(chars[i]);
  }
System.out.println(unicodeChars);

  //ommit the first 6 bytes from htmlDataBytes which are the wrong BOM
  htmlDataBytes = java.util.Arrays.copyOfRange(htmlDataBytes, 6, htmlDataBytes.length);

  //The wrong UTF-8 encoded single bytes which are not replaced by `0xefbfbd` 
  //are coincidentally UTF-16LE if two bytes immediately following each other.
  //So we are "repairing" this accordingly. 
  //Goal: all garbage shall be the replacement character 0xFFFD.

  //replace parts of a surrogate pair with 0xFFFD
  //replace the wrong UFT-8 bytes 0xefbfbd for replacement character with 0xFFFD
  ByteArrayInputStream in = new ByteArrayInputStream(htmlDataBytes);
  ByteArrayOutputStream out = new ByteArrayOutputStream();
  int b = -1;
  int[] btmp = new int[6];
  while ((b = in.read()) != -1) {
   btmp[0] = b;
   btmp[1] = in.read(); //there must always be two bytes because of wron encoding 16 bit Unicode
   if (btmp[0] != 0xef && btmp[1] != 0xef) { // not a replacement character
    if (btmp[1] > 0xd7 && btmp[1] < 0xe0) { // part of a surrogate pair
     out.write(0xFD); out.write(0xFF);
    } else {
     out.write(btmp[0]); out.write(btmp[1]); //two default bytes
    }
   } else { // at least one must be the replacelement 0xefbfbd
    btmp[2] = in.read(); btmp[3] = in.read(); //there must be at least two further bytes
    if (btmp[0] != 0xef && btmp[1] == 0xef && btmp[2] == 0xbf && btmp[3] == 0xbd ||
        btmp[0] == 0xef && btmp[1] == 0xbf && btmp[2] == 0xbd && btmp[3] != 0xef) {
     out.write(0xFD); out.write(0xFF);
    } else if (btmp[0] == 0xef && btmp[1] == 0xbf && btmp[2] == 0xbd && btmp[3] == 0xef) {
     btmp[4] = in.read(); btmp[5] = in.read();
     if (btmp[4] == 0xbf &&  btmp[5] == 0xbd) {
      out.write(0xFD); out.write(0xFF);
     } else {
      throw new Exception("Wrong byte sequence: "
      + String.format("%02X%02X%02X%02X%02X%02X", btmp[0], btmp[1], btmp[2], btmp[3], btmp[4], btmp[5]), 
      new Throwable().fillInStackTrace());
     }
    } else {
     throw new Exception("Wrong byte sequence: " 
      + String.format("%02X%02X%02X%02X%02X%02X", btmp[0], btmp[1], btmp[2], btmp[3], btmp[4], btmp[5]),
      new Throwable().fillInStackTrace());
    }
   }
  }

  htmlDataBytes = out.toByteArray();

  //now get this as UTF_16LE (2 byte for each character, little endian)
  String html = new String(htmlDataBytes, Charset.forName("UTF-16LE"));
System.out.println(html);

  //replace all of the wrongUnicode with the unicodeChars selected from plainDataBytes
  boolean insideTag = false;
  int unicodeCharCount = 0;
  char[] textChars = html.toCharArray();
  StringBuffer newHTML = new StringBuffer();
  for (int i = 0; i < textChars.length; i++) {
   if (textChars[i] == '<') insideTag = true;
   if (textChars[i] == '>') insideTag = false;
   if (!insideTag && textChars[i] > 127) {
    if (unicodeCharCount >= unicodeChars.length()) 
     throw new Exception("Unicode chars count don't match. " 
      + "We got from plain text " + unicodeChars.length() + " chars. Text until now:\n" + newHTML,
      new Throwable().fillInStackTrace());

    newHTML.append(unicodeChars.charAt(unicodeCharCount++));
   } else {
    newHTML.append(textChars[i]);
   }
  }

  html = newHTML.toString();
System.out.println(html);

  return html.getBytes("UTF-8");

 }

 static void doSomethingWithUTF8BytesFromClipboard(byte[] plainDataBytes, byte[] htmlDataBytes) throws Exception {

  if (plainDataBytes != null && htmlDataBytes != null) {

   String fileName; 
   OutputStream fileOut;

   fileName = "ResultPlainText.txt";
   fileOut = new FileOutputStream(fileName);
   fileOut.write(plainDataBytes, 0, plainDataBytes.length);
   fileOut.close();

   fileName = "ResultHTMLRaw.txt";
   fileOut = new FileOutputStream(fileName);
   fileOut.write(htmlDataBytes, 0, htmlDataBytes.length);
   fileOut.close();

   //do we have wrong encoded UTF-8 in htmlDataBytes?
   if (htmlDataBytes[0] == (byte)0xef && htmlDataBytes[1] == (byte)0xbf && htmlDataBytes[2] == (byte)0xbd 
    && htmlDataBytes[3] == (byte)0xef && htmlDataBytes[4] == (byte)0xbf && htmlDataBytes[5] == (byte)0xbd) {
    //try repair the UTF-8 HTML data bytes
    htmlDataBytes = repairUTF8HTMLDataBytes(plainDataBytes, htmlDataBytes);
          //do we have additional 0x00 byte at the end?
   } else if (htmlDataBytes[htmlDataBytes.length-1] == (byte)0x00) {
    //do repair this
    htmlDataBytes = java.util.Arrays.copyOf(htmlDataBytes, htmlDataBytes.length-1);
   }

   fileName = "ResultHTML.txt";
   fileOut = new FileOutputStream(fileName);
   fileOut.write(htmlDataBytes, 0, htmlDataBytes.length);
   fileOut.close();

  }

 }

 public static void main(String[] args) throws Exception {

  Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();

  byte[] htmlDataBytes = null;
  byte[] plainDataBytes = null;

  for (DataFlavor dataFlavor : clipboard.getAvailableDataFlavors()) {

   String mimeType = dataFlavor.getHumanPresentableName();

   if ("text/html".equalsIgnoreCase(mimeType)) {
    String paramClass = dataFlavor.getParameter("class");
    if ("[B".equals(paramClass)) {
     String paramCharset = dataFlavor.getParameter("charset");
     if (paramCharset != null  && "UTF-8".equalsIgnoreCase(paramCharset)) {

      htmlDataBytes = (byte[])clipboard.getData(dataFlavor);

     }
    } //else if("java.io.InputStream".equals(paramClass)) ...

   } else if ("text/plain".equalsIgnoreCase(mimeType)) {
    String paramClass = dataFlavor.getParameter("class");
    if ("[B".equals(paramClass)) {
     String paramCharset = dataFlavor.getParameter("charset");
     if (paramCharset != null  && "UTF-8".equalsIgnoreCase(paramCharset)) {

      plainDataBytes = (byte[])clipboard.getData(dataFlavor);

     }
    } //else if("java.io.InputStream".equals(paramClass)) ...
   }
  }

  doSomethingWithUTF8BytesFromClipboard(plainDataBytes, htmlDataBytes);

 }

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM