1/*
2 * Copyright 2017 JetBrains s.r.o.
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.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 */
23
24/*
25 * @test
26 * @bug 8174744
27 * @summary Wrong rendering of string containing surrogate pairs on macOS
28 */
29
30import java.awt.Color;
31import java.awt.Font;
32import java.awt.FontMetrics;
33import java.awt.Graphics;
34import java.awt.image.BufferedImage;
35
36public class SuppCharDrawTest {
37    private static final Font FONT = new Font(Font.MONOSPACED, Font.PLAIN, 12);
38    private static final int IMAGE_WIDTH = 20;
39    private static final int IMAGE_HEIGHT = 20;
40
41
42    public static void main(String[] args) {
43        BufferedImage base = renderFirstChar("A");
44        BufferedImage basePlusSurrogate = renderFirstChar("A \uD835\uDC00");
45
46        if (!imagesAreEqual(base, basePlusSurrogate)) {
47            throw new RuntimeException("Unexpected rendering change");
48        }
49    }
50
51    private static BufferedImage renderFirstChar(String s) {
52        BufferedImage image = new BufferedImage(IMAGE_WIDTH, IMAGE_HEIGHT, BufferedImage.TYPE_INT_RGB);
53        Graphics g = image.createGraphics();
54        g.setColor(Color.white);
55        g.fillRect(0, 0, IMAGE_WIDTH, IMAGE_HEIGHT);
56        g.setColor(Color.black);
57        g.setFont(FONT);
58        FontMetrics metrics = g.getFontMetrics();
59        g.clipRect(0, 0, metrics.charWidth(s.charAt(0)), IMAGE_HEIGHT);
60        g.drawString(s, 0, metrics.getAscent());
61        g.dispose();
62        return image;
63    }
64
65    private static boolean imagesAreEqual(BufferedImage i1, BufferedImage i2) {
66        if (i1.getWidth() != i2.getWidth() || i1.getHeight() != i2.getHeight()) return false;
67        for (int i = 0; i < i1.getWidth(); i++) {
68            for (int j = 0; j < i1.getHeight(); j++) {
69                if (i1.getRGB(i, j) != i2.getRGB(i, j)) {
70                    return false;
71                }
72            }
73        }
74        return true;
75    }
76}
77