From 986f3b0afdf8c9d4898e5fff081ccfd723da0b68 Mon Sep 17 00:00:00 2001 From: Andrew Haley Date: Thu, 25 Feb 2016 14:59:44 +0000 Subject: [PATCH 001/162] 8150652: Remove unused code in AArch64 back end Reviewed-by: kvn --- hotspot/src/cpu/aarch64/vm/sharedRuntime_aarch64.cpp | 4 ---- 1 file changed, 4 deletions(-) diff --git a/hotspot/src/cpu/aarch64/vm/sharedRuntime_aarch64.cpp b/hotspot/src/cpu/aarch64/vm/sharedRuntime_aarch64.cpp index 82640865457..c7966aea22e 100644 --- a/hotspot/src/cpu/aarch64/vm/sharedRuntime_aarch64.cpp +++ b/hotspot/src/cpu/aarch64/vm/sharedRuntime_aarch64.cpp @@ -211,10 +211,6 @@ static int reg2offset_out(VMReg r) { return (r->reg2stack() + SharedRuntime::out_preserve_stack_slots()) * VMRegImpl::stack_slot_size; } -template static const T& min (const T& a, const T& b) { - return (a > b) ? b : a; -} - // --------------------------------------------------------------------------- // Read the array of BasicTypes from a signature, and compute where the // arguments should go. Values in the VMRegPair regs array refer to 4-byte From 6c2df09dd910b04c4394ee32d3dc0efb5f877e58 Mon Sep 17 00:00:00 2001 From: Prasanta Sadhukhan Date: Wed, 9 Mar 2016 11:26:57 +0530 Subject: [PATCH 002/162] 8034239: PrintServiceLookup.lookupPrintServices() returns different amount of services in comparison with lpstat -v Reviewed-by: prr, jgodinez --- jdk/src/java.desktop/unix/classes/sun/print/IPPPrintService.java | 1 + 1 file changed, 1 insertion(+) diff --git a/jdk/src/java.desktop/unix/classes/sun/print/IPPPrintService.java b/jdk/src/java.desktop/unix/classes/sun/print/IPPPrintService.java index 9587067a750..ea89e9027aa 100644 --- a/jdk/src/java.desktop/unix/classes/sun/print/IPPPrintService.java +++ b/jdk/src/java.desktop/unix/classes/sun/print/IPPPrintService.java @@ -929,6 +929,7 @@ public class IPPPrintService implements PrintService, SunPrinterJobService { DocFlavor[] flavor = new DocFlavor[2]; flavor[0] = DocFlavor.SERVICE_FORMATTED.PAGEABLE; flavor[1] = DocFlavor.SERVICE_FORMATTED.PRINTABLE; + supportedDocFlavors = flavor; return flavor; } From 5a497fe7164092be7ed991d5f70db1c281bcf17f Mon Sep 17 00:00:00 2001 From: Alexander Stepanov Date: Wed, 9 Mar 2016 12:38:42 +0300 Subject: [PATCH 003/162] 8142406: [TEST] MultiResolution image: need test to cover the case when @2x image is corrupted Reviewed-by: serb, ssadetsky --- .../multiresolution/Corrupted2XImageTest.java | 140 ++++++++++++++++++ 1 file changed, 140 insertions(+) create mode 100644 jdk/test/java/awt/image/multiresolution/Corrupted2XImageTest.java diff --git a/jdk/test/java/awt/image/multiresolution/Corrupted2XImageTest.java b/jdk/test/java/awt/image/multiresolution/Corrupted2XImageTest.java new file mode 100644 index 00000000000..e7ef2f125b3 --- /dev/null +++ b/jdk/test/java/awt/image/multiresolution/Corrupted2XImageTest.java @@ -0,0 +1,140 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 8142406 + * @author a.stepanov + * @summary [HiDPI] [macosx] check that for a pair of images + * (image.ext, image@2x.ext) the 1st one is loaded + * in case if the 2nd is corrupted + * + * @requires (os.family == "mac") + * + * @library ../../../../lib/testlibrary/ + * @build ExtendedRobot + * @run main Corrupted2XImageTest + */ + +import java.awt.*; +import java.awt.geom.AffineTransform; +import java.awt.image.*; +import java.io.*; + +import javax.imageio.ImageIO; + +public class Corrupted2XImageTest extends Frame { + + private static final int SZ = 200; + private static final Color C = Color.BLUE; + + private final String format, name1x, name2x; + + public Corrupted2XImageTest(String format) throws IOException { + + this.format = format; + name1x = "test." + format; + name2x = "test@2x." + format; + createFiles(); + } + + private void UI() { + + setTitle(format); + setSize(SZ, SZ); + setResizable(false); + setLocation(50, 50); + setVisible(true); + } + + @Override + public void paint(Graphics g) { + + Image img = Toolkit.getDefaultToolkit().getImage( + new File(name1x).getAbsolutePath()); + g.drawImage(img, 0, 0, this); + } + + private void createFiles() throws IOException { + + BufferedImage img = + new BufferedImage(SZ, SZ, BufferedImage.TYPE_INT_RGB); + Graphics g = img.getGraphics(); + g.setColor(C); + g.fillRect(0, 0, SZ, SZ); + ImageIO.write(img, format, new File(name1x)); + + // corrupted @2x "image" - just a text file + Writer writer = new BufferedWriter(new OutputStreamWriter( + new FileOutputStream(new File(name2x)), "utf-8")); + writer.write("corrupted \"image\""); + writer.close(); + } + + // need this for jpg + private static boolean cmpColors(Color c1, Color c2) { + + int tol = 10; + return ( + Math.abs(c2.getRed() - c1.getRed() ) < tol && + Math.abs(c2.getGreen() - c1.getGreen()) < tol && + Math.abs(c2.getBlue() - c1.getBlue() ) < tol); + } + + private void doTest() throws Exception { + + ExtendedRobot r = new ExtendedRobot(); + System.out.println("format: " + format); + r.waitForIdle(1000); + EventQueue.invokeAndWait(this::UI); + r.waitForIdle(1000); + Point loc = getLocationOnScreen(); + Color c = r.getPixelColor(loc.x + SZ / 2, loc.y + SZ / 2); + if (!cmpColors(c, C)) { + throw new RuntimeException("test failed, color = " + c); } + System.out.println("ok"); + dispose(); + } + + private static boolean is2x() { + + AffineTransform tr = GraphicsEnvironment.getLocalGraphicsEnvironment(). + getDefaultScreenDevice().getDefaultConfiguration(). + getDefaultTransform(); + return Math.min(tr.getScaleX(), tr.getScaleY()) > 1.001; + } + + public static void main(String[] args) throws Exception { + + // TODO: update the test with sun.java2d.uiScale option (remove is2x()) + // after fix of JDK-8150844 enh. to run it on non-HiDPI machines as well + if (is2x()) { + // formats supported by Toolkit.getImage() + for (String format: new String[]{"gif", "jpg", "png"}) { + (new Corrupted2XImageTest(format)).doTest(); + } + } else { + System.out.println("this test is for HiDPI only"); + } + } +} From fa98d44f0ebcf3bacf46031b5be6736f6b95ee1d Mon Sep 17 00:00:00 2001 From: Sergey Bylokhov Date: Wed, 9 Mar 2016 14:23:20 +0300 Subject: [PATCH 004/162] 8144164: [macosx] Test java/awt/Focus/MouseClickRequestFocusRaceTest/MouseClickRequestFocusRaceTest failed Reviewed-by: avstepan, yan --- .../MouseClickRequestFocusRaceTest.html | 43 --- .../MouseClickRequestFocusRaceTest.java | 272 +++++------------- 2 files changed, 70 insertions(+), 245 deletions(-) delete mode 100644 jdk/test/java/awt/Focus/MouseClickRequestFocusRaceTest/MouseClickRequestFocusRaceTest.html diff --git a/jdk/test/java/awt/Focus/MouseClickRequestFocusRaceTest/MouseClickRequestFocusRaceTest.html b/jdk/test/java/awt/Focus/MouseClickRequestFocusRaceTest/MouseClickRequestFocusRaceTest.html deleted file mode 100644 index 7aeced5cfc3..00000000000 --- a/jdk/test/java/awt/Focus/MouseClickRequestFocusRaceTest/MouseClickRequestFocusRaceTest.html +++ /dev/null @@ -1,43 +0,0 @@ - - - - - -MouseClickRequestFocusRaceTest - - - -

MouseClickRequestFocusRaceTest
Bug ID: 5028014

- -

See the dialog box (usually in upper left corner) for instructions

- - - - diff --git a/jdk/test/java/awt/Focus/MouseClickRequestFocusRaceTest/MouseClickRequestFocusRaceTest.java b/jdk/test/java/awt/Focus/MouseClickRequestFocusRaceTest/MouseClickRequestFocusRaceTest.java index f3a9d8f61ee..c5abf9c0712 100644 --- a/jdk/test/java/awt/Focus/MouseClickRequestFocusRaceTest/MouseClickRequestFocusRaceTest.java +++ b/jdk/test/java/awt/Focus/MouseClickRequestFocusRaceTest/MouseClickRequestFocusRaceTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2006, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2006, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -21,57 +21,59 @@ * questions. */ -/* - test - @bug 5028014 - @summary Focus request & mouse click performed nearly synchronously shouldn't lead to a focus race. - @author anton.tarasov@sun.com: area=awt-focus - @run applet MouseClickRequestFocusRaceTest.html -*/ +import java.awt.AWTException; +import java.awt.FlowLayout; +import java.awt.KeyboardFocusManager; +import java.awt.Point; +import java.awt.Robot; +import java.awt.event.InputEvent; +import java.awt.event.KeyEvent; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; -import java.awt.*; -import javax.swing.*; -import java.awt.event.*; -import java.applet.Applet; +import javax.swing.JButton; +import javax.swing.JComponent; +import javax.swing.JFrame; +import javax.swing.JMenuItem; +import javax.swing.JPopupMenu; +import javax.swing.WindowConstants; -public class MouseClickRequestFocusRaceTest extends Applet { - Robot robot; - JFrame frame1 = new JFrame("Frame-1") { +import jdk.testlibrary.OSInfo; + +/** + * @test + * @bug 5028014 + * @summary Focus request & mouse click being performed nearly synchronously + * shouldn't break the focus subsystem + * @author anton.tarasov@sun.com: area=awt-focus + * @library ../../../../lib/testlibrary + * @build jdk.testlibrary.OSInfo + * @run main MouseClickRequestFocusRaceTest + */ +public class MouseClickRequestFocusRaceTest { + static Robot robot; + static JFrame frame1 = new JFrame("Frame-1") { public String toString() { return "Frame-1";} }; - JFrame frame2 = new JFrame("Frame-2") { + static JFrame frame2 = new JFrame("Frame-2") { public String toString() { return "Frame-2";} }; - JButton button1 = new JButton("button-1") { + static JButton button1 = new JButton("button-1") { public String toString() { return "button-1";} }; - JButton button2 = new JButton("button-2") { + static JButton button2 = new JButton("button-2") { public String toString() { return "button-2";} }; - JPopupMenu popup = new JPopupMenu(); + static JPopupMenu popup = new JPopupMenu(); public static void main(String[] args) { - MouseClickRequestFocusRaceTest app = new MouseClickRequestFocusRaceTest(); - app.init(); - app.start(); - } - - public void init() { try { robot = new Robot(); + robot.setAutoWaitForIdle(true); + robot.setAutoDelay(100); } catch (AWTException e) { throw new RuntimeException("Error: unable to create robot", e); } - // Create instructions for the user here, as well as set up - // the environment -- set the layout manager, add buttons, - // etc. - this.setLayout (new BorderLayout ()); - Sysout.createDialogWithInstructions(new String[] - {"Automatic test. Simply wait until it is done." - }); - } - - public void start() { frame1.add(button1); frame2.add(button2); frame1.setBounds(0, 0, 200, 300); @@ -110,198 +112,64 @@ public class MouseClickRequestFocusRaceTest extends Applet { frame1.setVisible(true); frame2.setVisible(true); -// ((SunToolkit)Toolkit.getDefaultToolkit()).realSync(); - robot.delay(1000); - test(); + robot.delay(1000); + try { + test(); + } finally { + frame1.dispose(); + frame2.dispose(); + } } - public void test() { + public static void test() { // Right click Frame-1 robot.mouseMove(frame1.getLocation().x + 100, frame1.getLocation().y + 200); robot.mousePress(InputEvent.BUTTON3_MASK); - robot.delay(100); robot.mouseRelease(InputEvent.BUTTON3_MASK); -// ((SunToolkit)Toolkit.getDefaultToolkit()).realSync(); robot.delay(1000); // Left click Frame-2 robot.mouseMove(frame2.getLocation().x + 100, frame1.getLocation().y + 200); robot.mousePress(InputEvent.BUTTON1_MASK); - robot.delay(100); robot.mouseRelease(InputEvent.BUTTON1_MASK); -// ((SunToolkit)Toolkit.getDefaultToolkit()).realSync(); robot.delay(1000); JComponent focusOwner = (JComponent)KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner(); JFrame focusedWindow = (JFrame)KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusedWindow(); - Sysout.println("focus owner: " + focusOwner); - Sysout.println("focused window: " + focusedWindow); + System.out.println("focus owner: " + focusOwner); + System.out.println("focused window: " + focusedWindow); // Verify that the focused window is the ancestor of the focus owner if (!focusedWindow.isAncestorOf(focusOwner)) { - throw new TestFailedException("The focus owner is not in the focused window!"); + throw new RuntimeException("The focus owner is not in the focused window!"); } - // Try to close native focused window - robot.keyPress(KeyEvent.VK_ALT); - robot.keyPress(KeyEvent.VK_F4); - robot.keyRelease(KeyEvent.VK_F4); - robot.keyRelease(KeyEvent.VK_ALT); - -// ((SunToolkit)Toolkit.getDefaultToolkit()).realSync(); - robot.delay(1000); - - // Verify that the Java focused window really mapped the native focused window. - if (focusedWindow.isVisible()) { - throw new TestFailedException("The focused window is different on Java and on the native level."); - } - } - - class TestFailedException extends RuntimeException { - public TestFailedException(String cause) { - super("Test failed."); - Sysout.println(cause); + if (!OSInfo.getOSType().equals(OSInfo.OSType.MACOSX)) { + // Try to close native focused window + robot.keyPress(KeyEvent.VK_ALT); + robot.keyPress(KeyEvent.VK_F4); + robot.keyRelease(KeyEvent.VK_F4); + robot.keyRelease(KeyEvent.VK_ALT); + robot.delay(1000); + // Verify that the Java focused window really mapped the native focused window. + if (focusedWindow.isVisible()) { + throw new RuntimeException("The focused window is different on Java and on the native level."); + } + } else { + // Try to move native focus to previous window + robot.keyPress(KeyEvent.VK_CONTROL); + robot.keyPress(KeyEvent.VK_F4); + robot.keyRelease(KeyEvent.VK_F4); + robot.keyRelease(KeyEvent.VK_CONTROL); + robot.delay(1000); + // Verify that the Java focused window really mapped the native focused window. + if (focusedWindow.isFocused()) { + throw new RuntimeException("The focused window is different on Java and on the native level."); + } } } } - -/**************************************************** - Standard Test Machinery - DO NOT modify anything below -- it's a standard - chunk of code whose purpose is to make user - interaction uniform, and thereby make it simpler - to read and understand someone else's test. - ****************************************************/ - -/** - This is part of the standard test machinery. - It creates a dialog (with the instructions), and is the interface - for sending text messages to the user. - To print the instructions, send an array of strings to Sysout.createDialog - WithInstructions method. Put one line of instructions per array entry. - To display a message for the tester to see, simply call Sysout.println - with the string to be displayed. - This mimics System.out.println but works within the test harness as well - as standalone. - */ - -class Sysout -{ - static TestDialog dialog; - - public static void createDialogWithInstructions( String[] instructions ) - { - dialog = new TestDialog( new Frame(), "Instructions" ); - dialog.printInstructions( instructions ); -// dialog.setVisible(true); - println( "Any messages for the tester will display here." ); - } - - public static void createDialog( ) - { - dialog = new TestDialog( new Frame(), "Instructions" ); - String[] defInstr = { "Instructions will appear here. ", "" } ; - dialog.printInstructions( defInstr ); -// dialog.setVisible(true); - println( "Any messages for the tester will display here." ); - } - - - public static void printInstructions( String[] instructions ) - { - dialog.printInstructions( instructions ); - } - - - public static void println( String messageIn ) - { - dialog.displayMessage( messageIn ); - } - -}// Sysout class - -/** - This is part of the standard test machinery. It provides a place for the - test instructions to be displayed, and a place for interactive messages - to the user to be displayed. - To have the test instructions displayed, see Sysout. - To have a message to the user be displayed, see Sysout. - Do not call anything in this dialog directly. - */ -class TestDialog extends Dialog -{ - - TextArea instructionsText; - TextArea messageText; - int maxStringLength = 80; - - //DO NOT call this directly, go through Sysout - public TestDialog( Frame frame, String name ) - { - super( frame, name ); - int scrollBoth = TextArea.SCROLLBARS_BOTH; - instructionsText = new TextArea( "", 15, maxStringLength, scrollBoth ); - add( "North", instructionsText ); - - messageText = new TextArea( "", 5, maxStringLength, scrollBoth ); - add("Center", messageText); - - pack(); - -// setVisible(true); - }// TestDialog() - - //DO NOT call this directly, go through Sysout - public void printInstructions( String[] instructions ) - { - //Clear out any current instructions - instructionsText.setText( "" ); - - //Go down array of instruction strings - - String printStr, remainingStr; - for( int i=0; i < instructions.length; i++ ) - { - //chop up each into pieces maxSringLength long - remainingStr = instructions[ i ]; - while( remainingStr.length() > 0 ) - { - //if longer than max then chop off first max chars to print - if( remainingStr.length() >= maxStringLength ) - { - //Try to chop on a word boundary - int posOfSpace = remainingStr. - lastIndexOf( ' ', maxStringLength - 1 ); - - if( posOfSpace <= 0 ) posOfSpace = maxStringLength - 1; - - printStr = remainingStr.substring( 0, posOfSpace + 1 ); - remainingStr = remainingStr.substring( posOfSpace + 1 ); - } - //else just print - else - { - printStr = remainingStr; - remainingStr = ""; - } - - instructionsText.append( printStr + "\n" ); - - }// while - - }// for - - }//printInstructions() - - //DO NOT call this directly, go through Sysout - public void displayMessage( String messageIn ) - { - messageText.append( messageIn + "\n" ); - System.out.println(messageIn); - } - -}// TestDialog class From 474586d1ae25fc1a40d0f0e7f5ad51300ab2f42c Mon Sep 17 00:00:00 2001 From: Jayathirth D V Date: Thu, 10 Mar 2016 14:14:28 +0530 Subject: [PATCH 005/162] 8139183: drawImage misses background's alpha channel Reviewed-by: flar, psadhukhan --- .../classes/sun/java2d/pipe/DrawImage.java | 18 +- .../image/DrawImage/ScaledImageAlphaTest.java | 154 ++++++++++++++++++ 2 files changed, 166 insertions(+), 6 deletions(-) create mode 100644 jdk/test/java/awt/image/DrawImage/ScaledImageAlphaTest.java diff --git a/jdk/src/java.desktop/share/classes/sun/java2d/pipe/DrawImage.java b/jdk/src/java.desktop/share/classes/sun/java2d/pipe/DrawImage.java index 728a5823e4d..b1ebb0136e9 100644 --- a/jdk/src/java.desktop/share/classes/sun/java2d/pipe/DrawImage.java +++ b/jdk/src/java.desktop/share/classes/sun/java2d/pipe/DrawImage.java @@ -340,8 +340,8 @@ public class DrawImage implements DrawImagePipe *
  • Image will be used only once and acceleration caching wouldn't help * */ - BufferedImage makeBufferedImage(Image img, Color bgColor, int type, - int sx1, int sy1, int sx2, int sy2) + private BufferedImage makeBufferedImage(Image img, Color bgColor, int type, + int sx1, int sy1, int sx2, int sy2) { final int width = sx2 - sx1; final int height = sy2 - sy1; @@ -430,10 +430,16 @@ public class DrawImage implements DrawImagePipe if (isBgOperation(srcData, bgColor)) { // We cannot perform bg operations during transform so make - // an opaque temp image with the appropriate background - // and work from there. - img = makeBufferedImage(img, bgColor, BufferedImage.TYPE_INT_RGB, - sx1, sy1, sx2, sy2); + // a temp image with the appropriate background based on + // background alpha value and work from there. If background + // alpha is opaque use INT_RGB else use INT_ARGB so that we + // will not lose translucency of background. + + int bgAlpha = bgColor.getAlpha(); + int type = ((bgAlpha == 255) + ? BufferedImage.TYPE_INT_RGB + : BufferedImage.TYPE_INT_ARGB); + img = makeBufferedImage(img, bgColor, type, sx1, sy1, sx2, sy2); // Temp image has appropriate subimage at 0,0 now. sx2 -= sx1; sy2 -= sy1; diff --git a/jdk/test/java/awt/image/DrawImage/ScaledImageAlphaTest.java b/jdk/test/java/awt/image/DrawImage/ScaledImageAlphaTest.java new file mode 100644 index 00000000000..0be030a8737 --- /dev/null +++ b/jdk/test/java/awt/image/DrawImage/ScaledImageAlphaTest.java @@ -0,0 +1,154 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 8139183 + * @summary Test verifies whether alpha channel of a translucent + * image is proper or not after scaling through drawImage. + * @run main ScaledImageAlphaTest + */ + +import java.awt.AlphaComposite; +import java.awt.Color; +import java.awt.Graphics2D; +import java.awt.GraphicsConfiguration; +import java.awt.GraphicsEnvironment; +import java.awt.Transparency; +import java.awt.image.BufferedImage; +import java.awt.image.VolatileImage; + +public class ScaledImageAlphaTest { + + static final int translucentAlpha = 128, opaqueAlpha = 255; + static final int[] translucentVariants = new int[] { + BufferedImage.TYPE_INT_ARGB, + BufferedImage.TYPE_INT_ARGB_PRE, + BufferedImage.TYPE_4BYTE_ABGR, + BufferedImage.TYPE_4BYTE_ABGR_PRE + }; + static final int[] alphaValues = new int[] { + translucentAlpha, + opaqueAlpha + }; + static int width = 50, height = 50; + static int scaleX = 5, scaleY = 5, scaleWidth = 40, scaleHeight = 40; + + private static void verifyAlpha(Color color, int alpha) { + + /* if extracted alpha value is equal alpha that we set + * for background color, alpha channel is not lost + * while scaling otherwise we have lost alpha channel. + */ + int extractedAlpha = color.getAlpha(); + + if (extractedAlpha != alpha) { + throw new RuntimeException("Alpha channel for background" + + " is lost while scaling"); + } + } + + private static void validateBufferedImageAlpha() { + + Color backgroundColor, extractedColor; + // verify for all translucent buffered image types + for (int type : translucentVariants) { + // verify for both opaque and translucent background color + for (int alpha : alphaValues) { + // create BufferedImage of dimension (50,50) + BufferedImage img = new + BufferedImage(width, height, type); + Graphics2D imgGraphics = (Graphics2D)img.getGraphics(); + /* scale image to smaller dimension and set any + * background color with alpha. + */ + backgroundColor = new Color(0, 255, 0, alpha); + imgGraphics. + drawImage(img, scaleX, scaleY, scaleWidth, scaleHeight, + backgroundColor, null); + imgGraphics.dispose(); + + /* get pixel information for background color with + * scaled coordinates. + */ + extractedColor = new Color(img.getRGB(scaleX, scaleY), true); + verifyAlpha(extractedColor, alpha); + } + } + } + + private static void validateVolatileImageAlpha() { + + Color backgroundColor, extractedColor; + VolatileImage img; + BufferedImage bufImg = new + BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); + for (int alpha : alphaValues) { + backgroundColor = new Color(0, 255, 0, alpha); + do { + img = createVolatileImage(width, height, + Transparency.TRANSLUCENT); + Graphics2D imgGraphics = (Graphics2D)img.getGraphics(); + // clear VolatileImage as by default it has white opaque image + imgGraphics.setComposite(AlphaComposite.Clear); + imgGraphics.fillRect(0,0, width, height); + + imgGraphics.setComposite(AlphaComposite.SrcOver); + /* scale image to smaller dimension and set background color + * to green with translucent alpha. + */ + imgGraphics. + drawImage(img, scaleX, scaleY, scaleWidth, scaleHeight, + backgroundColor, null); + //get BufferedImage out of VolatileImage + bufImg = img.getSnapshot(); + imgGraphics.dispose(); + } while (img.contentsLost()); + + /* get pixel information for background color with + * scaled coordinates. + */ + extractedColor = new Color(bufImg.getRGB(scaleX, scaleY), true); + verifyAlpha(extractedColor, alpha); + } + } + + private static VolatileImage createVolatileImage(int width, int height, + int transparency) { + GraphicsEnvironment ge = GraphicsEnvironment. + getLocalGraphicsEnvironment(); + GraphicsConfiguration gc = ge.getDefaultScreenDevice(). + getDefaultConfiguration(); + + VolatileImage image = gc.createCompatibleVolatileImage(width, height, + transparency); + return image; + } + + public static void main(String[] args) { + // test alpha channel with different types of BufferedImage + validateBufferedImageAlpha(); + // test alpha channel with VolatileImage + validateVolatileImageAlpha(); + } +} From b01f33a7b05043a5e48105b3e632261f9f9c9469 Mon Sep 17 00:00:00 2001 From: Alexander Stepanov Date: Thu, 10 Mar 2016 13:07:41 +0300 Subject: [PATCH 006/162] 8151269: [TEST] add test covering getSource() method for multiresolution image Reviewed-by: alexsch, serb --- .../MultiresolutionSourceTest.java | 169 ++++++++++++++++++ 1 file changed, 169 insertions(+) create mode 100644 jdk/test/java/awt/image/multiresolution/MultiresolutionSourceTest.java diff --git a/jdk/test/java/awt/image/multiresolution/MultiresolutionSourceTest.java b/jdk/test/java/awt/image/multiresolution/MultiresolutionSourceTest.java new file mode 100644 index 00000000000..e9aebf4052f --- /dev/null +++ b/jdk/test/java/awt/image/multiresolution/MultiresolutionSourceTest.java @@ -0,0 +1,169 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 8151269 + * @author a.stepanov + * @summary Multiresolution image: check that the base resolution variant + * source is passed to the corresponding ImageConsumer + * @run main MultiresolutionSourceTest + */ + +import java.awt.*; +import java.awt.image.*; + +public class MultiresolutionSourceTest { + + private static class Checker implements ImageConsumer { + + private final int refW, refH, refType; + private final boolean refHasAlpha; + private final Color refColor; + + public Checker(int w, + int h, + Color c, + boolean hasAlpha, + int transferType) { + refW = w; + refH = h; + refColor = c; + refHasAlpha = hasAlpha; + refType = transferType; + } + + @Override + public void imageComplete(int status) {} + + @Override + public void setColorModel(ColorModel model) { + + boolean a = model.hasAlpha(); + if (a != refHasAlpha) { + throw new RuntimeException("invalid hasAlpha: " + a); + } + + int tt = model.getTransferType(); + if (tt != refType) { + throw new RuntimeException("invalid transfer type: " + tt); + } + } + + @Override + public void setDimensions(int w, int h) { + + if (w != refW) { throw new RuntimeException("invalid width: " + w + + ", expected: " + refW); } + + if (h != refH) { throw new RuntimeException("invalid height: " + h + + ", expected: " + refH); } + } + + @Override + public void setHints(int flags) {} + + @Override + public void setPixels(int x, int y, int w, int h, ColorModel model, + byte pixels[], int offset, int scansize) { + + for (int i = 0; i < pixels.length; i++) { + int p = pixels[i]; + // just in case... + Color c = model.hasAlpha() ? + new Color(model.getRed (p), + model.getGreen(p), + model.getBlue (p), + model.getAlpha(p)) : + new Color(model.getRGB(p)); + + if (!c.equals(refColor)) { + throw new RuntimeException("invalid color: " + c + + ", expected: " + refColor); + } + } + } + + @Override + public void setPixels(int x, int y, int w, int h, ColorModel model, + int pixels[], int offset, int scansize) { + + for (int i = 0; i < pixels.length; i++) { + int p = pixels[i]; + Color c = model.hasAlpha() ? + new Color(model.getRed (p), + model.getGreen(p), + model.getBlue (p), + model.getAlpha(p)) : + new Color(model.getRGB(p)); + + if (!c.equals(refColor)) { + throw new RuntimeException("invalid color: " + c + + ", expected: " + refColor); + } + } + } + + @Override + public void setProperties(java.util.Hashtable props) {} + } + + private static BufferedImage generateImage(int w, int h, Color c, int type) { + + BufferedImage img = new BufferedImage(w, h, type); + Graphics g = img.getGraphics(); + g.setColor(c); + g.fillRect(0, 0, w, h); + return img; + } + + public static void main(String[] args) { + + final int w1 = 20, w2 = 100, h1 = 30, h2 = 50; + final Color + c1 = new Color(255, 0, 0, 100), c2 = Color.BLACK, gray = Color.GRAY; + + BufferedImage img1 = + generateImage(w1, h1, c1, BufferedImage.TYPE_INT_ARGB); + + BufferedImage dummy = + generateImage(w1 + 5, h1 + 5, gray, BufferedImage.TYPE_BYTE_GRAY); + + BufferedImage img2 = + generateImage(w2, h2, c2, BufferedImage.TYPE_BYTE_BINARY); + + BufferedImage vars[] = new BufferedImage[] {img1, dummy, img2}; + + // default base image index (zero) + BaseMultiResolutionImage mri1 = new BaseMultiResolutionImage(vars); + // base image index = 2 + BaseMultiResolutionImage mri2 = new BaseMultiResolutionImage(2, vars); + + // do checks + mri1.getSource().startProduction( + new Checker(w1, h1, c1, true, DataBuffer.TYPE_INT)); + + mri2.getSource().startProduction( + new Checker(w2, h2, c2, false, DataBuffer.TYPE_BYTE)); + } +} From b0127a7f0c8e0e4ad7977797082c1e073790f8fa Mon Sep 17 00:00:00 2001 From: Sergey Bylokhov Date: Fri, 4 Mar 2016 20:10:52 +0300 Subject: [PATCH 007/162] 8151288: Generation of property files for gtk l&f can be skipped on win/osx Reviewed-by: erikj --- jdk/make/gensrc/Gensrc-java.desktop.gmk | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/jdk/make/gensrc/Gensrc-java.desktop.gmk b/jdk/make/gensrc/Gensrc-java.desktop.gmk index 05e93c66e3f..42eb1a2fda0 100644 --- a/jdk/make/gensrc/Gensrc-java.desktop.gmk +++ b/jdk/make/gensrc/Gensrc-java.desktop.gmk @@ -1,5 +1,5 @@ # -# Copyright (c) 2011, 2015, Oracle and/or its affiliates. All rights reserved. +# Copyright (c) 2011, 2016, Oracle and/or its affiliates. All rights reserved. # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. # # This code is free software; you can redistribute it and/or modify it @@ -62,7 +62,9 @@ endif ifeq ($(OPENJDK_TARGET_OS), windows) PROP_SRC_DIRS += $(JDK_TOPDIR)/src/java.desktop/windows/classes/sun/awt/windows -else +endif + +ifeq ($(filter $(OPENJDK_TARGET_OS), windows macosx), ) PROP_SRC_DIRS += $(JDK_TOPDIR)/src/java.desktop/share/classes/com/sun/java/swing/plaf/gtk/resources endif From 4091ed9be75ab5e6e9e25828c58c9666a6ccbe1d Mon Sep 17 00:00:00 2001 From: Alexander Stepanov Date: Thu, 10 Mar 2016 17:19:15 +0300 Subject: [PATCH 008/162] 8151627: [TEST_BUG] fix test/java/awt/image/multiresolution/MultiResolutionRenderingHintsTest.java to run with Jake Reviewed-by: serb, yan --- .../image/multiresolution/MultiResolutionRenderingHintsTest.java | 1 + 1 file changed, 1 insertion(+) diff --git a/jdk/test/java/awt/image/multiresolution/MultiResolutionRenderingHintsTest.java b/jdk/test/java/awt/image/multiresolution/MultiResolutionRenderingHintsTest.java index 063088ca5c9..c6a6f845db4 100644 --- a/jdk/test/java/awt/image/multiresolution/MultiResolutionRenderingHintsTest.java +++ b/jdk/test/java/awt/image/multiresolution/MultiResolutionRenderingHintsTest.java @@ -47,6 +47,7 @@ import sun.java2d.loops.SurfaceType; * @author Alexander Scherbatiy * @summary Custom MultiResolution image support on HiDPI displays * @modules java.desktop/sun.java2d + * @modules java.desktop/sun.java2d.loops * @run main MultiResolutionRenderingHintsTest */ public class MultiResolutionRenderingHintsTest { From 34d87710df61102b28ecf11b4508066d2d2701a6 Mon Sep 17 00:00:00 2001 From: Rajeev Chamyal Date: Fri, 11 Mar 2016 10:57:47 +0530 Subject: [PATCH 009/162] 8145896: JInternalFrame setMaximum before adding to desktop throws null pointer exception Reviewed-by: serb, alexsch --- .../javax/swing/DefaultDesktopManager.java | 6 +- .../plaf/basic/BasicInternalFrameUI.java | 3 + .../8145896/TestJInternalFrameMaximize.java | 140 ++++++++++++++++++ 3 files changed, 148 insertions(+), 1 deletion(-) create mode 100644 jdk/test/javax/swing/JInternalFrame/8145896/TestJInternalFrameMaximize.java diff --git a/jdk/src/java.desktop/share/classes/javax/swing/DefaultDesktopManager.java b/jdk/src/java.desktop/share/classes/javax/swing/DefaultDesktopManager.java index 74778d50267..0a41c36d9a0 100644 --- a/jdk/src/java.desktop/share/classes/javax/swing/DefaultDesktopManager.java +++ b/jdk/src/java.desktop/share/classes/javax/swing/DefaultDesktopManager.java @@ -129,8 +129,12 @@ public class DefaultDesktopManager implements DesktopManager, java.io.Serializab } catch (PropertyVetoException e2) { } } else { + Container c = f.getParent(); + if (c == null) { + return; + } f.setNormalBounds(f.getBounds()); - Rectangle desktopBounds = f.getParent().getBounds(); + Rectangle desktopBounds = c.getBounds(); setBoundsForFrame(f, 0, 0, desktopBounds.width, desktopBounds.height); } diff --git a/jdk/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicInternalFrameUI.java b/jdk/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicInternalFrameUI.java index bcae2e3f8e8..dbcfb308b7c 100644 --- a/jdk/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicInternalFrameUI.java +++ b/jdk/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicInternalFrameUI.java @@ -1719,6 +1719,9 @@ public class BasicInternalFrameUI extends InternalFrameUI if ((frame.getParent() != null) && !componentListenerAdded) { f.getParent().addComponentListener(componentListener); componentListenerAdded = true; + if (f.isMaximum()) { + maximizeFrame(f); + } } } else if (JInternalFrame.TITLE_PROPERTY == prop || prop == "closable" || prop == "iconable" || diff --git a/jdk/test/javax/swing/JInternalFrame/8145896/TestJInternalFrameMaximize.java b/jdk/test/javax/swing/JInternalFrame/8145896/TestJInternalFrameMaximize.java new file mode 100644 index 00000000000..267a9708931 --- /dev/null +++ b/jdk/test/javax/swing/JInternalFrame/8145896/TestJInternalFrameMaximize.java @@ -0,0 +1,140 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 8145896 + * @summary JInternalFrame setMaximum before adding to desktop throws null pointer exception + * @library ../../regtesthelpers + * @build Util + * @run main TestJInternalFrameMaximize + */ +import java.awt.Point; +import java.awt.Robot; +import java.awt.event.ActionEvent; +import java.awt.event.InputEvent; +import java.beans.PropertyVetoException; +import javax.swing.JFrame; +import javax.swing.JDesktopPane; +import javax.swing.JMenu; +import javax.swing.JMenuBar; +import javax.swing.JMenuItem; +import javax.swing.JInternalFrame; +import javax.swing.SwingUtilities; +import javax.swing.UIManager; +import javax.swing.UnsupportedLookAndFeelException; + +public class TestJInternalFrameMaximize { + + private static JDesktopPane desktopPane; + private static JFrame frame; + private static int count = 0; + private static JMenu menu; + private static JMenuBar menuBar; + private static JMenuItem menuItem; + private static Robot robot; + private static volatile String errorMessage = ""; + + public static void main(String[] args) throws Exception { + robot = new Robot(); + UIManager.LookAndFeelInfo[] lookAndFeelArray + = UIManager.getInstalledLookAndFeels(); + for (UIManager.LookAndFeelInfo lookAndFeelItem : lookAndFeelArray) { + String lookAndFeelString = lookAndFeelItem.getClassName(); + if (tryLookAndFeel(lookAndFeelString)) { + createUI(); + robot.waitForIdle(); + executeTest(); + } + } + if (!"".equals(errorMessage)) { + throw new RuntimeException(errorMessage); + } + } + + private static boolean tryLookAndFeel(String lookAndFeelString) { + try { + UIManager.setLookAndFeel(lookAndFeelString); + return true; + } catch (UnsupportedLookAndFeelException | ClassNotFoundException | + InstantiationException | IllegalAccessException e) { + errorMessage += e.getMessage() + "\n"; + System.err.println("Caught Exception: " + e.getMessage()); + return false; + } + } + + private static void createUI() throws Exception { + + SwingUtilities.invokeAndWait(() -> { + frame = new JFrame("Test Frame"); + desktopPane = new JDesktopPane(); + frame.getContentPane().add(desktopPane); + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + + menuBar = new JMenuBar(); + frame.setJMenuBar(menuBar); + + menu = new JMenu("File"); + menuBar.add(menu); + + menuItem = new JMenuItem("New Child"); + menuItem.addActionListener((ActionEvent e) -> { + try { + JInternalFrame f = new JInternalFrame("Child " + + (++count), true, true, true, true); + f.setSize(200, 300); + f.setLocation(count * 20, count * 20); + f.setMaximum(true); + desktopPane.add(f); + f.setVisible(true); + } catch (PropertyVetoException ex) { + } catch (RuntimeException ex) { + errorMessage = "Test Failed"; + } finally { + frame.dispose(); + } + }); + menu.add(menuItem); + frame.setSize(500, 500); + frame.setLocationRelativeTo(null); + frame.setVisible(true); + }); + } + + private static void executeTest() throws Exception { + + Point point = Util.getCenterPoint(menu); + performMouseOperations(point); + point = Util.getCenterPoint(menuItem); + performMouseOperations(point); + } + + private static void performMouseOperations(Point point) { + robot.mouseMove(point.x, point.y); + robot.mousePress(InputEvent.BUTTON1_MASK); + robot.mouseRelease(InputEvent.BUTTON1_MASK); + robot.delay(1000); + robot.waitForIdle(); + } +} From c4c2df324741852be3740685ae618922639a0939 Mon Sep 17 00:00:00 2001 From: Rajeev Chamyal Date: Fri, 11 Mar 2016 11:00:38 +0530 Subject: [PATCH 010/162] 8145174: HiDPI splash screen support on Linux Reviewed-by: serb, alexsch --- jdk/make/lib/Awt2dLibraries.gmk | 23 +- .../mapfiles/libsplashscreen/mapfile-vers | 2 + .../share/classes/java/awt/SplashScreen.java | 2 +- .../common/awt/systemscale/systemScale.c | 52 ++++ .../common/awt/systemscale/systemScale.h | 33 +++ .../native/libawt_xawt/awt/awt_GraphicsEnv.c | 26 +- .../libsplashscreen/splashscreen_config.h | 2 +- .../native/libsplashscreen/splashscreen_sys.c | 46 ++++ .../unix/UnixMultiResolutionSplashTest.java | 241 ++++++++++++++++++ 9 files changed, 397 insertions(+), 30 deletions(-) create mode 100644 jdk/src/java.desktop/unix/native/common/awt/systemscale/systemScale.c create mode 100644 jdk/src/java.desktop/unix/native/common/awt/systemscale/systemScale.h create mode 100644 jdk/test/java/awt/SplashScreen/MultiResolutionSplash/unix/UnixMultiResolutionSplashTest.java diff --git a/jdk/make/lib/Awt2dLibraries.gmk b/jdk/make/lib/Awt2dLibraries.gmk index d6ba6443bf2..8ff75d888cf 100644 --- a/jdk/make/lib/Awt2dLibraries.gmk +++ b/jdk/make/lib/Awt2dLibraries.gmk @@ -203,11 +203,13 @@ endif ifeq ($(OPENJDK_TARGET_OS), windows) LIBAWT_DIRS += $(JDK_TOPDIR)/src/java.desktop/share/native/common/font \ - $(JDK_TOPDIR)/src/java.desktop/share/native/common/java2d/opengl \ + $(JDK_TOPDIR)/src/java.desktop/$(OPENJDK_TARGET_OS_TYPE)/native/common/awt/systemscale \ + $(JDK_TOPDIR)/src/java.desktop/share/native/common/java2d/opengl \ # Why does libawt need java.base headers? LIBAWT_CFLAGS += -I$(JDK_TOPDIR)/src/java.desktop/share/native/common/font \ -I$(JDK_TOPDIR)/src/java.desktop/share/native/common/java2d/opengl \ -I$(JDK_TOPDIR)/src/java.desktop/$(OPENJDK_TARGET_OS_TYPE)/native/common/java2d/opengl \ + -I$(JDK_TOPDIR)/src/java.desktop/$(OPENJDK_TARGET_OS_TYPE)/native/common/awt/systemscale \ -I$(JDK_TOPDIR)/src/java.desktop/windows/native/include \ -I$(JDK_TOPDIR)/src/java.desktop/share/native/include \ -I$(SUPPORT_OUTPUTDIR)/headers/java.base \ @@ -328,10 +330,14 @@ ifeq ($(findstring $(OPENJDK_TARGET_OS),windows macosx),) -I$(JDK_TOPDIR)/src/java.desktop/$(OPENJDK_TARGET_OS_TYPE)/native/common/font \ $(LIBJAVA_HEADER_FLAGS) # - + LIBAWT_XAWT_CFLAGS += -DXAWT -DXAWT_HACK \ -DPACKAGE_PATH=\"$(PACKAGE_PATH)\" \ $(CUPS_CFLAGS) + ifneq (,$(filter $(OPENJDK_TARGET_OS),linux solaris)) + LIBAWT_XAWT_DIRS += $(JDK_TOPDIR)/src/java.desktop/unix/native/common/awt/systemscale + LIBAWT_XAWT_CFLAGS += -I$(JDK_TOPDIR)/src/java.desktop/unix/native/common/awt/systemscale + endif ifeq ($(OPENJDK_TARGET_OS), solaris) LIBAWT_XAWT_CFLAGS += -DFUNCPROTO=15 @@ -882,12 +888,21 @@ ifndef BUILD_HEADLESS_ONLY else LIBSPLASHSCREEN_DIRS += $(JDK_TOPDIR)/src/java.desktop/macosx/native/libsplashscreen endif - + ifeq ($(OPENJDK_TARGET_OS), windows) + LIBSPLASHSCREEN_DIRS += $(JDK_TOPDIR)/src/java.desktop/windows/native/common/awt/systemscale + LIBSPLASHSCREEN_CFLAGS += -I$(JDK_TOPDIR)/src/java.desktop/windows/native/common/awt/systemscale + endif + LIBSPLASHSCREEN_CFLAGS += -DSPLASHSCREEN -DPNG_NO_MMX_CODE -DPNG_ARM_NEON_OPT=0 \ $(addprefix -I, $(LIBSPLASHSCREEN_DIRS)) \ $(LIBJAVA_HEADER_FLAGS) \ # + ifneq (,$(filter $(OPENJDK_TARGET_OS),linux solaris)) + LIBSPLASHSCREEN_DIRS += $(JDK_TOPDIR)/src/java.desktop/unix/native/common/awt/systemscale + LIBSPLASHSCREEN_CFLAGS += -I$(JDK_TOPDIR)/src/java.desktop/unix/native/common/awt/systemscale + endif + ifeq ($(OPENJDK_TARGET_OS), macosx) LIBSPLASHSCREEN_CFLAGS += -DWITH_MACOSX LIBSPLASHSCREEN_CFLAGS += -I$(JDK_TOPDIR)/src/java.desktop/macosx/native/libosxapp @@ -923,7 +938,7 @@ ifndef BUILD_HEADLESS_ONLY -framework JavaNativeFoundation else ifeq ($(OPENJDK_TARGET_OS), windows) LIBSPLASHSCREEN_LDFLAGS := -delayload:user32.dll - LIBSPLASHSCREEN_LIBS += kernel32.lib user32.lib gdi32.lib delayimp.lib + LIBSPLASHSCREEN_LIBS += kernel32.lib user32.lib gdi32.lib delayimp.lib $(WIN_JAVA_LIB) jvm.lib else LIBSPLASHSCREEN_LIBS += $(X_LIBS) -lX11 -lXext $(LIBM) -lpthread endif diff --git a/jdk/make/mapfiles/libsplashscreen/mapfile-vers b/jdk/make/mapfiles/libsplashscreen/mapfile-vers index 2be756be1e5..fec7b037f0d 100644 --- a/jdk/make/mapfiles/libsplashscreen/mapfile-vers +++ b/jdk/make/mapfiles/libsplashscreen/mapfile-vers @@ -42,6 +42,8 @@ SUNWprivate_1.1 { SplashInit; SplashClose; SplashSetFileJarName; + SplashSetScaleFactor; + SplashGetScaledImageName; local: *; }; diff --git a/jdk/src/java.desktop/share/classes/java/awt/SplashScreen.java b/jdk/src/java.desktop/share/classes/java/awt/SplashScreen.java index 4b6fab00428..952a6dc5bf2 100644 --- a/jdk/src/java.desktop/share/classes/java/awt/SplashScreen.java +++ b/jdk/src/java.desktop/share/classes/java/awt/SplashScreen.java @@ -251,7 +251,7 @@ public final class SplashScreen { assert scale > 0; if (scale > 0 && scale != 1) { bounds.setSize((int) (bounds.getWidth() / scale), - (int) (bounds.getWidth() / scale)); + (int) (bounds.getHeight() / scale)); } return bounds; } diff --git a/jdk/src/java.desktop/unix/native/common/awt/systemscale/systemScale.c b/jdk/src/java.desktop/unix/native/common/awt/systemscale/systemScale.c new file mode 100644 index 00000000000..fd574a89621 --- /dev/null +++ b/jdk/src/java.desktop/unix/native/common/awt/systemscale/systemScale.c @@ -0,0 +1,52 @@ +/* +* Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. +* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. +* +* This code is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License version 2 only, as +* published by the Free Software Foundation. +* +* This code is distributed in the hope that it will be useful, but WITHOUT +* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +* version 2 for more details (a copy is included in the LICENSE file that +* accompanied this code). +* +* You should have received a copy of the GNU General Public License version +* 2 along with this work; if not, write to the Free Software Foundation, +* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. +* +* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA +* or visit www.oracle.com if you need additional information or have any +* questions. +*/ + +#include "systemScale.h" +#include + +int getNativeScaleFactor() { + + static int scale = -2.0; + + if (scale == -2) { + scale = getScale("J2D_UISCALE"); + } + + if (scale >= 1) { + return (int) scale; + } + return getScale("GDK_SCALE"); +} + +int getScale(const char *name) { + char *uiScale = getenv(name); + if (uiScale != NULL) { + double scale = strtod(uiScale, NULL); + if (scale < 1) { + return -1; + } + return (int) scale; + } + return -1; +} + diff --git a/jdk/src/java.desktop/unix/native/common/awt/systemscale/systemScale.h b/jdk/src/java.desktop/unix/native/common/awt/systemscale/systemScale.h new file mode 100644 index 00000000000..a45d18ccdab --- /dev/null +++ b/jdk/src/java.desktop/unix/native/common/awt/systemscale/systemScale.h @@ -0,0 +1,33 @@ +/* +* Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. +* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. +* +* This code is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License version 2 only, as +* published by the Free Software Foundation. +* +* This code is distributed in the hope that it will be useful, but WITHOUT +* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +* version 2 for more details (a copy is included in the LICENSE file that +* accompanied this code). +* +* You should have received a copy of the GNU General Public License version +* 2 along with this work; if not, write to the Free Software Foundation, +* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. +* +* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA +* or visit www.oracle.com if you need additional information or have any +* questions. +*/ +#ifndef _AWT_SYSTEMSCALE_H +#define _AWT_SYSTEMSCALE_H + +#include +#include + +int getNativeScaleFactor(); +int getScale(const char *uiScale); + +#endif + diff --git a/jdk/src/java.desktop/unix/native/libawt_xawt/awt/awt_GraphicsEnv.c b/jdk/src/java.desktop/unix/native/libawt_xawt/awt/awt_GraphicsEnv.c index 6c9c2b49f01..7d2b8b0dbd0 100644 --- a/jdk/src/java.desktop/unix/native/libawt_xawt/awt/awt_GraphicsEnv.c +++ b/jdk/src/java.desktop/unix/native/libawt_xawt/awt/awt_GraphicsEnv.c @@ -43,7 +43,7 @@ #include #include #include - +#include "systemScale.h" #include #include "awt_GraphicsEnv.h" @@ -2083,17 +2083,6 @@ Java_sun_awt_X11GraphicsDevice_exitFullScreenExclusive * End DisplayMode/FullScreen support */ -int getScale(const char *name) { - char *uiScale = getenv(name); - if (uiScale != NULL) { - double scale = strtod(uiScale, NULL); - if (errno == ERANGE || scale < 1) { - return -1; - } - return (int) scale; - } - return -1; -} /* * Class: sun_awt_X11GraphicsDevice @@ -2104,16 +2093,5 @@ JNIEXPORT jint JNICALL Java_sun_awt_X11GraphicsDevice_getNativeScaleFactor (JNIEnv *env, jobject this, jint screen) { - // for debug purposes - static int scale = -2.0; - - if (scale == -2) { - scale = getScale("J2D_UISCALE"); - } - - if (scale >= 1) { - return scale; - } - - return getScale("GDK_SCALE"); + return getNativeScaleFactor(); } diff --git a/jdk/src/java.desktop/unix/native/libsplashscreen/splashscreen_config.h b/jdk/src/java.desktop/unix/native/libsplashscreen/splashscreen_config.h index 9d8255bdb27..927261d9444 100644 --- a/jdk/src/java.desktop/unix/native/libsplashscreen/splashscreen_config.h +++ b/jdk/src/java.desktop/unix/native/libsplashscreen/splashscreen_config.h @@ -39,6 +39,7 @@ #include #include #include +#include "systemScale.h" typedef uint32_t rgbquad_t; typedef uint16_t word_t; @@ -57,5 +58,4 @@ typedef XRectangle RECT_T; #define INLINE static #define SPLASHEXPORT - #endif diff --git a/jdk/src/java.desktop/unix/native/libsplashscreen/splashscreen_sys.c b/jdk/src/java.desktop/unix/native/libsplashscreen/splashscreen_sys.c index ed3bfaa1108..5c6d41ab947 100644 --- a/jdk/src/java.desktop/unix/native/libsplashscreen/splashscreen_sys.c +++ b/jdk/src/java.desktop/unix/native/libsplashscreen/splashscreen_sys.c @@ -802,5 +802,51 @@ SplashGetScaledImageName(const char* jarName, const char* fileName, float *scaleFactor) { *scaleFactor = 1; +#ifndef __linux__ + return NULL; +#endif + *scaleFactor = getNativeScaleFactor(); + if (*scaleFactor == 2.0) { + char *scaledImgName = NULL; + size_t length = 0; + char *stringToAppend = ".java-scale2x"; + char *dupFileName = strdup(fileName); + char *fileExtension = strrchr(dupFileName, '.'); + if (fileExtension == NULL) { + length = strlen(dupFileName) + strlen(stringToAppend) + 1; + scaledImgName = SAFE_SIZE_ARRAY_ALLOC(malloc, length, sizeof (char)); + int retVal = snprintf(scaledImgName, length, "%s%s", + dupFileName, stringToAppend); + if(retVal < 0 || (retVal != length - 1)) { + free(scaledImgName); + free(dupFileName); + *scaleFactor = 1; + return NULL; + } + } else { + int length_without_ext = fileExtension - dupFileName; + length = length_without_ext + + strlen(stringToAppend) + strlen(fileExtension) + 1; + scaledImgName = SAFE_SIZE_ARRAY_ALLOC(malloc, length, sizeof (char)); + int retVal = snprintf(scaledImgName, length, "%.*s%s%s", + length_without_ext, dupFileName, stringToAppend, fileExtension); + if(retVal < 0 || retVal != length - 1) { + free(scaledImgName); + free(dupFileName); + *scaleFactor = 1; + return NULL; + } + } + free(dupFileName); + FILE *fp; + if (!(fp = fopen(scaledImgName, "r"))) { + *scaleFactor = 1; + free(scaledImgName); + return NULL; + } + fclose(fp); + return scaledImgName; + } return NULL; } + diff --git a/jdk/test/java/awt/SplashScreen/MultiResolutionSplash/unix/UnixMultiResolutionSplashTest.java b/jdk/test/java/awt/SplashScreen/MultiResolutionSplash/unix/UnixMultiResolutionSplashTest.java new file mode 100644 index 00000000000..bf836973223 --- /dev/null +++ b/jdk/test/java/awt/SplashScreen/MultiResolutionSplash/unix/UnixMultiResolutionSplashTest.java @@ -0,0 +1,241 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import java.awt.Color; +import java.awt.Dialog; +import java.awt.Frame; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.Panel; +import java.awt.Rectangle; +import java.awt.Robot; +import java.awt.SplashScreen; +import java.awt.TextField; +import java.awt.Window; +import java.awt.event.KeyEvent; +import java.awt.image.BufferedImage; +import java.io.BufferedReader; +import java.io.File; +import java.io.InputStreamReader; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import javax.imageio.ImageIO; + +/** + * @test @bug 8145174 + * @summary HiDPI splash screen support on Linux + * @modules java.desktop/sun.java2d + * @run main UnixMultiResolutionSplashTest + */ +public class UnixMultiResolutionSplashTest { + + private static final int IMAGE_WIDTH = 300; + private static final int IMAGE_HEIGHT = 200; + private static int inx = 0; + private static final ImageInfo[] tests = { + new ImageInfo("splash1.png", "splash1.java-scale2x.png", Color.BLUE, Color.GREEN), + new ImageInfo("splash2", "splash2.java-scale2x", Color.WHITE, Color.BLACK), + new ImageInfo("splash3.", "splash3.java-scale2x.", Color.YELLOW, Color.RED) + }; + + public static void main(String[] args) throws Exception { + + if (args.length == 0) { + generateImages(); + for (ImageInfo test : tests) { + createChildProcess(test); + } + } else { + int index = Integer.parseInt(args[0]); + testSplash(tests[index]); + } + } + + static void createChildProcess(ImageInfo test) { + String javaPath = System.getProperty("java.home"); + File file = new File(test.name1x); + String classPathDir = System.getProperty("java.class.path"); + Map env = new HashMap(); + env.put("GDK_SCALE", "2"); + int exitValue = doExec(env, javaPath + File.separator + "bin" + File.separator + + "java", "-splash:" + file.getAbsolutePath(), "-cp", + classPathDir, "UnixMultiResolutionSplashTest", String.valueOf(inx++)); + if (exitValue != 0) { + throw new RuntimeException("Test Failed"); + } + } + + static void testSplash(ImageInfo test) throws Exception { + SplashScreen splashScreen = SplashScreen.getSplashScreen(); + if (splashScreen == null) { + throw new RuntimeException("Splash screen is not shown!"); + } + Graphics2D g = splashScreen.createGraphics(); + Rectangle splashBounds = splashScreen.getBounds(); + int screenX = (int) splashBounds.getCenterX(); + int screenY = (int) splashBounds.getCenterY(); + System.out.println(screenX); + System.out.println(screenY); + Robot robot = new Robot(); + Color splashScreenColor = robot.getPixelColor(screenX, screenY); + + float scaleFactor = getScaleFactor(); + Color testColor = (1 < scaleFactor) ? test.color2x : test.color1x; + if (!compare(testColor, splashScreenColor)) { + throw new RuntimeException( + "Image with wrong resolution is used for splash screen!"); + } + } + + static int doExec(Map envToSet, String... cmds) { + Process p = null; + ProcessBuilder pb = new ProcessBuilder(cmds); + Map env = pb.environment(); + for (String cmd : cmds) { + System.out.print(cmd + " "); + } + System.out.println(); + if (envToSet != null) { + env.putAll(envToSet); + } + BufferedReader rdr = null; + try { + List outputList = new ArrayList<>(); + pb.redirectErrorStream(true); + p = pb.start(); + rdr = new BufferedReader(new InputStreamReader(p.getInputStream())); + String in = rdr.readLine(); + while (in != null) { + outputList.add(in); + in = rdr.readLine(); + System.out.println(in); + } + p.waitFor(); + p.destroy(); + } catch (Exception ex) { + ex.printStackTrace(); + } + return p.exitValue(); + } + + static void testFocus() throws Exception { + + System.out.println("Focus Test!"); + Robot robot = new Robot(); + robot.setAutoDelay(50); + Frame frame = new Frame(); + frame.setSize(100, 100); + String test = "123"; + TextField textField = new TextField(test); + textField.selectAll(); + frame.add(textField); + frame.setVisible(true); + robot.waitForIdle(); + + robot.keyPress(KeyEvent.VK_A); + robot.keyRelease(KeyEvent.VK_A); + robot.keyPress(KeyEvent.VK_B); + robot.keyRelease(KeyEvent.VK_B); + robot.waitForIdle(); + + frame.dispose(); + if (!textField.getText().equals("ab")) { + throw new RuntimeException("Focus is lost!"); + } + } + + static boolean compare(Color c1, Color c2) { + return compare(c1.getRed(), c2.getRed()) + && compare(c1.getGreen(), c2.getGreen()) + && compare(c1.getBlue(), c2.getBlue()); + } + + static boolean compare(int n, int m) { + return Math.abs(n - m) <= 50; + } + + static float getScaleFactor() { + + final Dialog dialog = new Dialog((Window) null); + dialog.setSize(100, 100); + dialog.setModal(true); + float[] scaleFactors = new float[1]; + Panel panel = new Panel() { + + @Override + public void paint(Graphics g) { + String scaleStr = System.getenv("GDK_SCALE"); + if (scaleStr != null && !scaleStr.equals("")) { + try { + scaleFactors[0] = Float.valueOf(scaleStr); + } catch (NumberFormatException ex) { + scaleFactors[0] = 1.0f; + } + } + dialog.setVisible(false); + } + }; + dialog.add(panel); + dialog.setVisible(true); + dialog.dispose(); + return scaleFactors[0]; + } + + static void generateImages() throws Exception { + for (ImageInfo test : tests) { + generateImage(test.name1x, test.color1x, 1); + generateImage(test.name2x, test.color2x, 2); + } + } + + static void generateImage(String name, Color color, int scale) throws Exception { + File file = new File(name); + if (file.exists()) { + return; + } + BufferedImage image = new BufferedImage(scale * IMAGE_WIDTH, scale * IMAGE_HEIGHT, + BufferedImage.TYPE_INT_RGB); + Graphics g = image.getGraphics(); + g.setColor(color); + g.fillRect(0, 0, scale * IMAGE_WIDTH, scale * IMAGE_HEIGHT); + ImageIO.write(image, "png", file); + } + + static class ImageInfo { + + final String name1x; + final String name2x; + final Color color1x; + final Color color2x; + + public ImageInfo(String name1x, String name2x, Color color1x, Color color2x) { + this.name1x = name1x; + this.name2x = name2x; + this.color1x = color1x; + this.color2x = color2x; + } + } +} + From 4ea752f18eaa8045d97259f63e58b92557275724 Mon Sep 17 00:00:00 2001 From: Prem Balakrishnan Date: Fri, 11 Mar 2016 11:02:54 +0530 Subject: [PATCH 011/162] 7012008: JDesktopPane - Wrong background color with Win7+WindowsLnf Reviewed-by: ssadetsky, aivanov --- .../plaf/windows/WindowsLookAndFeel.java | 2 +- .../DesktopPaneBackgroundTest.java | 63 +++++++++++++++++++ 2 files changed, 64 insertions(+), 1 deletion(-) create mode 100644 jdk/test/javax/swing/JDesktopPane/DesktopPaneBackgroundTest.java diff --git a/jdk/src/java.desktop/share/classes/com/sun/java/swing/plaf/windows/WindowsLookAndFeel.java b/jdk/src/java.desktop/share/classes/com/sun/java/swing/plaf/windows/WindowsLookAndFeel.java index 16bb987de3a..26f7224b875 100644 --- a/jdk/src/java.desktop/share/classes/com/sun/java/swing/plaf/windows/WindowsLookAndFeel.java +++ b/jdk/src/java.desktop/share/classes/com/sun/java/swing/plaf/windows/WindowsLookAndFeel.java @@ -698,7 +698,7 @@ public class WindowsLookAndFeel extends BasicLookAndFeel // DeskTop. "Desktop.background", new DesktopProperty( - "win.desktop.backgroundColor", + "win.mdi.backgroundColor", table.get("desktop")), "Desktop.ancestorInputMap", new UIDefaults.LazyInputMap(new Object[] { diff --git a/jdk/test/javax/swing/JDesktopPane/DesktopPaneBackgroundTest.java b/jdk/test/javax/swing/JDesktopPane/DesktopPaneBackgroundTest.java new file mode 100644 index 00000000000..e8007e218d2 --- /dev/null +++ b/jdk/test/javax/swing/JDesktopPane/DesktopPaneBackgroundTest.java @@ -0,0 +1,63 @@ +/* +* Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. +* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. +* +* This code is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License version 2 only, as +* published by the Free Software Foundation. +* +* This code is distributed in the hope that it will be useful, but WITHOUT +* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +* version 2 for more details (a copy is included in the LICENSE file that +* accompanied this code). +* +* You should have received a copy of the GNU General Public License version +* 2 along with this work; if not, write to the Free Software Foundation, +* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. +* +* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA +* or visit www.oracle.com if you need additional information or have any +* questions. + */ + + /* +* @test +* @bug 7012008 +* @summary Verify JDesktopPane Background Color for WLAF +* @requires (os.family == "windows") +* @run main DesktopPaneBackgroundTest + */ +import java.awt.Color; +import java.awt.Toolkit; +import javax.swing.JDesktopPane; +import javax.swing.SwingUtilities; +import javax.swing.UIManager; + +public class DesktopPaneBackgroundTest { + + private static Color defaultBackgroudColor; + + public static void main(String[] args) throws Exception { + defaultBackgroudColor = (Color) Toolkit.getDefaultToolkit() + .getDesktopProperty("win.mdi.backgroundColor"); + + String[] lookAndFeel = new String[]{ + "com.sun.java.swing.plaf.windows.WindowsLookAndFeel", + "com.sun.java.swing.plaf.windows.WindowsClassicLookAndFeel"}; + + for (String laf : lookAndFeel) { + UIManager.setLookAndFeel(laf); + + SwingUtilities.invokeAndWait(() -> { + JDesktopPane desktopPane = new JDesktopPane(); + + Color background = desktopPane.getBackground(); + if (!background.equals(defaultBackgroudColor)) { + throw new RuntimeException("Invalid JDesktopPane " + + "Background Color for WLAF"); + } + }); + } + } +} From 3dc3d0c3e52d91bb3a205e6f8c6b1e79d9aa1928 Mon Sep 17 00:00:00 2001 From: Vikrant Agarwal Date: Fri, 11 Mar 2016 11:17:17 +0300 Subject: [PATCH 012/162] 6734341: REGTEST fails: SelectionAutoscrollTest.html Reviewed-by: serb, ssadetsky --- .../SelectionAutoscrollTest.html | 45 -------------- .../SelectionAutoscrollTest.java | 62 +++++++++++-------- 2 files changed, 36 insertions(+), 71 deletions(-) delete mode 100644 jdk/test/java/awt/TextArea/UsingWithMouse/SelectionAutoscrollTest.html diff --git a/jdk/test/java/awt/TextArea/UsingWithMouse/SelectionAutoscrollTest.html b/jdk/test/java/awt/TextArea/UsingWithMouse/SelectionAutoscrollTest.html deleted file mode 100644 index f3492dcad33..00000000000 --- a/jdk/test/java/awt/TextArea/UsingWithMouse/SelectionAutoscrollTest.html +++ /dev/null @@ -1,45 +0,0 @@ - - - - - - - - - -

    SelectionAutoscrollTest
    Bug ID: 6497109

    - -

    This is an AUTOMATIC test, simply wait for completion

    - - - - diff --git a/jdk/test/java/awt/TextArea/UsingWithMouse/SelectionAutoscrollTest.java b/jdk/test/java/awt/TextArea/UsingWithMouse/SelectionAutoscrollTest.java index 09df308ba23..6acb430a378 100644 --- a/jdk/test/java/awt/TextArea/UsingWithMouse/SelectionAutoscrollTest.java +++ b/jdk/test/java/awt/TextArea/UsingWithMouse/SelectionAutoscrollTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2007, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -22,11 +22,13 @@ */ /* - test - @bug 6497109 + @test + @bug 6497109 6734341 @summary TextArea must have selection expanding, and also be autoscrolled, if mouse is dragged from inside. + @library ../../regtesthelpers + @build Util @author Konstantin Voloshin: area=TextArea - @run applet SelectionAutoscrollTest.html + @run main SelectionAutoscrollTest */ /** @@ -38,12 +40,10 @@ */ -import java.applet.Applet; import java.awt.Frame; import java.awt.Panel; import java.awt.GridLayout; import java.awt.TextArea; - import java.awt.Point; import java.awt.Dimension; import java.awt.event.MouseEvent; @@ -52,16 +52,18 @@ import java.awt.Toolkit; import test.java.awt.regtesthelpers.Util; -public class SelectionAutoscrollTest extends Applet { +public class SelectionAutoscrollTest { TextArea textArea; Robot robot; final int desiredSelectionEnd = ('z'-'a'+1)*2; // 52 final static int SCROLL_DELAY = 10; // ms - public void start () { - createObjects(); - manipulateMouse(); - checkResults(); + public static void main(String[] args) { + SelectionAutoscrollTest selectionAutoscrollTest + = new SelectionAutoscrollTest(); + selectionAutoscrollTest.createObjects(); + selectionAutoscrollTest.manipulateMouse(); + selectionAutoscrollTest.checkResults(); } void createObjects() { @@ -102,7 +104,7 @@ public class SelectionAutoscrollTest extends Applet { robot.mousePress( MouseEvent.BUTTON1_MASK ); Util.waitForIdle( robot ); - for( int tremble=0; tremble < desiredSelectionEnd; ++tremble ) { + for( int tremble=0; tremble < 10; ++tremble ) { // Mouse is moved repeatedly here (with conservatively chosen // ammount of times), to give some time/chance for TextArea to // autoscroll and for text-selection to expand to the end. @@ -125,7 +127,7 @@ public class SelectionAutoscrollTest extends Applet { // and this is probably a bug). But, starting with 2nd iteration, // all events received will be mouse-dragged events. - moveMouseBelowTextArea( tremble%2!=0 ); + moveMouseBelowTextArea( tremble ); Util.waitForIdle( robot ); // it is needed to add some small delay on Gnome waitUntilScrollIsPerformed(robot); @@ -138,16 +140,28 @@ public class SelectionAutoscrollTest extends Applet { void moveMouseToCenterOfTextArea() { Dimension d = textArea.getSize(); Point l = textArea.getLocationOnScreen(); - robot.mouseMove( (int)(l.x+d.width*.5), (int)(l.y+d.height*.5) ); + Util.mouseMove(robot, l, new Point((int) (l.x + d.width * .5), + (int) (l.y + d.height * .5))); } - void moveMouseBelowTextArea( boolean shift ) { + void moveMouseBelowTextArea(int tremble) { Dimension d = textArea.getSize(); Point l = textArea.getLocationOnScreen(); - int x = (int)(l.x+d.width*.5); - int y = (int)(l.y+d.height*1.5); - if( shift ) y+=15; - robot.mouseMove( x, y ); + Point p1; + if (tremble == 0) { + p1 = new Point((int) (l.x + d.width * .5), + (int) (l.y + d.height * 0.5)); + } else { + p1 = new Point((int) (l.x + d.width * .5), + (int) (l.y + d.height * 1.5)); + } + Point p2 = new Point((int) (l.x + d.width * .5), + (int) (l.y + d.height * 1.5) + 15); + if (tremble % 2 == 0) { + Util.mouseMove(robot, p1, p2); + } else { + Util.mouseMove(robot, p2, p1); + } } void waitUntilScrollIsPerformed(Robot robot) { @@ -160,15 +174,11 @@ public class SelectionAutoscrollTest extends Applet { } void checkResults() { - //try { Thread.sleep( 30*1000 ); } - //catch( Exception e ) { throw new RuntimeException( e ); } - final int currentSelectionEnd = textArea.getSelectionEnd(); - System.out.println( - "TEST: Selection range after test is: ( " - + textArea.getSelectionStart() + ", " - + currentSelectionEnd + " )" + "TEST: Selection range after test is: ( " + + textArea.getSelectionStart() + ", " + + currentSelectionEnd + " )" ); boolean resultOk = ( currentSelectionEnd == desiredSelectionEnd ); From 775c1f4f733c3cfdbb65eed735cfeac5fb0d6c8d Mon Sep 17 00:00:00 2001 From: Alexander Stepanov Date: Fri, 11 Mar 2016 14:06:14 +0300 Subject: [PATCH 013/162] 8151699: [TEST_BUG] fix awt/image/multiresolution/MultiResolutionTrayIconTest Reviewed-by: serb --- .../MultiResolutionTrayIconTest.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/jdk/test/java/awt/image/multiresolution/MultiResolutionTrayIconTest/MultiResolutionTrayIconTest.java b/jdk/test/java/awt/image/multiresolution/MultiResolutionTrayIconTest/MultiResolutionTrayIconTest.java index f6f069b0ed8..87a6de00917 100644 --- a/jdk/test/java/awt/image/multiresolution/MultiResolutionTrayIconTest/MultiResolutionTrayIconTest.java +++ b/jdk/test/java/awt/image/multiresolution/MultiResolutionTrayIconTest/MultiResolutionTrayIconTest.java @@ -90,8 +90,10 @@ public class MultiResolutionTrayIconTest extends Applet { BufferedImage nok = generateImage(w / 2 + 2, h / 2 + 2, Color.RED); BaseMultiResolutionImage mri = new BaseMultiResolutionImage(new BufferedImage[] {nok, img}); - icon = new TrayIcon(img); + icon = new TrayIcon(img); + icon.setImageAutoSize(true); // just in case iconMRI = new TrayIcon(mri); + iconMRI.setImageAutoSize(true); } private void doTest() { From 3e11eda222f793e4a8d948a49ef54ea70b367400 Mon Sep 17 00:00:00 2001 From: Alexander Stepanov Date: Fri, 11 Mar 2016 19:45:03 +0300 Subject: [PATCH 014/162] 8151697: [TEST] minor update of test/java/awt/image/multiresolution/BaseMultiResolutionImageTest.java Reviewed-by: alexsch --- .../multiresolution/BaseMultiResolutionImageTest.java | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/jdk/test/java/awt/image/multiresolution/BaseMultiResolutionImageTest.java b/jdk/test/java/awt/image/multiresolution/BaseMultiResolutionImageTest.java index 1ce7b7faf82..02ba9d69e66 100644 --- a/jdk/test/java/awt/image/multiresolution/BaseMultiResolutionImageTest.java +++ b/jdk/test/java/awt/image/multiresolution/BaseMultiResolutionImageTest.java @@ -191,6 +191,17 @@ public class BaseMultiResolutionImageTest { if (!passed) { throw new RuntimeException("Resolution variants list is modifiable!"); } + + passed = false; + try { + mrImage.getGraphics(); + } catch (UnsupportedOperationException e) { + passed = true; + } + + if (!passed) { + throw new RuntimeException("getGraphics() method shouldn't be supported!"); + } } private static int getSize(int i) { From 1d135a878079d304c87f0c4d0cdae686ffdbc190 Mon Sep 17 00:00:00 2001 From: Alexander Scherbatiy Date: Fri, 11 Mar 2016 21:57:43 +0400 Subject: [PATCH 015/162] 8069348: SunGraphics2D.copyArea() does not properly work for scaled graphics in D3D Reviewed-by: flar, serb --- .../sun/java2d/OSXOffScreenSurfaceData.java | 33 ++-- .../classes/sun/java2d/OSXSurfaceData.java | 10 +- .../sun/java2d/opengl/CGLSurfaceData.java | 25 --- .../classes/sun/java2d/SunGraphics2D.java | 54 +++--- .../share/classes/sun/java2d/SurfaceData.java | 5 + .../sun/java2d/opengl/OGLSurfaceData.java | 20 +-- .../sun/java2d/x11/X11SurfaceData.java | 5 +- .../classes/sun/java2d/xr/XRSurfaceData.java | 7 +- .../sun/java2d/d3d/D3DSurfaceData.java | 19 +- .../java2d/windows/GDIWindowSurfaceData.java | 5 +- .../CopyScaledArea/CopyScaledAreaTest.java | 164 ++++++++++++++++++ .../JInternalFrame/8069348/bug8069348.java | 144 +++++++++++++++ 12 files changed, 379 insertions(+), 112 deletions(-) create mode 100644 jdk/test/java/awt/Graphics/CopyScaledArea/CopyScaledAreaTest.java create mode 100644 jdk/test/javax/swing/JInternalFrame/8069348/bug8069348.java diff --git a/jdk/src/java.desktop/macosx/classes/sun/java2d/OSXOffScreenSurfaceData.java b/jdk/src/java.desktop/macosx/classes/sun/java2d/OSXOffScreenSurfaceData.java index 9f4f5b2f219..c4a09d86cef 100644 --- a/jdk/src/java.desktop/macosx/classes/sun/java2d/OSXOffScreenSurfaceData.java +++ b/jdk/src/java.desktop/macosx/classes/sun/java2d/OSXOffScreenSurfaceData.java @@ -478,13 +478,9 @@ public class OSXOffScreenSurfaceData extends OSXSurfaceData // implements Raster // For the Sun2D renderer we should rely on the implementation of the super class. // BufImageSurfaceData.java doesn't have an implementation of copyArea() and relies on the super class. - int offsetX = 0; - int offsetY = 0; - if (sg2d.transformState == SunGraphics2D.TRANSFORM_ANY_TRANSLATE || - sg2d.transformState == SunGraphics2D.TRANSFORM_INT_TRANSLATE) { - offsetX = (int) sg2d.transform.getTranslateX(); - offsetY = (int) sg2d.transform.getTranslateY(); - } else if (sg2d.transformState != SunGraphics2D.TRANSFORM_ISIDENT) { return false; } + if (sg2d.transformState >= SunGraphics2D.TRANSFORM_TRANSLATESCALE) { + return false; + } // reset the clip (this is how it works on windows) // we actually can handle a case with any clips but windows ignores the light clip @@ -498,18 +494,23 @@ public class OSXOffScreenSurfaceData extends OSXSurfaceData // implements Raster return true; } - // the rectangle returned from clipCopyArea() is in the coordinate space of the surface (image) - // we need to substract the offsetX and offsetY to move it to the coordinate space of the graphics2d. - // sg2d.drawImage expects the destination rect to be in the coord space of the graphics2d. - // (vm) - x = clippedCopyAreaRect.x - offsetX; - y = clippedCopyAreaRect.y - offsetY; + // the rectangle returned from clipCopyArea() is in the coordinate space + // of the surface (image) + x = clippedCopyAreaRect.x; + y = clippedCopyAreaRect.y; w = clippedCopyAreaRect.width; h = clippedCopyAreaRect.height; - // copy (dst coordinates are in the coord space of the graphics2d, and src coordinates are - // in the coordinate space of the image) - sg2d.drawImage(this.bim, x + dx, y + dy, x + dx + w, y + dy + h, x + offsetX, y + offsetY, x + w + offsetX, y + h + offsetY, null); + // copy (dst coordinates are in the coord space of the graphics2d, and + // src coordinates are in the coordinate space of the image) + // sg2d.drawImage expects the destination rect to be in the coord space + // of the graphics2d. (vm) + // we need to substract the transX and transY to move it + // to the coordinate space of the graphics2d. + int dstX = x + dx - sg2d.transX; + int dstY = y + dy - sg2d.transY; + sg2d.drawImage(this.bim, dstX, dstY, dstX + w, dstY + h, + x, y, x + w, y + h, null); // restore the clip sg2d.setClip(clip); diff --git a/jdk/src/java.desktop/macosx/classes/sun/java2d/OSXSurfaceData.java b/jdk/src/java.desktop/macosx/classes/sun/java2d/OSXSurfaceData.java index d1444b81a90..a0fd6486cb5 100644 --- a/jdk/src/java.desktop/macosx/classes/sun/java2d/OSXSurfaceData.java +++ b/jdk/src/java.desktop/macosx/classes/sun/java2d/OSXSurfaceData.java @@ -1094,19 +1094,13 @@ public abstract class OSXSurfaceData extends BufImgSurfaceData { } /** - * Clips the copy area to the heavywieght bounds and returns the cliped rectangle. The tricky part here is the - * passed arguments x, y are in the coordinate space of the sg2d/lightweight comp. In order to do the clipping we - * translate them to the coordinate space of the surface, and the returned clipped rectangle is in the coordinate - * space of the surface. + * Clips the copy area to the heavyweight bounds and returns the clipped rectangle. + * The returned clipped rectangle is in the coordinate space of the surface. */ protected Rectangle clipCopyArea(SunGraphics2D sg2d, int x, int y, int w, int h, int dx, int dy) { // we need to clip against the heavyweight bounds copyAreaBounds.setBounds(sg2d.devClip.getLoX(), sg2d.devClip.getLoY(), sg2d.devClip.getWidth(), sg2d.devClip.getHeight()); - // put src rect into surface coordinate space - x += sg2d.transX; - y += sg2d.transY; - // clip src rect srcCopyAreaRect.setBounds(x, y, w, h); intersection(srcCopyAreaRect, copyAreaBounds, srcCopyAreaRect); diff --git a/jdk/src/java.desktop/macosx/classes/sun/java2d/opengl/CGLSurfaceData.java b/jdk/src/java.desktop/macosx/classes/sun/java2d/opengl/CGLSurfaceData.java index b59349f9cb8..2eb9048e71e 100644 --- a/jdk/src/java.desktop/macosx/classes/sun/java2d/opengl/CGLSurfaceData.java +++ b/jdk/src/java.desktop/macosx/classes/sun/java2d/opengl/CGLSurfaceData.java @@ -175,31 +175,6 @@ public abstract class CGLSurfaceData extends OGLSurfaceData { return scale; } - @Override - public boolean copyArea(SunGraphics2D sg2d, int x, int y, int w, int h, - int dx, int dy) { - final int state = sg2d.transformState; - if (state > SunGraphics2D.TRANSFORM_TRANSLATESCALE - || sg2d.compositeState >= SunGraphics2D.COMP_XOR) { - return false; - } - if (state <= SunGraphics2D.TRANSFORM_ANY_TRANSLATE) { - x += sg2d.transX; - y += sg2d.transY; - } else if (state == SunGraphics2D.TRANSFORM_TRANSLATESCALE) { - final double[] coords = {x, y, x + w, y + h, x + dx, y + dy}; - sg2d.transform.transform(coords, 0, coords, 0, 3); - x = (int) Math.ceil(coords[0] - 0.5); - y = (int) Math.ceil(coords[1] - 0.5); - w = ((int) Math.ceil(coords[2] - 0.5)) - x; - h = ((int) Math.ceil(coords[3] - 0.5)) - y; - dx = ((int) Math.ceil(coords[4] - 0.5)) - x; - dy = ((int) Math.ceil(coords[5] - 0.5)) - y; - } - oglRenderPipe.copyArea(sg2d, x, y, w, h, dx, dy); - return true; - } - protected native void clearWindow(); public static class CGLWindowSurfaceData extends CGLSurfaceData { diff --git a/jdk/src/java.desktop/share/classes/sun/java2d/SunGraphics2D.java b/jdk/src/java.desktop/share/classes/sun/java2d/SunGraphics2D.java index 967077d6585..8207213e3e5 100644 --- a/jdk/src/java.desktop/share/classes/sun/java2d/SunGraphics2D.java +++ b/jdk/src/java.desktop/share/classes/sun/java2d/SunGraphics2D.java @@ -2101,13 +2101,39 @@ public final class SunGraphics2D if (w <= 0 || h <= 0) { return; } + + if (transformState == SunGraphics2D.TRANSFORM_ISIDENT) { + // do nothing + } else if (transformState <= SunGraphics2D.TRANSFORM_ANY_TRANSLATE) { + x += transX; + y += transY; + } else if (transformState == SunGraphics2D.TRANSFORM_TRANSLATESCALE) { + final double[] coords = {x, y, x + w, y + h, x + dx, y + dy}; + transform.transform(coords, 0, coords, 0, 3); + x = (int) Math.ceil(coords[0] - 0.5); + y = (int) Math.ceil(coords[1] - 0.5); + w = ((int) Math.ceil(coords[2] - 0.5)) - x; + h = ((int) Math.ceil(coords[3] - 0.5)) - y; + dx = ((int) Math.ceil(coords[4] - 0.5)) - x; + dy = ((int) Math.ceil(coords[5] - 0.5)) - y; + // In case of negative scale transform, reflect the rect coords. + if (w < 0) { + w = -w; + x -= w; + } + if (h < 0) { + h = -h; + y -= h; + } + } else { + throw new InternalError("transformed copyArea not implemented yet"); + } + SurfaceData theData = surfaceData; if (theData.copyArea(this, x, y, w, h, dx, dy)) { return; } - if (transformState > TRANSFORM_TRANSLATESCALE) { - throw new InternalError("transformed copyArea not implemented yet"); - } + // REMIND: This method does not deal with missing data from the // source object (i.e. it does not send exposure events...) @@ -2126,26 +2152,6 @@ public final class SunGraphics2D lastCAcomp = comp; } - double[] coords = {x, y, x + w, y + h, x + dx, y + dy}; - transform.transform(coords, 0, coords, 0, 3); - - x = (int)Math.ceil(coords[0] - 0.5); - y = (int)Math.ceil(coords[1] - 0.5); - w = ((int)Math.ceil(coords[2] - 0.5)) - x; - h = ((int)Math.ceil(coords[3] - 0.5)) - y; - dx = ((int)Math.ceil(coords[4] - 0.5)) - x; - dy = ((int)Math.ceil(coords[5] - 0.5)) - y; - - // In case of negative scale transform, reflect the rect coords. - if (w < 0) { - w *= -1; - x -= w; - } - if (h < 0) { - h *= -1; - y -= h; - } - Blit ob = lastCAblit; if (dy == 0 && dx > 0 && dx < w) { while (w > 0) { @@ -2167,7 +2173,7 @@ public final class SunGraphics2D } return; } - ob.Blit(theData, theData, comp, clip, x, y, x+dx, y+dy, w, h); + ob.Blit(theData, theData, comp, clip, x, y, x+dx, y+dy, w, h); } /* diff --git a/jdk/src/java.desktop/share/classes/sun/java2d/SurfaceData.java b/jdk/src/java.desktop/share/classes/sun/java2d/SurfaceData.java index 4de1a1fc576..806bf05bced 100644 --- a/jdk/src/java.desktop/share/classes/sun/java2d/SurfaceData.java +++ b/jdk/src/java.desktop/share/classes/sun/java2d/SurfaceData.java @@ -1039,6 +1039,11 @@ public abstract class SurfaceData * Performs a copyarea within this surface. Returns * false if there is no algorithm to perform the copyarea * given the current settings of the SunGraphics2D. + * + * @param x the x coordinate of the area in device space + * @param y the y coordinate of the area in device space + * @param w the width of the area in device space + * @param h the height of the area in device space */ public boolean copyArea(SunGraphics2D sg2d, int x, int y, int w, int h, int dx, int dy) diff --git a/jdk/src/java.desktop/share/classes/sun/java2d/opengl/OGLSurfaceData.java b/jdk/src/java.desktop/share/classes/sun/java2d/opengl/OGLSurfaceData.java index 914b97aba05..5e6f802da14 100644 --- a/jdk/src/java.desktop/share/classes/sun/java2d/opengl/OGLSurfaceData.java +++ b/jdk/src/java.desktop/share/classes/sun/java2d/opengl/OGLSurfaceData.java @@ -542,20 +542,14 @@ public abstract class OGLSurfaceData extends SurfaceData return super.getMaskFill(sg2d); } - public boolean copyArea(SunGraphics2D sg2d, - int x, int y, int w, int h, int dx, int dy) - { - if (sg2d.transformState < SunGraphics2D.TRANSFORM_TRANSLATESCALE && - sg2d.compositeState < SunGraphics2D.COMP_XOR) - { - x += sg2d.transX; - y += sg2d.transY; - - oglRenderPipe.copyArea(sg2d, x, y, w, h, dx, dy); - - return true; + @Override + public boolean copyArea(SunGraphics2D sg2d, int x, int y, int w, int h, + int dx, int dy) { + if (sg2d.compositeState >= SunGraphics2D.COMP_XOR) { + return false; } - return false; + oglRenderPipe.copyArea(sg2d, x, y, w, h, dx, dy); + return true; } public void flush() { diff --git a/jdk/src/java.desktop/unix/classes/sun/java2d/x11/X11SurfaceData.java b/jdk/src/java.desktop/unix/classes/sun/java2d/x11/X11SurfaceData.java index 1d83b65a876..3ce34effd39 100644 --- a/jdk/src/java.desktop/unix/classes/sun/java2d/x11/X11SurfaceData.java +++ b/jdk/src/java.desktop/unix/classes/sun/java2d/x11/X11SurfaceData.java @@ -487,12 +487,9 @@ public abstract class X11SurfaceData extends XSurfaceData { makePipes(); } CompositeType comptype = sg2d.imageComp; - if (sg2d.transformState < SunGraphics2D.TRANSFORM_TRANSLATESCALE && - (CompositeType.SrcOverNoEa.equals(comptype) || + if ((CompositeType.SrcOverNoEa.equals(comptype) || CompositeType.SrcNoEa.equals(comptype))) { - x += sg2d.transX; - y += sg2d.transY; SunToolkit.awtLock(); try { boolean needExposures = canSourceSendExposures(x, y, w, h); diff --git a/jdk/src/java.desktop/unix/classes/sun/java2d/xr/XRSurfaceData.java b/jdk/src/java.desktop/unix/classes/sun/java2d/xr/XRSurfaceData.java index aabdda0db1e..b88c5507984 100644 --- a/jdk/src/java.desktop/unix/classes/sun/java2d/xr/XRSurfaceData.java +++ b/jdk/src/java.desktop/unix/classes/sun/java2d/xr/XRSurfaceData.java @@ -365,12 +365,9 @@ public abstract class XRSurfaceData extends XSurfaceData { makePipes(); } CompositeType comptype = sg2d.imageComp; - if (sg2d.transformState < SunGraphics2D.TRANSFORM_TRANSLATESCALE && - (CompositeType.SrcOverNoEa.equals(comptype) || - CompositeType.SrcNoEa.equals(comptype))) + if (CompositeType.SrcOverNoEa.equals(comptype) || + CompositeType.SrcNoEa.equals(comptype)) { - x += sg2d.transX; - y += sg2d.transY; try { SunToolkit.awtLock(); boolean needExposures = canSourceSendExposures(x, y, w, h); diff --git a/jdk/src/java.desktop/windows/classes/sun/java2d/d3d/D3DSurfaceData.java b/jdk/src/java.desktop/windows/classes/sun/java2d/d3d/D3DSurfaceData.java index c6b25970951..e2b08016e56 100644 --- a/jdk/src/java.desktop/windows/classes/sun/java2d/d3d/D3DSurfaceData.java +++ b/jdk/src/java.desktop/windows/classes/sun/java2d/d3d/D3DSurfaceData.java @@ -703,20 +703,13 @@ public class D3DSurfaceData extends SurfaceData implements AccelSurface { } @Override - public boolean copyArea(SunGraphics2D sg2d, - int x, int y, int w, int h, int dx, int dy) - { - if (sg2d.transformState < SunGraphics2D.TRANSFORM_TRANSLATESCALE && - sg2d.compositeState < SunGraphics2D.COMP_XOR) - { - x += sg2d.transX; - y += sg2d.transY; - - d3dRenderPipe.copyArea(sg2d, x, y, w, h, dx, dy); - - return true; + public boolean copyArea(SunGraphics2D sg2d, int x, int y, int w, int h, + int dx, int dy) { + if (sg2d.compositeState >= SunGraphics2D.COMP_XOR) { + return false; } - return false; + d3dRenderPipe.copyArea(sg2d, x, y, w, h, dx, dy); + return true; } @Override diff --git a/jdk/src/java.desktop/windows/classes/sun/java2d/windows/GDIWindowSurfaceData.java b/jdk/src/java.desktop/windows/classes/sun/java2d/windows/GDIWindowSurfaceData.java index 2ba2b11aa59..ad211ab473c 100644 --- a/jdk/src/java.desktop/windows/classes/sun/java2d/windows/GDIWindowSurfaceData.java +++ b/jdk/src/java.desktop/windows/classes/sun/java2d/windows/GDIWindowSurfaceData.java @@ -311,13 +311,10 @@ public class GDIWindowSurfaceData extends SurfaceData { int x, int y, int w, int h, int dx, int dy) { CompositeType comptype = sg2d.imageComp; - if (sg2d.transformState < SunGraphics2D.TRANSFORM_TRANSLATESCALE && - sg2d.clipState != SunGraphics2D.CLIP_SHAPE && + if (sg2d.clipState != SunGraphics2D.CLIP_SHAPE && (CompositeType.SrcOverNoEa.equals(comptype) || CompositeType.SrcNoEa.equals(comptype))) { - x += sg2d.transX; - y += sg2d.transY; int dstx1 = x + dx; int dsty1 = y + dy; int dstx2 = dstx1 + w; diff --git a/jdk/test/java/awt/Graphics/CopyScaledArea/CopyScaledAreaTest.java b/jdk/test/java/awt/Graphics/CopyScaledArea/CopyScaledAreaTest.java new file mode 100644 index 00000000000..92d8540787c --- /dev/null +++ b/jdk/test/java/awt/Graphics/CopyScaledArea/CopyScaledAreaTest.java @@ -0,0 +1,164 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import java.awt.*; +import java.awt.image.BufferedImage; +import java.awt.image.VolatileImage; +import static sun.awt.OSInfo.*; + +/** + * @test + * @bug 8069348 + * @summary SunGraphics2D.copyArea() does not properly work for scaled graphics + * @modules java.desktop/sun.awt + * @run main/othervm -Dsun.java2d.uiScale=2 CopyScaledAreaTest + * @run main/othervm -Dsun.java2d.opengl=true -Dsun.java2d.uiScale=2 CopyScaledAreaTest + * @run main/othervm -Dsun.java2d.d3d=true -Dsun.java2d.uiScale=2 CopyScaledAreaTest + * @run main/othervm -Dsun.java2d.d3d=false -Dsun.java2d.opengl=false + * -Dsun.java2d.uiScale=2 CopyScaledAreaTest + */ +public class CopyScaledAreaTest { + + private static final int IMAGE_WIDTH = 800; + private static final int IMAGE_HEIGHT = 800; + private static final int X = 50; + private static final int Y = 50; + private static final int W = 100; + private static final int H = 75; + private static final int DX = 15; + private static final int DY = 10; + private static final int N = 3; + private static final Color BACKGROUND_COLOR = Color.YELLOW; + private static final Color FILL_COLOR = Color.ORANGE; + private static final double[][] SCALES = {{1.3, 1.4}, {0.3, 2.3}, {2.7, 0.1}}; + + private static boolean isSupported() { + String d3d = System.getProperty("sun.java2d.d3d"); + return !Boolean.getBoolean(d3d) || getOSType() == OSType.WINDOWS; + } + + private static int scale(int x, double scale) { + return (int) Math.floor(x * scale); + } + + private static VolatileImage createVolatileImage(GraphicsConfiguration conf) { + return conf.createCompatibleVolatileImage(IMAGE_WIDTH, IMAGE_HEIGHT); + } + + // rendering to the image + private static void renderOffscreen(VolatileImage vImg, + GraphicsConfiguration conf, + double scaleX, + double scaleY) + { + int attempts = 0; + do { + + if (attempts > 10) { + throw new RuntimeException("Too many attempts!"); + } + + if (vImg.validate(conf) == VolatileImage.IMAGE_INCOMPATIBLE) { + // old vImg doesn't work with new GraphicsConfig; re-create it + vImg = createVolatileImage(conf); + } + Graphics2D g = vImg.createGraphics(); + // + // miscellaneous rendering commands... + // + g.setColor(BACKGROUND_COLOR); + g.fillRect(0, 0, IMAGE_WIDTH, IMAGE_HEIGHT); + g.scale(scaleX, scaleY); + + g.setColor(FILL_COLOR); + g.fillRect(X, Y, W, H); + + for (int i = 0; i < N; i++) { + g.copyArea(X + i * DX, Y + i * DY, W, H, DX, DY); + } + g.dispose(); + attempts++; + } while (vImg.contentsLost()); + } + + public static void main(String[] args) throws Exception { + + if (!isSupported()) { + return; + } + + GraphicsConfiguration graphicsConfiguration = + GraphicsEnvironment.getLocalGraphicsEnvironment() + .getDefaultScreenDevice().getDefaultConfiguration(); + + for(double[] scales: SCALES){ + testScale(scales[0], scales[1], graphicsConfiguration); + } + } + + private static void testScale(double scaleX, double scaleY, + GraphicsConfiguration gc) throws Exception + { + + BufferedImage buffImage = new BufferedImage(IMAGE_WIDTH, IMAGE_HEIGHT, + BufferedImage.TYPE_INT_RGB); + Graphics g = buffImage.createGraphics(); + + VolatileImage vImg = createVolatileImage(gc); + + int attempts = 0; + do { + + if (attempts > 10) { + throw new RuntimeException("Too many attempts!"); + } + + int returnCode = vImg.validate(gc); + if (returnCode == VolatileImage.IMAGE_RESTORED) { + // Contents need to be restored + renderOffscreen(vImg, gc, scaleX, scaleY); // restore contents + } else if (returnCode == VolatileImage.IMAGE_INCOMPATIBLE) { + // old vImg doesn't work with new GraphicsConfig; re-create it + vImg = createVolatileImage(gc); + renderOffscreen(vImg, gc, scaleX, scaleY); + } + g.drawImage(vImg, 0, 0, null); + attempts++; + } while (vImg.contentsLost()); + + g.dispose(); + + int x = scale(X + N * DX, scaleX) + 1; + int y = scale(Y + N * DY, scaleY) + 1; + int w = scale(W, scaleX) - 2; + int h = scale(H, scaleY) - 2; + + for (int i = x; i < x + w; i++) { + for (int j = y; j < y + h; j++) { + if (buffImage.getRGB(i, j) != FILL_COLOR.getRGB()) { + throw new RuntimeException("Wrong rectangle color!"); + } + } + } + } +} diff --git a/jdk/test/javax/swing/JInternalFrame/8069348/bug8069348.java b/jdk/test/javax/swing/JInternalFrame/8069348/bug8069348.java new file mode 100644 index 00000000000..d9deeefb99b --- /dev/null +++ b/jdk/test/javax/swing/JInternalFrame/8069348/bug8069348.java @@ -0,0 +1,144 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.Graphics; +import java.awt.Rectangle; +import java.awt.Robot; +import java.awt.event.InputEvent; +import javax.swing.JDesktopPane; +import javax.swing.JFrame; +import javax.swing.JInternalFrame; +import javax.swing.JPanel; +import javax.swing.SwingUtilities; +import static sun.awt.OSInfo.*; + +/** + * @test + * @bug 8069348 + * @summary SunGraphics2D.copyArea() does not properly work for scaled graphics + * @author Alexandr Scherbatiy + * @modules java.desktop/sun.awt + * @run main/othervm -Dsun.java2d.uiScale=2 bug8069348 + * @run main/othervm -Dsun.java2d.opengl=true -Dsun.java2d.uiScale=2 bug8069348 + * @run main/othervm -Dsun.java2d.d3d=true -Dsun.java2d.uiScale=2 bug8069348 + */ +public class bug8069348 { + + private static final int WIN_WIDTH = 500; + private static final int WIN_HEIGHT = 500; + + private static final Color DESKTOPPANE_COLOR = Color.YELLOW; + private static final Color FRAME_COLOR = Color.ORANGE; + + private static JFrame frame; + private static JInternalFrame internalFrame; + + public static void main(String[] args) throws Exception { + + if (!isSupported()) { + return; + } + + try { + + SwingUtilities.invokeAndWait(bug8069348::createAndShowGUI); + + Robot robot = new Robot(); + robot.setAutoDelay(50); + robot.waitForIdle(); + + Rectangle screenBounds = getInternalFrameScreenBounds(); + + int x = screenBounds.x + screenBounds.width / 2; + int y = screenBounds.y + 10; + int dx = screenBounds.width / 2; + int dy = screenBounds.height / 2; + + robot.mouseMove(x, y); + robot.waitForIdle(); + + robot.mousePress(InputEvent.BUTTON1_MASK); + robot.mouseMove(x + dx, y + dy); + robot.mouseRelease(InputEvent.BUTTON1_MASK); + robot.waitForIdle(); + + int cx = screenBounds.x + screenBounds.width + dx / 2; + int cy = screenBounds.y + screenBounds.height + dy / 2; + + robot.mouseMove(cx, cy); + if (!FRAME_COLOR.equals(robot.getPixelColor(cx, cy))) { + throw new RuntimeException("Internal frame is not correctly dragged!"); + } + } finally { + if (frame != null) { + frame.dispose(); + } + } + } + + private static boolean isSupported() { + String d3d = System.getProperty("sun.java2d.d3d"); + return !Boolean.getBoolean(d3d) || getOSType() == OSType.WINDOWS; + } + + private static Rectangle getInternalFrameScreenBounds() throws Exception { + Rectangle[] points = new Rectangle[1]; + SwingUtilities.invokeAndWait(() -> { + points[0] = new Rectangle(internalFrame.getLocationOnScreen(), + internalFrame.getSize()); + }); + return points[0]; + } + + private static void createAndShowGUI() { + + frame = new JFrame(); + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + + JDesktopPane desktopPane = new JDesktopPane(); + desktopPane.setBackground(DESKTOPPANE_COLOR); + + internalFrame = new JInternalFrame("Test") { + + @Override + public void paint(Graphics g) { + super.paint(g); + g.setColor(FRAME_COLOR); + g.fillRect(0, 0, getWidth(), getHeight()); + } + }; + internalFrame.setSize(WIN_WIDTH / 3, WIN_HEIGHT / 3); + internalFrame.setVisible(true); + desktopPane.add(internalFrame); + + JPanel panel = new JPanel(); + panel.setLayout(new BorderLayout()); + panel.add(desktopPane, BorderLayout.CENTER); + frame.add(panel); + frame.setSize(WIN_WIDTH, WIN_HEIGHT); + frame.setVisible(true); + frame.requestFocus(); + } +} From 1e99ae4108fc5524d16c1024432ac377ac9706ff Mon Sep 17 00:00:00 2001 From: Prasanta Sadhukhan Date: Mon, 14 Mar 2016 13:04:07 +0530 Subject: [PATCH 016/162] 8151621: [TEST_BUG] java/awt/print/PrinterJob/MultiMonPrintDlgTest.java doesn't work with jtreg Reviewed-by: yan, jdv --- .../PrinterJob/MultiMonPrintDlgTest.java | 92 ++++++++++++++----- 1 file changed, 67 insertions(+), 25 deletions(-) diff --git a/jdk/test/java/awt/print/PrinterJob/MultiMonPrintDlgTest.java b/jdk/test/java/awt/print/PrinterJob/MultiMonPrintDlgTest.java index 013de39b8a1..4086f663a5c 100644 --- a/jdk/test/java/awt/print/PrinterJob/MultiMonPrintDlgTest.java +++ b/jdk/test/java/awt/print/PrinterJob/MultiMonPrintDlgTest.java @@ -43,16 +43,18 @@ import javax.swing.SwingUtilities; */ public class MultiMonPrintDlgTest implements ActionListener { - Frame primaryFrame = null; - Frame secFrame = null; - GraphicsDevice gd[] = GraphicsEnvironment.getLocalGraphicsEnvironment(). + private static boolean testPassed; + private static Thread mainThread; + private static boolean testGeneratedInterrupt; + private static int sleepTime = 30000; + private static String message = "User has not executed the test"; + + static Frame primaryFrame = null; + static Frame secFrame = null; + static GraphicsDevice gd[] = GraphicsEnvironment.getLocalGraphicsEnvironment(). getScreenDevices(); - public MultiMonPrintDlgTest() throws Exception { - if (gd.length <= 1) { - System.out.println("This test should be run only on dual-monitor systems. Aborted!!"); - return; - } + private static void init() throws Exception { String[] instructions = { @@ -70,6 +72,10 @@ public class MultiMonPrintDlgTest implements ActionListener { instructions, "information", JOptionPane.INFORMATION_MESSAGE); }); + } + + private void executeTest() { + GraphicsDevice defDev = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice(); int x = 0; Frame f = null; @@ -95,31 +101,67 @@ public class MultiMonPrintDlgTest implements ActionListener { } public void actionPerformed (ActionEvent ae) { - try { - javax.print.attribute.PrintRequestAttributeSet prSet = - new javax.print.attribute.HashPrintRequestAttributeSet(); - java.awt.print.PrinterJob.getPrinterJob().pageDialog(prSet); - Window w = KeyboardFocusManager.getCurrentKeyboardFocusManager().getActiveWindow(); - int dialogButton = JOptionPane.showConfirmDialog (w, - "Did the pageDialog shown in non-default monitor?", - null, JOptionPane.YES_NO_OPTION); - if(dialogButton == JOptionPane.NO_OPTION) { - throw new RuntimeException("PageDialog is shown in wrong monitor"); - } + javax.print.attribute.PrintRequestAttributeSet prSet = + new javax.print.attribute.HashPrintRequestAttributeSet(); + java.awt.print.PrinterJob.getPrinterJob().pageDialog(prSet); + Window w = KeyboardFocusManager.getCurrentKeyboardFocusManager().getActiveWindow(); + int dialogButton = JOptionPane.showConfirmDialog (w, + "Did the pageDialog shown in non-default monitor?", + null, JOptionPane.YES_NO_OPTION); + if(dialogButton == JOptionPane.NO_OPTION) { + fail("PageDialog is shown in wrong monitor"); + } else { java.awt.print.PrinterJob.getPrinterJob().printDialog(prSet); dialogButton = JOptionPane.showConfirmDialog (w, - "Did the printDialog shown in non-default monitor?", - null, JOptionPane.YES_NO_OPTION); + "Did the printDialog shown in non-default monitor?", + null, JOptionPane.YES_NO_OPTION); if(dialogButton == JOptionPane.NO_OPTION) { - throw new RuntimeException("PrintDialog is shown in wrong monitor"); + fail("PrintDialog is shown in wrong monitor"); + } else { + pass(); } - } finally { - primaryFrame.dispose(); - secFrame.dispose(); } } + private static void dispose() { + primaryFrame.dispose(); + secFrame.dispose(); + } + + public static synchronized void pass() { + testPassed = true; + testGeneratedInterrupt = true; + mainThread.interrupt(); + } + + public static synchronized void fail(String msg) { + testPassed = false; + message = msg; + testGeneratedInterrupt = true; + mainThread.interrupt(); + } + public static void main (String args[]) throws Exception { + if (gd.length <= 1) { + System.out.println("This test should be run only on dual-monitor systems. Aborted!!"); + return; + } + init(); MultiMonPrintDlgTest test = new MultiMonPrintDlgTest(); + test.executeTest(); + mainThread = Thread.currentThread(); + + try { + mainThread.sleep(sleepTime); + } catch (InterruptedException ex) { + dispose(); + if (!testPassed && testGeneratedInterrupt) { + throw new RuntimeException(message); + } + } + if (!testGeneratedInterrupt) { + dispose(); + throw new RuntimeException(message); + } } } From 495a192c6957a16633fbdbeb973db769127987d3 Mon Sep 17 00:00:00 2001 From: Alexander Stepanov Date: Mon, 14 Mar 2016 12:20:38 +0300 Subject: [PATCH 017/162] 8150724: [TEST] HiDPI: create a test for multiresolution icons Reviewed-by: alexsch, yan --- .../MultiresolutionIconTest.java | 238 ++++++++++++++++++ 1 file changed, 238 insertions(+) create mode 100644 jdk/test/java/awt/image/multiresolution/MultiresolutionIconTest.java diff --git a/jdk/test/java/awt/image/multiresolution/MultiresolutionIconTest.java b/jdk/test/java/awt/image/multiresolution/MultiresolutionIconTest.java new file mode 100644 index 00000000000..c8b124d71f0 --- /dev/null +++ b/jdk/test/java/awt/image/multiresolution/MultiresolutionIconTest.java @@ -0,0 +1,238 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 8150724 8151303 + * @author a.stepanov + * @summary Check that correct resolution variants are chosen for icons + * when multiresolution image is used for their construction. + * + * @requires (os.family != "mac") + * + * @library ../../../../lib/testlibrary/ + * @build ExtendedRobot + * @run main/othervm/timeout=240 -Dsun.java2d.uiScale=1 MultiresolutionIconTest + * @run main/othervm/timeout=240 -Dsun.java2d.uiScale=2 MultiresolutionIconTest + */ + + +// TODO: please remove the "@requires" tag after 8151303 fix + + +import java.awt.*; +import java.awt.event.InputEvent; +import java.awt.geom.AffineTransform; +import java.awt.image.BaseMultiResolutionImage; +import java.awt.image.BufferedImage; +import javax.swing.*; + +public class MultiresolutionIconTest extends JFrame { + + private final static int SZ = 100; + private final static int N = 5; // number of components + + private final static String SCALE = "sun.java2d.uiScale"; + private final static Color C1X = Color.RED; + private final static Color C2X = Color.BLUE; + + private JLabel lbl; + private JTabbedPane tabbedPane; + + private final ExtendedRobot r; + + private static BufferedImage generateImage(int sz, Color c) { + + BufferedImage img = new BufferedImage(sz, sz, BufferedImage.TYPE_INT_RGB); + Graphics g = img.getGraphics(); + g.setColor(c); + g.fillRect(0, 0, sz, sz); + return img; + } + + public MultiresolutionIconTest(UIManager.LookAndFeelInfo lf) throws Exception { + + UIManager.setLookAndFeel(lf.getClassName()); + r = new ExtendedRobot(); + SwingUtilities.invokeAndWait(this::UI); + } + + private void UI() { + + setUndecorated(true); + + BufferedImage img1x = generateImage(SZ / 2, C1X); + BufferedImage img2x = generateImage(SZ, C2X); + BaseMultiResolutionImage mri = new BaseMultiResolutionImage( + new BufferedImage[]{img1x, img2x}); + Icon icon = new ImageIcon(mri); + + // hardcoded icon size for OS X (Mac OS X L&F) - see JDK-8151060 + BufferedImage tab1x = generateImage(16, C1X); + BufferedImage tab2x = generateImage(32, C2X); + BaseMultiResolutionImage tabMRI = new BaseMultiResolutionImage( + new BufferedImage[]{tab1x, tab2x}); + Icon tabIcon = new ImageIcon(tabMRI); + + setSize((N + 1) * SZ, SZ); + setLocation(50, 50); + + setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + getContentPane().setLayout(new GridLayout(1, 1)); + + JPanel p = new JPanel(); + p.setLayout(new GridLayout(1, N)); + + JButton btn = new JButton(icon); + p.add(btn); + + JToggleButton tbn = new JToggleButton(icon); + p.add(tbn); + + JRadioButton rbn = new JRadioButton(icon); + rbn.setHorizontalAlignment(SwingConstants.CENTER); + p.add(rbn); + + JCheckBox cbx = new JCheckBox(icon); + cbx.setHorizontalAlignment(SwingConstants.CENTER); + p.add(cbx); + + lbl = new JLabel(icon); + p.add(lbl); + + tabbedPane = new JTabbedPane(JTabbedPane.LEFT); + tabbedPane.addTab("", tabIcon, p); + getContentPane().add(tabbedPane); + + setResizable(false); + setVisible(true); + } + + private static boolean is2x() { + + AffineTransform tr = GraphicsEnvironment.getLocalGraphicsEnvironment(). + getDefaultScreenDevice().getDefaultConfiguration(). + getDefaultTransform(); + return (Math.min(tr.getScaleX(), tr.getScaleY()) > 1.001); + } + + private boolean checkPressedColor(int x, int y, Color ok) { + + r.mouseMove(x, y); + r.waitForIdle(); + r.mousePress(InputEvent.BUTTON1_DOWN_MASK); + r.waitForIdle(100); + Color c = r.getPixelColor(x, y); + r.waitForIdle(100); + r.mouseRelease(InputEvent.BUTTON1_DOWN_MASK); + r.waitForIdle(100); + if (!c.equals(ok)) { return false; } + // check the icon's color hasn't changed + // after the mouse was released + c = r.getPixelColor(x, y); + return c.equals(ok); + } + + private boolean checkTabIcon( + int xStart, int xEnd, int yStart, int yEnd, Color ok, Color nok) { + + for (int y = yStart; y < yEnd; y += 2) { + for (int x = xStart; x < xEnd; x += 2) { + Color c = r.getPixelColor(x, y); + if (c.equals(nok)) { return false; } + else if (c.equals(ok)) { + // shift a bit to avoid the selection effects + return checkPressedColor(x + 5, y + 5, ok); + } + } + } + + return false; // didn't find the icon + } + + + private void doTest() { + + r.waitForIdle(2000); + String scale = System.getProperty(SCALE); + System.out.println("scale = " + scale); + Color + expected = is2x() ? C2X : C1X, + unexpected = is2x() ? C1X : C2X; + + Point p = lbl.getLocationOnScreen(); + int x = p.x + lbl.getWidth() / 2; + int y = p.y + lbl.getHeight() / 2; + int w = lbl.getWidth(); + + boolean ok = true, curr; + Color c; + String components[] = new String[]{ + "JLabel", "JCheckBox", "JRadioButton", "JToggleButton", "JButton"}; + for (int i = 0; i < N; i++) { + + curr = true; + int t = x - i * w; + + // check icon color + c = r.getPixelColor(t, y); + System.out.print(components[i] + " icon: "); + if (!c.equals(expected)) { + curr = false; + } else { + // check icon color when mouse button pressed - see JDK-8151303 + curr = checkPressedColor(t, y, expected); + } + + System.out.println(curr ? "ok" : "nok"); + ok = ok && curr; + + r.waitForIdle(); + } + + int x0 = tabbedPane.getLocationOnScreen().x; + int x1 = x - ((N - 1) * w + w / 2); + int y0 = getLocationOnScreen().y; + int y1 = y0 + getHeight(); + curr = checkTabIcon(x0, x1, y0, y1, expected, unexpected); + + System.out.println("JTabbedPane icon: " + (curr ? "ok" : "nok")); + ok = ok && curr; + + if (!ok) { throw new RuntimeException("test failed"); } + + r.waitForIdle(); + dispose(); + } + + public static void main(String[] args) throws Exception { + + // TODO: remove is2x() check after JDK-8150844 fix + if (is2x() != "2".equals(System.getProperty(SCALE))) { return; } + + for (UIManager.LookAndFeelInfo LF: UIManager.getInstalledLookAndFeels()) { + System.out.println("\nL&F: " + LF.getName()); + (new MultiresolutionIconTest(LF)).doTest(); + } + } +} From 062ae6667210ca713c9a9d0d61bcdd524d85aae7 Mon Sep 17 00:00:00 2001 From: Manajit Halder Date: Mon, 14 Mar 2016 16:46:39 +0530 Subject: [PATCH 018/162] 8149456: [macosx] robot.keyPress do not generate key events (keyPressed and keyReleased) for function keys F13 to F19 Reviewed-by: ssadetsky, aniyogi --- .../macosx/native/libawt_lwawt/awt/CRobot.m | 239 +----------------- .../native/libawt_lwawt/awt/CRobotKeyCode.h | 157 ++++++++++++ .../native/libawt_lwawt/awt/CRobotKeyCode.m | 178 +++++++++++++ .../awt/keyboard/AllKeyCode/AllKeyCode.java | 227 +++++++++++++++++ 4 files changed, 566 insertions(+), 235 deletions(-) create mode 100644 jdk/src/java.desktop/macosx/native/libawt_lwawt/awt/CRobotKeyCode.h create mode 100644 jdk/src/java.desktop/macosx/native/libawt_lwawt/awt/CRobotKeyCode.m create mode 100644 jdk/test/java/awt/keyboard/AllKeyCode/AllKeyCode.java diff --git a/jdk/src/java.desktop/macosx/native/libawt_lwawt/awt/CRobot.m b/jdk/src/java.desktop/macosx/native/libawt_lwawt/awt/CRobot.m index 7fc6f62ec55..c8bcc573b03 100644 --- a/jdk/src/java.desktop/macosx/native/libawt_lwawt/awt/CRobot.m +++ b/jdk/src/java.desktop/macosx/native/libawt_lwawt/awt/CRobot.m @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -29,12 +29,12 @@ #import #import +#import "CRobotKeyCode.h" #import "LWCToolkit.h" #import "sun_lwawt_macosx_CRobot.h" #import "java_awt_event_InputEvent.h" #import "sizecalc.h" - // Starting number for event numbers generated by Robot. // Apple docs don't mention at all what are the requirements // for these numbers. It seems that they must be higher @@ -354,241 +354,10 @@ static void PostMouseEvent(const CGPoint point, CGMouseButton button, } } -// NOTE: Don't modify this table directly. It is machine generated. See below. -static const unsigned char javaToMacKeyCode[] = { - 127, // 0 0 VK_UNDEFINED No_Equivalent - 127, // 1 0x1 Not_Used - 127, // 2 0x2 Not_Used - 127, // 3 0x3 VK_CANCEL No_Equivalent - 127, // 4 0x4 Not_Used - 127, // 5 0x5 Not_Used - 127, // 6 0x6 Not_Used - 127, // 7 0x7 Not_Used - 51, // 8 0x8 VK_BACK_SPACE - 48, // 9 0x9 VK_TAB - 36, // 10 0xa VK_ENTER - 127, // 11 0xb Not_Used - 71, // 12 0xc VK_CLEAR - 127, // 13 0xd Not_Used - 127, // 14 0xe Not_Used - 127, // 15 0xf Not_Used - 56, // 16 0x10 VK_SHIFT - 59, // 17 0x11 VK_CONTROL - 58, // 18 0x12 VK_ALT - 113, // 19 0x13 VK_PAUSE - 57, // 20 0x14 VK_CAPS_LOCK - 127, // 21 0x15 VK_KANA No_Equivalent - 127, // 22 0x16 Not_Used - 127, // 23 0x17 Not_Used - 127, // 24 0x18 VK_FINAL No_Equivalent - 127, // 25 0x19 VK_KANJI No_Equivalent - 127, // 26 0x1a Not_Used - 53, // 27 0x1b VK_ESCAPE - 127, // 28 0x1c VK_CONVERT No_Equivalent - 127, // 29 0x1d VK_NONCONVERT No_Equivalent - 127, // 30 0x1e VK_ACCEPT No_Equivalent - 127, // 31 0x1f VK_MODECHANGE No_Equivalent - 49, // 32 0x20 VK_SPACE - 116, // 33 0x21 VK_PAGE_UP - 121, // 34 0x22 VK_PAGE_DOWN - 119, // 35 0x23 VK_END - 115, // 36 0x24 VK_HOME - 123, // 37 0x25 VK_LEFT - 126, // 38 0x26 VK_UP - 124, // 39 0x27 VK_RIGHT - 125, // 40 0x28 VK_DOWN - 127, // 41 0x29 Not_Used - 127, // 42 0x2a Not_Used - 127, // 43 0x2b Not_Used - 43, // 44 0x2c VK_COMMA - 27, // 45 0x2d VK_MINUS - 47, // 46 0x2e VK_PERIOD - 44, // 47 0x2f VK_SLASH - 29, // 48 0x30 VK_0 - 18, // 49 0x31 VK_1 - 19, // 50 0x32 VK_2 - 20, // 51 0x33 VK_3 - 21, // 52 0x34 VK_4 - 23, // 53 0x35 VK_5 - 22, // 54 0x36 VK_6 - 26, // 55 0x37 VK_7 - 28, // 56 0x38 VK_8 - 25, // 57 0x39 VK_9 - 127, // 58 0x3a Not_Used - 41, // 59 0x3b VK_SEMICOLON - 127, // 60 0x3c Not_Used - 24, // 61 0x3d VK_EQUALS - 127, // 62 0x3e Not_Used - 127, // 63 0x3f Not_Used - 127, // 64 0x40 Not_Used - 0, // 65 0x41 VK_A - 11, // 66 0x42 VK_B - 8, // 67 0x43 VK_C - 2, // 68 0x44 VK_D - 14, // 69 0x45 VK_E - 3, // 70 0x46 VK_F - 5, // 71 0x47 VK_G - 4, // 72 0x48 VK_H - 34, // 73 0x49 VK_I - 38, // 74 0x4a VK_J - 40, // 75 0x4b VK_K - 37, // 76 0x4c VK_L - 46, // 77 0x4d VK_M - 45, // 78 0x4e VK_N - 31, // 79 0x4f VK_O - 35, // 80 0x50 VK_P - 12, // 81 0x51 VK_Q - 15, // 82 0x52 VK_R - 1, // 83 0x53 VK_S - 17, // 84 0x54 VK_T - 32, // 85 0x55 VK_U - 9, // 86 0x56 VK_V - 13, // 87 0x57 VK_W - 7, // 88 0x58 VK_X - 16, // 89 0x59 VK_Y - 6, // 90 0x5a VK_Z - 33, // 91 0x5b VK_OPEN_BRACKET - 42, // 92 0x5c VK_BACK_SLASH - 30, // 93 0x5d VK_CLOSE_BRACKET - 127, // 94 0x5e Not_Used - 127, // 95 0x5f Not_Used - 82, // 96 0x60 VK_NUMPAD0 - 83, // 97 0x61 VK_NUMPAD1 - 84, // 98 0x62 VK_NUMPAD2 - 85, // 99 0x63 VK_NUMPAD3 - 86, // 100 0x64 VK_NUMPAD4 - 87, // 101 0x65 VK_NUMPAD5 - 88, // 102 0x66 VK_NUMPAD6 - 89, // 103 0x67 VK_NUMPAD7 - 91, // 104 0x68 VK_NUMPAD8 - 92, // 105 0x69 VK_NUMPAD9 - 67, // 106 0x6a VK_MULTIPLY - 69, // 107 0x6b VK_ADD - 127, // 108 0x6c VK_SEPARATER No_Equivalent - 78, // 109 0x6d VK_SUBTRACT - 65, // 110 0x6e VK_DECIMAL - 75, // 111 0x6f VK_DIVIDE - 122, // 112 0x70 VK_F1 - 120, // 113 0x71 VK_F2 - 99, // 114 0x72 VK_F3 - 118, // 115 0x73 VK_F4 - 96, // 116 0x74 VK_F5 - 97, // 117 0x75 VK_F6 - 98, // 118 0x76 VK_F7 - 100, // 119 0x77 VK_F8 - 101, // 120 0x78 VK_F9 - 109, // 121 0x79 VK_F10 - 103, // 122 0x7a VK_F11 - 111, // 123 0x7b VK_F12 - 127, // 124 0x7c Not_Used - 127, // 125 0x7d Not_Used - 127, // 126 0x7e Not_Used - 117, // 127 0x7f VK_DELETE - 127, // 128 0x80 VK_DEAD_GRAVE No_Equivalent - 127, // 129 0x81 VK_DEAD_ACUTE No_Equivalent - 127, // 130 0x82 VK_DEAD_CIRCUMFLEX No_Equivalent - 127, // 131 0x83 VK_DEAD_TILDE No_Equivalent - 127, // 132 0x84 VK_DEAD_MACRON No_Equivalent - 127, // 133 0x85 VK_DEAD_BREVE No_Equivalent - 127, // 134 0x86 VK_DEAD_ABOVEDOT No_Equivalent - 127, // 135 0x87 VK_DEAD_DIAERESIS No_Equivalent - 127, // 136 0x88 VK_DEAD_ABOVERING No_Equivalent - 127, // 137 0x89 VK_DEAD_DOUBLEACUTE No_Equivalent - 127, // 138 0x8a VK_DEAD_CARON No_Equivalent - 127, // 139 0x8b VK_DEAD_CEDILLA No_Equivalent - 127, // 140 0x8c VK_DEAD_OGONEK No_Equivalent - 127, // 141 0x8d VK_DEAD_IOTA No_Equivalent - 127, // 142 0x8e VK_DEAD_VOICED_SOUND No_Equivalent - 127, // 143 0x8f VK_DEAD_SEMIVOICED_SOUND No_Equivalent - 127, // 144 0x90 VK_NUM_LOCK No_Equivalent - 107, // 145 0x91 VK_SCROLL_LOCK - 127, // 146 0x92 Not_Used - 127, // 147 0x93 Not_Used - 127, // 148 0x94 Not_Used - 127, // 149 0x95 Not_Used - 127, // 150 0x96 VK_AMPERSAND No_Equivalent - 127, // 151 0x97 VK_ASTERISK No_Equivalent - 127, // 152 0x98 VK_QUOTEDBL No_Equivalent - 127, // 153 0x99 VK_LESS No_Equivalent - 105, // 154 0x9a VK_PRINTSCREEN - 127, // 155 0x9b VK_INSERT No_Equivalent - 114, // 156 0x9c VK_HELP - 55, // 157 0x9d VK_META - 127, // 158 0x9e Not_Used - 127, // 159 0x9f Not_Used - 127, // 160 0xa0 VK_GREATER No_Equivalent - 127, // 161 0xa1 VK_BRACELEFT No_Equivalent - 127, // 162 0xa2 VK_BRACERIGHT No_Equivalent - 127, // 163 0xa3 Not_Used - 127, // 164 0xa4 Not_Used - 127, // 165 0xa5 Not_Used - 127, // 166 0xa6 Not_Used - 127, // 167 0xa7 Not_Used - 127, // 168 0xa8 Not_Used - 127, // 169 0xa9 Not_Used - 127, // 170 0xaa Not_Used - 127, // 171 0xab Not_Used - 127, // 172 0xac Not_Used - 127, // 173 0xad Not_Used - 127, // 174 0xae Not_Used - 127, // 175 0xaf Not_Used - 127, // 176 0xb0 Not_Used - 127, // 177 0xb1 Not_Used - 127, // 178 0xb2 Not_Used - 127, // 179 0xb3 Not_Used - 127, // 180 0xb4 Not_Used - 127, // 181 0xb5 Not_Used - 127, // 182 0xb6 Not_Used - 127, // 183 0xb7 Not_Used - 127, // 184 0xb8 Not_Used - 127, // 185 0xb9 Not_Used - 127, // 186 0xba Not_Used - 127, // 187 0xbb Not_Used - 127, // 188 0xbc Not_Used - 127, // 189 0xbd Not_Used - 127, // 190 0xbe Not_Used - 127, // 191 0xbf Not_Used - 50, // 192 0xc0 VK_BACK_QUOTE - 127, // 193 0xc1 Not_Used - 127, // 194 0xc2 Not_Used - 127, // 195 0xc3 Not_Used - 127, // 196 0xc4 Not_Used - 127, // 197 0xc5 Not_Used - 127, // 198 0xc6 Not_Used - 127, // 199 0xc7 Not_Used - 127, // 200 0xc8 Not_Used - 127, // 201 0xc9 Not_Used - 127, // 202 0xca Not_Used - 127, // 203 0xcb Not_Used - 127, // 204 0xcc Not_Used - 127, // 205 0xcd Not_Used - 127, // 206 0xce Not_Used - 127, // 207 0xcf Not_Used - 127, // 208 0xd0 Not_Used - 127, // 209 0xd1 Not_Used - 127, // 210 0xd2 Not_Used - 127, // 211 0xd3 Not_Used - 127, // 212 0xd4 Not_Used - 127, // 213 0xd5 Not_Used - 127, // 214 0xd6 Not_Used - 127, // 215 0xd7 Not_Used - 127, // 216 0xd8 Not_Used - 127, // 217 0xd9 Not_Used - 127, // 218 0xda Not_Used - 127, // 219 0xdb Not_Used - 127, // 220 0xdc Not_Used - 127, // 221 0xdd Not_Used - 39 // 222 0xde VK_QUOTE -}; - -// NOTE: All values above 222 don't have an equivalent on MacOSX. static inline CGKeyCode GetCGKeyCode(jint javaKeyCode) { - if (javaKeyCode > 222) { - return 127; - } else { - return javaToMacKeyCode[javaKeyCode]; - } + CRobotKeyCodeMapping *keyCodeMapping = [CRobotKeyCodeMapping sharedInstance]; + return [keyCodeMapping getOSXKeyCodeForJavaKey:javaKeyCode]; } static int GetClickCount(BOOL isDown) { diff --git a/jdk/src/java.desktop/macosx/native/libawt_lwawt/awt/CRobotKeyCode.h b/jdk/src/java.desktop/macosx/native/libawt_lwawt/awt/CRobotKeyCode.h new file mode 100644 index 00000000000..d06b9e8ee46 --- /dev/null +++ b/jdk/src/java.desktop/macosx/native/libawt_lwawt/awt/CRobotKeyCode.h @@ -0,0 +1,157 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +#import + +#ifndef KeyCodeConverter_CRobotKeyCode_h +#define KeyCodeConverter_CRobotKeyCode_h + +const static int OSX_kVK_ANSI_A = 0x00; +const static int OSX_kVK_ANSI_S = 0x01; +const static int OSX_kVK_ANSI_D = 0x02; +const static int OSX_kVK_ANSI_F = 0x03; +const static int OSX_kVK_ANSI_H = 0x04; +const static int OSX_kVK_ANSI_G = 0x05; +const static int OSX_kVK_ANSI_Z = 0x06; +const static int OSX_kVK_ANSI_X = 0x07; +const static int OSX_kVK_ANSI_C = 0x08; +const static int OSX_kVK_ANSI_V = 0x09; +const static int OSX_kVK_ISO_Section = 0x0A; +const static int OSX_kVK_ANSI_B = 0x0B; +const static int OSX_kVK_ANSI_Q = 0x0C; +const static int OSX_kVK_ANSI_W = 0x0D; +const static int OSX_kVK_ANSI_E = 0x0E; +const static int OSX_kVK_ANSI_R = 0x0F; +const static int OSX_kVK_ANSI_Y = 0x10; +const static int OSX_kVK_ANSI_T = 0x11; +const static int OSX_kVK_ANSI_1 = 0x12; +const static int OSX_kVK_ANSI_2 = 0x13; +const static int OSX_kVK_ANSI_3 = 0x14; +const static int OSX_kVK_ANSI_4 = 0x15; +const static int OSX_kVK_ANSI_6 = 0x16; +const static int OSX_kVK_ANSI_5 = 0x17; +const static int OSX_kVK_ANSI_Equal = 0x18; +const static int OSX_kVK_ANSI_9 = 0x19; +const static int OSX_kVK_ANSI_7 = 0x1A; +const static int OSX_kVK_ANSI_Minus = 0x1B; +const static int OSX_kVK_ANSI_8 = 0x1C; +const static int OSX_kVK_ANSI_0 = 0x1D; +const static int OSX_kVK_ANSI_RightBracket = 0x1E; +const static int OSX_kVK_ANSI_O = 0x1F; +const static int OSX_kVK_ANSI_U = 0x20; +const static int OSX_kVK_ANSI_LeftBracket = 0x21; +const static int OSX_kVK_ANSI_I = 0x22; +const static int OSX_kVK_ANSI_P = 0x23; +const static int OSX_kVK_ANSI_L = 0x25; +const static int OSX_kVK_ANSI_J = 0x26; +const static int OSX_kVK_ANSI_Quote = 0x27; +const static int OSX_kVK_ANSI_K = 0x28; +const static int OSX_kVK_ANSI_Semicolon = 0x29; +const static int OSX_kVK_ANSI_Backslash = 0x2A; +const static int OSX_kVK_ANSI_Comma = 0x2B; +const static int OSX_kVK_ANSI_Slash = 0x2C; +const static int OSX_kVK_ANSI_N = 0x2D; +const static int OSX_kVK_ANSI_M = 0x2E; +const static int OSX_kVK_ANSI_Period = 0x2F; +const static int OSX_kVK_ANSI_Grave = 0x32; +const static int OSX_kVK_ANSI_KeypadDecimal = 0x41; +const static int OSX_kVK_ANSI_KeypadMultiply = 0x43; +const static int OSX_kVK_ANSI_KeypadPlus = 0x45; +const static int OSX_kVK_ANSI_KeypadClear = 0x47; +const static int OSX_kVK_ANSI_KeypadDivide = 0x4B; +const static int OSX_kVK_ANSI_KeypadEnter = 0x4C; +const static int OSX_kVK_ANSI_KeypadMinus = 0x4E; +const static int OSX_kVK_ANSI_KeypadEquals = 0x51; +const static int OSX_kVK_ANSI_Keypad0 = 0x52; +const static int OSX_kVK_ANSI_Keypad1 = 0x53; +const static int OSX_kVK_ANSI_Keypad2 = 0x54; +const static int OSX_kVK_ANSI_Keypad3 = 0x55; +const static int OSX_kVK_ANSI_Keypad4 = 0x56; +const static int OSX_kVK_ANSI_Keypad5 = 0x57; +const static int OSX_kVK_ANSI_Keypad6 = 0x58; +const static int OSX_kVK_ANSI_Keypad7 = 0x59; +const static int OSX_kVK_ANSI_Keypad8 = 0x5B; +const static int OSX_kVK_ANSI_Keypad9 = 0x5C; +const static int OSX_kVK_Return = 0x24; +const static int OSX_kVK_Tab = 0x30; +const static int OSX_kVK_Space = 0x31; +const static int OSX_Delete = 0x33; +const static int OSX_Escape = 0x35; +const static int OSX_Command = 0x37; +const static int OSX_Shift = 0x38; +const static int OSX_CapsLock = 0x39; +const static int OSX_Option = 0x3A; +const static int OSX_Control = 0x3B; +const static int OSX_RightShift = 0x3C; +const static int OSX_RightOption = 0x3D; +const static int OSX_RightControl = 0x3E; +const static int OSX_Function = 0x3F; +const static int OSX_F17 = 0x40; +const static int OSX_VolumeUp = 0x48; +const static int OSX_VolumeDown = 0x49; +const static int OSX_Mute = 0x4A; +const static int OSX_F18 = 0x4F; +const static int OSX_F19 = 0x50; +const static int OSX_F20 = 0x5A; +const static int OSX_F5 = 0x60; +const static int OSX_F6 = 0x61; +const static int OSX_F7 = 0x62; +const static int OSX_F3 = 0x63; +const static int OSX_F8 = 0x64; +const static int OSX_F9 = 0x65; +const static int OSX_F11 = 0x67; +const static int OSX_F13 = 0x69; +const static int OSX_F16 = 0x6A; +const static int OSX_F14 = 0x6B; +const static int OSX_F10 = 0x6D; +const static int OSX_F12 = 0x6F; +const static int OSX_F15 = 0x71; +const static int OSX_Help = 0x72; +const static int OSX_Home = 0x73; +const static int OSX_PageUp = 0x74; +const static int OSX_ForwardDelete = 0x75; +const static int OSX_F4 = 0x76; +const static int OSX_End = 0x77; +const static int OSX_F2 = 0x78; +const static int OSX_PageDown = 0x79; +const static int OSX_F1 = 0x7A; +const static int OSX_LeftArrow = 0x7B; +const static int OSX_RightArrow = 0x7C; +const static int OSX_DownArrow = 0x7D; +const static int OSX_UpArrow = 0x7E; +const static int OSX_Undefined = 0x7F; + +@interface CRobotKeyCodeMapping : NSObject { + +} + +@property (readwrite, retain) NSDictionary *javaToMacKeyMap; + ++ (CRobotKeyCodeMapping *)sharedInstance ; +- (int)getOSXKeyCodeForJavaKey:(int) javaKey; + +@end + +#endif diff --git a/jdk/src/java.desktop/macosx/native/libawt_lwawt/awt/CRobotKeyCode.m b/jdk/src/java.desktop/macosx/native/libawt_lwawt/awt/CRobotKeyCode.m new file mode 100644 index 00000000000..eb19f00d922 --- /dev/null +++ b/jdk/src/java.desktop/macosx/native/libawt_lwawt/awt/CRobotKeyCode.m @@ -0,0 +1,178 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +#import "CRobotKeyCode.h" +#import "java_awt_event_KeyEvent.h" + +@implementation CRobotKeyCodeMapping + +@synthesize javaToMacKeyMap; + ++(CRobotKeyCodeMapping *) sharedInstance { + static CRobotKeyCodeMapping *instance = nil; + static dispatch_once_t executeOnce; + + dispatch_once(&executeOnce, ^{ + instance = [[CRobotKeyCodeMapping alloc] init]; + }); + + return instance; +} + +-(id) init { + self = [super init]; + + if (nil != self) { + javaToMacKeyMap = [NSDictionary dictionaryWithObjectsAndKeys : + [NSNumber numberWithInt : OSX_Delete], [NSNumber numberWithInt : java_awt_event_KeyEvent_VK_BACK_SPACE], + [NSNumber numberWithInt : OSX_kVK_Tab], [NSNumber numberWithInt : java_awt_event_KeyEvent_VK_TAB], + [NSNumber numberWithInt : OSX_kVK_Return], [NSNumber numberWithInt : java_awt_event_KeyEvent_VK_ENTER], + [NSNumber numberWithInt : OSX_kVK_ANSI_KeypadClear], [NSNumber numberWithInt : java_awt_event_KeyEvent_VK_CLEAR], + [NSNumber numberWithInt : OSX_Shift], [NSNumber numberWithInt : java_awt_event_KeyEvent_VK_SHIFT], + [NSNumber numberWithInt : OSX_Control], [NSNumber numberWithInt : java_awt_event_KeyEvent_VK_CONTROL], + [NSNumber numberWithInt : OSX_Option], [NSNumber numberWithInt : java_awt_event_KeyEvent_VK_ALT], + [NSNumber numberWithInt : OSX_CapsLock], [NSNumber numberWithInt : java_awt_event_KeyEvent_VK_CAPS_LOCK], + [NSNumber numberWithInt : OSX_Escape], [NSNumber numberWithInt : java_awt_event_KeyEvent_VK_ESCAPE], + [NSNumber numberWithInt : OSX_kVK_Space], [NSNumber numberWithInt : java_awt_event_KeyEvent_VK_SPACE], + [NSNumber numberWithInt : OSX_PageUp], [NSNumber numberWithInt : java_awt_event_KeyEvent_VK_PAGE_UP], + [NSNumber numberWithInt : OSX_PageDown], [NSNumber numberWithInt : java_awt_event_KeyEvent_VK_PAGE_DOWN], + [NSNumber numberWithInt : OSX_End], [NSNumber numberWithInt : java_awt_event_KeyEvent_VK_END], + [NSNumber numberWithInt : OSX_Home], [NSNumber numberWithInt : java_awt_event_KeyEvent_VK_HOME], + [NSNumber numberWithInt : OSX_LeftArrow], [NSNumber numberWithInt : java_awt_event_KeyEvent_VK_LEFT], + [NSNumber numberWithInt : OSX_UpArrow], [NSNumber numberWithInt : java_awt_event_KeyEvent_VK_UP], + [NSNumber numberWithInt : OSX_RightArrow], [NSNumber numberWithInt : java_awt_event_KeyEvent_VK_RIGHT], + [NSNumber numberWithInt : OSX_DownArrow], [NSNumber numberWithInt : java_awt_event_KeyEvent_VK_DOWN], + [NSNumber numberWithInt : OSX_kVK_ANSI_Comma], [NSNumber numberWithInt : java_awt_event_KeyEvent_VK_COMMA], + [NSNumber numberWithInt : OSX_kVK_ANSI_Minus], [NSNumber numberWithInt : java_awt_event_KeyEvent_VK_MINUS], + [NSNumber numberWithInt : OSX_kVK_ANSI_Period], [NSNumber numberWithInt : java_awt_event_KeyEvent_VK_PERIOD], + [NSNumber numberWithInt : OSX_kVK_ANSI_Slash], [NSNumber numberWithInt : java_awt_event_KeyEvent_VK_SLASH], + + [NSNumber numberWithInt : OSX_kVK_ANSI_0], [NSNumber numberWithInt : java_awt_event_KeyEvent_VK_0], + [NSNumber numberWithInt : OSX_kVK_ANSI_1], [NSNumber numberWithInt : java_awt_event_KeyEvent_VK_1], + [NSNumber numberWithInt : OSX_kVK_ANSI_2], [NSNumber numberWithInt : java_awt_event_KeyEvent_VK_2], + [NSNumber numberWithInt : OSX_kVK_ANSI_3], [NSNumber numberWithInt : java_awt_event_KeyEvent_VK_3], + [NSNumber numberWithInt : OSX_kVK_ANSI_4], [NSNumber numberWithInt : java_awt_event_KeyEvent_VK_4], + [NSNumber numberWithInt : OSX_kVK_ANSI_5], [NSNumber numberWithInt : java_awt_event_KeyEvent_VK_5], + [NSNumber numberWithInt : OSX_kVK_ANSI_6], [NSNumber numberWithInt : java_awt_event_KeyEvent_VK_6], + [NSNumber numberWithInt : OSX_kVK_ANSI_7], [NSNumber numberWithInt : java_awt_event_KeyEvent_VK_7], + [NSNumber numberWithInt : OSX_kVK_ANSI_8], [NSNumber numberWithInt : java_awt_event_KeyEvent_VK_8], + [NSNumber numberWithInt : OSX_kVK_ANSI_9], [NSNumber numberWithInt : java_awt_event_KeyEvent_VK_9], + + [NSNumber numberWithInt : OSX_kVK_ANSI_Semicolon], [NSNumber numberWithInt : java_awt_event_KeyEvent_VK_SEMICOLON], + [NSNumber numberWithInt : OSX_kVK_ANSI_Equal], [NSNumber numberWithInt : java_awt_event_KeyEvent_VK_EQUALS], + + [NSNumber numberWithInt : OSX_kVK_ANSI_A], [NSNumber numberWithInt : java_awt_event_KeyEvent_VK_A], + [NSNumber numberWithInt : OSX_kVK_ANSI_B], [NSNumber numberWithInt : java_awt_event_KeyEvent_VK_B], + [NSNumber numberWithInt : OSX_kVK_ANSI_C], [NSNumber numberWithInt : java_awt_event_KeyEvent_VK_C], + [NSNumber numberWithInt : OSX_kVK_ANSI_D], [NSNumber numberWithInt : java_awt_event_KeyEvent_VK_D], + [NSNumber numberWithInt : OSX_kVK_ANSI_E], [NSNumber numberWithInt : java_awt_event_KeyEvent_VK_E], + [NSNumber numberWithInt : OSX_kVK_ANSI_F], [NSNumber numberWithInt : java_awt_event_KeyEvent_VK_F], + [NSNumber numberWithInt : OSX_kVK_ANSI_G], [NSNumber numberWithInt : java_awt_event_KeyEvent_VK_G], + [NSNumber numberWithInt : OSX_kVK_ANSI_H], [NSNumber numberWithInt : java_awt_event_KeyEvent_VK_H], + [NSNumber numberWithInt : OSX_kVK_ANSI_I], [NSNumber numberWithInt : java_awt_event_KeyEvent_VK_I], + [NSNumber numberWithInt : OSX_kVK_ANSI_J], [NSNumber numberWithInt : java_awt_event_KeyEvent_VK_J], + [NSNumber numberWithInt : OSX_kVK_ANSI_K], [NSNumber numberWithInt : java_awt_event_KeyEvent_VK_K], + [NSNumber numberWithInt : OSX_kVK_ANSI_L], [NSNumber numberWithInt : java_awt_event_KeyEvent_VK_L], + [NSNumber numberWithInt : OSX_kVK_ANSI_M], [NSNumber numberWithInt : java_awt_event_KeyEvent_VK_M], + [NSNumber numberWithInt : OSX_kVK_ANSI_N], [NSNumber numberWithInt : java_awt_event_KeyEvent_VK_N], + [NSNumber numberWithInt : OSX_kVK_ANSI_O], [NSNumber numberWithInt : java_awt_event_KeyEvent_VK_O], + [NSNumber numberWithInt : OSX_kVK_ANSI_P], [NSNumber numberWithInt : java_awt_event_KeyEvent_VK_P], + [NSNumber numberWithInt : OSX_kVK_ANSI_Q], [NSNumber numberWithInt : java_awt_event_KeyEvent_VK_Q], + [NSNumber numberWithInt : OSX_kVK_ANSI_R], [NSNumber numberWithInt : java_awt_event_KeyEvent_VK_R], + [NSNumber numberWithInt : OSX_kVK_ANSI_S], [NSNumber numberWithInt : java_awt_event_KeyEvent_VK_S], + [NSNumber numberWithInt : OSX_kVK_ANSI_T], [NSNumber numberWithInt : java_awt_event_KeyEvent_VK_T], + [NSNumber numberWithInt : OSX_kVK_ANSI_U], [NSNumber numberWithInt : java_awt_event_KeyEvent_VK_U], + [NSNumber numberWithInt : OSX_kVK_ANSI_V], [NSNumber numberWithInt : java_awt_event_KeyEvent_VK_V], + [NSNumber numberWithInt : OSX_kVK_ANSI_W], [NSNumber numberWithInt : java_awt_event_KeyEvent_VK_W], + [NSNumber numberWithInt : OSX_kVK_ANSI_X], [NSNumber numberWithInt : java_awt_event_KeyEvent_VK_X], + [NSNumber numberWithInt : OSX_kVK_ANSI_Y], [NSNumber numberWithInt : java_awt_event_KeyEvent_VK_Y], + [NSNumber numberWithInt : OSX_kVK_ANSI_Z], [NSNumber numberWithInt : java_awt_event_KeyEvent_VK_Z], + + [NSNumber numberWithInt : OSX_kVK_ANSI_LeftBracket], [NSNumber numberWithInt : java_awt_event_KeyEvent_VK_OPEN_BRACKET], + [NSNumber numberWithInt : OSX_kVK_ANSI_Backslash], [NSNumber numberWithInt : java_awt_event_KeyEvent_VK_BACK_SLASH], + [NSNumber numberWithInt : OSX_kVK_ANSI_RightBracket], [NSNumber numberWithInt : java_awt_event_KeyEvent_VK_CLOSE_BRACKET], + + [NSNumber numberWithInt : OSX_kVK_ANSI_Keypad0], [NSNumber numberWithInt : java_awt_event_KeyEvent_VK_NUMPAD0], + [NSNumber numberWithInt : OSX_kVK_ANSI_Keypad1], [NSNumber numberWithInt : java_awt_event_KeyEvent_VK_NUMPAD1], + [NSNumber numberWithInt : OSX_kVK_ANSI_Keypad2], [NSNumber numberWithInt : java_awt_event_KeyEvent_VK_NUMPAD2], + [NSNumber numberWithInt : OSX_kVK_ANSI_Keypad3], [NSNumber numberWithInt : java_awt_event_KeyEvent_VK_NUMPAD3], + [NSNumber numberWithInt : OSX_kVK_ANSI_Keypad4], [NSNumber numberWithInt : java_awt_event_KeyEvent_VK_NUMPAD4], + [NSNumber numberWithInt : OSX_kVK_ANSI_Keypad5], [NSNumber numberWithInt : java_awt_event_KeyEvent_VK_NUMPAD5], + [NSNumber numberWithInt : OSX_kVK_ANSI_Keypad6], [NSNumber numberWithInt : java_awt_event_KeyEvent_VK_NUMPAD6], + [NSNumber numberWithInt : OSX_kVK_ANSI_Keypad7], [NSNumber numberWithInt : java_awt_event_KeyEvent_VK_NUMPAD7], + [NSNumber numberWithInt : OSX_kVK_ANSI_Keypad8], [NSNumber numberWithInt : java_awt_event_KeyEvent_VK_NUMPAD8], + [NSNumber numberWithInt : OSX_kVK_ANSI_Keypad9], [NSNumber numberWithInt : java_awt_event_KeyEvent_VK_NUMPAD9], + + [NSNumber numberWithInt : OSX_kVK_ANSI_KeypadMultiply], [NSNumber numberWithInt : java_awt_event_KeyEvent_VK_MULTIPLY], + [NSNumber numberWithInt : OSX_kVK_ANSI_KeypadPlus], [NSNumber numberWithInt : java_awt_event_KeyEvent_VK_ADD], + [NSNumber numberWithInt : OSX_kVK_ANSI_KeypadMinus], [NSNumber numberWithInt : java_awt_event_KeyEvent_VK_SUBTRACT], + [NSNumber numberWithInt : OSX_kVK_ANSI_KeypadDecimal], [NSNumber numberWithInt : java_awt_event_KeyEvent_VK_DECIMAL], + [NSNumber numberWithInt : OSX_kVK_ANSI_KeypadDivide], [NSNumber numberWithInt : java_awt_event_KeyEvent_VK_DIVIDE], + + [NSNumber numberWithInt : OSX_F1], [NSNumber numberWithInt : java_awt_event_KeyEvent_VK_F1], + [NSNumber numberWithInt : OSX_F2], [NSNumber numberWithInt : java_awt_event_KeyEvent_VK_F2], + [NSNumber numberWithInt : OSX_F3], [NSNumber numberWithInt : java_awt_event_KeyEvent_VK_F3], + [NSNumber numberWithInt : OSX_F4], [NSNumber numberWithInt : java_awt_event_KeyEvent_VK_F4], + [NSNumber numberWithInt : OSX_F5], [NSNumber numberWithInt : java_awt_event_KeyEvent_VK_F5], + [NSNumber numberWithInt : OSX_F6], [NSNumber numberWithInt : java_awt_event_KeyEvent_VK_F6], + [NSNumber numberWithInt : OSX_F7], [NSNumber numberWithInt : java_awt_event_KeyEvent_VK_F7], + [NSNumber numberWithInt : OSX_F8], [NSNumber numberWithInt : java_awt_event_KeyEvent_VK_F8], + [NSNumber numberWithInt : OSX_F9], [NSNumber numberWithInt : java_awt_event_KeyEvent_VK_F9], + [NSNumber numberWithInt : OSX_F10], [NSNumber numberWithInt : java_awt_event_KeyEvent_VK_F10], + [NSNumber numberWithInt : OSX_F11], [NSNumber numberWithInt : java_awt_event_KeyEvent_VK_F11], + [NSNumber numberWithInt : OSX_F12], [NSNumber numberWithInt : java_awt_event_KeyEvent_VK_F12], + + [NSNumber numberWithInt : OSX_ForwardDelete], [NSNumber numberWithInt : java_awt_event_KeyEvent_VK_DELETE], + [NSNumber numberWithInt : OSX_Help], [NSNumber numberWithInt : java_awt_event_KeyEvent_VK_HELP], + [NSNumber numberWithInt : OSX_Command], [NSNumber numberWithInt : java_awt_event_KeyEvent_VK_META], + [NSNumber numberWithInt : OSX_kVK_ANSI_Grave], [NSNumber numberWithInt : java_awt_event_KeyEvent_VK_BACK_QUOTE], + [NSNumber numberWithInt : OSX_kVK_ANSI_Quote], [NSNumber numberWithInt : java_awt_event_KeyEvent_VK_QUOTE], + + [NSNumber numberWithInt : OSX_F13], [NSNumber numberWithInt : java_awt_event_KeyEvent_VK_F13], + [NSNumber numberWithInt : OSX_F14], [NSNumber numberWithInt : java_awt_event_KeyEvent_VK_F14], + [NSNumber numberWithInt : OSX_F15], [NSNumber numberWithInt : java_awt_event_KeyEvent_VK_F15], + [NSNumber numberWithInt : OSX_F16], [NSNumber numberWithInt : java_awt_event_KeyEvent_VK_F16], + [NSNumber numberWithInt : OSX_F17], [NSNumber numberWithInt : java_awt_event_KeyEvent_VK_F17], + [NSNumber numberWithInt : OSX_F18], [NSNumber numberWithInt : java_awt_event_KeyEvent_VK_F18], + [NSNumber numberWithInt : OSX_F19], [NSNumber numberWithInt : java_awt_event_KeyEvent_VK_F19], + [NSNumber numberWithInt : OSX_F20], [NSNumber numberWithInt : java_awt_event_KeyEvent_VK_F20], + + nil]; + } + + return self; +} + +-(int) getOSXKeyCodeForJavaKey : (int) javaKey { + id val = [javaToMacKeyMap objectForKey : [NSNumber numberWithInt : javaKey]]; + + if (nil != val) { + return [val intValue]; + } else { + return OSX_Undefined; + } +} + +@end diff --git a/jdk/test/java/awt/keyboard/AllKeyCode/AllKeyCode.java b/jdk/test/java/awt/keyboard/AllKeyCode/AllKeyCode.java new file mode 100644 index 00000000000..2cb9c5cd3f2 --- /dev/null +++ b/jdk/test/java/awt/keyboard/AllKeyCode/AllKeyCode.java @@ -0,0 +1,227 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + @test + @bug 8149456 8147834 8150230 + @requires os.family == "mac" + @summary KeyEvents for all keys + @run main AllKeyCode +*/ + +import java.awt.AWTException; +import java.awt.GridBagLayout; +import java.awt.Robot; +import java.awt.event.KeyEvent; +import java.awt.event.KeyListener; +import java.awt.Frame; +import java.awt.TextArea; + +public class AllKeyCode extends Frame { + + private static Frame frame; + private static TextArea textArea; + private static KeyListener keyListener; + private static int allKeyArr[]; + private static int keyPressedIndex; + + AllKeyCode() { + AllKeyCode.allKeyArr = new int[] { + KeyEvent.VK_BACK_SPACE, + KeyEvent.VK_TAB, + KeyEvent.VK_ENTER, + KeyEvent.VK_CLEAR, + KeyEvent.VK_SHIFT, + KeyEvent.VK_CONTROL, + KeyEvent.VK_ALT, + KeyEvent.VK_CAPS_LOCK, + KeyEvent.VK_ESCAPE, + KeyEvent.VK_SPACE, + KeyEvent.VK_PAGE_UP, + KeyEvent.VK_PAGE_DOWN, + KeyEvent.VK_END, + KeyEvent.VK_HOME, + KeyEvent.VK_LEFT, + KeyEvent.VK_UP, + KeyEvent.VK_RIGHT, + KeyEvent.VK_DOWN, + KeyEvent.VK_COMMA, + KeyEvent.VK_MINUS, + KeyEvent.VK_PERIOD, + KeyEvent.VK_SLASH, + KeyEvent.VK_0, + KeyEvent.VK_1, + KeyEvent.VK_2, + KeyEvent.VK_3, + KeyEvent.VK_4, + KeyEvent.VK_5, + KeyEvent.VK_6, + KeyEvent.VK_7, + KeyEvent.VK_8, + KeyEvent.VK_9, + KeyEvent.VK_SEMICOLON, + KeyEvent.VK_EQUALS, + KeyEvent.VK_A, + KeyEvent.VK_B, + KeyEvent.VK_C, + KeyEvent.VK_D, + KeyEvent.VK_E, + KeyEvent.VK_F, + KeyEvent.VK_G, + KeyEvent.VK_H, + KeyEvent.VK_I, + KeyEvent.VK_J, + KeyEvent.VK_K, + KeyEvent.VK_L, + KeyEvent.VK_M, + KeyEvent.VK_N, + KeyEvent.VK_O, + KeyEvent.VK_P, + KeyEvent.VK_Q, + KeyEvent.VK_R, + KeyEvent.VK_S, + KeyEvent.VK_T, + KeyEvent.VK_U, + KeyEvent.VK_V, + KeyEvent.VK_W, + KeyEvent.VK_X, + KeyEvent.VK_Y, + KeyEvent.VK_Z, + KeyEvent.VK_OPEN_BRACKET, + KeyEvent.VK_BACK_SLASH, + KeyEvent.VK_CLOSE_BRACKET, + KeyEvent.VK_NUMPAD0, + KeyEvent.VK_NUMPAD1, + KeyEvent.VK_NUMPAD2, + KeyEvent.VK_NUMPAD3, + KeyEvent.VK_NUMPAD4, + KeyEvent.VK_NUMPAD5, + KeyEvent.VK_NUMPAD6, + KeyEvent.VK_NUMPAD7, + KeyEvent.VK_NUMPAD8, + KeyEvent.VK_NUMPAD9, + KeyEvent.VK_MULTIPLY, + KeyEvent.VK_ADD, + KeyEvent.VK_SUBTRACT, + KeyEvent.VK_DECIMAL, + KeyEvent.VK_DIVIDE, + KeyEvent.VK_F1, + KeyEvent.VK_F2, + KeyEvent.VK_F3, + KeyEvent.VK_F4, + KeyEvent.VK_F5, + KeyEvent.VK_F6, + KeyEvent.VK_F7, + KeyEvent.VK_F8, + KeyEvent.VK_F9, + KeyEvent.VK_F10, + KeyEvent.VK_F11, + KeyEvent.VK_F12, + KeyEvent.VK_DELETE, + KeyEvent.VK_HELP, + KeyEvent.VK_META, + KeyEvent.VK_BACK_QUOTE, + KeyEvent.VK_QUOTE, + KeyEvent.VK_F13, + KeyEvent.VK_F14, + KeyEvent.VK_F15, + KeyEvent.VK_F16, + KeyEvent.VK_F17, + KeyEvent.VK_F18, + KeyEvent.VK_F19, + KeyEvent.VK_F20 + }; + + keyPressedIndex = -1; + } + + private void createAndShowGUI() { + frame = new Frame("Function Key Keycodes"); + textArea = new TextArea(); + textArea.setFocusable(true); + frame.add(textArea); + frame.pack(); + frame.setSize(200, 200); + + textArea.addKeyListener(keyListener = new KeyListener() { + + @Override + public void keyTyped(KeyEvent ke) { + } + + @Override + public void keyPressed(KeyEvent ke) { + if (allKeyArr[keyPressedIndex] != ke.getKeyCode()) { + throw new RuntimeException("Wrong keycode received"); + } + } + + @Override + public void keyReleased(KeyEvent ke) { + } + }); + frame.setVisible(true); + } + + private void removeListener() { + if (keyListener != null) { + textArea.removeKeyListener(keyListener); + keyListener = null; + } + } + + @Override + public void dispose() { + if (null != frame) { + frame.dispose(); + frame = null; + } + } + + public void generateFunctionKeyPress() { + try { + Robot robot = new Robot(); + robot.waitForIdle(); + + for (int i = 0; i < allKeyArr.length; i++) { + keyPressedIndex = i; + robot.keyPress(allKeyArr[i]); + robot.keyRelease(allKeyArr[i]); + robot.waitForIdle(); + } + removeListener(); + + } catch (AWTException e) { + throw new RuntimeException("Robot creation failed"); + } + } + + public static void main(String args[]) { + AllKeyCode allKeyObj = new AllKeyCode(); + allKeyObj.createAndShowGUI(); + allKeyObj.generateFunctionKeyPress(); + allKeyObj.dispose(); + + System.out.println("Test Passed"); + } +} From 01983638d21f9b015562469c3c76331d597d7a8d Mon Sep 17 00:00:00 2001 From: Erik Joelsson Date: Mon, 14 Mar 2016 13:10:50 -0700 Subject: [PATCH 019/162] 8151770: 9-client windows builds fail on windows since make file change for 8145174 Reviewed-by: prr --- jdk/make/lib/Awt2dLibraries.gmk | 29 +++++++++++------------------ 1 file changed, 11 insertions(+), 18 deletions(-) diff --git a/jdk/make/lib/Awt2dLibraries.gmk b/jdk/make/lib/Awt2dLibraries.gmk index 8ff75d888cf..6cc42d8ec5f 100644 --- a/jdk/make/lib/Awt2dLibraries.gmk +++ b/jdk/make/lib/Awt2dLibraries.gmk @@ -203,13 +203,11 @@ endif ifeq ($(OPENJDK_TARGET_OS), windows) LIBAWT_DIRS += $(JDK_TOPDIR)/src/java.desktop/share/native/common/font \ - $(JDK_TOPDIR)/src/java.desktop/$(OPENJDK_TARGET_OS_TYPE)/native/common/awt/systemscale \ - $(JDK_TOPDIR)/src/java.desktop/share/native/common/java2d/opengl \ + $(JDK_TOPDIR)/src/java.desktop/share/native/common/java2d/opengl \ # Why does libawt need java.base headers? LIBAWT_CFLAGS += -I$(JDK_TOPDIR)/src/java.desktop/share/native/common/font \ -I$(JDK_TOPDIR)/src/java.desktop/share/native/common/java2d/opengl \ -I$(JDK_TOPDIR)/src/java.desktop/$(OPENJDK_TARGET_OS_TYPE)/native/common/java2d/opengl \ - -I$(JDK_TOPDIR)/src/java.desktop/$(OPENJDK_TARGET_OS_TYPE)/native/common/awt/systemscale \ -I$(JDK_TOPDIR)/src/java.desktop/windows/native/include \ -I$(JDK_TOPDIR)/src/java.desktop/share/native/include \ -I$(SUPPORT_OUTPUTDIR)/headers/java.base \ @@ -313,6 +311,10 @@ ifeq ($(findstring $(OPENJDK_TARGET_OS),windows macosx),) $(JDK_TOPDIR)/src/java.desktop/$(OPENJDK_TARGET_OS_TYPE)/native/common/awt \ # + ifneq ($(filter $(OPENJDK_TARGET_OS),linux solaris), ) + LIBAWT_XAWT_DIRS += $(JDK_TOPDIR)/src/java.desktop/unix/native/common/awt/systemscale + endif + LIBAWT_XAWT_EXCLUDES := medialib LIBAWT_XAWT_CFLAGS := $(addprefix -I, $(shell $(FIND) $(LIBAWT_XAWT_DIRS) -type d)) \ @@ -330,14 +332,10 @@ ifeq ($(findstring $(OPENJDK_TARGET_OS),windows macosx),) -I$(JDK_TOPDIR)/src/java.desktop/$(OPENJDK_TARGET_OS_TYPE)/native/common/font \ $(LIBJAVA_HEADER_FLAGS) # - + LIBAWT_XAWT_CFLAGS += -DXAWT -DXAWT_HACK \ -DPACKAGE_PATH=\"$(PACKAGE_PATH)\" \ $(CUPS_CFLAGS) - ifneq (,$(filter $(OPENJDK_TARGET_OS),linux solaris)) - LIBAWT_XAWT_DIRS += $(JDK_TOPDIR)/src/java.desktop/unix/native/common/awt/systemscale - LIBAWT_XAWT_CFLAGS += -I$(JDK_TOPDIR)/src/java.desktop/unix/native/common/awt/systemscale - endif ifeq ($(OPENJDK_TARGET_OS), solaris) LIBAWT_XAWT_CFLAGS += -DFUNCPROTO=15 @@ -888,21 +886,16 @@ ifndef BUILD_HEADLESS_ONLY else LIBSPLASHSCREEN_DIRS += $(JDK_TOPDIR)/src/java.desktop/macosx/native/libsplashscreen endif - ifeq ($(OPENJDK_TARGET_OS), windows) - LIBSPLASHSCREEN_DIRS += $(JDK_TOPDIR)/src/java.desktop/windows/native/common/awt/systemscale - LIBSPLASHSCREEN_CFLAGS += -I$(JDK_TOPDIR)/src/java.desktop/windows/native/common/awt/systemscale + + ifneq ($(filter $(OPENJDK_TARGET_OS),linux solaris), ) + LIBSPLASHSCREEN_DIRS += $(JDK_TOPDIR)/src/java.desktop/unix/native/common/awt/systemscale endif - + LIBSPLASHSCREEN_CFLAGS += -DSPLASHSCREEN -DPNG_NO_MMX_CODE -DPNG_ARM_NEON_OPT=0 \ $(addprefix -I, $(LIBSPLASHSCREEN_DIRS)) \ $(LIBJAVA_HEADER_FLAGS) \ # - ifneq (,$(filter $(OPENJDK_TARGET_OS),linux solaris)) - LIBSPLASHSCREEN_DIRS += $(JDK_TOPDIR)/src/java.desktop/unix/native/common/awt/systemscale - LIBSPLASHSCREEN_CFLAGS += -I$(JDK_TOPDIR)/src/java.desktop/unix/native/common/awt/systemscale - endif - ifeq ($(OPENJDK_TARGET_OS), macosx) LIBSPLASHSCREEN_CFLAGS += -DWITH_MACOSX LIBSPLASHSCREEN_CFLAGS += -I$(JDK_TOPDIR)/src/java.desktop/macosx/native/libosxapp @@ -938,7 +931,7 @@ ifndef BUILD_HEADLESS_ONLY -framework JavaNativeFoundation else ifeq ($(OPENJDK_TARGET_OS), windows) LIBSPLASHSCREEN_LDFLAGS := -delayload:user32.dll - LIBSPLASHSCREEN_LIBS += kernel32.lib user32.lib gdi32.lib delayimp.lib $(WIN_JAVA_LIB) jvm.lib + LIBSPLASHSCREEN_LIBS += kernel32.lib user32.lib gdi32.lib delayimp.lib else LIBSPLASHSCREEN_LIBS += $(X_LIBS) -lX11 -lXext $(LIBM) -lpthread endif From dfd8fdc32c3c83c96479c8d23ef42f1a3b2a2db2 Mon Sep 17 00:00:00 2001 From: Semyon Sadetsky Date: Tue, 15 Mar 2016 09:11:43 +0300 Subject: [PATCH 020/162] 8143295: Validating issue in AWT Reviewed-by: serb, alexsch --- .../unix/classes/sun/awt/X11/XWindow.java | 3 -- .../unix/classes/sun/awt/X11/XWindowPeer.java | 40 +++++++++++-------- 2 files changed, 24 insertions(+), 19 deletions(-) diff --git a/jdk/src/java.desktop/unix/classes/sun/awt/X11/XWindow.java b/jdk/src/java.desktop/unix/classes/sun/awt/X11/XWindow.java index b431c14d9d1..907446ad81c 100644 --- a/jdk/src/java.desktop/unix/classes/sun/awt/X11/XWindow.java +++ b/jdk/src/java.desktop/unix/classes/sun/awt/X11/XWindow.java @@ -1008,13 +1008,10 @@ class XWindow extends XBaseWindow implements X11ComponentPeer { // if ( Check if it's a resize, a move, or a stacking order change ) // { Rectangle bounds = getBounds(); - final ComponentAccessor acc = AWTAccessor.getComponentAccessor(); if (!bounds.getSize().equals(oldBounds.getSize())) { - acc.setSize(target, bounds.width, bounds.height); postEventToEventQueue(new ComponentEvent(getEventSource(), ComponentEvent.COMPONENT_RESIZED)); } if (!bounds.getLocation().equals(oldBounds.getLocation())) { - acc.setLocation(target, bounds.x, bounds.y); postEventToEventQueue(new ComponentEvent(getEventSource(), ComponentEvent.COMPONENT_MOVED)); } // } diff --git a/jdk/src/java.desktop/unix/classes/sun/awt/X11/XWindowPeer.java b/jdk/src/java.desktop/unix/classes/sun/awt/X11/XWindowPeer.java index 862508ccfcf..a5dfc6afb62 100644 --- a/jdk/src/java.desktop/unix/classes/sun/awt/X11/XWindowPeer.java +++ b/jdk/src/java.desktop/unix/classes/sun/awt/X11/XWindowPeer.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2002, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -803,23 +803,31 @@ class XWindowPeer extends XPanelPeer implements WindowPeer, */ @Override public void handleConfigureNotifyEvent(XEvent xev) { + assert (SunToolkit.isAWTLockHeldByCurrentThread()); XConfigureEvent xe = xev.get_xconfigure(); - /* - * Correct window location which could be wrong in some cases. - * See getNewLocation() for the details. - */ - Point newLocation = getNewLocation(xe, 0, 0); - xe.set_x(scaleUp(newLocation.x)); - xe.set_y(scaleUp(newLocation.y)); - checkIfOnNewScreen(new Rectangle(newLocation.x, - newLocation.y, - scaleDown(xe.get_width()), - scaleDown(xe.get_height()))); + if (insLog.isLoggable(PlatformLogger.Level.FINE)) { + insLog.fine(xe.toString()); + } + checkIfOnNewScreen(toGlobal(new Rectangle(scaleDown(xe.get_x()), + scaleDown(xe.get_y()), + scaleDown(xe.get_width()), + scaleDown(xe.get_height())))); - // Don't call super until we've handled a screen change. Otherwise - // there could be a race condition in which a ComponentListener could - // see the old screen. - super.handleConfigureNotifyEvent(xev); + Rectangle oldBounds = getBounds(); + + x = scaleDown(xe.get_x()); + y = scaleDown(xe.get_y()); + width = scaleDown(xe.get_width()); + height = scaleDown(xe.get_height()); + + if (!getBounds().getSize().equals(oldBounds.getSize())) { + AWTAccessor.getComponentAccessor().setSize(target, width, height); + postEvent(new ComponentEvent(target, ComponentEvent.COMPONENT_RESIZED)); + } + if (!getBounds().getLocation().equals(oldBounds.getLocation())) { + AWTAccessor.getComponentAccessor().setLocation(target, x, y); + postEvent(new ComponentEvent(target, ComponentEvent.COMPONENT_MOVED)); + } repositionSecurityWarning(); } From 09a7c4bc4624dd39ab5500c394c1e298a43a711a Mon Sep 17 00:00:00 2001 From: Semyon Sadetsky Date: Tue, 15 Mar 2016 09:18:29 +0300 Subject: [PATCH 021/162] 8021961: setAlwaysOnTop doesn't behave correctly in Linux/Solaris under certain scenarios Reviewed-by: serb, azvegint --- .../unix/classes/sun/awt/X11/XWindowPeer.java | 50 ++++-- .../MultiWindowApp/ChildAlwaysOnTopTest.java | 160 ++++++++++++++++++ 2 files changed, 200 insertions(+), 10 deletions(-) create mode 100644 jdk/test/java/awt/Window/MultiWindowApp/ChildAlwaysOnTopTest.java diff --git a/jdk/src/java.desktop/unix/classes/sun/awt/X11/XWindowPeer.java b/jdk/src/java.desktop/unix/classes/sun/awt/X11/XWindowPeer.java index a5dfc6afb62..3dad9f30728 100644 --- a/jdk/src/java.desktop/unix/classes/sun/awt/X11/XWindowPeer.java +++ b/jdk/src/java.desktop/unix/classes/sun/awt/X11/XWindowPeer.java @@ -87,7 +87,7 @@ class XWindowPeer extends XPanelPeer implements WindowPeer, // used for modal blocking to keep existing z-order protected XWindowPeer prevTransientFor, nextTransientFor; // value of WM_TRANSIENT_FOR hint set on this window - private XWindowPeer curRealTransientFor; + private XBaseWindow curRealTransientFor; private boolean grab = false; // Whether to do a grab during showing @@ -1065,13 +1065,23 @@ class XWindowPeer extends XPanelPeer implements WindowPeer, log.fine("Promoting always-on-top state {0}", Boolean.valueOf(alwaysOnTop)); } XWM.getWM().setLayer(this, - alwaysOnTop ? - XLayerProtocol.LAYER_ALWAYS_ON_TOP : - XLayerProtocol.LAYER_NORMAL); + alwaysOnTop ? + XLayerProtocol.LAYER_ALWAYS_ON_TOP : + XLayerProtocol.LAYER_NORMAL); } public void updateAlwaysOnTopState() { this.alwaysOnTop = ((Window) this.target).isAlwaysOnTop(); + if (ownerPeer != null) { + XToolkit.awtLock(); + try { + restoreTransientFor(this); + applyWindowType(); + } + finally { + XToolkit.awtUnlock(); + } + } updateAlwaysOnTop(); } @@ -1115,7 +1125,27 @@ class XWindowPeer extends XPanelPeer implements WindowPeer, if (!vis && warningWindow != null) { warningWindow.setSecurityWarningVisible(false, false); } + boolean refreshChildsTransientFor = isVisible() != vis; super.setVisible(vis); + if (refreshChildsTransientFor) { + for (Window child : ((Window) target).getOwnedWindows()) { + XToolkit.awtLock(); + try { + if(!child.isLightweight() && child.isVisible()) { + ComponentPeer childPeer = AWTAccessor. + getComponentAccessor().getPeer(child); + if(childPeer instanceof XWindowPeer) { + XWindowPeer windowPeer = (XWindowPeer) childPeer; + restoreTransientFor(windowPeer); + windowPeer.applyWindowType(); + } + } + } + finally { + XToolkit.awtUnlock(); + } + } + } if (!vis && !isWithdrawn()) { // ICCCM, 4.1.4. Changing Window State: // "Iconic -> Withdrawn - The client should unmap the window and follow it @@ -1644,9 +1674,6 @@ class XWindowPeer extends XPanelPeer implements WindowPeer, window.prevTransientFor = transientForWindow; transientForWindow.nextTransientFor = window; } - if (window.curRealTransientFor == transientForWindow) { - return; - } if (!allStates && (window.getWMState() != transientForWindow.getWMState())) { return; } @@ -1658,11 +1685,14 @@ class XWindowPeer extends XPanelPeer implements WindowPeer, bpw = XlibUtil.getParentWindow(bpw); } long tpw = transientForWindow.getWindow(); - while (!XlibUtil.isToplevelWindow(tpw) && !XlibUtil.isXAWTToplevelWindow(tpw)) { + XBaseWindow parent = transientForWindow; + while (tpw != 0 && ((!XlibUtil.isToplevelWindow(tpw) && + !XlibUtil.isXAWTToplevelWindow(tpw)) || !parent.isVisible())) { tpw = XlibUtil.getParentWindow(tpw); + parent = XToolkit.windowToXWindow(tpw); } XlibWrapper.XSetTransientFor(XToolkit.getDisplay(), bpw, tpw); - window.curRealTransientFor = transientForWindow; + window.curRealTransientFor = parent; } /* @@ -1956,7 +1986,7 @@ class XWindowPeer extends XPanelPeer implements WindowPeer, switch (getWindowType()) { case NORMAL: - typeAtom = (ownerPeer == null) ? + typeAtom = curRealTransientFor == null ? protocol.XA_NET_WM_WINDOW_TYPE_NORMAL : protocol.XA_NET_WM_WINDOW_TYPE_DIALOG; break; diff --git a/jdk/test/java/awt/Window/MultiWindowApp/ChildAlwaysOnTopTest.java b/jdk/test/java/awt/Window/MultiWindowApp/ChildAlwaysOnTopTest.java new file mode 100644 index 00000000000..2fae159733f --- /dev/null +++ b/jdk/test/java/awt/Window/MultiWindowApp/ChildAlwaysOnTopTest.java @@ -0,0 +1,160 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/** + * @test @summary setAlwaysOnTop doesn't behave correctly in Linux/Solaris under + * certain scenarios + * @bug 8021961 + * @author Semyon Sadetsky + * @run main ChildAlwaysOnTopTest + */ + +import javax.swing.*; +import java.awt.*; + +public class ChildAlwaysOnTopTest { + + private static Window win1; + private static Window win2; + private static Point point; + + public static void main(String[] args) throws Exception { + if( Toolkit.getDefaultToolkit().isAlwaysOnTopSupported() ) { + + + test(null); + + Window f = new Frame(); + f.setBackground(Color.darkGray); + f.setSize(500, 500); + try { + test(f); + } finally { + f.dispose(); + } + + f = new Frame(); + f.setBackground(Color.darkGray); + f.setSize(500, 500); + f.setVisible(true); + f = new Dialog((Frame)f); + try { + test(f); + } finally { + ((Frame)f.getParent()).dispose(); + } + } + System.out.println("ok"); + } + + public static void test(Window parent) throws Exception { + SwingUtilities.invokeAndWait(new Runnable() { + @Override + public void run() { + win1 = parent == null ? new JDialog() : new JDialog(parent); + win1.setName("top"); + win2 = parent == null ? new JDialog() : new JDialog(parent); + win2.setName("behind"); + win1.setSize(200, 200); + Panel panel = new Panel(); + panel.setBackground(Color.GREEN); + win1.add(panel); + panel = new Panel(); + panel.setBackground(Color.RED); + win2.add(panel); + win1.setAlwaysOnTop(true); + win2.setAlwaysOnTop(false); + win1.setVisible(true); + } + }); + + Robot robot = new Robot(); + robot.delay(200); + robot.waitForIdle(); + + SwingUtilities.invokeAndWait(new Runnable() { + @Override + public void run() { + point = win1.getLocationOnScreen(); + win2.setBounds(win1.getBounds()); + win2.setVisible(true); + } + }); + + robot.delay(200); + robot.waitForIdle(); + + Color color = robot.getPixelColor(point.x + 100, point.y + 100); + if(!color.equals(Color.GREEN)) { + win1.dispose(); + win2.dispose(); + throw new RuntimeException("alawaysOnTop window is sent back by " + + "another child window setVisible(). " + color); + } + + SwingUtilities.invokeAndWait(new Runnable() { + @Override + public void run() { + win2.toFront(); + if (parent != null) { + parent.setLocation(win1.getLocation()); + parent.toFront(); + } + } + }); + + robot.delay(200); + robot.waitForIdle(); + + color = robot.getPixelColor(point.x + 100, point.y + 100); + if(!color.equals(Color.GREEN)) { + win1.dispose(); + win2.dispose(); + throw new RuntimeException("alawaysOnTop window is sent back by " + + "another child window toFront(). " + color); + } + + SwingUtilities.invokeAndWait(new Runnable() { + @Override + public void run() { + win1.setAlwaysOnTop(false); + if (parent != null) { + parent.setVisible(false); + parent.setVisible(true); + } + win2.toFront(); + } + }); + + robot.delay(200); + robot.waitForIdle(); + + color = robot.getPixelColor(point.x + 100, point.y + 100); + if(!color.equals(Color.RED)) { + throw new RuntimeException("Failed to unset alawaysOnTop " + color); + } + + win1.dispose(); + win2.dispose(); + } +} From 1948e2f95f0dca6ac3c3f35a6f2f5e2bef0035fc Mon Sep 17 00:00:00 2001 From: Semyon Sadetsky Date: Tue, 15 Mar 2016 09:22:48 +0300 Subject: [PATCH 022/162] 8139227: Text fields in JPopupMenu structure do not receive focus in hosted Applets Reviewed-by: serb, alexsch --- .../native/libawt/windows/awt_Window.cpp | 6 +- .../awt/Window/FindOwner/FindOwnerTest.html | 43 +++++++ .../awt/Window/FindOwner/FindOwnerTest.java | 112 ++++++++++++++++++ 3 files changed, 160 insertions(+), 1 deletion(-) create mode 100644 jdk/test/java/awt/Window/FindOwner/FindOwnerTest.html create mode 100644 jdk/test/java/awt/Window/FindOwner/FindOwnerTest.java diff --git a/jdk/src/java.desktop/windows/native/libawt/windows/awt_Window.cpp b/jdk/src/java.desktop/windows/native/libawt/windows/awt_Window.cpp index 8e066a3396b..6ca1641655d 100644 --- a/jdk/src/java.desktop/windows/native/libawt/windows/awt_Window.cpp +++ b/jdk/src/java.desktop/windows/native/libawt/windows/awt_Window.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1996, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -1154,6 +1154,7 @@ BOOL AwtWindow::IsOneOfOwnersOf(AwtWindow * wnd) { void AwtWindow::InitOwner(AwtWindow *owner) { DASSERT(owner != NULL); + AwtWindow *initialOwner = owner; while (owner != NULL && owner->IsSimpleWindow()) { HWND ownerOwnerHWND = ::GetWindow(owner->GetHWnd(), GW_OWNER); @@ -1163,6 +1164,9 @@ void AwtWindow::InitOwner(AwtWindow *owner) } owner = (AwtWindow *)AwtComponent::GetComponent(ownerOwnerHWND); } + if (!owner) { + owner = initialOwner->GetOwningFrameOrDialog(); + } m_owningFrameDialog = (AwtFrame *)owner; } diff --git a/jdk/test/java/awt/Window/FindOwner/FindOwnerTest.html b/jdk/test/java/awt/Window/FindOwner/FindOwnerTest.html new file mode 100644 index 00000000000..f0f8e47af77 --- /dev/null +++ b/jdk/test/java/awt/Window/FindOwner/FindOwnerTest.html @@ -0,0 +1,43 @@ + + + + + Testing Menus + + + + + + \ No newline at end of file diff --git a/jdk/test/java/awt/Window/FindOwner/FindOwnerTest.java b/jdk/test/java/awt/Window/FindOwner/FindOwnerTest.java new file mode 100644 index 00000000000..916c860a5f3 --- /dev/null +++ b/jdk/test/java/awt/Window/FindOwner/FindOwnerTest.java @@ -0,0 +1,112 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* @test + @bug 8139227 + @summary Text fields in JPopupMenu structure do not receive focus in hosted + Applets + @author Semyon Sadetsky + @run applet FindOwnerTest.html +*/ + +import java.applet.Applet; +import java.awt.*; +import java.awt.event.*; +import javax.swing.*; + +public class FindOwnerTest extends Applet +{ + + private boolean gained; + + public void init() { + super.init(); + } + + @Override + public void start() { + Window owner = SwingUtilities.windowForComponent(this); + + Window window1 = new Window(owner); + window1.setVisible(true); + + Window window2 = new Window(window1); + window2.setFocusable(true); + JTextField field = new JTextField("JTextField"); + field.addFocusListener(new FocusListener() { + @Override + public void focusGained(FocusEvent e) { + gained = true; + } + + @Override + public void focusLost(FocusEvent e) { + } + }); + window2.setBounds(100, 100, 200, 200); + window2.add(field); + window2.setVisible(true); + + try { + gained = false; + Robot robot = new Robot(); + robot.setAutoDelay(50); + robot.waitForIdle(); + robot.delay(200); + + Point p = field.getLocationOnScreen(); + System.out.println(p); + robot.mouseMove(p.x + 1, p.y + 1); + robot.mousePress(InputEvent.BUTTON1_MASK); + robot.mouseRelease(InputEvent.BUTTON1_MASK); + robot.waitForIdle(); + robot.delay(200); + + if (!gained) { + throw new Exception("Focus is not gained upon mouse click"); + } + System.out.println("ok"); + } catch (SecurityException e) { + + JOptionPane optionPane = new JOptionPane( + "You are in the browser so test is manual. Try to " + + "click \"JTextField\" in the opened window then press OK " + + "below", + JOptionPane.PLAIN_MESSAGE, JOptionPane.OK_CANCEL_OPTION); + JDialog dialog = + optionPane.createDialog(null,"FindOwnerTest instruction"); + dialog.setModalityType(Dialog.ModalityType.DOCUMENT_MODAL); + dialog.setVisible(true); + if (!gained) { + throw new RuntimeException( + "Focus is not gained upon mouse click"); + } + System.out.println("ok"); + } catch (Exception e) { + throw new RuntimeException(e); + } finally { + window1.dispose(); + stop(); + } + } +} \ No newline at end of file From b6e44767c0e4855981efc21d4ce52f2307c0a96d Mon Sep 17 00:00:00 2001 From: Alexander Scherbatiy Date: Tue, 15 Mar 2016 09:16:56 -0700 Subject: [PATCH 023/162] 8076545: Text size is twice bigger under Windows L&F on Win 8.1 with HiDPI display 8149453: [hidpi] JFileChooser does not scale properly on Windows with HiDPI display and Windows L&F 8149368: [hidpi] JLabel font is twice bigger than JTextArea font on Windows 7,HiDPI, Windows L&F Reviewed-by: flar, serb --- .../native/libawt/windows/ThemeReader.cpp | 21 +++++ .../libawt/windows/awt_DesktopProperties.cpp | 94 ++++++++++++------- .../libawt/windows/awt_DesktopProperties.h | 4 +- .../awt/font/FontScaling/FontScalingTest.java | 58 ++++++++++++ 4 files changed, 142 insertions(+), 35 deletions(-) create mode 100644 jdk/test/java/awt/font/FontScaling/FontScalingTest.java diff --git a/jdk/src/java.desktop/windows/native/libawt/windows/ThemeReader.cpp b/jdk/src/java.desktop/windows/native/libawt/windows/ThemeReader.cpp index ef677750b3d..2cebde74e5b 100644 --- a/jdk/src/java.desktop/windows/native/libawt/windows/ThemeReader.cpp +++ b/jdk/src/java.desktop/windows/native/libawt/windows/ThemeReader.cpp @@ -31,6 +31,8 @@ #include "awt_Object.h" #include "awt_Component.h" +#include "math.h" + // Important note about VC6 and VC7 (or XP Platform SDK) ! // // These type definitions have been imported from UxTheme.h @@ -745,6 +747,23 @@ JNIEXPORT jobject JNICALL Java_sun_awt_windows_ThemeReader_getPosition return NULL; } +void rescale(SIZE *size) { + HWND hWnd = ::GetDesktopWindow(); + HDC hDC = ::GetDC(hWnd); + int dpiX = ::GetDeviceCaps(hDC, LOGPIXELSX); + int dpiY = ::GetDeviceCaps(hDC, LOGPIXELSY); + + if (dpiX !=0 && dpiX != 96) { + float invScaleX = 96.0f / dpiX; + size->cx = (int)round(size->cx * invScaleX); + } + if (dpiY != 0 && dpiY != 96) { + float invScaleY = 96.0f / dpiY; + size->cy = (int)round(size->cy * invScaleY); + } + ::ReleaseDC(hWnd, hDC); +} + /* * Class: sun_awt_windows_ThemeReader * Method: getPartSize @@ -770,6 +789,8 @@ JNIEXPORT jobject JNICALL Java_sun_awt_windows_ThemeReader_getPartSize dimMID = env->GetMethodID(dimClassID, "", "(II)V"); CHECK_NULL_RETURN(dimMID, NULL); } + + rescale(&size); jobject dimObj = env->NewObject(dimClassID, dimMID, size.cx, size.cy); if (safe_ExceptionOccurred(env)) { env->ExceptionDescribe(); diff --git a/jdk/src/java.desktop/windows/native/libawt/windows/awt_DesktopProperties.cpp b/jdk/src/java.desktop/windows/native/libawt/windows/awt_DesktopProperties.cpp index 454a2fe74e4..adbe330dd2e 100644 --- a/jdk/src/java.desktop/windows/native/libawt/windows/awt_DesktopProperties.cpp +++ b/jdk/src/java.desktop/windows/native/libawt/windows/awt_DesktopProperties.cpp @@ -35,6 +35,8 @@ #include #include +#include "math.h" + // WDesktopProperties fields jfieldID AwtDesktopProperties::pDataID = 0; jmethodID AwtDesktopProperties::setBooleanPropertyID = 0; @@ -79,18 +81,35 @@ void AwtDesktopProperties::GetWindowsParameters() { } } +void getInvScale(float &invScaleX, float &invScaleY) { + HWND hWnd = ::GetDesktopWindow(); + HDC hDC = ::GetDC(hWnd); + int dpiX = ::GetDeviceCaps(hDC, LOGPIXELSX); + int dpiY = ::GetDeviceCaps(hDC, LOGPIXELSY); + ::ReleaseDC(hWnd, hDC); + invScaleX = (dpiX == 0.0f) ? 1.0f : 96.0f / dpiX; + invScaleY = (dpiY == 0.0f) ? 1.0f : 96.0f / dpiY; +} + +int rescale(int value, float invScale){ + return invScale == 1.0f ? value : (int)round(value * invScale); +} + void AwtDesktopProperties::GetSystemProperties() { HDC dc = CreateDC(TEXT("DISPLAY"), NULL, NULL, NULL); if (dc != NULL) { try { - SetFontProperty(dc, ANSI_FIXED_FONT, TEXT("win.ansiFixed.font")); - SetFontProperty(dc, ANSI_VAR_FONT, TEXT("win.ansiVar.font")); - SetFontProperty(dc, DEVICE_DEFAULT_FONT, TEXT("win.deviceDefault.font")); - SetFontProperty(dc, DEFAULT_GUI_FONT, TEXT("win.defaultGUI.font")); - SetFontProperty(dc, OEM_FIXED_FONT, TEXT("win.oemFixed.font")); - SetFontProperty(dc, SYSTEM_FONT, TEXT("win.system.font")); - SetFontProperty(dc, SYSTEM_FIXED_FONT, TEXT("win.systemFixed.font")); + float invScaleX; + float invScaleY; + getInvScale(invScaleX, invScaleY); + SetFontProperty(dc, ANSI_FIXED_FONT, TEXT("win.ansiFixed.font"), 1.0f); + SetFontProperty(dc, ANSI_VAR_FONT, TEXT("win.ansiVar.font"), 1.0f); + SetFontProperty(dc, DEVICE_DEFAULT_FONT, TEXT("win.deviceDefault.font"), 1.0f); + SetFontProperty(dc, DEFAULT_GUI_FONT, TEXT("win.defaultGUI.font"), invScaleY); + SetFontProperty(dc, OEM_FIXED_FONT, TEXT("win.oemFixed.font"), 1.0f); + SetFontProperty(dc, SYSTEM_FONT, TEXT("win.system.font"), 1.0f); + SetFontProperty(dc, SYSTEM_FIXED_FONT, TEXT("win.systemFixed.font"), 1.0f); } catch (std::bad_alloc&) { DeleteDC(dc); @@ -266,31 +285,35 @@ void AwtDesktopProperties::GetNonClientParameters() { } VERIFY( SystemParametersInfo(SPI_GETNONCLIENTMETRICS, ncmetrics.cbSize, &ncmetrics, FALSE) ); - SetFontProperty( TEXT("win.frame.captionFont"), ncmetrics.lfCaptionFont ); - SetIntegerProperty( TEXT("win.frame.captionHeight"), ncmetrics.iCaptionHeight ); - SetIntegerProperty( TEXT("win.frame.captionButtonWidth"), ncmetrics.iCaptionWidth ); - SetIntegerProperty( TEXT("win.frame.captionButtonHeight"), ncmetrics.iCaptionHeight ); - SetFontProperty( TEXT("win.frame.smallCaptionFont"), ncmetrics.lfSmCaptionFont ); - SetIntegerProperty( TEXT("win.frame.smallCaptionHeight"), ncmetrics.iSmCaptionHeight ); - SetIntegerProperty( TEXT("win.frame.smallCaptionButtonWidth"), ncmetrics.iSmCaptionWidth ); - SetIntegerProperty( TEXT("win.frame.smallCaptionButtonHeight"), ncmetrics.iSmCaptionHeight ); - SetIntegerProperty( TEXT("win.frame.sizingBorderWidth"), ncmetrics.iBorderWidth ); + float invScaleX; + float invScaleY; + getInvScale(invScaleX, invScaleY); + + SetFontProperty(TEXT("win.frame.captionFont"), ncmetrics.lfCaptionFont, invScaleY); + SetIntegerProperty(TEXT("win.frame.captionHeight"), rescale(ncmetrics.iCaptionHeight, invScaleY)); + SetIntegerProperty(TEXT("win.frame.captionButtonWidth"), rescale(ncmetrics.iCaptionWidth, invScaleX)); + SetIntegerProperty(TEXT("win.frame.captionButtonHeight"), rescale(ncmetrics.iCaptionHeight, invScaleY)); + SetFontProperty(TEXT("win.frame.smallCaptionFont"), ncmetrics.lfSmCaptionFont, invScaleY); + SetIntegerProperty(TEXT("win.frame.smallCaptionHeight"), rescale(ncmetrics.iSmCaptionHeight, invScaleY)); + SetIntegerProperty(TEXT("win.frame.smallCaptionButtonWidth"), rescale(ncmetrics.iSmCaptionWidth, invScaleX)); + SetIntegerProperty(TEXT("win.frame.smallCaptionButtonHeight"), rescale(ncmetrics.iSmCaptionHeight, invScaleY)); + SetIntegerProperty(TEXT("win.frame.sizingBorderWidth"), rescale(ncmetrics.iBorderWidth, invScaleX)); // menu properties - SetFontProperty( TEXT("win.menu.font"), ncmetrics.lfMenuFont ); - SetIntegerProperty( TEXT("win.menu.height"), ncmetrics.iMenuHeight ); - SetIntegerProperty( TEXT("win.menu.buttonWidth"), ncmetrics.iMenuWidth ); + SetFontProperty(TEXT("win.menu.font"), ncmetrics.lfMenuFont, invScaleY); + SetIntegerProperty(TEXT("win.menu.height"), rescale(ncmetrics.iMenuHeight, invScaleY)); + SetIntegerProperty(TEXT("win.menu.buttonWidth"), rescale(ncmetrics.iMenuWidth, invScaleX)); // scrollbar properties - SetIntegerProperty( TEXT("win.scrollbar.width"), ncmetrics.iScrollWidth ); - SetIntegerProperty( TEXT("win.scrollbar.height"), ncmetrics.iScrollHeight ); + SetIntegerProperty(TEXT("win.scrollbar.width"), rescale(ncmetrics.iScrollWidth, invScaleX)); + SetIntegerProperty(TEXT("win.scrollbar.height"), rescale(ncmetrics.iScrollHeight, invScaleY)); // status bar and tooltip properties - SetFontProperty( TEXT("win.status.font"), ncmetrics.lfStatusFont ); - SetFontProperty( TEXT("win.tooltip.font"), ncmetrics.lfStatusFont ); + SetFontProperty(TEXT("win.status.font"), ncmetrics.lfStatusFont, invScaleY); + SetFontProperty(TEXT("win.tooltip.font"), ncmetrics.lfStatusFont, invScaleY); // message box properties - SetFontProperty( TEXT("win.messagebox.font"), ncmetrics.lfMessageFont ); + SetFontProperty(TEXT("win.messagebox.font"), ncmetrics.lfMessageFont, invScaleY); } void AwtDesktopProperties::GetIconParameters() { @@ -302,10 +325,13 @@ void AwtDesktopProperties::GetIconParameters() { iconmetrics.cbSize = sizeof(iconmetrics); VERIFY( SystemParametersInfo(SPI_GETICONMETRICS, iconmetrics.cbSize, &iconmetrics, FALSE) ); - SetIntegerProperty(TEXT("win.icon.hspacing"), iconmetrics.iHorzSpacing); - SetIntegerProperty(TEXT("win.icon.vspacing"), iconmetrics.iVertSpacing); + float invScaleX; + float invScaleY; + getInvScale(invScaleX, invScaleY); + SetIntegerProperty(TEXT("win.icon.hspacing"), rescale(iconmetrics.iHorzSpacing, invScaleX)); + SetIntegerProperty(TEXT("win.icon.vspacing"), rescale(iconmetrics.iVertSpacing, invScaleY)); SetBooleanProperty(TEXT("win.icon.titleWrappingOn"), iconmetrics.iTitleWrap != 0); - SetFontProperty(TEXT("win.icon.font"), iconmetrics.lfFont); + SetFontProperty(TEXT("win.icon.font"), iconmetrics.lfFont, invScaleY); } /* Windows settings for these are also in the registry @@ -718,6 +744,7 @@ void AwtDesktopProperties::SetStringProperty(LPCTSTR propName, LPTSTR value) { } void AwtDesktopProperties::SetIntegerProperty(LPCTSTR propName, int value) { + jstring key = JNU_NewStringPlatform(GetEnv(), propName); if (key == NULL) { throw std::bad_alloc(); @@ -752,8 +779,8 @@ void AwtDesktopProperties::SetColorProperty(LPCTSTR propName, DWORD value) { } void AwtDesktopProperties::SetFontProperty(HDC dc, int fontID, - LPCTSTR propName) { - HGDIOBJ font = GetStockObject(fontID); + LPCTSTR propName, float invScale) { + HGDIOBJ font = GetStockObject(fontID); if (font != NULL && SelectObject(dc, font) != NULL) { int length = GetTextFace(dc, 0, NULL); @@ -789,8 +816,8 @@ void AwtDesktopProperties::SetFontProperty(HDC dc, int fontID, throw std::bad_alloc(); } - jint pointSize = metrics.tmHeight - - metrics.tmInternalLeading; + jint pointSize = rescale(metrics.tmHeight - + metrics.tmInternalLeading, invScale); jint style = java_awt_Font_PLAIN; if (metrics.tmWeight >= FW_BOLD) { @@ -818,7 +845,8 @@ void AwtDesktopProperties::SetFontProperty(HDC dc, int fontID, } } -void AwtDesktopProperties::SetFontProperty(LPCTSTR propName, const LOGFONT & font) { +void AwtDesktopProperties::SetFontProperty(LPCTSTR propName, const LOGFONT & font, + float invScale) { jstring fontName; jint pointSize; jint style; @@ -836,7 +864,7 @@ void AwtDesktopProperties::SetFontProperty(LPCTSTR propName, const LOGFONT & fon ReleaseDC(NULL, hdc); #endif // Java uses point sizes, but assumes 1 pixel = 1 point - pointSize = -font.lfHeight; + pointSize = rescale(-font.lfHeight, invScale); // convert Windows font style to Java style style = java_awt_Font_PLAIN; diff --git a/jdk/src/java.desktop/windows/native/libawt/windows/awt_DesktopProperties.h b/jdk/src/java.desktop/windows/native/libawt/windows/awt_DesktopProperties.h index e93530ef208..70f0bf895de 100644 --- a/jdk/src/java.desktop/windows/native/libawt/windows/awt_DesktopProperties.h +++ b/jdk/src/java.desktop/windows/native/libawt/windows/awt_DesktopProperties.h @@ -73,8 +73,8 @@ class AwtDesktopProperties { void SetIntegerProperty(LPCTSTR, int); void SetStringProperty(LPCTSTR, LPTSTR); void SetColorProperty(LPCTSTR, DWORD); - void SetFontProperty(HDC, int, LPCTSTR); - void SetFontProperty(LPCTSTR, const LOGFONT &); + void SetFontProperty(HDC, int, LPCTSTR, float invScale); + void SetFontProperty(LPCTSTR, const LOGFONT &, float invScale); void SetSoundProperty(LPCTSTR, LPCTSTR); JNIEnv * GetEnv() { diff --git a/jdk/test/java/awt/font/FontScaling/FontScalingTest.java b/jdk/test/java/awt/font/FontScaling/FontScalingTest.java new file mode 100644 index 00000000000..4c100ac8ca4 --- /dev/null +++ b/jdk/test/java/awt/font/FontScaling/FontScalingTest.java @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import javax.swing.JButton; +import javax.swing.SwingUtilities; +import javax.swing.UIManager; +import javax.swing.plaf.metal.MetalLookAndFeel; + +/* + * @test + * @bug 8076545 + * @summary Text size is twice bigger under Windows L&F on Win 8.1 with + * HiDPI display + */ +public class FontScalingTest { + + public static void main(String[] args) throws Exception { + int metalFontSize = getFontSize(MetalLookAndFeel.class.getName()); + int systemFontSize = getFontSize(UIManager.getSystemLookAndFeelClassName()); + + if (Math.abs(systemFontSize - metalFontSize) > 8) { + throw new RuntimeException("System L&F is too big!"); + } + } + + private static int getFontSize(String laf) throws Exception { + + UIManager.setLookAndFeel(laf); + final int[] sizes = new int[1]; + + SwingUtilities.invokeAndWait(() -> { + JButton button = new JButton("Test"); + sizes[0] = button.getFont().getSize(); + }); + + return sizes[0]; + } +} \ No newline at end of file From 23d01d22cd9a2cbe1e15190d652cf7139cfa1b3d Mon Sep 17 00:00:00 2001 From: Alexander Scherbatiy Date: Tue, 15 Mar 2016 22:40:38 -0700 Subject: [PATCH 024/162] 8149849: [hidpi] DnD issues (cannot DnD from JFileChooser to JEditorPane or other text component) when scale > 1 Reviewed-by: prr, serb --- .../native/libawt/windows/awt_DnDDT.cpp | 13 ++ .../8149849/DNDTextToScaledArea.java | 125 ++++++++++++++++++ 2 files changed, 138 insertions(+) create mode 100644 jdk/test/javax/swing/JTextArea/8149849/DNDTextToScaledArea.java diff --git a/jdk/src/java.desktop/windows/native/libawt/windows/awt_DnDDT.cpp b/jdk/src/java.desktop/windows/native/libawt/windows/awt_DnDDT.cpp index 8739fc8f576..908b459111e 100644 --- a/jdk/src/java.desktop/windows/native/libawt/windows/awt_DnDDT.cpp +++ b/jdk/src/java.desktop/windows/native/libawt/windows/awt_DnDDT.cpp @@ -127,6 +127,16 @@ ULONG __stdcall AwtDropTarget::Release() { return (ULONG)refs; } +void ScaleDown(POINT &cp, HWND m_window) { + int screen = AwtWin32GraphicsDevice::DeviceIndexForWindow(m_window); + Devices::InstanceAccess devices; + AwtWin32GraphicsDevice* device = devices->GetDevice(screen); + if (device) { + cp.x = device->ScaleDownX(cp.x); + cp.y = device->ScaleDownY(cp.y); + } +} + /** * DragEnter */ @@ -176,6 +186,7 @@ HRESULT __stdcall AwtDropTarget::DragEnter(IDataObject __RPC_FAR *pDataObj, DWOR cp.x = pt.x - wr.left; cp.y = pt.y - wr.top; + ScaleDown(cp, m_window); jint actions = call_dTCenter(env, m_dtcp, m_target, (jint)cp.x, (jint)cp.y, @@ -237,6 +248,7 @@ HRESULT __stdcall AwtDropTarget::DragOver(DWORD grfKeyState, POINTL pt, DWORD __ cp.x = pt.x - wr.left; cp.y = pt.y - wr.top; + ScaleDown(cp, m_window); actions = call_dTCmotion(env, m_dtcp, m_target,(jint)cp.x, (jint)cp.y, ::convertDROPEFFECTToActions(mapModsToDROPEFFECT(*pdwEffect, grfKeyState)), @@ -336,6 +348,7 @@ HRESULT __stdcall AwtDropTarget::Drop(IDataObject __RPC_FAR *pDataObj, DWORD grf cp.x = pt.x - wr.left; cp.y = pt.y - wr.top; + ScaleDown(cp, m_window); m_dropActions = java_awt_dnd_DnDConstants_ACTION_NONE; diff --git a/jdk/test/javax/swing/JTextArea/8149849/DNDTextToScaledArea.java b/jdk/test/javax/swing/JTextArea/8149849/DNDTextToScaledArea.java new file mode 100644 index 00000000000..501fa199620 --- /dev/null +++ b/jdk/test/javax/swing/JTextArea/8149849/DNDTextToScaledArea.java @@ -0,0 +1,125 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import java.awt.BorderLayout; +import java.awt.Component; +import java.awt.Dimension; +import java.awt.Point; +import java.awt.Robot; +import java.awt.event.InputEvent; +import javax.swing.JFrame; +import javax.swing.JPanel; +import javax.swing.JTextArea; +import javax.swing.SwingUtilities; + +/** + * @test + * @bug 8149849 + * @summary [hidpi] DnD issues (cannot DnD from JFileChooser to JEditorPane or + * other text component) when scale > 1 + * @run main/othervm -Dsun.java2d.uiScale=2 DNDTextToScaledArea + */ +public class DNDTextToScaledArea { + + private static final String TEXT = "ABCDEFGH"; + private static JFrame frame; + private static JTextArea srcTextArea; + private static JTextArea dstTextArea; + private static volatile Point srcPoint; + private static volatile Point dstPoint; + private static volatile boolean passed = false; + + public static void main(String[] args) throws Exception { + Robot robot = new Robot(); + robot.setAutoDelay(50); + + SwingUtilities.invokeAndWait(DNDTextToScaledArea::createAndShowGUI); + robot.waitForIdle(); + + SwingUtilities.invokeAndWait(() -> { + srcPoint = getPoint(srcTextArea, 0.1); + dstPoint = getPoint(dstTextArea, 0.75); + }); + robot.waitForIdle(); + + dragAndDrop(robot, srcPoint, dstPoint); + robot.waitForIdle(); + + SwingUtilities.invokeAndWait(() -> { + passed = TEXT.equals(dstTextArea.getText()); + frame.dispose(); + }); + robot.waitForIdle(); + + if (!passed) { + throw new RuntimeException("Text Drag and Drop failed!"); + } + } + + private static void createAndShowGUI() { + + frame = new JFrame(); + frame.setSize(300, 300); + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + + JPanel panel = new JPanel(new BorderLayout()); + + srcTextArea = new JTextArea(TEXT); + srcTextArea.setDragEnabled(true); + srcTextArea.selectAll(); + dstTextArea = new JTextArea(); + + panel.add(dstTextArea, BorderLayout.CENTER); + panel.add(srcTextArea, BorderLayout.SOUTH); + + frame.getContentPane().add(panel); + frame.setVisible(true); + } + + private static Point getPoint(Component component, double scale) { + Point point = component.getLocationOnScreen(); + Dimension bounds = component.getSize(); + point.translate((int) (bounds.width * scale), (int) (bounds.height * scale)); + return point; + } + + public static void dragAndDrop(Robot robot, Point src, Point dst) throws Exception { + + int x1 = src.x; + int y1 = src.y; + int x2 = dst.x; + int y2 = dst.y; + robot.mouseMove(x1, y1); + robot.mousePress(InputEvent.BUTTON1_MASK); + + float dmax = (float) Math.max(Math.abs(x2 - x1), Math.abs(y2 - y1)); + float dx = (x2 - x1) / dmax; + float dy = (y2 - y1) / dmax; + + for (int i = 0; i <= dmax; i += 5) { + robot.mouseMove((int) (x1 + dx * i), (int) (y1 + dy * i)); + } + + robot.mouseRelease(InputEvent.BUTTON1_MASK); + } +} From e20ce427c2164558d3c13b5eae0c9557f4159e09 Mon Sep 17 00:00:00 2001 From: Prasanta Sadhukhan Date: Wed, 16 Mar 2016 15:00:57 +0530 Subject: [PATCH 025/162] 8066139: Null return from PrintJob.getGraphics() running closed/java/awt/PrintJob/HighResTest/HighResTest.java Co-authored-by: Philip Race Reviewed-by: prr, jdv --- .../share/classes/sun/print/PrintJob2D.java | 1 + .../classes/sun/print/RasterPrinterJob.java | 1 + jdk/test/java/awt/PrintJob/HighResTest.java | 412 ++++++++++++++++++ 3 files changed, 414 insertions(+) create mode 100644 jdk/test/java/awt/PrintJob/HighResTest.java diff --git a/jdk/src/java.desktop/share/classes/sun/print/PrintJob2D.java b/jdk/src/java.desktop/share/classes/sun/print/PrintJob2D.java index 975e52ab86d..0d3df28921c 100644 --- a/jdk/src/java.desktop/share/classes/sun/print/PrintJob2D.java +++ b/jdk/src/java.desktop/share/classes/sun/print/PrintJob2D.java @@ -995,6 +995,7 @@ public class PrintJob2D extends PrintJob implements Printable, Runnable { public void run() { try { + attributes.remove(PageRanges.class); printerJob.print(attributes); } catch (PrinterException e) { //REMIND: need to store this away and not rethrow it. diff --git a/jdk/src/java.desktop/share/classes/sun/print/RasterPrinterJob.java b/jdk/src/java.desktop/share/classes/sun/print/RasterPrinterJob.java index 7ba84ab1630..b5d8f0daa8f 100644 --- a/jdk/src/java.desktop/share/classes/sun/print/RasterPrinterJob.java +++ b/jdk/src/java.desktop/share/classes/sun/print/RasterPrinterJob.java @@ -1212,6 +1212,7 @@ public abstract class RasterPrinterJob extends PrinterJob { pageRangesAttr = (PageRanges)attributes.get(PageRanges.class); if (!isSupportedValue(pageRangesAttr, attributes)) { pageRangesAttr = null; + setPageRange(-1, -1); } else { if ((SunPageSelection)attributes.get(SunPageSelection.class) == SunPageSelection.RANGE) { diff --git a/jdk/test/java/awt/PrintJob/HighResTest.java b/jdk/test/java/awt/PrintJob/HighResTest.java new file mode 100644 index 00000000000..e802214fdaf --- /dev/null +++ b/jdk/test/java/awt/PrintJob/HighResTest.java @@ -0,0 +1,412 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + + +/* + @test + @bug 4227128 8066139 + @summary Test printing at resolutions > 72dpi + @author dpm: area=awt.print + @run main/manual HighResTest + */ +import java.awt.Button; +import java.awt.Color; +import java.awt.Dimension; +import java.awt.Frame; +import java.awt.JobAttributes; +import java.awt.PageAttributes; +import java.awt.PrintJob; +import java.awt.Font; +import java.awt.FontMetrics; +import java.awt.Graphics; +import java.awt.JobAttributes.DialogType; +import java.awt.JobAttributes.SidesType; +import java.awt.PageAttributes.OrientationRequestedType; +import java.awt.PageAttributes.OriginType; +import java.awt.Dialog; +import java.awt.Panel; +import java.awt.TextArea; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + +public class HighResTest { + static Frame f = new Frame(); + + private static void init() { + String[] instructions = { + "To be able to run this test it is required to have a default", + "printer configured in your user environment.", + "If no default printer exists, then test passes.", + " ", + "There will be 2 print dialogs. The first dialog should show", + "portrait as the selected orientation. The 2nd dialog should show", + "landscape as the selected orientation.", + " ", + "Visual inspection of the printed pages is needed. A passing", + "test will print 2 pages in portrait and 2 pages in landscape.", + "The pages have on the center of the page the text \"Center\"", + "2 rectangles will appear above and below it, the one below is", + "filled." + }; + Sysout.createDialog(); + Sysout.printInstructions(instructions); + + PrintJob job = null; + Dimension dim = null; + JobAttributes jobAttributes = new JobAttributes(); + PageAttributes pageAttributes = new PageAttributes(); + String center = "Center"; + Font font = new Font("SansSerif", Font.PLAIN, 200); + FontMetrics metrics = null; + int width = 0; + Graphics g = null; + + jobAttributes.setDialog(DialogType.NATIVE); + pageAttributes.setOrigin(OriginType.PRINTABLE); + pageAttributes.setPrinterResolution(new int[]{1200, 1200, 3}); + pageAttributes.setOrientationRequested( + OrientationRequestedType.PORTRAIT); + jobAttributes.setSides(SidesType.TWO_SIDED_LONG_EDGE); + + job = f.getToolkit().getPrintJob(f, "Portrait Test", jobAttributes, + pageAttributes); + if (job != null) { + dim = job.getPageDimension(); + for (int i = 0; i < 2; i++) { + g = job.getGraphics(); + + g.drawLine(0, 0, dim.width, 0); + g.drawLine(dim.width, 0, dim.width, dim.height); + g.drawLine(dim.width, dim.height, 0, dim.height); + g.drawLine(0, dim.height, 0, 0); + + g.drawRect(dim.width / 2 - 200, dim.height / 3 - 300, 400, 600); + g.fillRect(dim.width / 2 - 200, 2 * dim.height / 3 - 300, 400, 600); + + g.setFont(font); + metrics = g.getFontMetrics(); + width = metrics.stringWidth(center); + g.setColor(Color.black); + g.drawString(center, (dim.width / 2) - (width / 2), dim.height / 2); + + g.dispose(); + } + job.end(); + job = null; + } + + pageAttributes.setOrientationRequested( + OrientationRequestedType.LANDSCAPE); + + job = f.getToolkit().getPrintJob(f, "Landscape Test", jobAttributes, + pageAttributes); + if (job != null) { + dim = job.getPageDimension(); + for (int i = 0; i < 2; i++) { + g = job.getGraphics(); + g.drawLine(0, 0, dim.width, 0); + g.drawLine(dim.width, 0, dim.width, dim.height); + g.drawLine(dim.width, dim.height, 0, dim.height); + g.drawLine(0, dim.height, 0, 0); + + g.drawRect(dim.width / 2 - 200, dim.height / 3 - 300, 400, 600); + g.fillRect(dim.width / 2 - 200, 2 * dim.height / 3 - 300, 400, 600); + + g.setFont(font); + metrics = g.getFontMetrics(); + width = metrics.stringWidth(center); + g.setColor(Color.black); + g.drawString(center, (dim.width / 2) - (width / 2), dim.height / 2); + + g.dispose(); + } + job.end(); + job = null; + } + System.out.println("done"); + } + + + + /** + * *************************************************** + * Standard Test Machinery Section DO NOT modify anything in this section -- it's a + standard chunk of code which has all of the + synchronisation necessary for the test harness. + By keeping it the same in all tests, it is easier + to read and understand someone else's test, as + well as insuring that all tests behave correctly + with the test harness. + There is a section following this for test-defined + classes + ***************************************************** + */ + private static boolean theTestPassed = false; + private static boolean testGeneratedInterrupt = false; + private static String failureMessage = ""; + + private static Thread mainThread = null; + + private static int sleepTime = 300000; + + public static void main(String args[]) throws InterruptedException { + mainThread = Thread.currentThread(); + try { + init(); + } catch (TestPassedException e) { + //The test passed, so just return from main and harness will + // interepret this return as a pass + return; + } + //At this point, neither test passed nor test failed has been + // called -- either would have thrown an exception and ended the + // test, so we know we have multiple threads. + + //Test involves other threads, so sleep and wait for them to + // called pass() or fail() + try { + Thread.sleep(sleepTime); + //Timed out, so fail the test + throw new RuntimeException("Timed out after " + sleepTime / 1000 + " seconds"); + } catch (InterruptedException e) { + if (!testGeneratedInterrupt) { + throw e; + } + + //reset flag in case hit this code more than once for some reason (just safety) + testGeneratedInterrupt = false; + if (theTestPassed == false) { + throw new RuntimeException(failureMessage); + } + } + + }//main + + public static synchronized void setTimeoutTo(int seconds) { + sleepTime = seconds * 1000; + } + + public static synchronized void pass() { + Sysout.println("The test passed."); + //first check if this is executing in main thread + if (mainThread == Thread.currentThread()) { + //Still in the main thread, so set the flag just for kicks, + // and throw a test passed exception which will be caught + // and end the test. + theTestPassed = true; + throw new TestPassedException(); + } + //pass was called from a different thread, so set the flag and interrupt + // the main thead. + theTestPassed = true; + testGeneratedInterrupt = true; + mainThread.interrupt(); + Sysout.dispose(); + }//pass() + + public static synchronized void fail() { + //test writer didn't specify why test failed, so give generic + fail("it just plain failed! :-)"); + } + + public static synchronized void fail(String whyFailed) { + Sysout.println("The test failed: " + whyFailed); + //check if this called from main thread + if (mainThread == Thread.currentThread()) { + //If main thread, fail now 'cause not sleeping + throw new RuntimeException(whyFailed); + } + theTestPassed = false; + testGeneratedInterrupt = true; + failureMessage = whyFailed; + mainThread.interrupt(); + Sysout.dispose(); + }//fail() + + }// class HighResTest + +//This exception is used to exit from any level of call nesting +// when it's determined that the test has passed, and immediately +// end the test. +class TestPassedException extends RuntimeException + { + } + +//*********** End Standard Test Machinery Section ********** + +//************** End classes defined for the test ******************* + + + + +/**************************************************** + Standard Test Machinery + DO NOT modify anything below -- it's a standard + chunk of code whose purpose is to make user + interaction uniform, and thereby make it simpler + to read and understand someone else's test. + ****************************************************/ + +/** + This is part of the standard test machinery. + It creates a dialog (with the instructions), and is the interface + for sending text messages to the user. + To print the instructions, send an array of strings to Sysout.createDialog + WithInstructions method. Put one line of instructions per array entry. + To display a message for the tester to see, simply call Sysout.println + with the string to be displayed. + This mimics System.out.println but works within the test harness as well + as standalone. + */ + +class Sysout { + private static TestDialog dialog; + + public static void createDialogWithInstructions(String[] instructions) { + dialog = new TestDialog(new Frame(), "Instructions"); + dialog.printInstructions(instructions); + println("Any messages for the tester will display here."); + } + + public static void createDialog() { + dialog = new TestDialog(new Frame(), "Instructions"); + String[] defInstr = {"Instructions will appear here. ", ""}; + dialog.printInstructions(defInstr); + println("Any messages for the tester will display here."); + } + + + public static void printInstructions(String[] instructions) { + dialog.printInstructions(instructions); + } + + + public static void println(String messageIn) { + dialog.displayMessage(messageIn); + } + + public static void dispose() { + Sysout.println("Shutting down the Java process.."); + HighResTest.f.dispose(); + dialog.dispose(); + } + }// Sysout class + +/** + This is part of the standard test machinery. It provides a place for the + test instructions to be displayed, and a place for interactive messages + to the user to be displayed. + To have the test instructions displayed, see Sysout. + To have a message to the user be displayed, see Sysout. + Do not call anything in this dialog directly. + */ +class TestDialog extends Dialog implements ActionListener +{ + + TextArea instructionsText; + TextArea messageText; + int maxStringLength = 80; + Panel buttonP = new Panel(); + Button passB = new Button("pass"); + Button failB = new Button("fail"); + + //DO NOT call this directly, go through Sysout + public TestDialog(Frame frame, String name) { + super(frame, name); + int scrollBoth = TextArea.SCROLLBARS_BOTH; + instructionsText = new TextArea("", 15, maxStringLength, scrollBoth); + add("North", instructionsText); + + messageText = new TextArea("", 5, maxStringLength, scrollBoth); + add("Center", messageText); + + passB = new Button("pass"); + passB.setActionCommand("pass"); + passB.addActionListener(this); + buttonP.add("East", passB); + + failB = new Button("fail"); + failB.setActionCommand("fail"); + failB.addActionListener(this); + buttonP.add("West", failB); + + add("South", buttonP); + pack(); + + show(); + }// TestDialog() + + //DO NOT call this directly, go through Sysout + public void printInstructions(String[] instructions) { + //Clear out any current instructions + instructionsText.setText(""); + + //Go down array of instruction strings + + String printStr, remainingStr; + for (int i = 0; i < instructions.length; i++) { + //chop up each into pieces maxSringLength long + remainingStr = instructions[i]; + while (remainingStr.length() > 0) { + //if longer than max then chop off first max chars to print + if (remainingStr.length() >= maxStringLength) { + //Try to chop on a word boundary + int posOfSpace = remainingStr. + lastIndexOf(' ', maxStringLength - 1); + + if (posOfSpace <= 0) { + posOfSpace = maxStringLength - 1; + } + + printStr = remainingStr.substring(0, posOfSpace + 1); + remainingStr = remainingStr.substring(posOfSpace + 1); + } //else just print + else { + printStr = remainingStr; + remainingStr = ""; + } + + instructionsText.append(printStr + "\n"); + + }// while + + }// for + + }//printInstructions() + + //DO NOT call this directly, go through Sysout + public void displayMessage(String messageIn) { + messageText.append(messageIn + "\n"); + } + + //catch presses of the passed and failed buttons. + //simply call the standard pass() or fail() static methods of + //HighResTest + public void actionPerformed(ActionEvent e) { + if (e.getActionCommand() == "pass") { + HighResTest.pass(); + } else { + HighResTest.fail(); + } + } +}// TestDialog class From a7d116c1f3b2e89510d6ae71033f72add2033b79 Mon Sep 17 00:00:00 2001 From: Nils Eliasson Date: Wed, 16 Mar 2016 10:45:43 +0100 Subject: [PATCH 026/162] 8150054: Make compilercontrol test ignore xcomp Add -Xmixed and use jtreg driver Reviewed-by: kvn --- .../compiler/compilercontrol/commandfile/CompileOnlyTest.java | 4 ++-- .../compiler/compilercontrol/commandfile/ExcludeTest.java | 4 ++-- .../test/compiler/compilercontrol/commandfile/LogTest.java | 4 ++-- .../test/compiler/compilercontrol/commandfile/PrintTest.java | 4 ++-- .../compiler/compilercontrol/commands/CompileOnlyTest.java | 4 ++-- .../test/compiler/compilercontrol/commands/ExcludeTest.java | 4 ++-- hotspot/test/compiler/compilercontrol/commands/LogTest.java | 4 ++-- hotspot/test/compiler/compilercontrol/commands/PrintTest.java | 4 ++-- .../compiler/compilercontrol/directives/CompileOnlyTest.java | 4 ++-- .../test/compiler/compilercontrol/directives/ExcludeTest.java | 4 ++-- hotspot/test/compiler/compilercontrol/directives/LogTest.java | 4 ++-- .../test/compiler/compilercontrol/directives/PrintTest.java | 4 ++-- .../test/compiler/compilercontrol/jcmd/AddAndRemoveTest.java | 4 ++-- .../compiler/compilercontrol/jcmd/AddCompileOnlyTest.java | 4 ++-- .../test/compiler/compilercontrol/jcmd/AddExcludeTest.java | 4 ++-- hotspot/test/compiler/compilercontrol/jcmd/AddLogTest.java | 4 ++-- .../compiler/compilercontrol/jcmd/AddPrintAssemblyTest.java | 4 ++-- .../compilercontrol/jcmd/ClearDirectivesFileStackTest.java | 4 ++-- .../compilercontrol/jcmd/ClearDirectivesStackTest.java | 4 ++-- .../compiler/compilercontrol/jcmd/PrintDirectivesTest.java | 4 ++-- .../compilercontrol/jcmd/StressAddMultiThreadedTest.java | 2 +- .../compiler/compilercontrol/matcher/MethodMatcherTest.java | 2 +- .../compiler/compilercontrol/mixed/RandomCommandsTest.java | 4 ++-- .../compilercontrol/mixed/RandomValidCommandsTest.java | 2 +- hotspot/test/compiler/compilercontrol/share/MultiCommand.java | 1 + .../compiler/compilercontrol/share/scenario/Scenario.java | 1 + 26 files changed, 47 insertions(+), 45 deletions(-) diff --git a/hotspot/test/compiler/compilercontrol/commandfile/CompileOnlyTest.java b/hotspot/test/compiler/compilercontrol/commandfile/CompileOnlyTest.java index e128f500901..2541d9d0b83 100644 --- a/hotspot/test/compiler/compilercontrol/commandfile/CompileOnlyTest.java +++ b/hotspot/test/compiler/compilercontrol/commandfile/CompileOnlyTest.java @@ -29,9 +29,9 @@ * @build compiler.compilercontrol.commandfile.CompileOnlyTest * pool.sub.* pool.subpack.* sun.hotspot.WhiteBox * compiler.testlibrary.CompilerUtils compiler.compilercontrol.share.actions.* - * @run main ClassFileInstaller sun.hotspot.WhiteBox + * @run driver ClassFileInstaller sun.hotspot.WhiteBox * sun.hotspot.WhiteBox$WhiteBoxPermission - * @run main/othervm compiler.compilercontrol.commandfile.CompileOnlyTest + * @run driver compiler.compilercontrol.commandfile.CompileOnlyTest */ package compiler.compilercontrol.commandfile; diff --git a/hotspot/test/compiler/compilercontrol/commandfile/ExcludeTest.java b/hotspot/test/compiler/compilercontrol/commandfile/ExcludeTest.java index 2b40af6182e..77c2a2e0748 100644 --- a/hotspot/test/compiler/compilercontrol/commandfile/ExcludeTest.java +++ b/hotspot/test/compiler/compilercontrol/commandfile/ExcludeTest.java @@ -29,9 +29,9 @@ * @build compiler.compilercontrol.commandfile.ExcludeTest * pool.sub.* pool.subpack.* sun.hotspot.WhiteBox * compiler.testlibrary.CompilerUtils compiler.compilercontrol.share.actions.* - * @run main ClassFileInstaller sun.hotspot.WhiteBox + * @run driver ClassFileInstaller sun.hotspot.WhiteBox * sun.hotspot.WhiteBox$WhiteBoxPermission - * @run main/othervm compiler.compilercontrol.commandfile.ExcludeTest + * @run driver compiler.compilercontrol.commandfile.ExcludeTest */ package compiler.compilercontrol.commandfile; diff --git a/hotspot/test/compiler/compilercontrol/commandfile/LogTest.java b/hotspot/test/compiler/compilercontrol/commandfile/LogTest.java index a35474235e8..ce45d52b11c 100644 --- a/hotspot/test/compiler/compilercontrol/commandfile/LogTest.java +++ b/hotspot/test/compiler/compilercontrol/commandfile/LogTest.java @@ -29,9 +29,9 @@ * @build compiler.compilercontrol.commandfile.LogTest * pool.sub.* pool.subpack.* sun.hotspot.WhiteBox * compiler.testlibrary.CompilerUtils compiler.compilercontrol.share.actions.* - * @run main ClassFileInstaller sun.hotspot.WhiteBox + * @run driver ClassFileInstaller sun.hotspot.WhiteBox * sun.hotspot.WhiteBox$WhiteBoxPermission - * @run main/othervm compiler.compilercontrol.commandfile.LogTest + * @run driver compiler.compilercontrol.commandfile.LogTest */ package compiler.compilercontrol.commandfile; diff --git a/hotspot/test/compiler/compilercontrol/commandfile/PrintTest.java b/hotspot/test/compiler/compilercontrol/commandfile/PrintTest.java index ede2eb65776..5e90521eabf 100644 --- a/hotspot/test/compiler/compilercontrol/commandfile/PrintTest.java +++ b/hotspot/test/compiler/compilercontrol/commandfile/PrintTest.java @@ -30,9 +30,9 @@ * @build compiler.compilercontrol.commandfile.PrintTest * pool.sub.* pool.subpack.* sun.hotspot.WhiteBox * compiler.testlibrary.CompilerUtils compiler.compilercontrol.share.actions.* - * @run main ClassFileInstaller sun.hotspot.WhiteBox + * @run driver ClassFileInstaller sun.hotspot.WhiteBox * sun.hotspot.WhiteBox$WhiteBoxPermission - * @run main/othervm compiler.compilercontrol.commandfile.PrintTest + * @run driver compiler.compilercontrol.commandfile.PrintTest */ package compiler.compilercontrol.commandfile; diff --git a/hotspot/test/compiler/compilercontrol/commands/CompileOnlyTest.java b/hotspot/test/compiler/compilercontrol/commands/CompileOnlyTest.java index f08fb34e318..7a1b0c1da40 100644 --- a/hotspot/test/compiler/compilercontrol/commands/CompileOnlyTest.java +++ b/hotspot/test/compiler/compilercontrol/commands/CompileOnlyTest.java @@ -29,9 +29,9 @@ * @build compiler.compilercontrol.commands.CompileOnlyTest * pool.sub.* pool.subpack.* sun.hotspot.WhiteBox * compiler.testlibrary.CompilerUtils compiler.compilercontrol.share.actions.* - * @run main ClassFileInstaller sun.hotspot.WhiteBox + * @run driver ClassFileInstaller sun.hotspot.WhiteBox * sun.hotspot.WhiteBox$WhiteBoxPermission - * @run main/othervm compiler.compilercontrol.commands.CompileOnlyTest + * @run driver compiler.compilercontrol.commands.CompileOnlyTest */ package compiler.compilercontrol.commands; diff --git a/hotspot/test/compiler/compilercontrol/commands/ExcludeTest.java b/hotspot/test/compiler/compilercontrol/commands/ExcludeTest.java index 0af19c1a35e..b84befca8c2 100644 --- a/hotspot/test/compiler/compilercontrol/commands/ExcludeTest.java +++ b/hotspot/test/compiler/compilercontrol/commands/ExcludeTest.java @@ -29,9 +29,9 @@ * @build compiler.compilercontrol.commands.ExcludeTest * pool.sub.* pool.subpack.* sun.hotspot.WhiteBox * compiler.testlibrary.CompilerUtils compiler.compilercontrol.share.actions.* - * @run main ClassFileInstaller sun.hotspot.WhiteBox + * @run driver ClassFileInstaller sun.hotspot.WhiteBox * sun.hotspot.WhiteBox$WhiteBoxPermission - * @run main/othervm compiler.compilercontrol.commands.ExcludeTest + * @run driver compiler.compilercontrol.commands.ExcludeTest */ package compiler.compilercontrol.commands; diff --git a/hotspot/test/compiler/compilercontrol/commands/LogTest.java b/hotspot/test/compiler/compilercontrol/commands/LogTest.java index 07a437853cc..4ffebe41a32 100644 --- a/hotspot/test/compiler/compilercontrol/commands/LogTest.java +++ b/hotspot/test/compiler/compilercontrol/commands/LogTest.java @@ -29,9 +29,9 @@ * @build compiler.compilercontrol.commands.LogTest * pool.sub.* pool.subpack.* sun.hotspot.WhiteBox * compiler.testlibrary.CompilerUtils compiler.compilercontrol.share.actions.* - * @run main ClassFileInstaller sun.hotspot.WhiteBox + * @run driver ClassFileInstaller sun.hotspot.WhiteBox * sun.hotspot.WhiteBox$WhiteBoxPermission - * @run main/othervm compiler.compilercontrol.commands.LogTest + * @run driver compiler.compilercontrol.commands.LogTest */ package compiler.compilercontrol.commands; diff --git a/hotspot/test/compiler/compilercontrol/commands/PrintTest.java b/hotspot/test/compiler/compilercontrol/commands/PrintTest.java index eddeadbfbe7..d9ac685ca8f 100644 --- a/hotspot/test/compiler/compilercontrol/commands/PrintTest.java +++ b/hotspot/test/compiler/compilercontrol/commands/PrintTest.java @@ -30,9 +30,9 @@ * @build compiler.compilercontrol.commands.PrintTest * pool.sub.* pool.subpack.* sun.hotspot.WhiteBox * compiler.testlibrary.CompilerUtils compiler.compilercontrol.share.actions.* - * @run main ClassFileInstaller sun.hotspot.WhiteBox + * @run driver ClassFileInstaller sun.hotspot.WhiteBox * sun.hotspot.WhiteBox$WhiteBoxPermission - * @run main/othervm compiler.compilercontrol.commands.PrintTest + * @run driver compiler.compilercontrol.commands.PrintTest */ package compiler.compilercontrol.commands; diff --git a/hotspot/test/compiler/compilercontrol/directives/CompileOnlyTest.java b/hotspot/test/compiler/compilercontrol/directives/CompileOnlyTest.java index bdc3a39f32f..439e5e9505d 100644 --- a/hotspot/test/compiler/compilercontrol/directives/CompileOnlyTest.java +++ b/hotspot/test/compiler/compilercontrol/directives/CompileOnlyTest.java @@ -29,9 +29,9 @@ * @build compiler.compilercontrol.directives.CompileOnlyTest * pool.sub.* pool.subpack.* sun.hotspot.WhiteBox * compiler.testlibrary.CompilerUtils compiler.compilercontrol.share.actions.* - * @run main ClassFileInstaller sun.hotspot.WhiteBox + * @run driver ClassFileInstaller sun.hotspot.WhiteBox * sun.hotspot.WhiteBox$WhiteBoxPermission - * @run main/othervm compiler.compilercontrol.directives.CompileOnlyTest + * @run driver compiler.compilercontrol.directives.CompileOnlyTest */ package compiler.compilercontrol.directives; diff --git a/hotspot/test/compiler/compilercontrol/directives/ExcludeTest.java b/hotspot/test/compiler/compilercontrol/directives/ExcludeTest.java index 44b33dd43c1..0569cdfe323 100644 --- a/hotspot/test/compiler/compilercontrol/directives/ExcludeTest.java +++ b/hotspot/test/compiler/compilercontrol/directives/ExcludeTest.java @@ -29,9 +29,9 @@ * @build compiler.compilercontrol.directives.ExcludeTest * pool.sub.* pool.subpack.* sun.hotspot.WhiteBox * compiler.testlibrary.CompilerUtils compiler.compilercontrol.share.actions.* - * @run main ClassFileInstaller sun.hotspot.WhiteBox + * @run driver ClassFileInstaller sun.hotspot.WhiteBox * sun.hotspot.WhiteBox$WhiteBoxPermission - * @run main/othervm compiler.compilercontrol.directives.ExcludeTest + * @run driver compiler.compilercontrol.directives.ExcludeTest */ package compiler.compilercontrol.directives; diff --git a/hotspot/test/compiler/compilercontrol/directives/LogTest.java b/hotspot/test/compiler/compilercontrol/directives/LogTest.java index 634aee5cb01..1f84d4aea5e 100644 --- a/hotspot/test/compiler/compilercontrol/directives/LogTest.java +++ b/hotspot/test/compiler/compilercontrol/directives/LogTest.java @@ -29,9 +29,9 @@ * @build compiler.compilercontrol.directives.LogTest * pool.sub.* pool.subpack.* sun.hotspot.WhiteBox * compiler.testlibrary.CompilerUtils compiler.compilercontrol.share.actions.* - * @run main ClassFileInstaller sun.hotspot.WhiteBox + * @run driver ClassFileInstaller sun.hotspot.WhiteBox * sun.hotspot.WhiteBox$WhiteBoxPermission - * @run main/othervm compiler.compilercontrol.directives.LogTest + * @run driver compiler.compilercontrol.directives.LogTest */ package compiler.compilercontrol.directives; diff --git a/hotspot/test/compiler/compilercontrol/directives/PrintTest.java b/hotspot/test/compiler/compilercontrol/directives/PrintTest.java index 78ac4de4cee..bbd92c1704b 100644 --- a/hotspot/test/compiler/compilercontrol/directives/PrintTest.java +++ b/hotspot/test/compiler/compilercontrol/directives/PrintTest.java @@ -30,9 +30,9 @@ * @build compiler.compilercontrol.directives.PrintTest * pool.sub.* pool.subpack.* sun.hotspot.WhiteBox * compiler.testlibrary.CompilerUtils compiler.compilercontrol.share.actions.* - * @run main ClassFileInstaller sun.hotspot.WhiteBox + * @run driver ClassFileInstaller sun.hotspot.WhiteBox * sun.hotspot.WhiteBox$WhiteBoxPermission - * @run main/othervm compiler.compilercontrol.directives.PrintTest + * @run driver compiler.compilercontrol.directives.PrintTest */ package compiler.compilercontrol.directives; diff --git a/hotspot/test/compiler/compilercontrol/jcmd/AddAndRemoveTest.java b/hotspot/test/compiler/compilercontrol/jcmd/AddAndRemoveTest.java index 21d7af2efb7..372b50a72b6 100644 --- a/hotspot/test/compiler/compilercontrol/jcmd/AddAndRemoveTest.java +++ b/hotspot/test/compiler/compilercontrol/jcmd/AddAndRemoveTest.java @@ -29,9 +29,9 @@ * @build compiler.compilercontrol.jcmd.AddAndRemoveTest * pool.sub.* pool.subpack.* sun.hotspot.WhiteBox * compiler.testlibrary.CompilerUtils compiler.compilercontrol.share.actions.* - * @run main ClassFileInstaller sun.hotspot.WhiteBox + * @run driver ClassFileInstaller sun.hotspot.WhiteBox * sun.hotspot.WhiteBox$WhiteBoxPermission - * @run main/othervm compiler.compilercontrol.jcmd.AddAndRemoveTest + * @run driver compiler.compilercontrol.jcmd.AddAndRemoveTest */ package compiler.compilercontrol.jcmd; diff --git a/hotspot/test/compiler/compilercontrol/jcmd/AddCompileOnlyTest.java b/hotspot/test/compiler/compilercontrol/jcmd/AddCompileOnlyTest.java index 5f17ad0cc27..5b2a9e26843 100644 --- a/hotspot/test/compiler/compilercontrol/jcmd/AddCompileOnlyTest.java +++ b/hotspot/test/compiler/compilercontrol/jcmd/AddCompileOnlyTest.java @@ -29,9 +29,9 @@ * @build compiler.compilercontrol.jcmd.AddCompileOnlyTest * pool.sub.* pool.subpack.* sun.hotspot.WhiteBox * compiler.testlibrary.CompilerUtils compiler.compilercontrol.share.actions.* - * @run main ClassFileInstaller sun.hotspot.WhiteBox + * @run driver ClassFileInstaller sun.hotspot.WhiteBox * sun.hotspot.WhiteBox$WhiteBoxPermission - * @run main/othervm compiler.compilercontrol.jcmd.AddCompileOnlyTest + * @run driver compiler.compilercontrol.jcmd.AddCompileOnlyTest */ package compiler.compilercontrol.jcmd; diff --git a/hotspot/test/compiler/compilercontrol/jcmd/AddExcludeTest.java b/hotspot/test/compiler/compilercontrol/jcmd/AddExcludeTest.java index c72b6c06e4e..a06c32616d8 100644 --- a/hotspot/test/compiler/compilercontrol/jcmd/AddExcludeTest.java +++ b/hotspot/test/compiler/compilercontrol/jcmd/AddExcludeTest.java @@ -29,9 +29,9 @@ * @build compiler.compilercontrol.jcmd.AddExcludeTest * pool.sub.* pool.subpack.* sun.hotspot.WhiteBox * compiler.testlibrary.CompilerUtils compiler.compilercontrol.share.actions.* - * @run main ClassFileInstaller sun.hotspot.WhiteBox + * @run driver ClassFileInstaller sun.hotspot.WhiteBox * sun.hotspot.WhiteBox$WhiteBoxPermission - * @run main/othervm compiler.compilercontrol.jcmd.AddExcludeTest + * @run driver compiler.compilercontrol.jcmd.AddExcludeTest */ package compiler.compilercontrol.jcmd; diff --git a/hotspot/test/compiler/compilercontrol/jcmd/AddLogTest.java b/hotspot/test/compiler/compilercontrol/jcmd/AddLogTest.java index 900c57978ab..266cf3c5dda 100644 --- a/hotspot/test/compiler/compilercontrol/jcmd/AddLogTest.java +++ b/hotspot/test/compiler/compilercontrol/jcmd/AddLogTest.java @@ -29,9 +29,9 @@ * @build compiler.compilercontrol.jcmd.AddLogTest * pool.sub.* pool.subpack.* sun.hotspot.WhiteBox * compiler.testlibrary.CompilerUtils compiler.compilercontrol.share.actions.* - * @run main ClassFileInstaller sun.hotspot.WhiteBox + * @run driver ClassFileInstaller sun.hotspot.WhiteBox * sun.hotspot.WhiteBox$WhiteBoxPermission - * @run main/othervm compiler.compilercontrol.jcmd.AddLogTest + * @run driver compiler.compilercontrol.jcmd.AddLogTest */ package compiler.compilercontrol.jcmd; diff --git a/hotspot/test/compiler/compilercontrol/jcmd/AddPrintAssemblyTest.java b/hotspot/test/compiler/compilercontrol/jcmd/AddPrintAssemblyTest.java index 8f9c0250138..9697711c294 100644 --- a/hotspot/test/compiler/compilercontrol/jcmd/AddPrintAssemblyTest.java +++ b/hotspot/test/compiler/compilercontrol/jcmd/AddPrintAssemblyTest.java @@ -30,9 +30,9 @@ * @build compiler.compilercontrol.jcmd.AddPrintAssemblyTest * pool.sub.* pool.subpack.* sun.hotspot.WhiteBox * compiler.testlibrary.CompilerUtils compiler.compilercontrol.share.actions.* - * @run main ClassFileInstaller sun.hotspot.WhiteBox + * @run driver ClassFileInstaller sun.hotspot.WhiteBox * sun.hotspot.WhiteBox$WhiteBoxPermission - * @run main/othervm compiler.compilercontrol.jcmd.AddPrintAssemblyTest + * @run driver compiler.compilercontrol.jcmd.AddPrintAssemblyTest */ package compiler.compilercontrol.jcmd; diff --git a/hotspot/test/compiler/compilercontrol/jcmd/ClearDirectivesFileStackTest.java b/hotspot/test/compiler/compilercontrol/jcmd/ClearDirectivesFileStackTest.java index 25966f9f726..da1fef49141 100644 --- a/hotspot/test/compiler/compilercontrol/jcmd/ClearDirectivesFileStackTest.java +++ b/hotspot/test/compiler/compilercontrol/jcmd/ClearDirectivesFileStackTest.java @@ -30,9 +30,9 @@ * @build compiler.compilercontrol.jcmd.ClearDirectivesFileStackTest * pool.sub.* pool.subpack.* sun.hotspot.WhiteBox * compiler.testlibrary.CompilerUtils compiler.compilercontrol.share.actions.* - * @run main ClassFileInstaller sun.hotspot.WhiteBox + * @run driver ClassFileInstaller sun.hotspot.WhiteBox * sun.hotspot.WhiteBox$WhiteBoxPermission - * @run main/othervm compiler.compilercontrol.jcmd.ClearDirectivesFileStackTest + * @run driver compiler.compilercontrol.jcmd.ClearDirectivesFileStackTest */ package compiler.compilercontrol.jcmd; diff --git a/hotspot/test/compiler/compilercontrol/jcmd/ClearDirectivesStackTest.java b/hotspot/test/compiler/compilercontrol/jcmd/ClearDirectivesStackTest.java index f9f382da110..c9d9f8dcfd0 100644 --- a/hotspot/test/compiler/compilercontrol/jcmd/ClearDirectivesStackTest.java +++ b/hotspot/test/compiler/compilercontrol/jcmd/ClearDirectivesStackTest.java @@ -29,9 +29,9 @@ * @build compiler.compilercontrol.jcmd.ClearDirectivesStackTest * pool.sub.* pool.subpack.* sun.hotspot.WhiteBox * compiler.testlibrary.CompilerUtils compiler.compilercontrol.share.actions.* - * @run main ClassFileInstaller sun.hotspot.WhiteBox + * @run driver ClassFileInstaller sun.hotspot.WhiteBox * sun.hotspot.WhiteBox$WhiteBoxPermission - * @run main/othervm compiler.compilercontrol.jcmd.ClearDirectivesStackTest + * @run driver compiler.compilercontrol.jcmd.ClearDirectivesStackTest */ package compiler.compilercontrol.jcmd; diff --git a/hotspot/test/compiler/compilercontrol/jcmd/PrintDirectivesTest.java b/hotspot/test/compiler/compilercontrol/jcmd/PrintDirectivesTest.java index 5821de76d75..7afd4d6f8b3 100644 --- a/hotspot/test/compiler/compilercontrol/jcmd/PrintDirectivesTest.java +++ b/hotspot/test/compiler/compilercontrol/jcmd/PrintDirectivesTest.java @@ -30,9 +30,9 @@ * @build compiler.compilercontrol.jcmd.PrintDirectivesTest * pool.sub.* pool.subpack.* sun.hotspot.WhiteBox * compiler.testlibrary.CompilerUtils compiler.compilercontrol.share.actions.* - * @run main ClassFileInstaller sun.hotspot.WhiteBox + * @run driver ClassFileInstaller sun.hotspot.WhiteBox * sun.hotspot.WhiteBox$WhiteBoxPermission - * @run main/othervm compiler.compilercontrol.jcmd.PrintDirectivesTest + * @run driver compiler.compilercontrol.jcmd.PrintDirectivesTest */ package compiler.compilercontrol.jcmd; diff --git a/hotspot/test/compiler/compilercontrol/jcmd/StressAddMultiThreadedTest.java b/hotspot/test/compiler/compilercontrol/jcmd/StressAddMultiThreadedTest.java index 5bf1464fd55..26c225380ac 100644 --- a/hotspot/test/compiler/compilercontrol/jcmd/StressAddMultiThreadedTest.java +++ b/hotspot/test/compiler/compilercontrol/jcmd/StressAddMultiThreadedTest.java @@ -31,7 +31,7 @@ * pool.sub.* pool.subpack.* sun.hotspot.WhiteBox * compiler.testlibrary.CompilerUtils * compiler.compilercontrol.share.actions.* - * @run main ClassFileInstaller sun.hotspot.WhiteBox + * @run driver ClassFileInstaller sun.hotspot.WhiteBox * sun.hotspot.WhiteBox$WhiteBoxPermission * @run driver compiler.compilercontrol.jcmd.StressAddMultiThreadedTest */ diff --git a/hotspot/test/compiler/compilercontrol/matcher/MethodMatcherTest.java b/hotspot/test/compiler/compilercontrol/matcher/MethodMatcherTest.java index 00ca74d108d..87cd26a8958 100644 --- a/hotspot/test/compiler/compilercontrol/matcher/MethodMatcherTest.java +++ b/hotspot/test/compiler/compilercontrol/matcher/MethodMatcherTest.java @@ -42,7 +42,7 @@ import java.util.regex.Pattern; * @summary Tests CompilerCommand's method matcher * @library /testlibrary /test/lib /compiler/whitebox ../share / * @build compiler.compilercontrol.matcher.MethodMatcherTest - * @run main ClassFileInstaller sun.hotspot.WhiteBox + * @run driver ClassFileInstaller sun.hotspot.WhiteBox * sun.hotspot.WhiteBox$WhiteBoxPermission * @run main/othervm -Xbootclasspath/a:. -XX:+UnlockDiagnosticVMOptions * -XX:+WhiteBoxAPI compiler.compilercontrol.matcher.MethodMatcherTest diff --git a/hotspot/test/compiler/compilercontrol/mixed/RandomCommandsTest.java b/hotspot/test/compiler/compilercontrol/mixed/RandomCommandsTest.java index 13df53afdfe..c954dba9011 100644 --- a/hotspot/test/compiler/compilercontrol/mixed/RandomCommandsTest.java +++ b/hotspot/test/compiler/compilercontrol/mixed/RandomCommandsTest.java @@ -29,9 +29,9 @@ * @build compiler.compilercontrol.mixed.RandomCommandsTest * pool.sub.* pool.subpack.* sun.hotspot.WhiteBox * compiler.testlibrary.CompilerUtils compiler.compilercontrol.share.actions.* - * @run main ClassFileInstaller sun.hotspot.WhiteBox + * @run driver ClassFileInstaller sun.hotspot.WhiteBox * sun.hotspot.WhiteBox$WhiteBoxPermission - * @run main/othervm/timeout=600 compiler.compilercontrol.mixed.RandomCommandsTest + * @run driver/timeout=600 compiler.compilercontrol.mixed.RandomCommandsTest */ package compiler.compilercontrol.mixed; diff --git a/hotspot/test/compiler/compilercontrol/mixed/RandomValidCommandsTest.java b/hotspot/test/compiler/compilercontrol/mixed/RandomValidCommandsTest.java index 7b837e672c5..e8739e8abde 100644 --- a/hotspot/test/compiler/compilercontrol/mixed/RandomValidCommandsTest.java +++ b/hotspot/test/compiler/compilercontrol/mixed/RandomValidCommandsTest.java @@ -30,7 +30,7 @@ * @build compiler.compilercontrol.mixed.RandomValidCommandsTest * pool.sub.* pool.subpack.* sun.hotspot.WhiteBox * compiler.testlibrary.CompilerUtils compiler.compilercontrol.share.actions.* - * @run main ClassFileInstaller sun.hotspot.WhiteBox + * @run driver ClassFileInstaller sun.hotspot.WhiteBox * sun.hotspot.WhiteBox$WhiteBoxPermission * @run main/othervm/timeout=600 compiler.compilercontrol.mixed.RandomValidCommandsTest */ diff --git a/hotspot/test/compiler/compilercontrol/share/MultiCommand.java b/hotspot/test/compiler/compilercontrol/share/MultiCommand.java index 8072e5b712b..f85591da663 100644 --- a/hotspot/test/compiler/compilercontrol/share/MultiCommand.java +++ b/hotspot/test/compiler/compilercontrol/share/MultiCommand.java @@ -72,6 +72,7 @@ public class MultiCommand extends AbstractTestBase { @Override public void test() { Scenario.Builder builder = Scenario.getBuilder(); + builder.addFlag("-Xmixed"); for (CompileCommand cc : testCases) { cc.print(); builder.add(cc); diff --git a/hotspot/test/compiler/compilercontrol/share/scenario/Scenario.java b/hotspot/test/compiler/compilercontrol/share/scenario/Scenario.java index 49109151d82..a2408da7fbb 100644 --- a/hotspot/test/compiler/compilercontrol/share/scenario/Scenario.java +++ b/hotspot/test/compiler/compilercontrol/share/scenario/Scenario.java @@ -200,6 +200,7 @@ public final class Scenario { private final List jcmdCommands = new ArrayList<>(); public Builder() { + addFlag("-Xmixed"); builders.put(Type.FILE, new CommandFileBuilder(Type.FILE.fileName)); builders.put(Type.OPTION, new CommandOptionsBuilder()); builders.put(Type.DIRECTIVE, new DirectiveBuilder( From 4333fe028fb56e7c5004b14d3bf6218f46f7bc3c Mon Sep 17 00:00:00 2001 From: Sergey Bylokhov Date: Wed, 16 Mar 2016 15:36:06 +0300 Subject: [PATCH 027/162] 8151857: [TEST_BUG] bug6544309.java fails intermittently Reviewed-by: yan, avstepan --- .../swing/JPopupMenu/6544309/bug6544309.java | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/jdk/test/javax/swing/JPopupMenu/6544309/bug6544309.java b/jdk/test/javax/swing/JPopupMenu/6544309/bug6544309.java index ee30642f069..f0c76a48712 100644 --- a/jdk/test/javax/swing/JPopupMenu/6544309/bug6544309.java +++ b/jdk/test/javax/swing/JPopupMenu/6544309/bug6544309.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2011, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -30,9 +30,14 @@ @run main bug6544309 */ -import javax.swing.*; -import java.awt.event.*; -import java.awt.*; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.KeyEvent; + +import javax.swing.JDialog; +import javax.swing.JMenuItem; +import javax.swing.JPopupMenu; +import javax.swing.SwingUtilities; public class bug6544309 { private JDialog dialog; @@ -41,6 +46,8 @@ public class bug6544309 { public static void main(String[] args) throws Exception { robot = new ExtendedRobot(); + // move mouse outside menu to prevent auto selection + robot.mouseMove(100,100); final bug6544309 test = new bug6544309(); try { SwingUtilities.invokeAndWait(new Runnable() { From aa5097cc9d8f04241dd90ff6b9010d2c353f9166 Mon Sep 17 00:00:00 2001 From: Sergey Bylokhov Date: Wed, 16 Mar 2016 15:55:27 +0300 Subject: [PATCH 028/162] 8146239: Support of PCM_FLOAT for the AU file format Reviewed-by: amenkov --- .../com/sun/media/sound/AuFileFormat.java | 35 +++--- .../com/sun/media/sound/AuFileReader.java | 80 ++++++------- .../com/sun/media/sound/AuFileWriter.java | 113 +++++------------- 3 files changed, 90 insertions(+), 138 deletions(-) diff --git a/jdk/src/java.desktop/share/classes/com/sun/media/sound/AuFileFormat.java b/jdk/src/java.desktop/share/classes/com/sun/media/sound/AuFileFormat.java index 7a8c5bc6a68..7a91bfc0a75 100644 --- a/jdk/src/java.desktop/share/classes/com/sun/media/sound/AuFileFormat.java +++ b/jdk/src/java.desktop/share/classes/com/sun/media/sound/AuFileFormat.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -45,11 +45,12 @@ final class AuFileFormat extends AudioFileFormat { static final int AU_LINEAR_24 = 4; /* 24-bit linear PCM */ static final int AU_LINEAR_32 = 5; /* 32-bit linear PCM */ static final int AU_FLOAT = 6; /* 32-bit IEEE floating point */ - static final int AU_DOUBLE = 7; /* 64-bit IEEE floating point */ - static final int AU_ADPCM_G721 = 23; /* 4-bit CCITT g.721 ADPCM */ - static final int AU_ADPCM_G722 = 24; /* CCITT g.722 ADPCM */ - static final int AU_ADPCM_G723_3 = 25; /* CCITT g.723 3-bit ADPCM */ - static final int AU_ADPCM_G723_5 = 26; /* CCITT g.723 5-bit ADPCM */ +// we don't support these ... +// static final int AU_DOUBLE = 7; /* 64-bit IEEE floating point */ +// static final int AU_ADPCM_G721 = 23; /* 4-bit CCITT g.721 ADPCM */ +// static final int AU_ADPCM_G722 = 24; /* CCITT g.722 ADPCM */ +// static final int AU_ADPCM_G723_3 = 25; /* CCITT g.723 3-bit ADPCM */ +// static final int AU_ADPCM_G723_5 = 26; /* CCITT g.723 5-bit ADPCM */ static final int AU_ALAW_8 = 27; /* 8-bit ISDN A-law */ static final int AU_HEADERSIZE = 24; @@ -64,24 +65,28 @@ final class AuFileFormat extends AudioFileFormat { auType = -1; - if( AudioFormat.Encoding.ALAW.equals(encoding) ) { - if( format.getSampleSizeInBits()==8 ) { + if (AudioFormat.Encoding.ALAW.equals(encoding)) { + if (format.getSampleSizeInBits() == 8) { auType = AU_ALAW_8; } - } else if( AudioFormat.Encoding.ULAW.equals(encoding) ) { - if( format.getSampleSizeInBits()==8 ) { + } else if (AudioFormat.Encoding.ULAW.equals(encoding)) { + if (format.getSampleSizeInBits() == 8) { auType = AU_ULAW_8; } - } else if( AudioFormat.Encoding.PCM_SIGNED.equals(encoding) ) { - if( format.getSampleSizeInBits()==8 ) { + } else if (AudioFormat.Encoding.PCM_SIGNED.equals(encoding)) { + if (format.getSampleSizeInBits() == 8) { auType = AU_LINEAR_8; - } else if( format.getSampleSizeInBits()==16 ) { + } else if (format.getSampleSizeInBits() == 16) { auType = AU_LINEAR_16; - } else if( format.getSampleSizeInBits()==24 ) { + } else if (format.getSampleSizeInBits() == 24) { auType = AU_LINEAR_24; - } else if( format.getSampleSizeInBits()==32 ) { + } else if (format.getSampleSizeInBits() == 32) { auType = AU_LINEAR_32; } + } else if (AudioFormat.Encoding.PCM_FLOAT.equals(encoding)) { + if (format.getSampleSizeInBits() == 32) { + auType = AU_FLOAT; + } } } diff --git a/jdk/src/java.desktop/share/classes/com/sun/media/sound/AuFileReader.java b/jdk/src/java.desktop/share/classes/com/sun/media/sound/AuFileReader.java index 180f45c9076..876c3b78e80 100644 --- a/jdk/src/java.desktop/share/classes/com/sun/media/sound/AuFileReader.java +++ b/jdk/src/java.desktop/share/classes/com/sun/media/sound/AuFileReader.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -30,6 +30,7 @@ import java.io.IOException; import java.io.InputStream; import javax.sound.sampled.AudioFileFormat; +import javax.sound.sampled.AudioFileFormat.Type; import javax.sound.sampled.AudioFormat; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.UnsupportedAudioFileException; @@ -56,7 +57,7 @@ public final class AuFileReader extends SunFileReader { final int headerSize = dis.readInt(); final int dataSize = dis.readInt(); - final int encoding_local = dis.readInt(); + final int auType = dis.readInt(); final int sampleRate = dis.readInt(); final int channels = dis.readInt(); if (channels <= 0) { @@ -65,40 +66,38 @@ public final class AuFileReader extends SunFileReader { final int sampleSizeInBits; final AudioFormat.Encoding encoding; - switch (encoding_local) { - case AuFileFormat.AU_ULAW_8: - encoding = AudioFormat.Encoding.ULAW; - sampleSizeInBits = 8; - break; - case AuFileFormat.AU_ALAW_8: - encoding = AudioFormat.Encoding.ALAW; - sampleSizeInBits = 8; - break; - case AuFileFormat.AU_LINEAR_8: - // $$jb: 04.29.99: 8bit linear is *signed*, not *unsigned* - encoding = AudioFormat.Encoding.PCM_SIGNED; - sampleSizeInBits = 8; - break; - case AuFileFormat.AU_LINEAR_16: - encoding = AudioFormat.Encoding.PCM_SIGNED; - sampleSizeInBits = 16; - break; - case AuFileFormat.AU_LINEAR_24: - encoding = AudioFormat.Encoding.PCM_SIGNED; - - sampleSizeInBits = 24; - break; - case AuFileFormat.AU_LINEAR_32: - encoding = AudioFormat.Encoding.PCM_SIGNED; - - sampleSizeInBits = 32; - break; - // $jb: 03.19.99: we don't support these ... - /* case AuFileFormat.AU_FLOAT: - encoding = new AudioFormat.FLOAT; - sampleSizeInBits = 32; - break; - case AuFileFormat.AU_DOUBLE: + switch (auType) { + case AuFileFormat.AU_ULAW_8: + encoding = AudioFormat.Encoding.ULAW; + sampleSizeInBits = 8; + break; + case AuFileFormat.AU_ALAW_8: + encoding = AudioFormat.Encoding.ALAW; + sampleSizeInBits = 8; + break; + case AuFileFormat.AU_LINEAR_8: + // $$jb: 04.29.99: 8bit linear is *signed*, not *unsigned* + encoding = AudioFormat.Encoding.PCM_SIGNED; + sampleSizeInBits = 8; + break; + case AuFileFormat.AU_LINEAR_16: + encoding = AudioFormat.Encoding.PCM_SIGNED; + sampleSizeInBits = 16; + break; + case AuFileFormat.AU_LINEAR_24: + encoding = AudioFormat.Encoding.PCM_SIGNED; + sampleSizeInBits = 24; + break; + case AuFileFormat.AU_LINEAR_32: + encoding = AudioFormat.Encoding.PCM_SIGNED; + sampleSizeInBits = 32; + break; + case AuFileFormat.AU_FLOAT: + encoding = AudioFormat.Encoding.PCM_FLOAT; + sampleSizeInBits = 32; + break; + // we don't support these ... + /* case AuFileFormat.AU_DOUBLE: encoding = new AudioFormat.DOUBLE; sampleSizeInBits = 8; break; @@ -117,9 +116,9 @@ public final class AuFileReader extends SunFileReader { SamplePerUnit = 8; break; */ - default: - // unsupported filetype, throw exception - throw new UnsupportedAudioFileException("not a valid AU file"); + default: + // unsupported filetype, throw exception + throw new UnsupportedAudioFileException("not a valid AU file"); } final int frameSize = calculatePCMFrameSize(sampleSizeInBits, channels); @@ -136,7 +135,6 @@ public final class AuFileReader extends SunFileReader { final AudioFormat format = new AudioFormat(encoding, sampleRate, sampleSizeInBits, channels, frameSize, sampleRate, true); - return new AuFileFormat(AudioFileFormat.Type.AU, dataSize + headerSize, - format, length); + return new AuFileFormat(Type.AU, dataSize + headerSize, format, length); } } diff --git a/jdk/src/java.desktop/share/classes/com/sun/media/sound/AuFileWriter.java b/jdk/src/java.desktop/share/classes/com/sun/media/sound/AuFileWriter.java index b498c916435..723ffcd2c42 100644 --- a/jdk/src/java.desktop/share/classes/com/sun/media/sound/AuFileWriter.java +++ b/jdk/src/java.desktop/share/classes/com/sun/media/sound/AuFileWriter.java @@ -39,6 +39,7 @@ import java.io.SequenceInputStream; import java.util.Objects; import javax.sound.sampled.AudioFileFormat; +import javax.sound.sampled.AudioFileFormat.Type; import javax.sound.sampled.AudioFormat; import javax.sound.sampled.AudioInputStream; import javax.sound.sampled.AudioSystem; @@ -59,32 +60,32 @@ public final class AuFileWriter extends SunFileWriter { * Constructs a new AuFileWriter object. */ public AuFileWriter() { - super(new AudioFileFormat.Type[]{AudioFileFormat.Type.AU}); + super(new Type[]{Type.AU}); } @Override - public AudioFileFormat.Type[] getAudioFileTypes(AudioInputStream stream) { + public Type[] getAudioFileTypes(AudioInputStream stream) { - AudioFileFormat.Type[] filetypes = new AudioFileFormat.Type[types.length]; + Type[] filetypes = new Type[types.length]; System.arraycopy(types, 0, filetypes, 0, types.length); // make sure we can write this stream AudioFormat format = stream.getFormat(); AudioFormat.Encoding encoding = format.getEncoding(); - if( (AudioFormat.Encoding.ALAW.equals(encoding)) || - (AudioFormat.Encoding.ULAW.equals(encoding)) || - (AudioFormat.Encoding.PCM_SIGNED.equals(encoding)) || - (AudioFormat.Encoding.PCM_UNSIGNED.equals(encoding)) ) { - + if (AudioFormat.Encoding.ALAW.equals(encoding) + || AudioFormat.Encoding.ULAW.equals(encoding) + || AudioFormat.Encoding.PCM_SIGNED.equals(encoding) + || AudioFormat.Encoding.PCM_UNSIGNED.equals(encoding) + || AudioFormat.Encoding.PCM_FLOAT.equals(encoding)) { return filetypes; } - return new AudioFileFormat.Type[0]; + return new Type[0]; } @Override - public int write(AudioInputStream stream, AudioFileFormat.Type fileType, OutputStream out) throws IOException { + public int write(AudioInputStream stream, Type fileType, OutputStream out) throws IOException { Objects.requireNonNull(stream); Objects.requireNonNull(fileType); Objects.requireNonNull(out); @@ -101,7 +102,7 @@ public final class AuFileWriter extends SunFileWriter { } @Override - public int write(AudioInputStream stream, AudioFileFormat.Type fileType, File out) throws IOException { + public int write(AudioInputStream stream, Type fileType, File out) throws IOException { Objects.requireNonNull(stream); Objects.requireNonNull(fileType); Objects.requireNonNull(out); @@ -141,61 +142,35 @@ public final class AuFileWriter extends SunFileWriter { * Returns the AudioFileFormat describing the file that will be written from this AudioInputStream. * Throws IllegalArgumentException if not supported. */ - private AudioFileFormat getAudioFileFormat(AudioFileFormat.Type type, AudioInputStream stream) { + private AudioFileFormat getAudioFileFormat(Type type, AudioInputStream stream) { if (!isFileTypeSupported(type, stream)) { throw new IllegalArgumentException("File type " + type + " not supported."); } - AudioFormat format = null; - AuFileFormat fileFormat = null; - AudioFormat.Encoding encoding = AudioFormat.Encoding.PCM_SIGNED; - AudioFormat streamFormat = stream.getFormat(); - AudioFormat.Encoding streamEncoding = streamFormat.getEncoding(); - - - int sampleSizeInBits; - int fileSize; - - if( (AudioFormat.Encoding.ALAW.equals(streamEncoding)) || - (AudioFormat.Encoding.ULAW.equals(streamEncoding)) ) { - - encoding = streamEncoding; - sampleSizeInBits = streamFormat.getSampleSizeInBits(); - - } else if ( streamFormat.getSampleSizeInBits()==8 ) { + AudioFormat.Encoding encoding = streamFormat.getEncoding(); + if (AudioFormat.Encoding.PCM_UNSIGNED.equals(encoding)) { encoding = AudioFormat.Encoding.PCM_SIGNED; - sampleSizeInBits=8; - - } else { - - encoding = AudioFormat.Encoding.PCM_SIGNED; - sampleSizeInBits=streamFormat.getSampleSizeInBits(); } + // We always write big endian au files, this is by far the standard + AudioFormat format = new AudioFormat(encoding, + streamFormat.getSampleRate(), + streamFormat.getSampleSizeInBits(), + streamFormat.getChannels(), + streamFormat.getFrameSize(), + streamFormat.getFrameRate(), true); - format = new AudioFormat( encoding, - streamFormat.getSampleRate(), - sampleSizeInBits, - streamFormat.getChannels(), - streamFormat.getFrameSize(), - streamFormat.getFrameRate(), - true); // AU is always big endian - - - if( stream.getFrameLength()!=AudioSystem.NOT_SPECIFIED ) { + int fileSize; + if (stream.getFrameLength() != AudioSystem.NOT_SPECIFIED) { fileSize = (int)stream.getFrameLength()*streamFormat.getFrameSize() + AuFileFormat.AU_HEADERSIZE; } else { fileSize = AudioSystem.NOT_SPECIFIED; } - fileFormat = new AuFileFormat( AudioFileFormat.Type.AU, - fileSize, - format, - (int)stream.getFrameLength() ); - - return fileFormat; + return new AuFileFormat(Type.AU, fileSize, format, + (int) stream.getFrameLength()); } private InputStream getFileStream(AuFileFormat auFileFormat, AudioInputStream audioStream) throws IOException { @@ -212,7 +187,7 @@ public final class AuFileWriter extends SunFileWriter { if (dataSizeInBytes>0x7FFFFFFFl) { dataSizeInBytes=UNKNOWN_SIZE; } - int encoding_local = auFileFormat.getAuType(); + int auType = auFileFormat.getAuType(); int sampleRate = (int)format.getSampleRate(); int channels = format.getChannels(); @@ -222,43 +197,17 @@ public final class AuFileWriter extends SunFileWriter { DataOutputStream dos = null; SequenceInputStream auStream = null; - AudioFormat audioStreamFormat = null; - AudioFormat.Encoding encoding = null; - InputStream codedAudioStream = audioStream; - - // if we need to do any format conversion, do it here. - - codedAudioStream = audioStream; - - audioStreamFormat = audioStream.getFormat(); - encoding = audioStreamFormat.getEncoding(); - + // if we need to do any format conversion, we do it here. //$$ fb 2001-07-13: Bug 4391108 - if( (AudioFormat.Encoding.PCM_UNSIGNED.equals(encoding)) || - (AudioFormat.Encoding.PCM_SIGNED.equals(encoding) - && !audioStreamFormat.isBigEndian()) ) { - // We always write big endian au files, this is by far the standard - codedAudioStream = AudioSystem.getAudioInputStream( new AudioFormat ( - AudioFormat.Encoding.PCM_SIGNED, - audioStreamFormat.getSampleRate(), - audioStreamFormat.getSampleSizeInBits(), - audioStreamFormat.getChannels(), - audioStreamFormat.getFrameSize(), - audioStreamFormat.getFrameRate(), - true), - audioStream ); - - - } + audioStream = AudioSystem.getAudioInputStream(format, audioStream); baos = new ByteArrayOutputStream(); dos = new DataOutputStream(baos); - dos.writeInt(AuFileFormat.AU_SUN_MAGIC); dos.writeInt(headerSize); dos.writeInt((int)dataSizeInBytes); - dos.writeInt(encoding_local); + dos.writeInt(auType); dos.writeInt(sampleRate); dos.writeInt(channels); @@ -269,7 +218,7 @@ public final class AuFileWriter extends SunFileWriter { header = baos.toByteArray(); headerStream = new ByteArrayInputStream( header ); auStream = new SequenceInputStream(headerStream, - new NoCloseInputStream(codedAudioStream)); + new NoCloseInputStream(audioStream)); return auStream; } From 8147c0ae94537a322dab28d763eb460f887f5833 Mon Sep 17 00:00:00 2001 From: Prasanta Sadhukhan Date: Thu, 17 Mar 2016 11:23:31 +0530 Subject: [PATCH 029/162] 6379088: Suboptimal expression in javax.imageio.ImageTypeSpecifier.getBitsPerBand(int) Reviewed-by: prr, serb, jdv --- .../share/classes/javax/imageio/ImageTypeSpecifier.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/jdk/src/java.desktop/share/classes/javax/imageio/ImageTypeSpecifier.java b/jdk/src/java.desktop/share/classes/javax/imageio/ImageTypeSpecifier.java index 82e6e1a8756..e50958f1757 100644 --- a/jdk/src/java.desktop/share/classes/javax/imageio/ImageTypeSpecifier.java +++ b/jdk/src/java.desktop/share/classes/javax/imageio/ImageTypeSpecifier.java @@ -997,7 +997,7 @@ public class ImageTypeSpecifier { * negative or greater than the largest band index. */ public int getBitsPerBand(int band) { - if (band < 0 | band >= getNumBands()) { + if (band < 0 || band >= getNumBands()) { throw new IllegalArgumentException("band out of range!"); } return sampleModel.getSampleSize(band); From 42ba4188b0e5e230c2c7f59588bee2733d0c5bd7 Mon Sep 17 00:00:00 2001 From: Tobias Hartmann Date: Thu, 17 Mar 2016 09:41:46 +0100 Subject: [PATCH 030/162] 8151882: -XX:+Verbose prints messages even if no other flag is set We should only print messages if PrintOpto && WizardMode is set. Reviewed-by: kvn, neliasso --- hotspot/src/share/vm/opto/reg_split.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/hotspot/src/share/vm/opto/reg_split.cpp b/hotspot/src/share/vm/opto/reg_split.cpp index 5e14b9d5abc..781a53cc00b 100644 --- a/hotspot/src/share/vm/opto/reg_split.cpp +++ b/hotspot/src/share/vm/opto/reg_split.cpp @@ -287,7 +287,7 @@ uint PhaseChaitin::split_USE(MachSpillCopyNode::SpillType spill_type, Node *def, Node* clone_node(Node* def, Block *b, Compile* C) { if (def->needs_anti_dependence_check()) { #ifdef ASSERT - if (Verbose) { + if (PrintOpto && WizardMode) { tty->print_cr("RA attempts to clone node with anti_dependence:"); def->dump(-1); tty->cr(); tty->print_cr("into block:"); From 2b48dbfd93326ed5b7ee6339e270a3857da06913 Mon Sep 17 00:00:00 2001 From: Tom Rodriguez Date: Thu, 17 Mar 2016 12:04:04 -0700 Subject: [PATCH 031/162] 8151874: [JVMCI] canInlineMethod should check is_not_compilable for correct CompLevel Reviewed-by: twisti --- hotspot/src/share/vm/jvmci/jvmciCompilerToVM.cpp | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/hotspot/src/share/vm/jvmci/jvmciCompilerToVM.cpp b/hotspot/src/share/vm/jvmci/jvmciCompilerToVM.cpp index a444c909e9e..eae731ca7cf 100644 --- a/hotspot/src/share/vm/jvmci/jvmciCompilerToVM.cpp +++ b/hotspot/src/share/vm/jvmci/jvmciCompilerToVM.cpp @@ -448,7 +448,10 @@ C2V_END C2V_VMENTRY(jboolean, canInlineMethod,(JNIEnv *, jobject, jobject jvmci_method)) methodHandle method = CompilerToVM::asMethod(jvmci_method); - return !method->is_not_compilable() && !CompilerOracle::should_not_inline(method) && !method->dont_inline(); + // In hosted mode ignore the not_compilable flags since they are never set by + // the JVMCI compiler. + bool is_compilable = UseJVMCICompiler ? !method->is_not_compilable(CompLevel_full_optimization) : true; + return is_compilable && !CompilerOracle::should_not_inline(method) && !method->dont_inline(); C2V_END C2V_VMENTRY(jboolean, shouldInlineMethod,(JNIEnv *, jobject, jobject jvmci_method)) From 338ff211b42ccfcdda2a9d7823a2b34e39ff4f72 Mon Sep 17 00:00:00 2001 From: Nils Eliasson Date: Thu, 17 Mar 2016 21:55:55 +0100 Subject: [PATCH 032/162] 8152090: Code missing from JDK-8150054 causing many test failures Add missing method Reviewed-by: kvn --- .../compiler/compilercontrol/share/scenario/Scenario.java | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/hotspot/test/compiler/compilercontrol/share/scenario/Scenario.java b/hotspot/test/compiler/compilercontrol/share/scenario/Scenario.java index a2408da7fbb..505f36e7272 100644 --- a/hotspot/test/compiler/compilercontrol/share/scenario/Scenario.java +++ b/hotspot/test/compiler/compilercontrol/share/scenario/Scenario.java @@ -208,6 +208,10 @@ public final class Scenario { jcmdStateBuilder = new JcmdStateBuilder(Type.JCMD.fileName); } + public void addFlag(String flag) { + vmopts.add(flag); + } + public void add(CompileCommand compileCommand) { String[] vmOptions = compileCommand.command.vmOpts; Collections.addAll(vmopts, vmOptions); From ba7e4da495c96261926ae88d9c492ee5963abdad Mon Sep 17 00:00:00 2001 From: Tobias Hartmann Date: Fri, 18 Mar 2016 09:32:29 +0100 Subject: [PATCH 033/162] 8023191: OSR nmethods should be flushed to free space in CodeCache Treat OSR nmethods like normal nmethods and flush them if they are cold/unused. Reviewed-by: kvn --- hotspot/src/share/vm/code/nmethod.cpp | 31 +++++---- hotspot/src/share/vm/code/nmethod.hpp | 17 ++++- hotspot/src/share/vm/oops/instanceKlass.cpp | 7 +- hotspot/src/share/vm/oops/instanceKlass.hpp | 2 +- hotspot/src/share/vm/runtime/sweeper.cpp | 75 +++++++++++++-------- hotspot/src/share/vm/runtime/sweeper.hpp | 8 +-- 6 files changed, 90 insertions(+), 50 deletions(-) diff --git a/hotspot/src/share/vm/code/nmethod.cpp b/hotspot/src/share/vm/code/nmethod.cpp index 46fe64850e4..204a225eb47 100644 --- a/hotspot/src/share/vm/code/nmethod.cpp +++ b/hotspot/src/share/vm/code/nmethod.cpp @@ -1387,9 +1387,17 @@ void nmethod::make_unloaded(BoolObjectClosure* is_alive, oop cause) { void nmethod::invalidate_osr_method() { assert(_entry_bci != InvocationEntryBci, "wrong kind of nmethod"); +#ifndef ASSERT + // Make sure osr nmethod is invalidated only once + if (!is_in_use()) { + return; + } +#endif // Remove from list of active nmethods - if (method() != NULL) - method()->method_holder()->remove_osr_nmethod(this); + if (method() != NULL) { + bool removed = method()->method_holder()->remove_osr_nmethod(this); + assert(!removed || is_in_use(), "unused osr nmethod should be invalidated"); + } } void nmethod::log_state_change() const { @@ -1510,7 +1518,7 @@ bool nmethod::make_not_entrant_or_zombie(unsigned int state) { // happens or they get unloaded. if (state == zombie) { { - // Flushing dependecies must be done before any possible + // Flushing dependencies must be done before any possible // safepoint can sneak in, otherwise the oops used by the // dependency logic could have become stale. MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag); @@ -1526,7 +1534,7 @@ bool nmethod::make_not_entrant_or_zombie(unsigned int state) { // zombie only - if a JVMTI agent has enabled the CompiledMethodUnload // event and it hasn't already been reported for this nmethod then - // report it now. The event may have been reported earilier if the GC + // report it now. The event may have been reported earlier if the GC // marked it for unloading). JvmtiDeferredEventQueue support means // we no longer go to a safepoint here. post_compiled_method_unload(); @@ -1554,8 +1562,10 @@ bool nmethod::make_not_entrant_or_zombie(unsigned int state) { void nmethod::flush() { // Note that there are no valid oops in the nmethod anymore. - assert(is_zombie() || (is_osr_method() && is_unloaded()), "must be a zombie method"); - assert(is_marked_for_reclamation() || (is_osr_method() && is_unloaded()), "must be marked for reclamation"); + assert(!is_osr_method() || is_unloaded() || is_zombie(), + "osr nmethod must be unloaded or zombie before flushing"); + assert(is_zombie() || is_osr_method(), "must be a zombie method"); + assert(is_marked_for_reclamation() || is_osr_method(), "must be marked for reclamation"); assert (!is_locked_by_vm(), "locked methods shouldn't be flushed"); assert_locked_or_safepoint(CodeCache_lock); @@ -1563,9 +1573,9 @@ void nmethod::flush() { // completely deallocate this method Events::log(JavaThread::current(), "flushing nmethod " INTPTR_FORMAT, p2i(this)); if (PrintMethodFlushing) { - tty->print_cr("*flushing nmethod %3d/" INTPTR_FORMAT ". Live blobs:" UINT32_FORMAT + tty->print_cr("*flushing %s nmethod %3d/" INTPTR_FORMAT ". Live blobs:" UINT32_FORMAT "/Free CodeCache:" SIZE_FORMAT "Kb", - _compile_id, p2i(this), CodeCache::blob_count(), + is_osr_method() ? "osr" : "",_compile_id, p2i(this), CodeCache::blob_count(), CodeCache::unallocated_capacity(CodeCache::get_code_blob_type(this))/1024); } @@ -2917,10 +2927,7 @@ void nmethod::print() const { tty->print("((nmethod*) " INTPTR_FORMAT ") ", p2i(this)); tty->print(" for method " INTPTR_FORMAT , p2i(method())); tty->print(" { "); - if (is_in_use()) tty->print("in_use "); - if (is_not_entrant()) tty->print("not_entrant "); - if (is_zombie()) tty->print("zombie "); - if (is_unloaded()) tty->print("unloaded "); + tty->print_cr("%s ", state()); if (on_scavenge_root_list()) tty->print("scavenge_root "); tty->print_cr("}:"); } diff --git a/hotspot/src/share/vm/code/nmethod.hpp b/hotspot/src/share/vm/code/nmethod.hpp index 6c0d9f839ac..dedc1211ef5 100644 --- a/hotspot/src/share/vm/code/nmethod.hpp +++ b/hotspot/src/share/vm/code/nmethod.hpp @@ -207,7 +207,7 @@ class nmethod : public CodeBlob { unsigned int _has_wide_vectors:1; // Preserve wide vectors at safepoints // Protected by Patching_lock - volatile unsigned char _state; // {alive, not_entrant, zombie, unloaded} + volatile unsigned char _state; // {in_use, not_entrant, zombie, unloaded} volatile unsigned char _unloading_clock; // Incremented after GC unloaded/cleaned the nmethod @@ -438,7 +438,20 @@ class nmethod : public CodeBlob { bool is_alive() const { return _state == in_use || _state == not_entrant; } bool is_not_entrant() const { return _state == not_entrant; } bool is_zombie() const { return _state == zombie; } - bool is_unloaded() const { return _state == unloaded; } + bool is_unloaded() const { return _state == unloaded; } + + // returns a string version of the nmethod state + const char* state() const { + switch(_state) { + case in_use: return "in use"; + case not_entrant: return "not_entrant"; + case zombie: return "zombie"; + case unloaded: return "unloaded"; + default: + fatal("unexpected nmethod state: %d", _state); + return NULL; + } + } #if INCLUDE_RTM_OPT // rtm state accessing and manipulating diff --git a/hotspot/src/share/vm/oops/instanceKlass.cpp b/hotspot/src/share/vm/oops/instanceKlass.cpp index d1297af03df..81978f37010 100644 --- a/hotspot/src/share/vm/oops/instanceKlass.cpp +++ b/hotspot/src/share/vm/oops/instanceKlass.cpp @@ -2523,8 +2523,8 @@ void InstanceKlass::add_osr_nmethod(nmethod* n) { } } - -void InstanceKlass::remove_osr_nmethod(nmethod* n) { +// Remove osr nmethod from the list. Return true if found and removed. +bool InstanceKlass::remove_osr_nmethod(nmethod* n) { // This is a short non-blocking critical region, so the no safepoint check is ok. MutexLockerEx ml(OsrList_lock, Mutex::_no_safepoint_check_flag); assert(n->is_osr_method(), "wrong kind of nmethod"); @@ -2533,6 +2533,7 @@ void InstanceKlass::remove_osr_nmethod(nmethod* n) { int max_level = CompLevel_none; // Find the max comp level excluding n Method* m = n->method(); // Search for match + bool found = false; while(cur != NULL && cur != n) { if (TieredCompilation && m == cur->method()) { // Find max level before n @@ -2543,6 +2544,7 @@ void InstanceKlass::remove_osr_nmethod(nmethod* n) { } nmethod* next = NULL; if (cur == n) { + found = true; next = cur->osr_link(); if (last == NULL) { // Remove first element @@ -2563,6 +2565,7 @@ void InstanceKlass::remove_osr_nmethod(nmethod* n) { } m->set_highest_osr_comp_level(max_level); } + return found; } int InstanceKlass::mark_osr_nmethods(const Method* m) { diff --git a/hotspot/src/share/vm/oops/instanceKlass.hpp b/hotspot/src/share/vm/oops/instanceKlass.hpp index 47924e5d03b..7e637a84431 100644 --- a/hotspot/src/share/vm/oops/instanceKlass.hpp +++ b/hotspot/src/share/vm/oops/instanceKlass.hpp @@ -829,7 +829,7 @@ public: nmethod* osr_nmethods_head() const { return _osr_nmethods_head; }; void set_osr_nmethods_head(nmethod* h) { _osr_nmethods_head = h; }; void add_osr_nmethod(nmethod* n); - void remove_osr_nmethod(nmethod* n); + bool remove_osr_nmethod(nmethod* n); int mark_osr_nmethods(const Method* m); nmethod* lookup_osr_nmethod(const Method* m, int bci, int level, bool match_level) const; diff --git a/hotspot/src/share/vm/runtime/sweeper.cpp b/hotspot/src/share/vm/runtime/sweeper.cpp index 5a902266205..78d6eda8ba0 100644 --- a/hotspot/src/share/vm/runtime/sweeper.cpp +++ b/hotspot/src/share/vm/runtime/sweeper.cpp @@ -355,8 +355,8 @@ void NMethodSweeper::possibly_sweep() { bool forced = _force_sweep; // Force stack scanning if there is only 10% free space in the code cache. - // We force stack scanning only non-profiled code heap gets full, since critical - // allocation go to the non-profiled heap and we must be make sure that there is + // We force stack scanning only if the non-profiled code heap gets full, since critical + // allocations go to the non-profiled heap and we must be make sure that there is // enough space. double free_percent = 1 / CodeCache::reverse_free_ratio(CodeBlobType::MethodNonProfiled) * 100; if (free_percent <= StartAggressiveSweepingAt) { @@ -423,12 +423,19 @@ void NMethodSweeper::sweep_code_cache() { // Now ready to process nmethod and give up CodeCache_lock { MutexUnlockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag); + // Save information before potentially flushing the nmethod int size = nm->total_size(); bool is_c2_method = nm->is_compiled_by_c2(); + bool is_osr = nm->is_osr_method(); + int compile_id = nm->compile_id(); + intptr_t address = p2i(nm); + const char* state_before = nm->state(); + const char* state_after = ""; MethodStateChange type = process_nmethod(nm); switch (type) { case Flushed: + state_after = "flushed"; freed_memory += size; ++flushed_count; if (is_c2_method) { @@ -436,9 +443,11 @@ void NMethodSweeper::sweep_code_cache() { } break; case MarkedForReclamation: + state_after = "marked for reclamation"; ++marked_for_reclamation_count; break; case MadeZombie: + state_after = "made zombie"; ++zombified_count; break; case None: @@ -446,7 +455,11 @@ void NMethodSweeper::sweep_code_cache() { default: ShouldNotReachHere(); } + if (PrintMethodFlushing && Verbose && type != None) { + tty->print_cr("### %s nmethod %3d/" PTR_FORMAT " (%s) %s", is_osr ? "osr" : "", compile_id, address, state_before, state_after); + } } + _seen++; handle_safepoint_request(); } @@ -533,7 +546,7 @@ class NMethodMarker: public StackObj { NMethodMarker(nmethod* nm) { JavaThread* current = JavaThread::current(); assert (current->is_Code_cache_sweeper_thread(), "Must be"); - _thread = (CodeCacheSweeperThread*)JavaThread::current(); + _thread = (CodeCacheSweeperThread*)current; if (!nm->is_zombie() && !nm->is_unloaded()) { // Only expose live nmethods for scanning _thread->set_scanned_nmethod(nm); @@ -545,6 +558,10 @@ class NMethodMarker: public StackObj { }; void NMethodSweeper::release_nmethod(nmethod* nm) { + // Make sure the released nmethod is no longer referenced by the sweeper thread + CodeCacheSweeperThread* thread = (CodeCacheSweeperThread*)JavaThread::current(); + thread->set_scanned_nmethod(NULL); + // Clean up any CompiledICHolders { ResourceMark rm; @@ -575,7 +592,7 @@ NMethodSweeper::MethodStateChange NMethodSweeper::process_nmethod(nmethod* nm) { if (nm->is_locked_by_vm()) { // But still remember to clean-up inline caches for alive nmethods if (nm->is_alive()) { - // Clean inline caches that point to zombie/non-entrant methods + // Clean inline caches that point to zombie/non-entrant/unloaded nmethods MutexLocker cl(CompiledIC_lock); nm->cleanup_inline_caches(); SWEEP(nm); @@ -589,42 +606,44 @@ NMethodSweeper::MethodStateChange NMethodSweeper::process_nmethod(nmethod* nm) { // there are no inline caches that refer to it. if (nm->is_marked_for_reclamation()) { assert(!nm->is_locked_by_vm(), "must not flush locked nmethods"); - if (PrintMethodFlushing && Verbose) { - tty->print_cr("### Nmethod %3d/" PTR_FORMAT " (marked for reclamation) being flushed", nm->compile_id(), p2i(nm)); - } release_nmethod(nm); assert(result == None, "sanity"); result = Flushed; } else { - if (PrintMethodFlushing && Verbose) { - tty->print_cr("### Nmethod %3d/" PTR_FORMAT " (zombie) being marked for reclamation", nm->compile_id(), p2i(nm)); - } nm->mark_for_reclamation(); // Keep track of code cache state change _bytes_changed += nm->total_size(); SWEEP(nm); assert(result == None, "sanity"); result = MarkedForReclamation; + assert(nm->is_marked_for_reclamation(), "nmethod must be marked for reclamation"); } } else if (nm->is_not_entrant()) { // If there are no current activations of this method on the // stack we can safely convert it to a zombie method if (nm->can_convert_to_zombie()) { - // Clear ICStubs to prevent back patching stubs of zombie or unloaded + // Clear ICStubs to prevent back patching stubs of zombie or flushed // nmethods during the next safepoint (see ICStub::finalize). { MutexLocker cl(CompiledIC_lock); nm->clear_ic_stubs(); } - if (PrintMethodFlushing && Verbose) { - tty->print_cr("### Nmethod %3d/" PTR_FORMAT " (not entrant) being made zombie", nm->compile_id(), p2i(nm)); - } // Code cache state change is tracked in make_zombie() nm->make_zombie(); SWEEP(nm); - assert(result == None, "sanity"); - result = MadeZombie; - assert(nm->is_zombie(), "nmethod must be zombie"); + if (nm->is_osr_method()) { + // No inline caches will ever point to osr methods, so we can just remove it. + // Make sure that we unregistered the nmethod with the heap and flushed all + // dependencies before removing the nmethod (done in make_zombie()). + assert(nm->is_zombie(), "nmethod must be unregistered"); + release_nmethod(nm); + assert(result == None, "sanity"); + result = Flushed; + } else { + assert(result == None, "sanity"); + result = MadeZombie; + assert(nm->is_zombie(), "nmethod must be zombie"); + } } else { // Still alive, clean up its inline caches MutexLocker cl(CompiledIC_lock); @@ -632,9 +651,13 @@ NMethodSweeper::MethodStateChange NMethodSweeper::process_nmethod(nmethod* nm) { SWEEP(nm); } } else if (nm->is_unloaded()) { - // Unloaded code, just make it a zombie - if (PrintMethodFlushing && Verbose) { - tty->print_cr("### Nmethod %3d/" PTR_FORMAT " (unloaded) being made zombie", nm->compile_id(), p2i(nm)); + // Code is unloaded, so there are no activations on the stack. + // Convert the nmethod to zombie or flush it directly in the OSR case. + { + // Clean ICs of unloaded nmethods as well because they may reference other + // unloaded nmethods that may be flushed earlier in the sweeper cycle. + MutexLocker cl(CompiledIC_lock); + nm->cleanup_inline_caches(); } if (nm->is_osr_method()) { SWEEP(nm); @@ -643,12 +666,6 @@ NMethodSweeper::MethodStateChange NMethodSweeper::process_nmethod(nmethod* nm) { assert(result == None, "sanity"); result = Flushed; } else { - { - // Clean ICs of unloaded nmethods as well because they may reference other - // unloaded nmethods that may be flushed earlier in the sweeper cycle. - MutexLocker cl(CompiledIC_lock); - nm->cleanup_inline_caches(); - } // Code cache state change is tracked in make_zombie() nm->make_zombie(); SWEEP(nm); @@ -657,7 +674,7 @@ NMethodSweeper::MethodStateChange NMethodSweeper::process_nmethod(nmethod* nm) { } } else { possibly_flush(nm); - // Clean-up all inline caches that point to zombie/non-reentrant methods + // Clean inline caches that point to zombie/non-entrant/unloaded nmethods MutexLocker cl(CompiledIC_lock); nm->cleanup_inline_caches(); SWEEP(nm); @@ -668,10 +685,10 @@ NMethodSweeper::MethodStateChange NMethodSweeper::process_nmethod(nmethod* nm) { void NMethodSweeper::possibly_flush(nmethod* nm) { if (UseCodeCacheFlushing) { - if (!nm->is_locked_by_vm() && !nm->is_osr_method() && !nm->is_native_method()) { + if (!nm->is_locked_by_vm() && !nm->is_native_method()) { bool make_not_entrant = false; - // Do not make native methods and OSR-methods not-entrant + // Do not make native methods not-entrant nm->dec_hotness_counter(); // Get the initial value of the hotness counter. This value depends on the // ReservedCodeCacheSize diff --git a/hotspot/src/share/vm/runtime/sweeper.hpp b/hotspot/src/share/vm/runtime/sweeper.hpp index ccf5125c808..8f1f5b52576 100644 --- a/hotspot/src/share/vm/runtime/sweeper.hpp +++ b/hotspot/src/share/vm/runtime/sweeper.hpp @@ -45,12 +45,12 @@ class WhiteBox; // and sweep_code_cache() cannot execute at the same time. // To reclaim memory, nmethods are first marked as 'not-entrant'. Methods can // be made not-entrant by (i) the sweeper, (ii) deoptimization, (iii) dependency -// invalidation, and (iv) being replaced be a different method version (tiered -// compilation). Not-entrant nmethod cannot be called by Java threads, but they -// can still be active on the stack. To ensure that active nmethod are not reclaimed, +// invalidation, and (iv) being replaced by a different method version (tiered +// compilation). Not-entrant nmethods cannot be called by Java threads, but they +// can still be active on the stack. To ensure that active nmethods are not reclaimed, // we have to wait until the next marking phase has completed. If a not-entrant // nmethod was NOT marked as active, it can be converted to 'zombie' state. To safely -// remove the nmethod, all inline caches (IC) that point to the the nmethod must be +// remove the nmethod, all inline caches (IC) that point to the nmethod must be // cleared. After that, the nmethod can be evicted from the code cache. Each nmethod's // state change happens during separate sweeps. It may take at least 3 sweeps before an // nmethod's space is freed. From 99a06be4059c405e36ebf627aed26cf3b2c14ca5 Mon Sep 17 00:00:00 2001 From: Christian Thalinger Date: Thu, 17 Mar 2016 10:55:15 -1000 Subject: [PATCH 034/162] 8151829: [JVMCI] incorrect documentation about jvmci.compiler property Reviewed-by: kvn --- .../src/jdk/vm/ci/runtime/JVMCICompilerFactory.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/hotspot/src/jdk.vm.ci/share/classes/jdk.vm.ci.runtime/src/jdk/vm/ci/runtime/JVMCICompilerFactory.java b/hotspot/src/jdk.vm.ci/share/classes/jdk.vm.ci.runtime/src/jdk/vm/ci/runtime/JVMCICompilerFactory.java index 7bb1f592224..8262924bf5a 100644 --- a/hotspot/src/jdk.vm.ci/share/classes/jdk.vm.ci.runtime/src/jdk/vm/ci/runtime/JVMCICompilerFactory.java +++ b/hotspot/src/jdk.vm.ci/share/classes/jdk.vm.ci.runtime/src/jdk/vm/ci/runtime/JVMCICompilerFactory.java @@ -28,8 +28,7 @@ package jdk.vm.ci.runtime; public interface JVMCICompilerFactory { /** - * Get the name of this compiler. The compiler will be selected when the jvmci.compiler system - * property is equal to this name. + * Get the name of this compiler. */ String getCompilerName(); From 565799b7971fb2b575669c679b718f4872a11f05 Mon Sep 17 00:00:00 2001 From: Christian Thalinger Date: Thu, 17 Mar 2016 16:10:09 -1000 Subject: [PATCH 035/162] 8151723: [JVMCI] JVMCIRuntime::treat_as_trivial: Don't limit trivial prefixes to boot class path Reviewed-by: dnsimon --- hotspot/src/share/vm/jvmci/jvmciRuntime.cpp | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/hotspot/src/share/vm/jvmci/jvmciRuntime.cpp b/hotspot/src/share/vm/jvmci/jvmciRuntime.cpp index 367afbf36e1..c1ee53f1d5e 100644 --- a/hotspot/src/share/vm/jvmci/jvmciRuntime.cpp +++ b/hotspot/src/share/vm/jvmci/jvmciRuntime.cpp @@ -800,12 +800,9 @@ void JVMCIRuntime::shutdown(TRAPS) { bool JVMCIRuntime::treat_as_trivial(Method* method) { if (_HotSpotJVMCIRuntime_initialized) { - oop loader = method->method_holder()->class_loader(); - if (loader == NULL) { - for (int i = 0; i < _trivial_prefixes_count; i++) { - if (method->method_holder()->name()->starts_with(_trivial_prefixes[i])) { - return true; - } + for (int i = 0; i < _trivial_prefixes_count; i++) { + if (method->method_holder()->name()->starts_with(_trivial_prefixes[i])) { + return true; } } } From 4036d37a8fcd17869cbcc7394631229d00aea325 Mon Sep 17 00:00:00 2001 From: Christian Thalinger Date: Thu, 17 Mar 2016 16:10:58 -1000 Subject: [PATCH 036/162] 8152134: [JVMCI] printing compile queues always prints C2 regardless of UseJVMCICompiler Reviewed-by: dnsimon --- hotspot/src/share/vm/compiler/compileBroker.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/hotspot/src/share/vm/compiler/compileBroker.cpp b/hotspot/src/share/vm/compiler/compileBroker.cpp index 672fed6f7f4..74f8ced0f11 100644 --- a/hotspot/src/share/vm/compiler/compileBroker.cpp +++ b/hotspot/src/share/vm/compiler/compileBroker.cpp @@ -773,7 +773,8 @@ void CompileBroker::init_compiler_sweeper_threads(int c1_compiler_count, int c2_ #endif // !ZERO && !SHARK // Initialize the compilation queue if (c2_compiler_count > 0) { - _c2_compile_queue = new CompileQueue("C2 compile queue"); + const char* name = JVMCI_ONLY(UseJVMCICompiler ? "JVMCI compile queue" :) "C2 compile queue"; + _c2_compile_queue = new CompileQueue(name); _compilers[1]->set_num_compiler_threads(c2_compiler_count); } if (c1_compiler_count > 0) { From 591784c35a5dedef47a330616bd8afaa898c8aac Mon Sep 17 00:00:00 2001 From: Filipp Zhinkin Date: Thu, 17 Mar 2016 09:50:00 +0300 Subject: [PATCH 037/162] 8152004: CTW crashes with failed assertion after 8150646 integration Reviewed-by: kvn, neliasso --- hotspot/src/share/vm/ci/ciReplay.cpp | 4 +--- hotspot/src/share/vm/classfile/classLoader.cpp | 3 +-- hotspot/src/share/vm/compiler/compileBroker.cpp | 3 ++- hotspot/src/share/vm/runtime/arguments.cpp | 7 +++++++ 4 files changed, 11 insertions(+), 6 deletions(-) diff --git a/hotspot/src/share/vm/ci/ciReplay.cpp b/hotspot/src/share/vm/ci/ciReplay.cpp index aee1baf56e8..0181836f6cb 100644 --- a/hotspot/src/share/vm/ci/ciReplay.cpp +++ b/hotspot/src/share/vm/ci/ciReplay.cpp @@ -1,4 +1,4 @@ -/* Copyright (c) 2013, 2015, Oracle and/or its affiliates. All rights reserved. +/* Copyright (c) 2013, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -1057,8 +1057,6 @@ void* ciReplay::load_inline_data(ciMethod* method, int entry_bci, int comp_level int ciReplay::replay_impl(TRAPS) { HandleMark hm; ResourceMark rm; - // Make sure we don't run with background compilation - BackgroundCompilation = false; if (ReplaySuppressInitializers > 2) { // ReplaySuppressInitializers > 2 means that we want to allow diff --git a/hotspot/src/share/vm/classfile/classLoader.cpp b/hotspot/src/share/vm/classfile/classLoader.cpp index 0a1e20df3f0..a378fe59be5 100644 --- a/hotspot/src/share/vm/classfile/classLoader.cpp +++ b/hotspot/src/share/vm/classfile/classLoader.cpp @@ -1358,8 +1358,7 @@ void ClassLoader::compile_the_world() { EXCEPTION_MARK; HandleMark hm(THREAD); ResourceMark rm(THREAD); - // Make sure we don't run with background compilation - BackgroundCompilation = false; + // Find bootstrap loader Handle system_class_loader (THREAD, SystemDictionary::java_system_loader()); // Iterate over all bootstrap class path entries diff --git a/hotspot/src/share/vm/compiler/compileBroker.cpp b/hotspot/src/share/vm/compiler/compileBroker.cpp index 74f8ced0f11..a4cc0516e76 100644 --- a/hotspot/src/share/vm/compiler/compileBroker.cpp +++ b/hotspot/src/share/vm/compiler/compileBroker.cpp @@ -1170,7 +1170,8 @@ nmethod* CompileBroker::compile_method(const methodHandle& method, int osr_bci, CompilationPolicy::policy()->delay_compilation(method()); return NULL; } - compile_method_base(method, osr_bci, comp_level, hot_method, hot_count, comment, !directive->BackgroundCompilationOption, THREAD); + bool is_blocking = !directive->BackgroundCompilationOption || CompileTheWorld || ReplayCompiles; + compile_method_base(method, osr_bci, comp_level, hot_method, hot_count, comment, is_blocking, THREAD); } // return requested nmethod diff --git a/hotspot/src/share/vm/runtime/arguments.cpp b/hotspot/src/share/vm/runtime/arguments.cpp index fa307ff891c..9dc3352ab44 100644 --- a/hotspot/src/share/vm/runtime/arguments.cpp +++ b/hotspot/src/share/vm/runtime/arguments.cpp @@ -2484,6 +2484,13 @@ bool Arguments::check_vm_args_consistency() { warning("Reserved Stack Area not supported on this platform"); } #endif + + if (BackgroundCompilation && (CompileTheWorld || ReplayCompiles)) { + if (!FLAG_IS_DEFAULT(BackgroundCompilation)) { + warning("BackgroundCompilation disabled due to CompileTheWorld or ReplayCompiles options."); + } + FLAG_SET_CMDLINE(bool, BackgroundCompilation, false); + } return status; } From dd801fbc59029ff4b3508c42c3bc3b6ad8609562 Mon Sep 17 00:00:00 2001 From: Prasanta Sadhukhan Date: Thu, 17 Mar 2016 12:48:25 +0530 Subject: [PATCH 038/162] 8151110: libfontmanager should free memory with delete[] if it was allocated with new[] Reviewed-by: prr, serb --- jdk/src/java.desktop/share/native/libfontmanager/hb-jdk-font.cc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/jdk/src/java.desktop/share/native/libfontmanager/hb-jdk-font.cc b/jdk/src/java.desktop/share/native/libfontmanager/hb-jdk-font.cc index 194731f4e7e..1727bb80ea3 100644 --- a/jdk/src/java.desktop/share/native/libfontmanager/hb-jdk-font.cc +++ b/jdk/src/java.desktop/share/native/libfontmanager/hb-jdk-font.cc @@ -293,7 +293,7 @@ reference_table(hb_face_t *face HB_UNUSED, hb_tag_t tag, void *user_data) { return NULL; } length = env->GetArrayLength(tableBytes); - buffer = new jbyte[length]; + buffer = (jbyte *)calloc(length, sizeof(jbyte)); env->GetByteArrayRegion(tableBytes, 0, length, buffer); return hb_blob_create((const char *)buffer, length, From fb2e7f2844d57967e81fc5da070759c35be25db2 Mon Sep 17 00:00:00 2001 From: Alexander Stepanov Date: Thu, 17 Mar 2016 13:17:39 +0300 Subject: [PATCH 039/162] 8151714: [TEST] add a test for JOptionPane dialog multiresolution icons Reviewed-by: alexsch --- .../MultiResolutionJOptionPaneIconTest.java | 181 ++++++++++++++++++ 1 file changed, 181 insertions(+) create mode 100644 jdk/test/java/awt/image/multiresolution/MultiResolutionJOptionPaneIconTest.java diff --git a/jdk/test/java/awt/image/multiresolution/MultiResolutionJOptionPaneIconTest.java b/jdk/test/java/awt/image/multiresolution/MultiResolutionJOptionPaneIconTest.java new file mode 100644 index 00000000000..ea3cee55515 --- /dev/null +++ b/jdk/test/java/awt/image/multiresolution/MultiResolutionJOptionPaneIconTest.java @@ -0,0 +1,181 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + @test + @bug 8150176 8150844 + @author a.stepanov + @summary Check if correct resolution variant is used + for JOptionPane dialog / internal frame icons. + @library ../../../../lib/testlibrary/ + @build ExtendedRobot + @run main/othervm/timeout=300 -Dsun.java2d.uiScale=1 MultiResolutionJOptionPaneIconTest + @run main/othervm/timeout=300 -Dsun.java2d.uiScale=2 MultiResolutionJOptionPaneIconTest +*/ + +import java.awt.*; +import java.awt.event.*; +import java.awt.image.*; +import javax.swing.*; + +public class MultiResolutionJOptionPaneIconTest implements ActionListener { + + private final static Color C1X = Color.ORANGE, C2X = Color.CYAN; + + private final boolean isInternal; + + private volatile JFrame test; + private volatile JDialog dialog; + private volatile JInternalFrame frame; + private final JDesktopPane parentPane = new JDesktopPane(); + private final JButton run = new JButton("run"); + + private final ExtendedRobot robot = new ExtendedRobot(); + + private static BufferedImage getSquare(int sz, Color c) { + + BufferedImage img = new BufferedImage(sz, sz, BufferedImage.TYPE_INT_RGB); + Graphics g = img.getGraphics(); + g.setColor(c); + g.fillRect(0, 0, sz, sz); + return img; + } + + private static Icon getIcon() { + + BaseMultiResolutionImage mri = new BaseMultiResolutionImage( + new BufferedImage[]{getSquare(16, C1X), getSquare(32, C2X)}); + return new ImageIcon(mri); + } + + public MultiResolutionJOptionPaneIconTest(boolean internal, + UIManager.LookAndFeelInfo lf) throws Exception { + + UIManager.setLookAndFeel(lf.getClassName()); + + isInternal = internal; + robot.setAutoDelay(50); + SwingUtilities.invokeAndWait(this::UI); + } + + private void UI() { + + test = new JFrame(); + test.setLayout(new BorderLayout()); + test.add(parentPane, BorderLayout.CENTER); + run.addActionListener(this); + test.add(run, BorderLayout.SOUTH); + test.setUndecorated(true); + test.setSize(400, 300); + test.setLocation(50, 50); + test.setVisible(true); + } + + private void disposeAll() { + + if (dialog != null) { dialog.dispose(); } + if (frame != null) { frame.dispose(); } + if (test != null) { test.dispose(); } + } + + public void doTest() throws Exception { + + robot.waitForIdle(1000); + clickButton(robot); + robot.waitForIdle(2000); + + Component c = isInternal ? + frame.getContentPane() : dialog.getContentPane(); + + System.out.println("\ncheck " + (isInternal ? "internal frame" : + "dialog") + " icon:"); + + Point pt = c.getLocationOnScreen(); + checkColors(pt.x, c.getWidth(), pt.y, c.getHeight()); + System.out.println("ok"); + robot.waitForIdle(); + SwingUtilities.invokeAndWait(this::disposeAll); + robot.waitForIdle(); + } + + private void checkColors(int x0, int w, int y0, int h) { + + boolean is2x = "2".equals(System.getProperty("sun.java2d.uiScale")); + Color + expected = is2x ? C2X : C1X, + unexpected = is2x ? C1X : C2X; + + for (int y = y0; y < y0 + h; y += 5) { + for (int x = x0; x < x0 + w; x += 5) { + + Color c = robot.getPixelColor(x, y); + if (c.equals(unexpected)) { + throw new RuntimeException( + "invalid color was found, test failed"); + } else if (c.equals(expected)) { return; } + } + } + + // no icon found at all + throw new RuntimeException("the icon wasn't found"); + } + + private void showDialogOrFrame() { + + JOptionPane pane = new JOptionPane("", + JOptionPane.DEFAULT_OPTION, + JOptionPane.INFORMATION_MESSAGE, + getIcon()); + pane.setOptions(new Object[]{}); // no buttons + + if (isInternal) { + frame = pane.createInternalFrame(parentPane, ""); + frame.setLocation(0, 0); + frame.setVisible(true); + } else { + dialog = pane.createDialog(parentPane, ""); + dialog.setVisible(true); + } + } + + public void clickButton(ExtendedRobot robot) { + + Point pt = run.getLocationOnScreen(); + robot.mouseMove(pt.x + run.getWidth() / 2, pt.y + run.getHeight() / 2); + robot.waitForIdle(); + robot.click(); + } + + @Override + public void actionPerformed(ActionEvent event) { showDialogOrFrame(); } + + + public static void main(String[] args) throws Exception { + + for (UIManager.LookAndFeelInfo LF: UIManager.getInstalledLookAndFeels()) { + System.out.println("\nL&F: " + LF.getName()); + (new MultiResolutionJOptionPaneIconTest(false, LF)).doTest(); + (new MultiResolutionJOptionPaneIconTest(true , LF)).doTest(); + } + } +} From c93af6f4c063874e4ed74eae6644a256e2248b1f Mon Sep 17 00:00:00 2001 From: Peter Brunet Date: Thu, 17 Mar 2016 21:58:19 -0500 Subject: [PATCH 040/162] 8145228: Java Access Bridge, getAccessibleStatesStringFromContext doesn't wrap the call to getAccessibleRole Use invokeAndWait in two places that were missing that Reviewed-by: alexsch, prr --- .../sun/java/accessibility/internal/AccessBridge.java | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/jdk/src/jdk.accessibility/windows/classes/com/sun/java/accessibility/internal/AccessBridge.java b/jdk/src/jdk.accessibility/windows/classes/com/sun/java/accessibility/internal/AccessBridge.java index 5ab82f3aa2c..acd7323cd1b 100644 --- a/jdk/src/jdk.accessibility/windows/classes/com/sun/java/accessibility/internal/AccessBridge.java +++ b/jdk/src/jdk.accessibility/windows/classes/com/sun/java/accessibility/internal/AccessBridge.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -1408,7 +1408,9 @@ final public class AccessBridge { s.indexOf(AccessibleState.MANAGES_DESCENDANTS.toDisplayString(Locale.US)) == -1) { // Indicate whether this component manages its own // children - AccessibleRole role = ac.getAccessibleRole(); + AccessibleRole role = InvocationUtils.invokeAndWait(() -> { + return ac.getAccessibleRole(); + }, ac); if (role == AccessibleRole.LIST || role == AccessibleRole.TABLE || role == AccessibleRole.TREE) { @@ -1666,7 +1668,9 @@ final public class AccessBridge { */ private AccessibleComponent getAccessibleComponentFromContext(AccessibleContext ac) { if (ac != null) { - AccessibleComponent acmp = ac.getAccessibleComponent(); + AccessibleComponent acmp = InvocationUtils.invokeAndWait(() -> { + return ac.getAccessibleComponent(); + }, ac); if (acmp != null) { debugString("Returning AccessibleComponent Context"); return acmp; From 3ef4ddf1308e4a37f5448bbafb1964c3d26dc56d Mon Sep 17 00:00:00 2001 From: Ambarish Rapte Date: Fri, 18 Mar 2016 17:00:08 +0530 Subject: [PATCH 041/162] 8149636: TextField flicker & over scroll when selection scrolls beyond the bounds of TextField Reviewed-by: ssadetsky, psadhukhan --- .../native/libawt/windows/awt_TextArea.cpp | 46 +-- .../native/libawt/windows/awt_TextField.cpp | 45 +-- .../OverScrollTest/OverScrollTest.java | 109 ++++++ .../OverScrollTest/OverScrollTest.java | 109 ++++++ .../ScrollSelectionTest.html | 43 --- .../ScrollSelectionTest.java | 361 ++++++++++-------- 6 files changed, 428 insertions(+), 285 deletions(-) create mode 100644 jdk/test/java/awt/TextArea/OverScrollTest/OverScrollTest.java create mode 100644 jdk/test/java/awt/TextField/OverScrollTest/OverScrollTest.java delete mode 100644 jdk/test/java/awt/TextField/ScrollSelectionTest/ScrollSelectionTest.html diff --git a/jdk/src/java.desktop/windows/native/libawt/windows/awt_TextArea.cpp b/jdk/src/java.desktop/windows/native/libawt/windows/awt_TextArea.cpp index 0b96ad99a4b..7ec74314bfd 100644 --- a/jdk/src/java.desktop/windows/native/libawt/windows/awt_TextArea.cpp +++ b/jdk/src/java.desktop/windows/native/libawt/windows/awt_TextArea.cpp @@ -225,31 +225,18 @@ AwtTextArea::HandleEvent(MSG *msg, BOOL synthetic) /* * We consume WM_MOUSEMOVE while the left mouse button is pressed, - * so we have to simulate autoscrolling when mouse is moved outside - * of the client area. + * so we have to simulate selection autoscrolling when mouse is moved + * outside of the client area. */ POINT p; RECT r; - BOOL bScrollLeft = FALSE; - BOOL bScrollRight = FALSE; - BOOL bScrollUp = FALSE; BOOL bScrollDown = FALSE; p.x = msg->pt.x; p.y = msg->pt.y; VERIFY(::GetClientRect(GetHWnd(), &r)); - if (p.x < 0) { - bScrollLeft = TRUE; - p.x = 0; - } else if (p.x > r.right) { - bScrollRight = TRUE; - p.x = r.right - 1; - } - if (p.y < 0) { - bScrollUp = TRUE; - p.y = 0; - } else if (p.y > r.bottom) { + if (p.y > r.bottom) { bScrollDown = TRUE; p.y = r.bottom - 1; } @@ -269,32 +256,7 @@ AwtTextArea::HandleEvent(MSG *msg, BOOL synthetic) EditSetSel(cr); } - - if (bScrollLeft == TRUE || bScrollRight == TRUE) { - SCROLLINFO si; - memset(&si, 0, sizeof(si)); - si.cbSize = sizeof(si); - si.fMask = SIF_PAGE | SIF_POS | SIF_RANGE; - - VERIFY(::GetScrollInfo(GetHWnd(), SB_HORZ, &si)); - if (bScrollLeft == TRUE) { - si.nPos = si.nPos - si.nPage / 2; - si.nPos = max(si.nMin, si.nPos); - } else if (bScrollRight == TRUE) { - si.nPos = si.nPos + si.nPage / 2; - si.nPos = min(si.nPos, si.nMax); - } - /* - * Okay to use 16-bit position since RichEdit control adjusts - * its scrollbars so that their range is always 16-bit. - */ - DASSERT(abs(si.nPos) < 0x8000); - SendMessage(WM_HSCROLL, - MAKEWPARAM(SB_THUMBPOSITION, LOWORD(si.nPos))); - } - if (bScrollUp == TRUE) { - SendMessage(EM_LINESCROLL, 0, -1); - } else if (bScrollDown == TRUE) { + if (bScrollDown == TRUE) { SendMessage(EM_LINESCROLL, 0, 1); } delete msg; diff --git a/jdk/src/java.desktop/windows/native/libawt/windows/awt_TextField.cpp b/jdk/src/java.desktop/windows/native/libawt/windows/awt_TextField.cpp index 1c966aaf065..01c73f068ee 100644 --- a/jdk/src/java.desktop/windows/native/libawt/windows/awt_TextField.cpp +++ b/jdk/src/java.desktop/windows/native/libawt/windows/awt_TextField.cpp @@ -157,27 +157,12 @@ AwtTextField::HandleEvent(MSG *msg, BOOL synthetic) /* * We consume WM_MOUSEMOVE while the left mouse button is pressed, - * so we have to simulate autoscrolling when mouse is moved outside - * of the client area. + * so we have to simulate selection autoscrolling when mouse is moved + * outside of the client area. */ POINT p; - RECT r; - BOOL bScrollLeft = FALSE; - BOOL bScrollRight = FALSE; - BOOL bScrollUp = FALSE; - BOOL bScrollDown = FALSE; - p.x = msg->pt.x; p.y = msg->pt.y; - VERIFY(::GetClientRect(GetHWnd(), &r)); - - if (p.x < 0) { - bScrollLeft = TRUE; - p.x = 0; - } else if (p.x > r.right) { - bScrollRight = TRUE; - p.x = r.right - 1; - } LONG lCurPos = EditGetCharFromPos(p); if (GetStartSelectionPos() != -1 && @@ -193,32 +178,6 @@ AwtTextField::HandleEvent(MSG *msg, BOOL synthetic) EditSetSel(cr); } - - if (bScrollLeft == TRUE || bScrollRight == TRUE) { - SCROLLINFO si; - memset(&si, 0, sizeof(si)); - si.cbSize = sizeof(si); - si.fMask = SIF_PAGE | SIF_POS | SIF_RANGE; - - SendMessage(EM_SHOWSCROLLBAR, SB_HORZ, TRUE); - VERIFY(::GetScrollInfo(GetHWnd(), SB_HORZ, &si)); - SendMessage(EM_SHOWSCROLLBAR, SB_HORZ, FALSE); - - if (bScrollLeft == TRUE) { - si.nPos = si.nPos - si.nPage / 2; - si.nPos = max(si.nMin, si.nPos); - } else if (bScrollRight == TRUE) { - si.nPos = si.nPos + si.nPage / 2; - si.nPos = min(si.nPos, si.nMax); - } - /* - * Okay to use 16-bit position since RichEdit control adjusts - * its scrollbars so that their range is always 16-bit. - */ - DASSERT(abs(si.nPos) < 0x8000); - SendMessage(WM_HSCROLL, - MAKEWPARAM(SB_THUMBPOSITION, LOWORD(si.nPos))); - } delete msg; return mrConsume; } else if (msg->message == WM_KEYDOWN) { diff --git a/jdk/test/java/awt/TextArea/OverScrollTest/OverScrollTest.java b/jdk/test/java/awt/TextArea/OverScrollTest/OverScrollTest.java new file mode 100644 index 00000000000..6dbf975c6d9 --- /dev/null +++ b/jdk/test/java/awt/TextArea/OverScrollTest/OverScrollTest.java @@ -0,0 +1,109 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + @test + @bug 8149636 + @summary TextArea over scrolls to right when selecting text towards right. + @requires os.family == "windows" + @run main OverScrollTest + */ + +import java.awt.Frame; +import java.awt.FlowLayout; +import java.awt.Point; +import java.awt.Rectangle; +import java.awt.Robot; +import java.awt.TextArea; +import java.awt.event.InputEvent; + +public class OverScrollTest { + Frame mainFrame; + TextArea textArea; + Robot robot; + + OverScrollTest() { + try { + robot = new Robot(); + } catch (Exception ex) { + throw new RuntimeException(ex.getMessage()); + } + + mainFrame = new Frame(); + mainFrame.setSize(400, 200); + mainFrame.setLocation(200, 200); + mainFrame.setLayout(new FlowLayout()); + + textArea = new TextArea(2, 10); + textArea.setSize(300, 100); + textArea.setText("123456 789123"); + mainFrame.add(textArea); + mainFrame.setVisible(true); + textArea.requestFocusInWindow(); + } + + public void dispose() { + if (mainFrame != null) { + mainFrame.dispose(); + } + } + + public void performTest() { + Point loc = textArea.getLocationOnScreen(); + Rectangle textAreaBounds = new Rectangle(); + textArea.getBounds(textAreaBounds); + + // Move mouse at center in first row of TextArea. + robot.mouseMove(loc.x + textAreaBounds.width / 2, loc.y + 5); + + // Perform selection by scrolling to right from end of char sequence. + robot.mousePress(InputEvent.BUTTON1_MASK); + for (int i = 0; i < textAreaBounds.width; i += 15) { + robot.mouseMove(i + loc.x + textAreaBounds.width / 2, loc.y + 5); + robot.delay(10); + } + robot.mouseRelease(InputEvent.BUTTON1_MASK); + robot.waitForIdle(); + + // Perform double click on beginning word of TextArea + robot.mouseMove(loc.x + 5, loc.y + 5); + robot.mousePress(InputEvent.BUTTON1_MASK); + robot.mouseRelease(InputEvent.BUTTON1_MASK); + robot.delay(100); + robot.mousePress(InputEvent.BUTTON1_MASK); + robot.mouseRelease(InputEvent.BUTTON1_MASK); + robot.waitForIdle(); + + dispose(); + if (!textArea.getSelectedText().contains("123456")) { + throw new RuntimeException ("TextArea over scrolled towards right. " + + "Selected text should contain: '123456' " + + "Actual selected test: '" + textArea.getSelectedText() + "'"); + } + } + + public static void main(String argv[]) throws RuntimeException { + OverScrollTest test = new OverScrollTest(); + test.performTest(); + } +} diff --git a/jdk/test/java/awt/TextField/OverScrollTest/OverScrollTest.java b/jdk/test/java/awt/TextField/OverScrollTest/OverScrollTest.java new file mode 100644 index 00000000000..c156d900e98 --- /dev/null +++ b/jdk/test/java/awt/TextField/OverScrollTest/OverScrollTest.java @@ -0,0 +1,109 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + @test + @bug 8149636 + @summary TextField over scrolls to right when selecting text towards right. + @requires os.family == "windows" + @run main OverScrollTest + */ + +import java.awt.Frame; +import java.awt.FlowLayout; +import java.awt.Point; +import java.awt.Rectangle; +import java.awt.Robot; +import java.awt.TextField; +import java.awt.event.InputEvent; + +public class OverScrollTest { + Frame mainFrame; + TextField textField; + Robot robot; + + OverScrollTest() { + try { + robot = new Robot(); + } catch (Exception ex) { + throw new RuntimeException(ex.getMessage()); + } + + mainFrame = new Frame(); + mainFrame.setSize(400, 200); + mainFrame.setLocation(200, 200); + mainFrame.setLayout(new FlowLayout()); + + textField = new TextField(10); + textField.setSize(300, 100); + textField.setText("123456 789123"); + mainFrame.add(textField); + mainFrame.setVisible(true); + textField.requestFocusInWindow(); + } + + public void dispose() { + if (mainFrame != null) { + mainFrame.dispose(); + } + } + + public void performTest() { + Point loc = textField.getLocationOnScreen(); + Rectangle textFieldBounds = new Rectangle(); + textField.getBounds(textFieldBounds); + + // Move mouse at center in first row of TextField. + robot.mouseMove(loc.x + textFieldBounds.width / 2, loc.y + 5); + + // Perform selection by scrolling to right from end of char sequence. + robot.mousePress(InputEvent.BUTTON1_MASK); + for (int i = 0; i < textFieldBounds.width; i += 15) { + robot.mouseMove(i + loc.x + textFieldBounds.width / 2, loc.y + 5); + robot.delay(10); + } + robot.mouseRelease(InputEvent.BUTTON1_MASK); + robot.waitForIdle(); + + // Perform double click on beginning word of TextField + robot.mouseMove(loc.x + 5, loc.y + 5); + robot.mousePress(InputEvent.BUTTON1_MASK); + robot.mouseRelease(InputEvent.BUTTON1_MASK); + robot.delay(100); + robot.mousePress(InputEvent.BUTTON1_MASK); + robot.mouseRelease(InputEvent.BUTTON1_MASK); + robot.waitForIdle(); + + dispose(); + if (!textField.getSelectedText().contains("123456")) { + throw new RuntimeException ("TextField over scrolled towards right. " + + "Selected text should contain: '123456' " + + "Actual selected test: '" + textField.getSelectedText() + "'"); + } + } + + public static void main(String argv[]) throws RuntimeException { + OverScrollTest test = new OverScrollTest(); + test.performTest(); + } +} diff --git a/jdk/test/java/awt/TextField/ScrollSelectionTest/ScrollSelectionTest.html b/jdk/test/java/awt/TextField/ScrollSelectionTest/ScrollSelectionTest.html deleted file mode 100644 index 0c99a555a69..00000000000 --- a/jdk/test/java/awt/TextField/ScrollSelectionTest/ScrollSelectionTest.html +++ /dev/null @@ -1,43 +0,0 @@ - - - - - - ScrollSelectionTest - - - -

    ScrollSelectionTest
    4118621:

    - -

    See the dialog box (usually in upper left corner) for instructions

    - - - - diff --git a/jdk/test/java/awt/TextField/ScrollSelectionTest/ScrollSelectionTest.java b/jdk/test/java/awt/TextField/ScrollSelectionTest/ScrollSelectionTest.java index 482a31245ed..2d38c9ab96f 100644 --- a/jdk/test/java/awt/TextField/ScrollSelectionTest/ScrollSelectionTest.java +++ b/jdk/test/java/awt/TextField/ScrollSelectionTest/ScrollSelectionTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2010, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -22,193 +22,240 @@ */ /* - test - @bug 4118621 - @summary tests that selected text isn't scrolled when there is enough room. - @author prs: area=TextField - @run applet/manual=yesno ScrollSelectionTest.html -*/ - -/** - * ScrollSelectionTest.java - * - * summary: tests that selected text isn't scrolled when there is enough room. + @test + @bug 4118621 8149636 + @summary Test the selection scrolling in TextField. + @run main/manual ScrollSelectionTest */ - -import java.applet.Applet; +import java.awt.Button; import java.awt.Dialog; +import java.awt.FlowLayout; import java.awt.Frame; -import java.awt.TextField; +import java.awt.Panel; import java.awt.TextArea; +import java.awt.TextField; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; -public class ScrollSelectionTest extends Applet - { +public class ScrollSelectionTest { - Frame frame = new Frame("ScrollSelectionTest frame"); - TextField tf = new TextField(40); + static Frame mainFrame; + static TextField textField; - public void init() - { - tf.setText("abcdefghijklmnopqrstuvwxyz"); - frame.add(tf); - tf.select(0, 20); + private static void init() throws Exception { + String[] instructions + = { + "INSTRUCTIONS: There are 2 Tests", + "Test1: Text visibility with Scroll", + "This is a test for a win32 specific problem", + "If you see all the letters from 'a' to 'z' and", + "letters from 'a' to 't' are selected then test passes.", + "You may have to activate the frame to see the selection", + "highlighted (e.g. by clicking on frame's title).", + ".", + "Test2: Flicker with selection scroll", + "Mouse press on the TextField text.", + "Move mouse towards left or right with selecting text.", + "Move mouse away outside the bounds of TextField.", + "No flicker should be observed.", + }; - String[] instructions = { - "INSTRUCTIONS:", - "This is a test for a win32 specific problem", - "If you see all the letters from 'a' to 'z' and", - "letters from 'a' to 't' are selected then test passes.", - "You may have to activate the frame to see the selection" - + " highlighted (e.g. by clicking on frame's title)." - }; - Sysout.createDialogWithInstructions( instructions ); + Sysout.createDialog(); + Sysout.printInstructions(instructions); + } - }// init() + public static void initTestWindow() { + mainFrame = new Frame("ScrollSelectionTest frame"); + mainFrame.setBounds(500, 0, 400, 200); - public void start () - { - setSize (300,300); - setVisible(true); + textField = new TextField(40); + textField.setText("abcdefghijklmnopqrstuvwxyz"); + mainFrame.add(textField); + mainFrame.setLayout(new FlowLayout()); + textField.select(0, 20); + mainFrame.setVisible(true); + } - frame.setVisible(true); - frame.setBounds (400, 0, 300, 300); + public static void dispose() { + Sysout.dispose(); + mainFrame.dispose(); + } - }// start() + /** + * *************************************************** + * Standard Test Machinery Section DO NOT modify anything in this section -- + * it's a standard chunk of code which has all of the synchronization + * necessary for the test harness. By keeping it the same in all tests, it + * is easier to read and understand someone else's test, as well as insuring + * that all tests behave correctly with the test harness. There is a section + * following this for test-defined classes + * **************************************************** + */ + private static boolean theTestPassed = false; + private static boolean testGeneratedInterrupt = false; + private static String failureMessage = ""; + private static Thread mainThread = null; + final private static int sleepTime = 300000; - }// class ScrollSelectionTest + public static void main(String args[]) throws Exception { + mainThread = Thread.currentThread(); + try { + init(); + initTestWindow(); + } catch (Exception e) { + e.printStackTrace(); + } + try { + mainThread.sleep(sleepTime); + } catch (InterruptedException e) { + dispose(); + if (testGeneratedInterrupt && !theTestPassed) { + throw new Exception(failureMessage); + } + } + if (!testGeneratedInterrupt) { + dispose(); + throw new RuntimeException("Timed out after " + sleepTime / 1000 + + " seconds"); + } + } -/**************************************************** - Standard Test Machinery - DO NOT modify anything below -- it's a standard - chunk of code whose purpose is to make user - interaction uniform, and thereby make it simpler - to read and understand someone else's test. - ****************************************************/ + public static synchronized void pass() { + theTestPassed = true; + testGeneratedInterrupt = true; + mainThread.interrupt(); + } + public static synchronized void fail(String whyFailed) { + theTestPassed = false; + testGeneratedInterrupt = true; + failureMessage = whyFailed; + mainThread.interrupt(); + } +} + +// *********** End Standard Test Machinery Section ********** /** - This is part of the standard test machinery. - It creates a dialog (with the instructions), and is the interface - for sending text messages to the user. - To print the instructions, send an array of strings to Sysout.createDialog - WithInstructions method. Put one line of instructions per array entry. - To display a message for the tester to see, simply call Sysout.println - with the string to be displayed. - This mimics System.out.println but works within the test harness as well - as standalone. + * ************************************************** + * Standard Test Machinery DO NOT modify anything below -- it's a standard chunk + * of code whose purpose is to make user interaction uniform, and thereby make + * it simpler to read and understand someone else's test. + * ************************************************** */ +/** + * This is part of the standard test machinery. It creates a dialog (with the + * instructions), and is the interface for sending text messages to the user. To + * print the instructions, send an array of strings to Sysout.createDialog + * WithInstructions method. Put one line of instructions per array entry. To + * display a message for the tester to see, simply call Sysout.println with the + * string to be displayed. This mimics System.out.println but works within the + * test harness as well as standalone. + */ +class Sysout { + private static TestDialog dialog; + private static Frame frame; -class Sysout - { - private static TestDialog dialog; - - public static void createDialogWithInstructions( String[] instructions ) - { - dialog = new TestDialog( new Frame(), "Instructions" ); - dialog.printInstructions( instructions ); - dialog.show(); - println( "Any messages for the tester will display here." ); + public static void createDialog() { + frame = new Frame(); + dialog = new TestDialog(frame, "Instructions"); + String[] defInstr = {"Instructions will appear here. ", ""}; + dialog.printInstructions(defInstr); + dialog.setVisible(true); + println("Any messages for the tester will display here."); } - public static void createDialog( ) - { - dialog = new TestDialog( new Frame(), "Instructions" ); - String[] defInstr = { "Instructions will appear here. ", "" } ; - dialog.printInstructions( defInstr ); - dialog.show(); - println( "Any messages for the tester will display here." ); + public static void printInstructions(String[] instructions) { + dialog.printInstructions(instructions); } - - public static void printInstructions( String[] instructions ) - { - dialog.printInstructions( instructions ); + public static void println(String messageIn) { + dialog.displayMessage(messageIn); } - - public static void println( String messageIn ) - { - dialog.displayMessage( messageIn ); + public static void dispose() { + dialog.dispose(); + frame.dispose(); } - - }// Sysout class +} /** - This is part of the standard test machinery. It provides a place for the - test instructions to be displayed, and a place for interactive messages - to the user to be displayed. - To have the test instructions displayed, see Sysout. - To have a message to the user be displayed, see Sysout. - Do not call anything in this dialog directly. - */ -class TestDialog extends Dialog - { + * This is part of the standard test machinery. It provides a place for the test + * instructions to be displayed, and a place for interactive messages to the + * user to be displayed. To have the test instructions displayed, see Sysout. To + * have a message to the user be displayed, see Sysout. Do not call anything in + * this dialog directly. + */ +class TestDialog extends Dialog implements ActionListener { + TextArea instructionsText; + TextArea messageText; + int maxStringLength = 80; + Panel buttonP; + Button failB; + Button passB; - TextArea instructionsText; - TextArea messageText; - int maxStringLength = 80; + // DO NOT call this directly, go through Sysout + public TestDialog(Frame frame, String name) { + super(frame, name); + int scrollBoth = TextArea.SCROLLBARS_BOTH; + instructionsText = new TextArea("", 15, maxStringLength, scrollBoth); + add("North", instructionsText); - //DO NOT call this directly, go through Sysout - public TestDialog( Frame frame, String name ) - { - super( frame, name ); - int scrollBoth = TextArea.SCROLLBARS_BOTH; - instructionsText = new TextArea( "", 15, maxStringLength, scrollBoth ); - add( "North", instructionsText ); + messageText = new TextArea("", 5, maxStringLength, scrollBoth); + add("Center", messageText); - messageText = new TextArea( "", 5, maxStringLength, scrollBoth ); - add("South", messageText); + buttonP = new Panel(); + passB = new Button("pass"); + passB.setActionCommand("pass"); + passB.addActionListener(this); + buttonP.add("East", passB); - pack(); + failB = new Button("Fail"); + failB.setActionCommand("fail"); + failB.addActionListener(this); + buttonP.add("West", failB); - show(); - }// TestDialog() - - //DO NOT call this directly, go through Sysout - public void printInstructions( String[] instructions ) - { - //Clear out any current instructions - instructionsText.setText( "" ); - - //Go down array of instruction strings - - String printStr, remainingStr; - for( int i=0; i < instructions.length; i++ ) - { - //chop up each into pieces maxSringLength long - remainingStr = instructions[ i ]; - while( remainingStr.length() > 0 ) - { - //if longer than max then chop off first max chars to print - if( remainingStr.length() >= maxStringLength ) - { - //Try to chop on a word boundary - int posOfSpace = remainingStr. - lastIndexOf( ' ', maxStringLength - 1 ); - - if( posOfSpace <= 0 ) posOfSpace = maxStringLength - 1; - - printStr = remainingStr.substring( 0, posOfSpace + 1 ); - remainingStr = remainingStr.substring( posOfSpace + 1 ); - } - //else just print - else - { - printStr = remainingStr; - remainingStr = ""; - } - - instructionsText.append( printStr + "\n" ); - - }// while - - }// for - - }//printInstructions() - - //DO NOT call this directly, go through Sysout - public void displayMessage( String messageIn ) - { - messageText.append( messageIn + "\n" ); + add("South", buttonP); + pack(); + setVisible(true); } - }// TestDialog class + // DO NOT call this directly, go through Sysout + public void printInstructions(String[] instructions) { + instructionsText.setText(""); + String printStr, remainingStr; + for (int i = 0; i < instructions.length; i++) { + remainingStr = instructions[i]; + while (remainingStr.length() > 0) { + if (remainingStr.length() >= maxStringLength) { + int posOfSpace = remainingStr. + lastIndexOf(' ', maxStringLength - 1); + + if (posOfSpace <= 0) { + posOfSpace = maxStringLength - 1; + } + + printStr = remainingStr.substring(0, posOfSpace + 1); + remainingStr = remainingStr.substring(posOfSpace + 1); + } + else { + printStr = remainingStr; + remainingStr = ""; + } + instructionsText.append(printStr + "\n"); + } + } + } + + public void displayMessage(String messageIn) { + messageText.append(messageIn + "\n"); + } + + @Override + public void actionPerformed(ActionEvent e) { + if (e.getActionCommand().equals("pass")) { + ScrollSelectionTest.pass(); + } else { + ScrollSelectionTest.fail("User Clicked Fail"); + } + } +} From 579f0ea8ec7b36b5913036bbd552d10a39e7bd5a Mon Sep 17 00:00:00 2001 From: Guy Delamarter Date: Mon, 21 Mar 2016 08:42:20 +0100 Subject: [PATCH 042/162] 8144693: Intrinsify StringCoding.hasNegatives() on SPARC Implemented C2 instrinsic for StringCode.hasNegatives() on SPARC. Reviewed-by: kvn, jrose, thartmann --- .../src/cpu/sparc/vm/macroAssembler_sparc.cpp | 101 +++++++++++++++ .../src/cpu/sparc/vm/macroAssembler_sparc.hpp | 7 +- hotspot/src/cpu/sparc/vm/sparc.ad | 16 +++ .../intrinsics/string/TestHasNegatives.java | 119 ++++++++++++++++++ 4 files changed, 242 insertions(+), 1 deletion(-) create mode 100644 hotspot/test/compiler/intrinsics/string/TestHasNegatives.java diff --git a/hotspot/src/cpu/sparc/vm/macroAssembler_sparc.cpp b/hotspot/src/cpu/sparc/vm/macroAssembler_sparc.cpp index 9524e707ff4..f6770b0c3db 100644 --- a/hotspot/src/cpu/sparc/vm/macroAssembler_sparc.cpp +++ b/hotspot/src/cpu/sparc/vm/macroAssembler_sparc.cpp @@ -4666,8 +4666,109 @@ void MacroAssembler::array_equals(bool is_array_equ, Register ary1, Register ary bind(Ldone); } +void MacroAssembler::has_negatives(Register inp, Register size, Register result, Register t2, Register t3, Register t4, Register t5) { + + // test for negative bytes in input string of a given size + // result 1 if found, 0 otherwise. + + Label Lcore, Ltail, Lreturn, Lcore_rpt; + + assert_different_registers(inp, size, t2, t3, t4, t5, result); + + Register i = result; // result used as integer index i until very end + Register lmask = t2; // t2 is aliased to lmask + + // INITIALIZATION + // =========================================================== + // initialize highbits mask -> lmask = 0x8080808080808080 (8B/64b) + // compute unaligned offset -> i + // compute core end index -> t5 + Assembler::sethi(0x80808000, t2); //! sethi macro fails to emit optimal + add(t2, 0x80, t2); + sllx(t2, 32, t3); + or3(t3, t2, lmask); // 0x8080808080808080 -> lmask + sra(size,0,size); + andcc(inp, 0x7, i); // unaligned offset -> i + br(Assembler::zero, true, Assembler::pn, Lcore); // starts 8B aligned? + delayed()->add(size, -8, t5); // (annuled) core end index -> t5 + + // =========================================================== + + // UNALIGNED HEAD + // =========================================================== + // * unaligned head handling: grab aligned 8B containing unaligned inp(ut) + // * obliterate (ignore) bytes outside string by shifting off reg ends + // * compare with bitmask, short circuit return true if one or more high + // bits set. + cmp(size, 0); + br(Assembler::zero, true, Assembler::pn, Lreturn); // short-circuit? + delayed()->mov(0,result); // annuled so i not clobbered for following + neg(i, t4); + add(i, size, t5); + ldx(inp, t4, t3); // raw aligned 8B containing unaligned head -> t3 + mov(8, t4); + sub(t4, t5, t4); + sra(t4, 31, t5); + andn(t4, t5, t5); + add(i, t5, t4); + sll(t5, 3, t5); + sll(t4, 3, t4); // # bits to shift right, left -> t5,t4 + srlx(t3, t5, t3); + sllx(t3, t4, t3); // bytes outside string in 8B header obliterated -> t3 + andcc(lmask, t3, G0); + brx(Assembler::notZero, true, Assembler::pn, Lreturn); // short circuit? + delayed()->mov(1,result); // annuled so i not clobbered for following + add(size, -8, t5); // core end index -> t5 + mov(8, t4); + sub(t4, i, i); // # bytes examined in unalgn head (<8) -> i + // =========================================================== + + // ALIGNED CORE + // =========================================================== + // * iterate index i over aligned 8B sections of core, comparing with + // bitmask, short circuit return true if one or more high bits set + // t5 contains core end index/loop limit which is the index + // of the MSB of last (unaligned) 8B fully contained in the string. + // inp contains address of first byte in string/array + // lmask contains 8B high bit mask for comparison + // i contains next index to be processed (adr. inp+i is on 8B boundary) + bind(Lcore); + cmp_and_br_short(i, t5, Assembler::greater, Assembler::pn, Ltail); + bind(Lcore_rpt); + ldx(inp, i, t3); + andcc(t3, lmask, G0); + brx(Assembler::notZero, true, Assembler::pn, Lreturn); + delayed()->mov(1, result); // annuled so i not clobbered for following + add(i, 8, i); + cmp_and_br_short(i, t5, Assembler::lessEqual, Assembler::pn, Lcore_rpt); + // =========================================================== + + // ALIGNED TAIL (<8B) + // =========================================================== + // handle aligned tail of 7B or less as complete 8B, obliterating end of + // string bytes by shifting them off end, compare what's left with bitmask + // inp contains address of first byte in string/array + // lmask contains 8B high bit mask for comparison + // i contains next index to be processed (adr. inp+i is on 8B boundary) + bind(Ltail); + subcc(size, i, t4); // # of remaining bytes in string -> t4 + // return 0 if no more remaining bytes + br(Assembler::lessEqual, true, Assembler::pn, Lreturn); + delayed()->mov(0, result); // annuled so i not clobbered for following + ldx(inp, i, t3); // load final 8B (aligned) containing tail -> t3 + mov(8, t5); + sub(t5, t4, t4); + mov(0, result); // ** i clobbered at this point + sll(t4, 3, t4); // bits beyond end of string -> t4 + srlx(t3, t4, t3); // bytes beyond end now obliterated -> t3 + andcc(lmask, t3, G0); + movcc(Assembler::notZero, false, xcc, 1, result); + bind(Lreturn); +} + #endif + // Use BIS for zeroing (count is in bytes). void MacroAssembler::bis_zeroing(Register to, Register count, Register temp, Label& Ldone) { assert(UseBlockZeroing && VM_Version::has_block_zeroing(), "only works with BIS zeroing"); diff --git a/hotspot/src/cpu/sparc/vm/macroAssembler_sparc.hpp b/hotspot/src/cpu/sparc/vm/macroAssembler_sparc.hpp index fe0c36ace97..dbbfbbc1267 100644 --- a/hotspot/src/cpu/sparc/vm/macroAssembler_sparc.hpp +++ b/hotspot/src/cpu/sparc/vm/macroAssembler_sparc.hpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -1392,6 +1392,11 @@ public: void array_equals(bool is_array_equ, Register ary1, Register ary2, Register limit, Register tmp, Register result, bool is_byte); + // test for negative bytes in input string of a given size, result 0 if none + void has_negatives(Register inp, Register size, Register result, + Register t2, Register t3, Register t4, + Register t5); + #endif // Use BIS for zeroing diff --git a/hotspot/src/cpu/sparc/vm/sparc.ad b/hotspot/src/cpu/sparc/vm/sparc.ad index f24c1f9b384..d669d8732b8 100644 --- a/hotspot/src/cpu/sparc/vm/sparc.ad +++ b/hotspot/src/cpu/sparc/vm/sparc.ad @@ -10168,6 +10168,22 @@ instruct array_equalsC(o0RegP ary1, o1RegP ary2, g3RegI tmp1, notemp_iRegI resul ins_pipe(long_memory_op); %} +instruct has_negatives(o0RegP pAryR, g3RegI iSizeR, notemp_iRegI resultR, + iRegL tmp1L, iRegL tmp2L, iRegL tmp3L, iRegL tmp4L, + flagsReg ccr) +%{ + match(Set resultR (HasNegatives pAryR iSizeR)); + effect(TEMP resultR, TEMP tmp1L, TEMP tmp2L, TEMP tmp3L, TEMP tmp4L, USE pAryR, USE iSizeR, KILL ccr); + format %{ "has negatives byte[] $pAryR,$iSizeR -> $resultR // KILL $tmp1L,$tmp2L,$tmp3L,$tmp4L" %} + ins_encode %{ + __ has_negatives($pAryR$$Register, $iSizeR$$Register, + $resultR$$Register, + $tmp1L$$Register, $tmp2L$$Register, + $tmp3L$$Register, $tmp4L$$Register); + %} + ins_pipe(long_memory_op); +%} + // char[] to byte[] compression instruct string_compress(o0RegP src, o1RegP dst, g3RegI len, notemp_iRegI result, iRegL tmp, flagsReg ccr) %{ predicate(UseVIS < 3); diff --git a/hotspot/test/compiler/intrinsics/string/TestHasNegatives.java b/hotspot/test/compiler/intrinsics/string/TestHasNegatives.java new file mode 100644 index 00000000000..500b620cce1 --- /dev/null +++ b/hotspot/test/compiler/intrinsics/string/TestHasNegatives.java @@ -0,0 +1,119 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 8054307 + * @summary Validates StringCoding.hasNegatives intrinsic with a small range of tests. + * @run main/bootclasspath java.lang.TestHasNegatives + */ +package java.lang; + +import java.lang.StringCoding; + +/* + * @summary Validates StringCoding.hasNegatives intrinsic with a small + * range of tests. Must be run with modified bootclasspath + * to allow existence in java.lang package. + */ +public class TestHasNegatives { + + private static byte[] tBa = new byte[4096 + 16]; + + /** + * Completely initialize the test array, preparing it for tests of the + * StringCoding.hasNegatives method with a given array segment offset, + * length, and number of negative bytes. + */ + public static void initialize(int off, int len, int neg) { + assert (len + off <= tBa.length); + // insert "canary" (negative) values before offset + for (int i = 0; i < off; ++i) { + tBa[i] = (byte) (((i + 15) & 0x7F) | 0x80); + } + // fill the array segment + for (int i = off; i < len + off; ++i) { + tBa[i] = (byte) (((i - off + 15) & 0x7F)); + } + if (neg != 0) { + // modify a number (neg) disparate array bytes inside + // segment to be negative. + int div = (neg > 1) ? (len - 1) / (neg - 1) : 0; + int idx; + for (int i = 0; i < neg; ++i) { + idx = off + (len - 1) - div * i; + tBa[idx] = (byte) (0x80 | tBa[idx]); + } + } + // insert "canary" negative values after array segment + for (int i = len + off; i < tBa.length; ++i) { + tBa[i] = (byte) (((i + 15) & 0x7F) | 0x80); + } + } + + /** Sizes of array segments to test. */ + private static int sizes[] = { 1, 2, 3, 4, 5, 6, 7, 8, 10, 11, 13, 17, 19, 23, 37, 61, 131, + 4099 }; + + /** + * Test different array segment sizes, offsets, and number of negative + * bytes. + */ + public static void test_hasNegatives() throws Exception { + int len, off; + int ng; + boolean r; + + for (ng = 0; ng < 57; ++ng) { // number of negatives in array segment + for (off = 0; off < 8; ++off) { // starting offset of array segment + for (int i = 0; i < sizes.length; ++i) { // array segment size + // choice + len = sizes[i]; + if (len + off > tBa.length) + continue; + initialize(off, len, ng); + r = StringCoding.hasNegatives(tBa, off, len); + if (r ^ ((ng == 0) ? false : true)) { + throw new Exception("Failed test hasNegatives " + "offset: " + off + " " + + "length: " + len + " " + "return: " + r + " " + "negatives: " + + ng); + } + } + } + } + } + + public void run() throws Exception { + // iterate to eventually get intrinsic inlined + for (int j = 0; j < 1000; ++j) { + test_hasNegatives(); + } + } + + public static void main(String[] args) throws Exception { + (new TestHasNegatives()).run(); + System.out.println("hasNegatives validated"); + } +} From 5751808a6ca62374f49e79997e185cb70d5c2ac6 Mon Sep 17 00:00:00 2001 From: Zoltan Majo Date: Mon, 21 Mar 2016 09:51:20 +0100 Subject: [PATCH 043/162] 8148754: C2 loop unrolling fails due to unexpected graph shape Check if graph shape is appropriate for optimization, bail out optimization if not. Reviewed-by: kvn, twisti, shade, dnsimon --- hotspot/src/share/vm/opto/loopTransform.cpp | 42 ++++++++------------- hotspot/src/share/vm/opto/loopnode.cpp | 35 +++++++++++++++++ hotspot/src/share/vm/opto/loopnode.hpp | 3 ++ hotspot/src/share/vm/opto/superword.cpp | 18 +++------ 4 files changed, 59 insertions(+), 39 deletions(-) diff --git a/hotspot/src/share/vm/opto/loopTransform.cpp b/hotspot/src/share/vm/opto/loopTransform.cpp index 8c077f11d5f..d819e69059e 100644 --- a/hotspot/src/share/vm/opto/loopTransform.cpp +++ b/hotspot/src/share/vm/opto/loopTransform.cpp @@ -1453,20 +1453,14 @@ void PhaseIdealLoop::do_unroll( IdealLoopTree *loop, Node_List &old_new, bool ad Node *opaq = NULL; if (adjust_min_trip) { // If not maximally unrolling, need adjustment // Search for zero-trip guard. - assert( loop_head->is_main_loop(), "" ); - assert( ctrl->Opcode() == Op_IfTrue || ctrl->Opcode() == Op_IfFalse, "" ); - Node *iff = ctrl->in(0); - assert( iff->Opcode() == Op_If, "" ); - Node *bol = iff->in(1); - assert( bol->Opcode() == Op_Bool, "" ); - Node *cmp = bol->in(1); - assert( cmp->Opcode() == Op_CmpI, "" ); - opaq = cmp->in(2); - // Occasionally it's possible for a zero-trip guard Opaque1 node to be - // optimized away and then another round of loop opts attempted. - // We can not optimize this particular loop in that case. - if (opaq->Opcode() != Op_Opaque1) - return; // Cannot find zero-trip guard! Bail out! + + // Check the shape of the graph at the loop entry. If an inappropriate + // graph shape is encountered, the compiler bails out loop unrolling; + // compilation of the method will still succeed. + if (!is_canonical_main_loop_entry(loop_head)) { + return; + } + opaq = ctrl->in(0)->in(1)->in(1)->in(2); // Zero-trip test uses an 'opaque' node which is not shared. assert(opaq->outcnt() == 1 && opaq->in(1) == limit, ""); } @@ -2109,7 +2103,6 @@ void PhaseIdealLoop::do_range_check( IdealLoopTree *loop, Node_List &old_new ) { #endif assert(RangeCheckElimination, ""); CountedLoopNode *cl = loop->_head->as_CountedLoop(); - assert(cl->is_main_loop(), ""); // protect against stride not being a constant if (!cl->stride_is_con()) @@ -2121,20 +2114,17 @@ void PhaseIdealLoop::do_range_check( IdealLoopTree *loop, Node_List &old_new ) { // to not ever trip end tests Node *main_limit = cl->limit(); + // Check graph shape. Cannot optimize a loop if zero-trip + // Opaque1 node is optimized away and then another round + // of loop opts attempted. + if (!is_canonical_main_loop_entry(cl)) { + return; + } + // Need to find the main-loop zero-trip guard Node *ctrl = cl->in(LoopNode::EntryControl); - assert(ctrl->Opcode() == Op_IfTrue || ctrl->Opcode() == Op_IfFalse, ""); Node *iffm = ctrl->in(0); - assert(iffm->Opcode() == Op_If, ""); - Node *bolzm = iffm->in(1); - assert(bolzm->Opcode() == Op_Bool, ""); - Node *cmpzm = bolzm->in(1); - assert(cmpzm->is_Cmp(), ""); - Node *opqzm = cmpzm->in(2); - // Can not optimize a loop if zero-trip Opaque1 node is optimized - // away and then another round of loop opts attempted. - if (opqzm->Opcode() != Op_Opaque1) - return; + Node *opqzm = iffm->in(1)->in(1)->in(2); assert(opqzm->in(1) == main_limit, "do not understand situation"); // Find the pre-loop limit; we will expand its iterations to diff --git a/hotspot/src/share/vm/opto/loopnode.cpp b/hotspot/src/share/vm/opto/loopnode.cpp index 9ead9464abb..59ca3261c20 100644 --- a/hotspot/src/share/vm/opto/loopnode.cpp +++ b/hotspot/src/share/vm/opto/loopnode.cpp @@ -3275,6 +3275,41 @@ Node* PhaseIdealLoop::compute_lca_of_uses(Node* n, Node* early, bool verify) { return LCA; } +// Check the shape of the graph at the loop entry. In some cases, +// the shape of the graph does not match the shape outlined below. +// That is caused by the Opaque1 node "protecting" the shape of +// the graph being removed by, for example, the IGVN performed +// in PhaseIdealLoop::build_and_optimize(). +// +// After the Opaque1 node has been removed, optimizations (e.g., split-if, +// loop unswitching, and IGVN, or a combination of them) can freely change +// the graph's shape. As a result, the graph shape outlined below cannot +// be guaranteed anymore. +bool PhaseIdealLoop::is_canonical_main_loop_entry(CountedLoopNode* cl) { + assert(cl->is_main_loop(), "check should be applied to main loops"); + Node* ctrl = cl->in(LoopNode::EntryControl); + if (ctrl == NULL || (!ctrl->is_IfTrue() && !ctrl->is_IfFalse())) { + return false; + } + Node* iffm = ctrl->in(0); + if (iffm == NULL || !iffm->is_If()) { + return false; + } + Node* bolzm = iffm->in(1); + if (bolzm == NULL || !bolzm->is_Bool()) { + return false; + } + Node* cmpzm = bolzm->in(1); + if (cmpzm == NULL || !cmpzm->is_Cmp()) { + return false; + } + Node* opqzm = cmpzm->in(2); + if (opqzm == NULL || opqzm->Opcode() != Op_Opaque1) { + return false; + } + return true; +} + //------------------------------get_late_ctrl---------------------------------- // Compute latest legal control. Node *PhaseIdealLoop::get_late_ctrl( Node *n, Node *early ) { diff --git a/hotspot/src/share/vm/opto/loopnode.hpp b/hotspot/src/share/vm/opto/loopnode.hpp index c853a2a6145..09512cdafb5 100644 --- a/hotspot/src/share/vm/opto/loopnode.hpp +++ b/hotspot/src/share/vm/opto/loopnode.hpp @@ -656,6 +656,9 @@ class PhaseIdealLoop : public PhaseTransform { bool cast_incr_before_loop(Node* incr, Node* ctrl, Node* loop); public: + + static bool is_canonical_main_loop_entry(CountedLoopNode* cl); + bool has_node( Node* n ) const { guarantee(n != NULL, "No Node."); return _nodes[n->_idx] != NULL; diff --git a/hotspot/src/share/vm/opto/superword.cpp b/hotspot/src/share/vm/opto/superword.cpp index 9b4fe74d66c..74c7de0cc14 100644 --- a/hotspot/src/share/vm/opto/superword.cpp +++ b/hotspot/src/share/vm/opto/superword.cpp @@ -3074,21 +3074,13 @@ void SuperWord::align_initial_loop_index(MemNode* align_to_ref) { //----------------------------get_pre_loop_end--------------------------- // Find pre loop end from main loop. Returns null if none. CountedLoopEndNode* SuperWord::get_pre_loop_end(CountedLoopNode* cl) { - Node* ctrl = cl->in(LoopNode::EntryControl); - if (!ctrl->is_IfTrue() && !ctrl->is_IfFalse()) return NULL; - Node* iffm = ctrl->in(0); - if (!iffm->is_If()) return NULL; - Node* bolzm = iffm->in(1); - if (!bolzm->is_Bool()) return NULL; - Node* cmpzm = bolzm->in(1); - if (!cmpzm->is_Cmp()) return NULL; - Node* opqzm = cmpzm->in(2); - // Can not optimize a loop if zero-trip Opaque1 node is optimized - // away and then another round of loop opts attempted. - if (opqzm->Opcode() != Op_Opaque1) { + // The loop cannot be optimized if the graph shape at + // the loop entry is inappropriate. + if (!PhaseIdealLoop::is_canonical_main_loop_entry(cl)) { return NULL; } - Node* p_f = iffm->in(0); + + Node* p_f = cl->in(LoopNode::EntryControl)->in(0)->in(0); if (!p_f->is_IfFalse()) return NULL; if (!p_f->in(0)->is_CountedLoopEnd()) return NULL; CountedLoopEndNode* pre_end = p_f->in(0)->as_CountedLoopEnd(); From f058b201f67aa3e6e744aa40c29f6355654e423d Mon Sep 17 00:00:00 2001 From: Nils Eliasson Date: Fri, 18 Mar 2016 15:54:47 +0100 Subject: [PATCH 044/162] 8152169: LockCompilationTest.java fails due method present in the compiler queue Too many compiles waiting, wait time not enough Reviewed-by: twisti --- .../whitebox/LockCompilationTest.java | 29 +++++++++++++++---- 1 file changed, 23 insertions(+), 6 deletions(-) diff --git a/hotspot/test/compiler/whitebox/LockCompilationTest.java b/hotspot/test/compiler/whitebox/LockCompilationTest.java index 3efe08edf8f..4ba039699e4 100644 --- a/hotspot/test/compiler/whitebox/LockCompilationTest.java +++ b/hotspot/test/compiler/whitebox/LockCompilationTest.java @@ -23,12 +23,12 @@ /* * @test LockCompilationTest - * @bug 8059624 + * @bug 8059624 8152169 * @library /testlibrary /test/lib / * @modules java.management * @build LockCompilationTest - * @run main ClassFileInstaller sun.hotspot.WhiteBox - * sun.hotspot.WhiteBox$WhiteBoxPermission + * @run driver ClassFileInstaller sun.hotspot.WhiteBox + * sun.hotspot.WhiteBox$WhiteBoxPermission * @run main/othervm -Xbootclasspath/a:. -Xmixed -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI LockCompilationTest * @summary testing of WB::lock/unlockCompilation() */ @@ -42,10 +42,25 @@ import compiler.whitebox.CompilerWhiteBoxTest; import jdk.test.lib.Asserts; public class LockCompilationTest extends CompilerWhiteBoxTest { + public static void main(String[] args) throws Exception { - // This case waits for 10 seconds and verifies that the method hasn't been + // This case waits for 5 seconds and verifies that the method hasn't been // compiled during that time. Only do that for one of the test cases. - CompilerWhiteBoxTest.main(LockCompilationTest::new, new String[] {"METHOD_TEST"}); + + // Only compile SimpleTestCase$Helper.method and exclude all other to ensure no + // contention on the compile queue causes problems. + String directive = + "[{ match:\"*SimpleTestCase$Helper.method\", Exclude:false}, " + + " { match:\"*.*\", Exclude:true}]"; + if (WHITE_BOX.addCompilerDirective(directive) != 2) { + throw new RuntimeException("Could not add directive"); + } + try { + CompilerWhiteBoxTest.main(LockCompilationTest::new, new String[] {"METHOD_TEST"}); + } finally { + WHITE_BOX.removeCompilerDirective(2); + } + } private LockCompilationTest(TestCase testCase) { @@ -66,7 +81,9 @@ public class LockCompilationTest extends CompilerWhiteBoxTest { // to check if it works correctly w/ safepoints System.out.println("going to safepoint"); WHITE_BOX.fullGC(); - waitBackgroundCompilation(); + // Sleep a while and then make sure the compile is still waiting + Thread.sleep(5000); + Asserts.assertTrue( WHITE_BOX.isMethodQueuedForCompilation(method), method + " must be in queue"); From 38f31bbade1e79c582e39cd7fee9d66308c97595 Mon Sep 17 00:00:00 2001 From: Guy Delamarter Date: Mon, 21 Mar 2016 08:42:00 +0100 Subject: [PATCH 045/162] 8144693: Intrinsify StringCoding.hasNegatives() on SPARC Implemented C2 instrinsic for StringCode.hasNegatives() on SPARC. Reviewed-by: kvn, jrose, thartmann --- jdk/src/java.base/share/classes/java/lang/StringCoding.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/jdk/src/java.base/share/classes/java/lang/StringCoding.java b/jdk/src/java.base/share/classes/java/lang/StringCoding.java index fe875372218..ccbe6f24b43 100644 --- a/jdk/src/java.base/share/classes/java/lang/StringCoding.java +++ b/jdk/src/java.base/share/classes/java/lang/StringCoding.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -146,7 +146,7 @@ class StringCoding { } @HotSpotIntrinsicCandidate - private static boolean hasNegatives(byte[] ba, int off, int len) { + public static boolean hasNegatives(byte[] ba, int off, int len) { for (int i = off; i < off + len; i++) { if (ba[i] < 0) { return true; From df733afc3c70ed607f3c22e3823001ebaebb8ca4 Mon Sep 17 00:00:00 2001 From: Semyon Sadetsky Date: Tue, 22 Mar 2016 13:07:27 +0300 Subject: [PATCH 046/162] 8152201: [TEST_BUG] test/java/awt/Window/FindOwner/FindOwnerTest.java has @test tag Reviewed-by: prr, serb, alexsch --- jdk/test/java/awt/Window/FindOwner/FindOwnerTest.java | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/jdk/test/java/awt/Window/FindOwner/FindOwnerTest.java b/jdk/test/java/awt/Window/FindOwner/FindOwnerTest.java index 916c860a5f3..8c09faa6b8a 100644 --- a/jdk/test/java/awt/Window/FindOwner/FindOwnerTest.java +++ b/jdk/test/java/awt/Window/FindOwner/FindOwnerTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2016 Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -21,12 +21,10 @@ * questions. */ -/* @test - @bug 8139227 +/* @bug 8139227 @summary Text fields in JPopupMenu structure do not receive focus in hosted Applets @author Semyon Sadetsky - @run applet FindOwnerTest.html */ import java.applet.Applet; From 0e3d547866420715bcecd815e42f8b7863545c37 Mon Sep 17 00:00:00 2001 From: Avik Niyogi Date: Tue, 22 Mar 2016 16:07:36 +0530 Subject: [PATCH 047/162] 8148555: [macosx] An uncaught exception was raised entering Emoji into JTextArea Reviewed-by: serb, alexsch, rchamyal --- .../macosx/native/libawt_lwawt/awt/AWTView.m | 439 +++++++++--------- .../JTextArea/8148555/JTextAreaEmojiTest.java | 160 +++++++ 2 files changed, 385 insertions(+), 214 deletions(-) create mode 100644 jdk/test/javax/swing/JTextArea/8148555/JTextAreaEmojiTest.java diff --git a/jdk/src/java.desktop/macosx/native/libawt_lwawt/awt/AWTView.m b/jdk/src/java.desktop/macosx/native/libawt_lwawt/awt/AWTView.m index 8070995baa6..67115418d38 100644 --- a/jdk/src/java.desktop/macosx/native/libawt_lwawt/awt/AWTView.m +++ b/jdk/src/java.desktop/macosx/native/libawt_lwawt/awt/AWTView.m @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -43,6 +43,7 @@ -(void) resetTrackingArea; -(void) deliverJavaKeyEventHelper: (NSEvent*) event; -(BOOL) isCodePointInUnicodeBlockNeedingIMEvent: (unichar) codePoint; +-(NSMutableString *) parseString : (id) complexString; @end // Uncomment this line to see fprintfs of each InputMethod API being called on this View @@ -66,26 +67,26 @@ static BOOL shouldUsePressAndHold() { // Note: Must be called on main (AppKit) thread only - (id) initWithRect: (NSRect) rect platformView: (jobject) cPlatformView - windowLayer: (CALayer*) windowLayer + windowLayer: (CALayer*) windowLayer { -AWT_ASSERT_APPKIT_THREAD; + AWT_ASSERT_APPKIT_THREAD; // Initialize ourselves self = [super initWithFrame: rect]; if (self == nil) return self; - + m_cPlatformView = cPlatformView; fInputMethodLOCKABLE = NULL; fKeyEventsNeeded = NO; fProcessingKeystroke = NO; - + fEnablePressAndHold = shouldUsePressAndHold(); fInPressAndHold = NO; fPAHNeedsToSelect = NO; - + mouseIsOver = NO; [self resetTrackingArea]; [self setAutoresizesSubviews:NO]; - + if (windowLayer != nil) { self.cglLayer = windowLayer; //Layer hosting view @@ -96,7 +97,7 @@ AWT_ASSERT_APPKIT_THREAD; //[self setLayerContentsRedrawPolicy: NSViewLayerContentsRedrawDuringViewResize]; //[self setLayerContentsPlacement: NSViewLayerContentsPlacementTopLeft]; //[self setAutoresizingMask: NSViewHeightSizable | NSViewWidthSizable]; - + #ifdef REMOTELAYER CGLLayer *parentLayer = (CGLLayer*)self.cglLayer; parentLayer.parentLayer = NULL; @@ -118,36 +119,36 @@ AWT_ASSERT_APPKIT_THREAD; } #endif /* REMOTELAYER */ } - + return self; } - (void) dealloc { -AWT_ASSERT_APPKIT_THREAD; - + AWT_ASSERT_APPKIT_THREAD; + self.cglLayer = nil; - + JNIEnv *env = [ThreadUtilities getJNIEnvUncached]; (*env)->DeleteGlobalRef(env, m_cPlatformView); m_cPlatformView = NULL; - + if (fInputMethodLOCKABLE != NULL) { JNIEnv *env = [ThreadUtilities getJNIEnvUncached]; - + JNFDeleteGlobalRef(env, fInputMethodLOCKABLE); fInputMethodLOCKABLE = NULL; } - - + + [super dealloc]; } - (void) viewDidMoveToWindow { -AWT_ASSERT_APPKIT_THREAD; - + AWT_ASSERT_APPKIT_THREAD; + [AWTToolkit eventCountPlusPlus]; - + [JNFRunLoop performOnMainThreadWaiting:NO withBlock:^() { [[self window] makeFirstResponder: self]; }]; @@ -231,7 +232,7 @@ AWT_ASSERT_APPKIT_THREAD; NSPoint eventLocation = [event locationInWindow]; NSPoint localPoint = [self convertPoint: eventLocation fromView: nil]; - + if ([self mouse: localPoint inRect: [self bounds]]) { [self deliverJavaMouseEvent: event]; } else { @@ -275,10 +276,10 @@ AWT_ASSERT_APPKIT_THREAD; - (void) keyDown: (NSEvent *)event { fProcessingKeystroke = YES; fKeyEventsNeeded = YES; - + // Allow TSM to look at the event and potentially send back NSTextInputClient messages. [self interpretKeyEvents:[NSArray arrayWithObject:event]]; - + if (fEnablePressAndHold && [event willBeHandledByComplexInputMethod]) { fProcessingKeystroke = NO; if (!fInPressAndHold) { @@ -287,14 +288,14 @@ AWT_ASSERT_APPKIT_THREAD; } return; } - + NSString *eventCharacters = [event characters]; BOOL isDeadKey = (eventCharacters != nil && [eventCharacters length] == 0); - + if ((![self hasMarkedText] && fKeyEventsNeeded) || isDeadKey) { [self deliverJavaKeyEventHelper: event]; } - + fProcessingKeystroke = NO; } @@ -307,15 +308,15 @@ AWT_ASSERT_APPKIT_THREAD; } - (BOOL) performKeyEquivalent: (NSEvent *) event { - // if IM is active key events should be ignored + // if IM is active key events should be ignored if (![self hasMarkedText] && !fInPressAndHold) { [self deliverJavaKeyEventHelper: event]; } - - // Workaround for 8020209: special case for "Cmd =" and "Cmd ." - // because Cocoa calls performKeyEquivalent twice for these keystrokes - NSUInteger modFlags = [event modifierFlags] & - (NSCommandKeyMask | NSAlternateKeyMask | NSShiftKeyMask | NSControlKeyMask); + + // Workaround for 8020209: special case for "Cmd =" and "Cmd ." + // because Cocoa calls performKeyEquivalent twice for these keystrokes + NSUInteger modFlags = [event modifierFlags] & + (NSCommandKeyMask | NSAlternateKeyMask | NSShiftKeyMask | NSControlKeyMask); if (modFlags == NSCommandKeyMask) { NSString *eventChars = [event charactersIgnoringModifiers]; if ([eventChars length] == 1) { @@ -325,9 +326,9 @@ AWT_ASSERT_APPKIT_THREAD; return YES; } } - + } - + return NO; } @@ -341,36 +342,36 @@ AWT_ASSERT_APPKIT_THREAD; if ([window isKindOfClass: [AWTWindow_Panel class]] || [window isKindOfClass: [AWTWindow_Normal class]]) { isEnabled = [(AWTWindow*)[window delegate] isEnabled]; } - + if (!isEnabled) { return; } - + NSEventType type = [event type]; - + // check synthesized mouse entered/exited events if ((type == NSMouseEntered && mouseIsOver) || (type == NSMouseExited && !mouseIsOver)) { return; }else if ((type == NSMouseEntered && !mouseIsOver) || (type == NSMouseExited && mouseIsOver)) { mouseIsOver = !mouseIsOver; } - + [AWTToolkit eventCountPlusPlus]; - + JNIEnv *env = [ThreadUtilities getJNIEnv]; - + NSPoint eventLocation = [event locationInWindow]; NSPoint localPoint = [self convertPoint: eventLocation fromView: nil]; NSPoint absP = [NSEvent mouseLocation]; - + // Convert global numbers between Cocoa's coordinate system and Java. // TODO: need consitent way for doing that both with global as well as with local coordinates. // The reason to do it here is one more native method for getting screen dimension otherwise. - + NSRect screenRect = [[[NSScreen screens] objectAtIndex:0] frame]; absP.y = screenRect.size.height - absP.y; jint clickCount; - + if (type == NSMouseEntered || type == NSMouseExited || type == NSScrollWheel || @@ -379,7 +380,7 @@ AWT_ASSERT_APPKIT_THREAD; } else { clickCount = [event clickCount]; } - + static JNF_CLASS_CACHE(jc_NSEvent, "sun/lwawt/macosx/NSEvent"); static JNF_CTOR_CACHE(jctor_NSEvent, jc_NSEvent, "(IIIIIIIIDD)V"); jobject jEvent = JNFNewObject(env, jctor_NSEvent, @@ -392,7 +393,7 @@ AWT_ASSERT_APPKIT_THREAD; [event deltaY], [event deltaX]); CHECK_NULL(jEvent); - + static JNF_CLASS_CACHE(jc_PlatformView, "sun/lwawt/macosx/CPlatformView"); static JNF_MEMBER_CACHE(jm_deliverMouseEvent, jc_PlatformView, "deliverMouseEvent", "(Lsun/lwawt/macosx/NSEvent;)V"); JNFCallVoidMethod(env, m_cPlatformView, jm_deliverMouseEvent, jEvent); @@ -404,10 +405,10 @@ AWT_ASSERT_APPKIT_THREAD; [self removeTrackingArea:rolloverTrackingArea]; [rolloverTrackingArea release]; } - + int options = (NSTrackingActiveAlways | NSTrackingMouseEnteredAndExited | NSTrackingMouseMoved | NSTrackingEnabledDuringMouseDrag); - + rolloverTrackingArea = [[NSTrackingArea alloc] initWithRect:[self visibleRect] options: options owner:self @@ -434,17 +435,17 @@ AWT_ASSERT_APPKIT_THREAD; } [sLastKeyEvent release]; sLastKeyEvent = [event retain]; - + [AWTToolkit eventCountPlusPlus]; JNIEnv *env = [ThreadUtilities getJNIEnv]; - + jstring characters = NULL; jstring charactersIgnoringModifiers = NULL; if ([event type] != NSFlagsChanged) { characters = JNFNSToJavaString(env, [event characters]); charactersIgnoringModifiers = JNFNSToJavaString(env, [event charactersIgnoringModifiers]); } - + static JNF_CLASS_CACHE(jc_NSEvent, "sun/lwawt/macosx/NSEvent"); static JNF_CTOR_CACHE(jctor_NSEvent, jc_NSEvent, "(IISLjava/lang/String;Ljava/lang/String;)V"); jobject jEvent = JNFNewObject(env, jctor_NSEvent, @@ -454,12 +455,12 @@ AWT_ASSERT_APPKIT_THREAD; characters, charactersIgnoringModifiers); CHECK_NULL(jEvent); - + static JNF_CLASS_CACHE(jc_PlatformView, "sun/lwawt/macosx/CPlatformView"); static JNF_MEMBER_CACHE(jm_deliverKeyEvent, jc_PlatformView, "deliverKeyEvent", "(Lsun/lwawt/macosx/NSEvent;)V"); JNFCallVoidMethod(env, m_cPlatformView, jm_deliverKeyEvent, jEvent); - + if (characters != NULL) { (*env)->DeleteLocalRef(env, characters); } @@ -479,34 +480,34 @@ AWT_ASSERT_APPKIT_THREAD; - (void) drawRect:(NSRect)dirtyRect { -AWT_ASSERT_APPKIT_THREAD; - + AWT_ASSERT_APPKIT_THREAD; + [super drawRect:dirtyRect]; JNIEnv *env = [ThreadUtilities getJNIEnv]; if (env != NULL) { -/* - if ([self inLiveResize]) { - NSRect rs[4]; - NSInteger count; - [self getRectsExposedDuringLiveResize:rs count:&count]; - for (int i = 0; i < count; i++) { - JNU_CallMethodByName(env, NULL, [m_awtWindow cPlatformView], - "deliverWindowDidExposeEvent", "(FFFF)V", - (jfloat)rs[i].origin.x, (jfloat)rs[i].origin.y, - (jfloat)rs[i].size.width, (jfloat)rs[i].size.height); - if ((*env)->ExceptionOccurred(env)) { - (*env)->ExceptionDescribe(env); - (*env)->ExceptionClear(env); - } - } - } else { -*/ + /* + if ([self inLiveResize]) { + NSRect rs[4]; + NSInteger count; + [self getRectsExposedDuringLiveResize:rs count:&count]; + for (int i = 0; i < count; i++) { + JNU_CallMethodByName(env, NULL, [m_awtWindow cPlatformView], + "deliverWindowDidExposeEvent", "(FFFF)V", + (jfloat)rs[i].origin.x, (jfloat)rs[i].origin.y, + (jfloat)rs[i].size.width, (jfloat)rs[i].size.height); + if ((*env)->ExceptionOccurred(env)) { + (*env)->ExceptionDescribe(env); + (*env)->ExceptionClear(env); + } + } + } else { + */ static JNF_CLASS_CACHE(jc_CPlatformView, "sun/lwawt/macosx/CPlatformView"); static JNF_MEMBER_CACHE(jm_deliverWindowDidExposeEvent, jc_CPlatformView, "deliverWindowDidExposeEvent", "()V"); JNFCallVoidMethod(env, m_cPlatformView, jm_deliverWindowDidExposeEvent); -/* - } -*/ + /* + } + */ } } @@ -518,6 +519,15 @@ AWT_ASSERT_APPKIT_THREAD; return NO; } +-(NSMutableString *) parseString : (id) complexString { + if ([complexString isKindOfClass:[NSString class]]) { + return [complexString mutableCopy]; + } + else { + return [complexString mutableString]; + } +} + // NSAccessibility support - (jobject)awtComponent:(JNIEnv*)env { @@ -557,17 +567,17 @@ AWT_ASSERT_APPKIT_THREAD; - (id)accessibilityAttributeValue:(NSString *)attribute { AWT_ASSERT_APPKIT_THREAD; - + if ([attribute isEqualToString:NSAccessibilityChildrenAttribute]) { JNIEnv *env = [ThreadUtilities getJNIEnv]; - + (*env)->PushLocalFrame(env, 4); - + id result = NSAccessibilityUnignoredChildrenForOnlyChild([self getAxData:env]); - + (*env)->PopLocalFrame(env, NULL); - + return result; } else @@ -584,28 +594,28 @@ AWT_ASSERT_APPKIT_THREAD; { AWT_ASSERT_APPKIT_THREAD; JNIEnv *env = [ThreadUtilities getJNIEnv]; - + (*env)->PushLocalFrame(env, 4); - + id result = [[self getAxData:env] accessibilityHitTest:point withEnv:env]; - + (*env)->PopLocalFrame(env, NULL); - + return result; } - (id)accessibilityFocusedUIElement { AWT_ASSERT_APPKIT_THREAD; - + JNIEnv *env = [ThreadUtilities getJNIEnv]; - + (*env)->PushLocalFrame(env, 4); - + id result = [[self getAxData:env] accessibilityFocusedUIElement]; - + (*env)->PopLocalFrame(env, NULL); - + return result; } @@ -625,7 +635,8 @@ AWT_ASSERT_APPKIT_THREAD; NSString *selectedText = [self accessibleSelectedText]; NSAttributedString *styledText = [[NSAttributedString alloc] initWithString:selectedText]; NSData *rtfdData = [styledText RTFDFromRange:NSMakeRange(0, [styledText length]) - documentAttributes:@{NSDocumentTypeDocumentAttribute: NSRTFTextDocumentType}]; + documentAttributes: + @{NSDocumentTypeDocumentAttribute: NSRTFTextDocumentType}]; [styledText release]; return rtfdData; } @@ -643,12 +654,12 @@ AWT_ASSERT_APPKIT_THREAD; - (id)validRequestorForSendType:(NSString *)sendType returnType:(NSString *)returnType { if ([[self window] firstResponder] != self) return nil; // let AWT components handle themselves - + if ([sendType isEqual:NSStringPboardType] || [returnType isEqual:NSStringPboardType]) { NSString *selectedText = [self accessibleSelectedText]; if (selectedText) return self; } - + return nil; } @@ -660,13 +671,13 @@ AWT_ASSERT_APPKIT_THREAD; [pboard declareTypes:[NSArray arrayWithObject:NSStringPboardType] owner:nil]; return [pboard setString:[self accessibleSelectedText] forType:NSStringPboardType]; } - + if ([types containsObject:NSRTFDPboardType]) { [pboard declareTypes:[NSArray arrayWithObject:NSRTFDPboardType] owner:nil]; return [pboard setData:[self accessibleSelectedTextAsRTFD] forType:NSRTFDPboardType]; } - + return NO; } @@ -678,17 +689,17 @@ AWT_ASSERT_APPKIT_THREAD; NSString *text = [pboard stringForType:NSStringPboardType]; return [self replaceAccessibleTextSelection:text]; } - + if ([[pboard types] containsObject:NSRTFDPboardType]) { NSData *rtfdData = [pboard dataForType:NSRTFDPboardType]; NSAttributedString *styledText = [[NSAttributedString alloc] initWithRTFD:rtfdData documentAttributes:NULL]; NSString *text = [styledText string]; [styledText release]; - + return [self replaceAccessibleTextSelection:text]; } - + return NO; } @@ -710,12 +721,12 @@ AWT_ASSERT_APPKIT_THREAD; // If draggingSource is nil route the message to the superclass (if responding to the selector): CDragSource *dragSource = self._dragSource; NSDragOperation dragOp = NSDragOperationNone; - + if (dragSource != nil) dragOp = [dragSource draggingSourceOperationMaskForLocal:flag]; else if ([super respondsToSelector:@selector(draggingSourceOperationMaskForLocal:)]) dragOp = [super draggingSourceOperationMaskForLocal:flag]; - + return dragOp; } @@ -724,12 +735,12 @@ AWT_ASSERT_APPKIT_THREAD; // If draggingSource is nil route the message to the superclass (if responding to the selector): CDragSource *dragSource = self._dragSource; NSArray* array = nil; - + if (dragSource != nil) array = [dragSource namesOfPromisedFilesDroppedAtDestination:dropDestination]; else if ([super respondsToSelector:@selector(namesOfPromisedFilesDroppedAtDestination:)]) array = [super namesOfPromisedFilesDroppedAtDestination:dropDestination]; - + return array; } @@ -737,7 +748,7 @@ AWT_ASSERT_APPKIT_THREAD; { // If draggingSource is nil route the message to the superclass (if responding to the selector): CDragSource *dragSource = self._dragSource; - + if (dragSource != nil) [dragSource draggedImage:image beganAt:screenPoint]; else if ([super respondsToSelector:@selector(draggedImage::)]) @@ -748,7 +759,7 @@ AWT_ASSERT_APPKIT_THREAD; { // If draggingSource is nil route the message to the superclass (if responding to the selector): CDragSource *dragSource = self._dragSource; - + if (dragSource != nil) [dragSource draggedImage:image endedAt:screenPoint operation:operation]; else if ([super respondsToSelector:@selector(draggedImage:::)]) @@ -759,7 +770,7 @@ AWT_ASSERT_APPKIT_THREAD; { // If draggingSource is nil route the message to the superclass (if responding to the selector): CDragSource *dragSource = self._dragSource; - + if (dragSource != nil) [dragSource draggedImage:image movedTo:screenPoint]; else if ([super respondsToSelector:@selector(draggedImage::)]) @@ -771,12 +782,12 @@ AWT_ASSERT_APPKIT_THREAD; // If draggingSource is nil route the message to the superclass (if responding to the selector): CDragSource *dragSource = self._dragSource; BOOL result = FALSE; - + if (dragSource != nil) result = [dragSource ignoreModifierKeysWhileDragging]; else if ([super respondsToSelector:@selector(ignoreModifierKeysWhileDragging)]) result = [super ignoreModifierKeysWhileDragging]; - + return result; } @@ -789,12 +800,12 @@ AWT_ASSERT_APPKIT_THREAD; // If draggingDestination is nil route the message to the superclass: CDropTarget *dropTarget = self._dropTarget; NSDragOperation dragOp = NSDragOperationNone; - + if (dropTarget != nil) dragOp = [dropTarget draggingEntered:sender]; else if ([super respondsToSelector:@selector(draggingEntered:)]) dragOp = [super draggingEntered:sender]; - + return dragOp; } @@ -803,12 +814,12 @@ AWT_ASSERT_APPKIT_THREAD; // If draggingDestination is nil route the message to the superclass: CDropTarget *dropTarget = self._dropTarget; NSDragOperation dragOp = NSDragOperationNone; - + if (dropTarget != nil) dragOp = [dropTarget draggingUpdated:sender]; else if ([super respondsToSelector:@selector(draggingUpdated:)]) dragOp = [super draggingUpdated:sender]; - + return dragOp; } @@ -816,7 +827,7 @@ AWT_ASSERT_APPKIT_THREAD; { // If draggingDestination is nil route the message to the superclass: CDropTarget *dropTarget = self._dropTarget; - + if (dropTarget != nil) [dropTarget draggingExited:sender]; else if ([super respondsToSelector:@selector(draggingExited:)]) @@ -828,12 +839,12 @@ AWT_ASSERT_APPKIT_THREAD; // If draggingDestination is nil route the message to the superclass: CDropTarget *dropTarget = self._dropTarget; BOOL result = FALSE; - + if (dropTarget != nil) result = [dropTarget prepareForDragOperation:sender]; else if ([super respondsToSelector:@selector(prepareForDragOperation:)]) result = [super prepareForDragOperation:sender]; - + return result; } @@ -842,12 +853,12 @@ AWT_ASSERT_APPKIT_THREAD; // If draggingDestination is nil route the message to the superclass: CDropTarget *dropTarget = self._dropTarget; BOOL result = FALSE; - + if (dropTarget != nil) result = [dropTarget performDragOperation:sender]; else if ([super respondsToSelector:@selector(performDragOperation:)]) result = [super performDragOperation:sender]; - + return result; } @@ -855,7 +866,7 @@ AWT_ASSERT_APPKIT_THREAD; { // If draggingDestination is nil route the message to the superclass: CDropTarget *dropTarget = self._dropTarget; - + if (dropTarget != nil) [dropTarget concludeDragOperation:sender]; else if ([super respondsToSelector:@selector(concludeDragOperation:)]) @@ -866,7 +877,7 @@ AWT_ASSERT_APPKIT_THREAD; { // If draggingDestination is nil route the message to the superclass: CDropTarget *dropTarget = self._dropTarget; - + if (dropTarget != nil) [dropTarget draggingEnded:sender]; else if ([super respondsToSelector:@selector(draggingEnded:)]) @@ -885,49 +896,49 @@ JNF_CLASS_CACHE(jc_CInputMethod, "sun/lwawt/macosx/CInputMethod"); #ifdef IM_DEBUG fprintf(stderr, "AWTView InputMethod Selector Called : [insertText]: %s\n", [aString UTF8String]); #endif // IM_DEBUG - + if (fInputMethodLOCKABLE == NULL) { return; } - + // Insert happens at the end of PAH fInPressAndHold = NO; - + // insertText gets called when the user commits text generated from an input method. It also gets // called during ordinary input as well. We only need to send an input method event when we have marked // text, or 'text in progress'. We also need to send the event if we get an insert text out of the blue! // (i.e., when the user uses the Character palette or Inkwell), or when the string to insert is a complex // Unicode value. - NSUInteger utf16Length = [aString lengthOfBytesUsingEncoding:NSUTF16StringEncoding]; - NSUInteger utf8Length = [aString lengthOfBytesUsingEncoding:NSUTF8StringEncoding]; + + NSMutableString * useString = [self parseString:aString]; + NSUInteger utf16Length = [useString lengthOfBytesUsingEncoding:NSUTF16StringEncoding]; + NSUInteger utf8Length = [useString lengthOfBytesUsingEncoding:NSUTF8StringEncoding]; BOOL aStringIsComplex = NO; if ((utf16Length > 2) || - ((utf8Length > 1) && [self isCodePointInUnicodeBlockNeedingIMEvent:[aString characterAtIndex:0]])) { + ((utf8Length > 1) && [self isCodePointInUnicodeBlockNeedingIMEvent:[useString characterAtIndex:0]])) { aStringIsComplex = YES; } - + if ([self hasMarkedText] || !fProcessingKeystroke || aStringIsComplex) { JNIEnv *env = [ThreadUtilities getJNIEnv]; - + static JNF_MEMBER_CACHE(jm_selectPreviousGlyph, jc_CInputMethod, "selectPreviousGlyph", "()V"); // We need to select the previous glyph so that it is overwritten. if (fPAHNeedsToSelect) { JNFCallVoidMethod(env, fInputMethodLOCKABLE, jm_selectPreviousGlyph); fPAHNeedsToSelect = NO; } - + static JNF_MEMBER_CACHE(jm_insertText, jc_CInputMethod, "insertText", "(Ljava/lang/String;)V"); - jstring insertedText = JNFNSToJavaString(env, aString); + jstring insertedText = JNFNSToJavaString(env, useString); JNFCallVoidMethod(env, fInputMethodLOCKABLE, jm_insertText, insertedText); // AWT_THREADING Safe (AWTRunLoopMode) (*env)->DeleteLocalRef(env, insertedText); - + // The input method event will create psuedo-key events for each character in the committed string. // We also don't want to send the character that triggered the insertText, usually a return. [3337563] fKeyEventsNeeded = NO; } - fPAHNeedsToSelect = NO; - } - (void) doCommandBySelector:(SEL)aSelector @@ -947,7 +958,7 @@ JNF_CLASS_CACHE(jc_CInputMethod, "sun/lwawt/macosx/CInputMethod"); { if (!fInputMethodLOCKABLE) return; - + BOOL isAttributedString = [aString isKindOfClass:[NSAttributedString class]]; NSAttributedString *attrString = (isAttributedString ? (NSAttributedString *)aString : nil); NSString *incomingString = (isAttributedString ? [aString string] : aString); @@ -958,14 +969,14 @@ JNF_CLASS_CACHE(jc_CInputMethod, "sun/lwawt/macosx/CInputMethod"); static JNF_MEMBER_CACHE(jm_addAttribute, jc_CInputMethod, "addAttribute", "(ZZII)V"); static JNF_MEMBER_CACHE(jm_dispatchText, jc_CInputMethod, "dispatchText", "(IIZ)V"); JNIEnv *env = [ThreadUtilities getJNIEnv]; - + // NSInputContext already did the analysis of the TSM event and created attributes indicating // the underlining and color that should be done to the string. We need to look at the underline // style and color to determine what kind of Java hilighting needs to be done. jstring inProcessText = JNFNSToJavaString(env, incomingString); JNFCallVoidMethod(env, fInputMethodLOCKABLE, jm_startIMUpdate, inProcessText); // AWT_THREADING Safe (AWTRunLoopMode) (*env)->DeleteLocalRef(env, inProcessText); - + if (isAttributedString) { NSUInteger length; NSRange effectiveRange; @@ -981,25 +992,25 @@ JNF_CLASS_CACHE(jc_CInputMethod, "sun/lwawt/macosx/CInputMethod"); (NSNumber *)[attributes objectForKey:NSUnderlineStyleAttributeName]; NSInteger underlineSize = [underlineSizeObj integerValue]; isThickUnderline = (underlineSize > 1); - + NSColor *underlineColorObj = (NSColor *)[attributes objectForKey:NSUnderlineColorAttributeName]; isGray = !([underlineColorObj isEqual:[NSColor blackColor]]); - + JNFCallVoidMethod(env, fInputMethodLOCKABLE, jm_addAttribute, isThickUnderline, isGray, effectiveRange.location, effectiveRange.length); // AWT_THREADING Safe (AWTRunLoopMode) } } } - + static JNF_MEMBER_CACHE(jm_selectPreviousGlyph, jc_CInputMethod, "selectPreviousGlyph", "()V"); // We need to select the previous glyph so that it is overwritten. if (fPAHNeedsToSelect) { JNFCallVoidMethod(env, fInputMethodLOCKABLE, jm_selectPreviousGlyph); fPAHNeedsToSelect = NO; } - + JNFCallVoidMethod(env, fInputMethodLOCKABLE, jm_dispatchText, selectionRange.location, selectionRange.length, JNI_FALSE); // AWT_THREADING Safe (AWTRunLoopMode) - + // If the marked text is being cleared (zero-length string) don't handle the key event. if ([incomingString length] == 0) { fKeyEventsNeeded = NO; @@ -1011,16 +1022,16 @@ JNF_CLASS_CACHE(jc_CInputMethod, "sun/lwawt/macosx/CInputMethod"); #ifdef IM_DEBUG fprintf(stderr, "AWTView InputMethod Selector Called : [unmarkText]\n"); #endif // IM_DEBUG - + if (!fInputMethodLOCKABLE) { return; } - + // unmarkText cancels any input in progress and commits it to the text field. static JNF_MEMBER_CACHE(jm_unmarkText, jc_CInputMethod, "unmarkText", "()V"); JNIEnv *env = [ThreadUtilities getJNIEnv]; JNFCallVoidMethod(env, fInputMethodLOCKABLE, jm_unmarkText); // AWT_THREADING Safe (AWTRunLoopMode) - + } - (BOOL) hasMarkedText @@ -1028,24 +1039,24 @@ JNF_CLASS_CACHE(jc_CInputMethod, "sun/lwawt/macosx/CInputMethod"); #ifdef IM_DEBUG fprintf(stderr, "AWTView InputMethod Selector Called : [hasMarkedText]\n"); #endif // IM_DEBUG - + if (!fInputMethodLOCKABLE) { return NO; } - + static JNF_MEMBER_CACHE(jf_fCurrentText, jc_CInputMethod, "fCurrentText", "Ljava/text/AttributedString;"); static JNF_MEMBER_CACHE(jf_fCurrentTextLength, jc_CInputMethod, "fCurrentTextLength", "I"); JNIEnv *env = [ThreadUtilities getJNIEnv]; jobject currentText = JNFGetObjectField(env, fInputMethodLOCKABLE, jf_fCurrentText); - + jint currentTextLength = JNFGetIntField(env, fInputMethodLOCKABLE, jf_fCurrentTextLength); - + BOOL hasMarkedText = (currentText != NULL && currentTextLength > 0); - + if (currentText != NULL) { (*env)->DeleteLocalRef(env, currentText); } - + return hasMarkedText; } @@ -1054,7 +1065,7 @@ JNF_CLASS_CACHE(jc_CInputMethod, "sun/lwawt/macosx/CInputMethod"); #ifdef IM_DEBUG fprintf(stderr, "AWTView InputMethod Selector Called : [conversationIdentifier]\n"); #endif // IM_DEBUG - + return (NSInteger) self; } @@ -1066,16 +1077,16 @@ JNF_CLASS_CACHE(jc_CInputMethod, "sun/lwawt/macosx/CInputMethod"); #ifdef IM_DEBUG fprintf(stderr, "AWTView InputMethod Selector Called : [attributedSubstringFromRange] location=%lu, length=%lu\n", (unsigned long)theRange.location, (unsigned long)theRange.length); #endif // IM_DEBUG - + static JNF_MEMBER_CACHE(jm_substringFromRange, jc_CInputMethod, "attributedSubstringFromRange", "(II)Ljava/lang/String;"); JNIEnv *env = [ThreadUtilities getJNIEnv]; jobject theString = JNFCallObjectMethod(env, fInputMethodLOCKABLE, jm_substringFromRange, theRange.location, theRange.length); // AWT_THREADING Safe (AWTRunLoopMode) - + id result = [[[NSAttributedString alloc] initWithString:JNFJavaToNSString(env, theString)] autorelease]; #ifdef IM_DEBUG NSLog(@"attributedSubstringFromRange returning \"%@\"", result); #endif // IM_DEBUG - + (*env)->DeleteLocalRef(env, theString); return result; } @@ -1085,24 +1096,24 @@ JNF_CLASS_CACHE(jc_CInputMethod, "sun/lwawt/macosx/CInputMethod"); */ - (NSRange) markedRange { - + #ifdef IM_DEBUG fprintf(stderr, "AWTView InputMethod Selector Called : [markedRange]\n"); #endif // IM_DEBUG - + if (!fInputMethodLOCKABLE) { return NSMakeRange(NSNotFound, 0); } - + static JNF_MEMBER_CACHE(jm_markedRange, jc_CInputMethod, "markedRange", "()[I"); JNIEnv *env = [ThreadUtilities getJNIEnv]; jarray array; jboolean isCopy; jint *_array; NSRange range = NSMakeRange(NSNotFound, 0); - + array = JNFCallObjectMethod(env, fInputMethodLOCKABLE, jm_markedRange); // AWT_THREADING Safe (AWTRunLoopMode) - + if (array) { _array = (*env)->GetIntArrayElements(env, array, &isCopy); if (_array != NULL) { @@ -1116,7 +1127,7 @@ JNF_CLASS_CACHE(jc_CInputMethod, "sun/lwawt/macosx/CInputMethod"); } (*env)->DeleteLocalRef(env, array); } - + return range; } @@ -1128,18 +1139,18 @@ JNF_CLASS_CACHE(jc_CInputMethod, "sun/lwawt/macosx/CInputMethod"); if (!fInputMethodLOCKABLE) { return NSMakeRange(NSNotFound, 0); } - + static JNF_MEMBER_CACHE(jm_selectedRange, jc_CInputMethod, "selectedRange", "()[I"); JNIEnv *env = [ThreadUtilities getJNIEnv]; jarray array; jboolean isCopy; jint *_array; NSRange range = NSMakeRange(NSNotFound, 0); - + #ifdef IM_DEBUG fprintf(stderr, "AWTView InputMethod Selector Called : [selectedRange]\n"); #endif // IM_DEBUG - + array = JNFCallObjectMethod(env, fInputMethodLOCKABLE, jm_selectedRange); // AWT_THREADING Safe (AWTRunLoopMode) if (array) { _array = (*env)->GetIntArrayElements(env, array, &isCopy); @@ -1150,7 +1161,7 @@ JNF_CLASS_CACHE(jc_CInputMethod, "sun/lwawt/macosx/CInputMethod"); } (*env)->DeleteLocalRef(env, array); } - + return range; } @@ -1161,7 +1172,7 @@ JNF_CLASS_CACHE(jc_CInputMethod, "sun/lwawt/macosx/CInputMethod"); if (!fInputMethodLOCKABLE) { return NSZeroRect; } - + static JNF_MEMBER_CACHE(jm_firstRectForCharacterRange, jc_CInputMethod, "firstRectForCharacterRange", "(I)[I"); JNIEnv *env = [ThreadUtilities getJNIEnv]; @@ -1169,16 +1180,16 @@ JNF_CLASS_CACHE(jc_CInputMethod, "sun/lwawt/macosx/CInputMethod"); jboolean isCopy; jint *_array; NSRect rect; - + #ifdef IM_DEBUG fprintf(stderr, "AWTView InputMethod Selector Called : [firstRectForCharacterRange:] location=%lu, length=%lu\n", (unsigned long)theRange.location, (unsigned long)theRange.length); #endif // IM_DEBUG - + array = JNFCallObjectMethod(env, fInputMethodLOCKABLE, jm_firstRectForCharacterRange, theRange.location); // AWT_THREADING Safe (AWTRunLoopMode) - + _array = (*env)->GetIntArrayElements(env, array, &isCopy); if (_array) { rect = ConvertNSScreenRect(env, NSMakeRect(_array[0], _array[1], _array[2], _array[3])); @@ -1187,7 +1198,7 @@ JNF_CLASS_CACHE(jc_CInputMethod, "sun/lwawt/macosx/CInputMethod"); rect = NSZeroRect; } (*env)->DeleteLocalRef(env, array); - + #ifdef IM_DEBUG fprintf(stderr, "firstRectForCharacterRange returning x=%f, y=%f, width=%f, height=%f\n", @@ -1204,23 +1215,23 @@ JNF_CLASS_CACHE(jc_CInputMethod, "sun/lwawt/macosx/CInputMethod"); if (!fInputMethodLOCKABLE) { return NSNotFound; } - + static JNF_MEMBER_CACHE(jm_characterIndexForPoint, jc_CInputMethod, "characterIndexForPoint", "(II)I"); JNIEnv *env = [ThreadUtilities getJNIEnv]; - + NSPoint flippedLocation = ConvertNSScreenPoint(env, thePoint); - + #ifdef IM_DEBUG fprintf(stderr, "AWTView InputMethod Selector Called : [characterIndexForPoint:(NSPoint)thePoint] x=%f, y=%f\n", flippedLocation.x, flippedLocation.y); #endif // IM_DEBUG - + jint index = JNFCallIntMethod(env, fInputMethodLOCKABLE, jm_characterIndexForPoint, (jint)flippedLocation.x, (jint)flippedLocation.y); // AWT_THREADING Safe (AWTRunLoopMode) - + #ifdef IM_DEBUG fprintf(stderr, "characterIndexForPoint returning %ld\n", index); #endif // IM_DEBUG - + if (index == -1) { return NSNotFound; } else { @@ -1233,7 +1244,7 @@ JNF_CLASS_CACHE(jc_CInputMethod, "sun/lwawt/macosx/CInputMethod"); #ifdef IM_DEBUG fprintf(stderr, "AWTView InputMethod Selector Called : [validAttributesForMarkedText]\n"); #endif // IM_DEBUG - + return [NSArray array]; } @@ -1242,14 +1253,14 @@ JNF_CLASS_CACHE(jc_CInputMethod, "sun/lwawt/macosx/CInputMethod"); #ifdef IM_DEBUG fprintf(stderr, "AWTView InputMethod Selector Called : [setInputMethod]\n"); #endif // IM_DEBUG - + JNIEnv *env = [ThreadUtilities getJNIEnv]; - + // Get rid of the old one if (fInputMethodLOCKABLE) { JNFDeleteGlobalRef(env, fInputMethodLOCKABLE); } - + // Save a global ref to the new input method. if (inputMethod != NULL) fInputMethodLOCKABLE = JNFNewGlobalRef(env, inputMethod); @@ -1262,7 +1273,7 @@ JNF_CLASS_CACHE(jc_CInputMethod, "sun/lwawt/macosx/CInputMethod"); #ifdef IM_DEBUG fprintf(stderr, "AWTView InputMethod Selector Called : [abandonInput]\n"); #endif // IM_DEBUG - + [ThreadUtilities performOnMainThread:@selector(markedTextAbandoned:) on:[NSInputManager currentInputManager] withObject:self waitUntilDone:YES]; [self unmarkText]; } @@ -1284,22 +1295,22 @@ Java_sun_lwawt_macosx_CPlatformView_nativeCreateView (JNIEnv *env, jobject obj, jint originX, jint originY, jint width, jint height, jlong windowLayerPtr) { __block AWTView *newView = nil; - -JNF_COCOA_ENTER(env); - + + JNF_COCOA_ENTER(env); + NSRect rect = NSMakeRect(originX, originY, width, height); jobject cPlatformView = (*env)->NewGlobalRef(env, obj); - + [ThreadUtilities performOnMainThreadWaiting:YES block:^(){ - + CALayer *windowLayer = jlong_to_ptr(windowLayerPtr); newView = [[AWTView alloc] initWithRect:rect platformView:cPlatformView windowLayer:windowLayer]; }]; - -JNF_COCOA_EXIT(env); - + + JNF_COCOA_EXIT(env); + return ptr_to_jlong(newView); } @@ -1313,24 +1324,24 @@ JNIEXPORT void JNICALL Java_sun_lwawt_macosx_CPlatformView_nativeSetAutoResizable (JNIEnv *env, jclass cls, jlong viewPtr, jboolean toResize) { -JNF_COCOA_ENTER(env); + JNF_COCOA_ENTER(env); - NSView *view = (NSView *)jlong_to_ptr(viewPtr); - - [ThreadUtilities performOnMainThreadWaiting:NO block:^(){ - - if (toResize) { - [view setAutoresizingMask: NSViewHeightSizable | NSViewWidthSizable]; - } else { - [view setAutoresizingMask: NSViewMinYMargin | NSViewMaxXMargin]; - } - - if ([view superview] != nil) { - [[view superview] setAutoresizesSubviews:(BOOL)toResize]; - } - + NSView *view = (NSView *)jlong_to_ptr(viewPtr); + + [ThreadUtilities performOnMainThreadWaiting:NO block:^(){ + + if (toResize) { + [view setAutoresizingMask: NSViewHeightSizable | NSViewWidthSizable]; + } else { + [view setAutoresizingMask: NSViewMinYMargin | NSViewMaxXMargin]; + } + + if ([view superview] != nil) { + [[view superview] setAutoresizesSubviews:(BOOL)toResize]; + } + }]; -JNF_COCOA_EXIT(env); + JNF_COCOA_EXIT(env); } /* @@ -1345,17 +1356,17 @@ Java_sun_lwawt_macosx_CPlatformView_nativeGetNSViewDisplayID { __block jint ret; //CGDirectDisplayID -JNF_COCOA_ENTER(env); + JNF_COCOA_ENTER(env); - NSView *view = (NSView *)jlong_to_ptr(viewPtr); + NSView *view = (NSView *)jlong_to_ptr(viewPtr); NSWindow *window = [view window]; [ThreadUtilities performOnMainThreadWaiting:YES block:^(){ - - ret = (jint)[[AWTWindow getNSWindowDisplayID_AppKitThread: window] intValue]; + + ret = (jint)[[AWTWindow getNSWindowDisplayID_AppKitThread: window] intValue]; }]; -JNF_COCOA_EXIT(env); + JNF_COCOA_EXIT(env); return ret; } @@ -1372,13 +1383,13 @@ Java_sun_lwawt_macosx_CPlatformView_nativeGetLocationOnScreen { jobject jRect = NULL; -JNF_COCOA_ENTER(env); + JNF_COCOA_ENTER(env); __block NSRect rect = NSZeroRect; - NSView *view = (NSView *)jlong_to_ptr(viewPtr); + NSView *view = (NSView *)jlong_to_ptr(viewPtr); [ThreadUtilities performOnMainThreadWaiting:YES block:^(){ - + NSRect viewBounds = [view bounds]; NSRect frameInWindow = [view convertRect:viewBounds toView:nil]; rect = [[view window] convertRectToScreen:frameInWindow]; @@ -1388,7 +1399,7 @@ JNF_COCOA_ENTER(env); }]; jRect = NSToJavaRect(env, rect); -JNF_COCOA_EXIT(env); + JNF_COCOA_EXIT(env); return jRect; } @@ -1404,16 +1415,16 @@ JNIEXPORT jboolean JNICALL Java_sun_lwawt_macosx_CPlatformView_nativeIsViewUnder { __block jboolean underMouse = JNI_FALSE; -JNF_COCOA_ENTER(env); + JNF_COCOA_ENTER(env); NSView *nsView = OBJC(viewPtr); - [ThreadUtilities performOnMainThreadWaiting:YES block:^(){ - NSPoint ptWindowCoords = [[nsView window] mouseLocationOutsideOfEventStream]; - NSPoint ptViewCoords = [nsView convertPoint:ptWindowCoords fromView:nil]; - underMouse = [nsView hitTest:ptViewCoords] != nil; + [ThreadUtilities performOnMainThreadWaiting:YES block:^(){ + NSPoint ptWindowCoords = [[nsView window] mouseLocationOutsideOfEventStream]; + NSPoint ptViewCoords = [nsView convertPoint:ptWindowCoords fromView:nil]; + underMouse = [nsView hitTest:ptViewCoords] != nil; }]; -JNF_COCOA_EXIT(env); + JNF_COCOA_EXIT(env); return underMouse; } diff --git a/jdk/test/javax/swing/JTextArea/8148555/JTextAreaEmojiTest.java b/jdk/test/javax/swing/JTextArea/8148555/JTextAreaEmojiTest.java new file mode 100644 index 00000000000..5b16e3c53e3 --- /dev/null +++ b/jdk/test/javax/swing/JTextArea/8148555/JTextAreaEmojiTest.java @@ -0,0 +1,160 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import java.awt.Color; +import java.awt.GridBagConstraints; +import java.awt.GridBagLayout; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import javax.swing.BorderFactory; +import javax.swing.JButton; +import javax.swing.JFrame; +import javax.swing.JPanel; +import javax.swing.JTextArea; +import javax.swing.SwingUtilities; +import static javax.swing.WindowConstants.EXIT_ON_CLOSE; + +/* @test + * @bug 8148555 + * @summary verifies JTextArea emoji enter exception. Emoji is not supported. + * @requires (os.family=="mac") + * @run main JTextAreaEmojiTest + */ +public class JTextAreaEmojiTest implements + ActionListener { + + private static GridBagLayout layout; + private static JPanel textAreaPanel; + private static JPanel mainControlPanel; + private static JPanel instructionPanel; + private static JPanel resultButtonPanel; + private static JPanel controlPanel; + private static JTextArea instructionTextArea; + private static JTextArea emojiTextArea; + private static JButton passButton; + private static JButton failButton; + + private static JFrame mainFrame; + + public static void main(String[] args) throws Exception { + + JTextAreaEmojiTest test = new JTextAreaEmojiTest(); + } + + public JTextAreaEmojiTest() throws Exception { + createControlPanelUI(); + } + + public final void createControlPanelUI() throws Exception { + SwingUtilities.invokeAndWait(new Runnable() { + @Override + public void run() { + layout = new GridBagLayout(); + mainControlPanel = new JPanel(layout); + instructionPanel = new JPanel(layout); + resultButtonPanel = new JPanel(layout); + textAreaPanel = new JPanel(layout); + controlPanel = new JPanel(layout); + + GridBagConstraints gbc = new GridBagConstraints(); + String instructions + = "1) Text Area size should be zero" + + "\n2) Select one emoji from Character Viewer" + + "\n3) If Text Area size increases displaying" + + "Blank or supported emoji for default font, click pass" + + "\n4) Else press fail"; + instructionTextArea = new JTextArea(); + instructionTextArea.setText(instructions); + instructionTextArea.setEnabled(false); + instructionTextArea.setDisabledTextColor(Color.black); + instructionTextArea.setBackground(Color.white); + instructionTextArea.setBorder( + BorderFactory.createLineBorder(Color.black)); + gbc.gridx = 0; + gbc.gridy = 0; + gbc.fill = GridBagConstraints.HORIZONTAL; + instructionPanel.add(instructionTextArea, gbc); + + emojiTextArea = new JTextArea(); + emojiTextArea.setEnabled(true); + emojiTextArea.setDisabledTextColor(Color.black); + emojiTextArea.setBackground(Color.white); + emojiTextArea.setBorder( + BorderFactory.createLineBorder(Color.black)); + gbc.gridx = 0; + gbc.gridy = 1; + gbc.fill = GridBagConstraints.HORIZONTAL; + textAreaPanel.add(emojiTextArea, gbc); + + passButton = new JButton("Pass"); + passButton.setActionCommand("Pass"); + passButton.addActionListener(JTextAreaEmojiTest.this); + failButton = new JButton("Fail"); + failButton.setActionCommand("Fail"); + failButton.addActionListener(JTextAreaEmojiTest.this); + gbc.gridx = 0; + gbc.gridy = 0; + resultButtonPanel.add(passButton, gbc); + gbc.gridx = 1; + gbc.gridy = 0; + resultButtonPanel.add(failButton, gbc); + + gbc.gridx = 0; + gbc.gridy = 0; + mainControlPanel.add(instructionPanel, gbc); + gbc.gridx = 0; + gbc.gridy = 1; + mainControlPanel.add(textAreaPanel, gbc); + gbc.gridx = 0; + gbc.gridy = 2; + mainControlPanel.add(resultButtonPanel, gbc); + + mainControlPanel.add(controlPanel, gbc); + mainFrame = new JFrame("Control Panel"); + mainFrame.add(mainControlPanel); + mainFrame.pack(); + mainFrame.setDefaultCloseOperation(EXIT_ON_CLOSE); + mainFrame.setVisible(true); + } + }); + } + + @Override + public void actionPerformed(ActionEvent evt) { + if (evt.getSource() instanceof JButton) { + JButton btn = (JButton) evt.getSource(); + cleanUp(); + + switch (btn.getActionCommand()) { + case "Pass": + break; + case "Fail": + throw new AssertionError("Test case has failed!"); + } + } + } + + private static void cleanUp() { + mainFrame.dispose(); + } +} From aa55cc6846ffb8b870e496b7f614d82b6fe22f13 Mon Sep 17 00:00:00 2001 From: Severin Gehwolf Date: Tue, 22 Mar 2016 18:23:39 +0100 Subject: [PATCH 048/162] 8152440: Zero build fails after JDK-8146801 Define InitArrayShortSize macro for Zero as well. Reviewed-by: aph --- hotspot/src/cpu/zero/vm/globals_zero.hpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/hotspot/src/cpu/zero/vm/globals_zero.hpp b/hotspot/src/cpu/zero/vm/globals_zero.hpp index a9a2f45fe5d..52a3cacbd70 100644 --- a/hotspot/src/cpu/zero/vm/globals_zero.hpp +++ b/hotspot/src/cpu/zero/vm/globals_zero.hpp @@ -42,7 +42,8 @@ define_pd_global(bool, UncommonNullCast, true); define_pd_global(intx, CodeEntryAlignment, 32); define_pd_global(intx, OptoLoopAlignment, 16); define_pd_global(intx, InlineFrequencyCount, 100); -define_pd_global(intx, InlineSmallCode, 1000 ); +define_pd_global(intx, InlineSmallCode, 1000); +define_pd_global(intx, InitArrayShortSize, -1); // not used #define DEFAULT_STACK_YELLOW_PAGES (2) #define DEFAULT_STACK_RED_PAGES (1) From dd439c9998f1e5407accb6a3d13cc5a5771b95cb Mon Sep 17 00:00:00 2001 From: Phil Race Date: Tue, 22 Mar 2016 14:46:48 -0700 Subject: [PATCH 049/162] 8055463: Need public API allowing full access to font collections in Font.createFont() Reviewed-by: serb, vadim --- .../macosx/classes/sun/font/CFontManager.java | 88 --------- .../share/classes/java/awt/Font.java | 160 +++++++++++++++- .../share/classes/sun/font/FileFont.java | 29 ++- .../share/classes/sun/font/FontManager.java | 6 +- .../classes/sun/font/SunFontManager.java | 25 ++- .../awt/FontClass/CreateFont/BigFont.java | 4 + .../CreateFont/CreateFontArrayTest.java | 181 ++++++++++++++++++ .../awt/font/FontNames/GetLCIDFromLocale.java | 4 +- 8 files changed, 378 insertions(+), 119 deletions(-) create mode 100644 jdk/test/java/awt/FontClass/CreateFont/CreateFontArrayTest.java diff --git a/jdk/src/java.desktop/macosx/classes/sun/font/CFontManager.java b/jdk/src/java.desktop/macosx/classes/sun/font/CFontManager.java index d152a5f01c0..9e883938e46 100644 --- a/jdk/src/java.desktop/macosx/classes/sun/font/CFontManager.java +++ b/jdk/src/java.desktop/macosx/classes/sun/font/CFontManager.java @@ -142,94 +142,6 @@ public final class CFontManager extends SunFontManager { } } - @Override - public Font2D createFont2D(File fontFile, int fontFormat, boolean isCopy, CreatedFontTracker tracker) throws FontFormatException { - - String fontFilePath = fontFile.getPath(); - Font2D font2D = null; - final File fFile = fontFile; - final CreatedFontTracker _tracker = tracker; - try { - switch (fontFormat) { - case Font.TRUETYPE_FONT: - font2D = new TrueTypeFont(fontFilePath, null, 0, true); - break; - case Font.TYPE1_FONT: - font2D = new Type1Font(fontFilePath, null, isCopy); - break; - default: - throw new FontFormatException("Unrecognised Font Format"); - } - } catch (FontFormatException e) { - if (isCopy) { - java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction() { - public Object run() { - if (_tracker != null) { - _tracker.subBytes((int)fFile.length()); - } - fFile.delete(); - return null; - } - }); - } - throw(e); - } - if (isCopy) { - FileFont.setFileToRemove(font2D, fontFile, tracker); - synchronized (FontManager.class) { - - if (tmpFontFiles == null) { - tmpFontFiles = new Vector(); - } - tmpFontFiles.add(fontFile); - - if (fileCloser == null) { - final Runnable fileCloserRunnable = new Runnable() { - public void run() { - java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction() { - public Object run() { - - for (int i=0;i) () -> { - /* The thread must be a member of a thread group - * which will not get GCed before VM exit. - * Make its parent the top-level thread group. - */ - ThreadGroup rootTG = ThreadGroupUtils.getRootThreadGroup(); - fileCloser = new ManagedLocalsThread(rootTG, fileCloserRunnable); - fileCloser.setContextClassLoader(null); - Runtime.getRuntime().addShutdownHook(fileCloser); - return null; - } - ); - } - } - } - return font2D; - } - protected void registerFontsInDir(String dirName, boolean useJavaRasterizer, int fontRank, boolean defer, boolean resolveSymLinks) { loadNativeDirFonts(dirName); super.registerFontsInDir(dirName, useJavaRasterizer, fontRank, defer, resolveSymLinks); diff --git a/jdk/src/java.desktop/share/classes/java/awt/Font.java b/jdk/src/java.desktop/share/classes/java/awt/Font.java index 261ee156acf..8edd2227bad 100644 --- a/jdk/src/java.desktop/share/classes/java/awt/Font.java +++ b/jdk/src/java.desktop/share/classes/java/awt/Font.java @@ -611,8 +611,9 @@ public class Font implements java.io.Serializable * so that when the Font2D is GC'd it can also remove the file. */ FontManager fm = FontManagerFactory.getInstance(); - this.font2DHandle = fm.createFont2D(fontFile, fontFormat, isCopy, - tracker).handle; + Font2D[] fonts = + fm.createFont2D(fontFile, fontFormat, false, isCopy, tracker); + this.font2DHandle = fonts[0].handle; this.name = this.font2DHandle.font2D.getFontName(Locale.getDefault()); this.style = Font.PLAIN; this.size = 1; @@ -841,6 +842,132 @@ public class Font implements java.io.Serializable return hasPerm; } + + /** + * Returns a new array of {@code Font} decoded from the specified stream. + * The returned {@code Font[]} will have at least one element. + *

    + * The explicit purpose of this variation on the + * {@code createFont(int, InputStream)} method is to support font + * sources which represent a TrueType/OpenType font collection and + * be able to return all individual fonts in that collection. + * Consequently this method will throw {@code FontFormatException} + * if the data source does not contain at least one TrueType/OpenType + * font. The same exception will also be thrown if any of the fonts in + * the collection does not contain the required font tables. + *

    + * The condition "at least one", allows for the stream to represent + * a single OpenType/TrueType font. That is, it does not have to be + * a collection. + * Each {@code Font} element of the returned array is + * created with a point size of 1 and style {@link #PLAIN PLAIN}. + * This base font can then be used with the {@code deriveFont} + * methods in this class to derive new {@code Font} objects with + * varying sizes, styles, transforms and font features. + *

    This method does not close the {@link InputStream}. + *

    + * To make each {@code Font} available to Font constructors it + * must be registered in the {@code GraphicsEnvironment} by calling + * {@link GraphicsEnvironment#registerFont(Font) registerFont(Font)}. + * @param fontStream an {@code InputStream} object representing the + * input data for the font or font collection. + * @return a new {@code Font[]}. + * @throws FontFormatException if the {@code fontStream} data does + * not contain the required font tables for any of the elements of + * the collection, or if it contains no fonts at all. + * @throws IOException if the {@code fontStream} cannot be completely read. + * @see GraphicsEnvironment#registerFont(Font) + * @since 9 + */ + public static Font[] createFonts(InputStream fontStream) + throws FontFormatException, IOException { + + final int fontFormat = Font.TRUETYPE_FONT; + if (hasTempPermission()) { + return createFont0(fontFormat, fontStream, true, null); + } + + // Otherwise, be extra conscious of pending temp file creation and + // resourcefully handle the temp file resources, among other things. + CreatedFontTracker tracker = CreatedFontTracker.getTracker(); + boolean acquired = false; + try { + acquired = tracker.acquirePermit(); + if (!acquired) { + throw new IOException("Timed out waiting for resources."); + } + return createFont0(fontFormat, fontStream, true, tracker); + } catch (InterruptedException e) { + throw new IOException("Problem reading font data."); + } finally { + if (acquired) { + tracker.releasePermit(); + } + } + } + + /* used to implement Font.createFont */ + private Font(Font2D font2D) { + + this.createdFont = true; + this.font2DHandle = font2D.handle; + this.name = font2D.getFontName(Locale.getDefault()); + this.style = Font.PLAIN; + this.size = 1; + this.pointSize = 1f; + } + + /** + * Returns a new array of {@code Font} decoded from the specified file. + * The returned {@code Font[]} will have at least one element. + *

    + * The explicit purpose of this variation on the + * {@code createFont(int, File)} method is to support font + * sources which represent a TrueType/OpenType font collection and + * be able to return all individual fonts in that collection. + * Consequently this method will throw {@code FontFormatException} + * if the data source does not contain at least one TrueType/OpenType + * font. The same exception will also be thrown if any of the fonts in + * the collection does not contain the required font tables. + *

    + * The condition "at least one", allows for the stream to represent + * a single OpenType/TrueType font. That is, it does not have to be + * a collection. + * Each {@code Font} element of the returned array is + * created with a point size of 1 and style {@link #PLAIN PLAIN}. + * This base font can then be used with the {@code deriveFont} + * methods in this class to derive new {@code Font} objects with + * varying sizes, styles, transforms and font features. + *

    + * To make each {@code Font} available to Font constructors it + * must be registered in the {@code GraphicsEnvironment} by calling + * {@link GraphicsEnvironment#registerFont(Font) registerFont(Font)}. + * @param fontFile a {@code File} object containing the + * input data for the font or font collection. + * @return a new {@code Font[]}. + * @throws FontFormatException if the {@code File} does + * not contain the required font tables for any of the elements of + * the collection, or if it contains no fonts at all. + * @throws IOException if the {@code fontFile} cannot be read. + * @see GraphicsEnvironment#registerFont(Font) + * @since 9 + */ + public static Font[] createFonts(File fontFile) + throws FontFormatException, IOException + { + int fontFormat = Font.TRUETYPE_FONT; + fontFile = checkFontFile(fontFormat, fontFile); + FontManager fm = FontManagerFactory.getInstance(); + Font2D[] font2DArr = + fm.createFont2D(fontFile, fontFormat, true, false, null); + int num = font2DArr.length; + Font[] fonts = new Font[num]; + for (int i = 0; i < num; i++) { + fonts[i] = new Font(font2DArr[i]); + } + return fonts; + } + /** * Returns a new {@code Font} using the specified font type * and input data. The new {@code Font} is @@ -873,7 +1000,7 @@ public class Font implements java.io.Serializable throws java.awt.FontFormatException, java.io.IOException { if (hasTempPermission()) { - return createFont0(fontFormat, fontStream, null); + return createFont0(fontFormat, fontStream, false, null)[0]; } // Otherwise, be extra conscious of pending temp file creation and @@ -885,7 +1012,7 @@ public class Font implements java.io.Serializable if (!acquired) { throw new IOException("Timed out waiting for resources."); } - return createFont0(fontFormat, fontStream, tracker); + return createFont0(fontFormat, fontStream, false, tracker)[0]; } catch (InterruptedException e) { throw new IOException("Problem reading font data."); } finally { @@ -895,8 +1022,9 @@ public class Font implements java.io.Serializable } } - private static Font createFont0(int fontFormat, InputStream fontStream, - CreatedFontTracker tracker) + private static Font[] createFont0(int fontFormat, InputStream fontStream, + boolean allFonts, + CreatedFontTracker tracker) throws java.awt.FontFormatException, java.io.IOException { if (fontFormat != Font.TRUETYPE_FONT && @@ -965,8 +1093,15 @@ public class Font implements java.io.Serializable * without waiting for the results of that constructor. */ copiedFontData = true; - Font font = new Font(tFile, fontFormat, true, tracker); - return font; + FontManager fm = FontManagerFactory.getInstance(); + Font2D[] font2DArr = + fm.createFont2D(tFile, fontFormat, allFonts, true, tracker); + int num = font2DArr.length; + Font[] fonts = new Font[num]; + for (int i = 0; i < num; i++) { + fonts[i] = new Font(font2DArr[i]); + } + return fonts; } finally { if (tracker != null) { tracker.remove(tFile); @@ -1037,6 +1172,13 @@ public class Font implements java.io.Serializable public static Font createFont(int fontFormat, File fontFile) throws java.awt.FontFormatException, java.io.IOException { + fontFile = checkFontFile(fontFormat, fontFile); + return new Font(fontFile, fontFormat, false, null); + } + + private static File checkFontFile(int fontFormat, File fontFile) + throws FontFormatException, IOException { + fontFile = new File(fontFile.getPath()); if (fontFormat != Font.TRUETYPE_FONT && @@ -1052,7 +1194,7 @@ public class Font implements java.io.Serializable if (!fontFile.canRead()) { throw new IOException("Can't read " + fontFile); } - return new Font(fontFile, fontFormat, false, null); + return fontFile; } /** diff --git a/jdk/src/java.desktop/share/classes/sun/font/FileFont.java b/jdk/src/java.desktop/share/classes/sun/font/FileFont.java index 60b2377c9da..6764c309851 100644 --- a/jdk/src/java.desktop/share/classes/sun/font/FileFont.java +++ b/jdk/src/java.desktop/share/classes/sun/font/FileFont.java @@ -36,6 +36,7 @@ import sun.java2d.Disposer; import sun.java2d.DisposerRecord; import java.io.IOException; +import java.util.List; import java.security.AccessController; import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; @@ -116,17 +117,17 @@ public abstract class FileFont extends PhysicalFont { return true; } - void setFileToRemove(File file, CreatedFontTracker tracker) { - Disposer.addObjectRecord(this, - new CreatedFontFileDisposerRecord(file, tracker)); - } + static void setFileToRemove(List fonts, + File file, int cnt, + CreatedFontTracker tracker) + { + CreatedFontFileDisposerRecord dr = + new CreatedFontFileDisposerRecord(file, cnt, tracker); - // MACOSX begin -- Make this static so that we can pass in CFont - static void setFileToRemove(Object font, File file, CreatedFontTracker tracker) { - Disposer.addObjectRecord(font, - new CreatedFontFileDisposerRecord(file, tracker)); + for (Font2D f : fonts) { + Disposer.addObjectRecord(f, dr); + } } - // MACOSX - end /* This is called when a font scaler is determined to * be unusable (ie bad). @@ -251,11 +252,13 @@ public abstract class FileFont extends PhysicalFont { implements DisposerRecord { File fontFile = null; + int count = 0; // number of fonts referencing this file object. CreatedFontTracker tracker; - private CreatedFontFileDisposerRecord(File file, + private CreatedFontFileDisposerRecord(File file, int cnt, CreatedFontTracker tracker) { fontFile = file; + count = (cnt > 0) ? cnt : 1; this.tracker = tracker; } @@ -263,6 +266,12 @@ public abstract class FileFont extends PhysicalFont { java.security.AccessController.doPrivileged( new java.security.PrivilegedAction() { public Object run() { + synchronized (fontFile) { + count--; + if (count > 0) { + return null; + } + } if (fontFile != null) { try { if (tracker != null) { diff --git a/jdk/src/java.desktop/share/classes/sun/font/FontManager.java b/jdk/src/java.desktop/share/classes/sun/font/FontManager.java index 1e496271a16..455daf69cfa 100644 --- a/jdk/src/java.desktop/share/classes/sun/font/FontManager.java +++ b/jdk/src/java.desktop/share/classes/sun/font/FontManager.java @@ -81,13 +81,15 @@ public interface FontManager { * * @param fontFile the file holding the font data * @param fontFormat the expected font format + * @param all whether to retrieve all fonts in the resource or + * just the first one. * @param isCopy {@code true} if the file is a copy and needs to be * deleted, {@code false} otherwise * * @return the created Font2D instance */ - public Font2D createFont2D(File fontFile, int fontFormat, - boolean isCopy, CreatedFontTracker tracker) + public Font2D[] createFont2D(File fontFile, int fontFormat, boolean all, + boolean isCopy, CreatedFontTracker tracker) throws FontFormatException; /** diff --git a/jdk/src/java.desktop/share/classes/sun/font/SunFontManager.java b/jdk/src/java.desktop/share/classes/sun/font/SunFontManager.java index 7f5626194fe..67bb3fd383a 100644 --- a/jdk/src/java.desktop/share/classes/sun/font/SunFontManager.java +++ b/jdk/src/java.desktop/share/classes/sun/font/SunFontManager.java @@ -40,6 +40,7 @@ import java.util.HashMap; import java.util.HashSet; import java.util.Hashtable; import java.util.Iterator; +import java.util.List; import java.util.Locale; import java.util.Map; import java.util.NoSuchElementException; @@ -2420,15 +2421,15 @@ public abstract class SunFontManager implements FontSupport, FontManagerForSGE { protected abstract String getFontPath(boolean noType1Fonts); - // MACOSX begin -- need to access this in subclass - protected Thread fileCloser = null; - // MACOSX end + Thread fileCloser = null; Vector tmpFontFiles = null; - public Font2D createFont2D(File fontFile, int fontFormat, - boolean isCopy, CreatedFontTracker tracker) + public Font2D[] createFont2D(File fontFile, int fontFormat, boolean all, + boolean isCopy, CreatedFontTracker tracker) throws FontFormatException { + List fList = new ArrayList(); + int cnt = 1; String fontFilePath = fontFile.getPath(); FileFont font2D = null; final File fFile = fontFile; @@ -2437,9 +2438,19 @@ public abstract class SunFontManager implements FontSupport, FontManagerForSGE { switch (fontFormat) { case Font.TRUETYPE_FONT: font2D = new TrueTypeFont(fontFilePath, null, 0, true); + fList.add(font2D); + if (!all) { + break; + } + cnt = ((TrueTypeFont)font2D).getFontCount(); + int index = 1; + while (index < cnt) { + fList.add(new TrueTypeFont(fontFilePath, null, index++, true)); + } break; case Font.TYPE1_FONT: font2D = new Type1Font(fontFilePath, null, isCopy); + fList.add(font2D); break; default: throw new FontFormatException("Unrecognised Font Format"); @@ -2460,7 +2471,7 @@ public abstract class SunFontManager implements FontSupport, FontManagerForSGE { throw(e); } if (isCopy) { - font2D.setFileToRemove(fontFile, tracker); + FileFont.setFileToRemove(fList, fontFile, cnt, tracker); synchronized (FontManager.class) { if (tmpFontFiles == null) { @@ -2511,7 +2522,7 @@ public abstract class SunFontManager implements FontSupport, FontManagerForSGE { } } } - return font2D; + return fList.toArray(new Font2D[0]); } /* remind: used in X11GraphicsEnvironment and called often enough diff --git a/jdk/test/java/awt/FontClass/CreateFont/BigFont.java b/jdk/test/java/awt/FontClass/CreateFont/BigFont.java index fb765bd7656..ddcf8fc1b0b 100644 --- a/jdk/test/java/awt/FontClass/CreateFont/BigFont.java +++ b/jdk/test/java/awt/FontClass/CreateFont/BigFont.java @@ -60,12 +60,16 @@ public class BigFont extends Applet { System.out.println("Applet " + id + " "+ Thread.currentThread().getThreadGroup()); + if (System.getSecurityManager() == null) { + System.setSecurityManager(new SecurityManager()); + } // Larger than size for a single font. int fontSize = 64 * 1000 * 1000; SizedInputStream sis = new SizedInputStream(fontSize); try { Font font = Font.createFont(Font.TRUETYPE_FONT, sis); } catch (Throwable t) { + t.printStackTrace(); if (t instanceof FontFormatException || fontSize <= sis.getCurrentSize()) { diff --git a/jdk/test/java/awt/FontClass/CreateFont/CreateFontArrayTest.java b/jdk/test/java/awt/FontClass/CreateFont/CreateFontArrayTest.java new file mode 100644 index 00000000000..d68b2e4409f --- /dev/null +++ b/jdk/test/java/awt/FontClass/CreateFont/CreateFontArrayTest.java @@ -0,0 +1,181 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 8055463 + * @summary Test createFont APIs + * @run CreateFontArrayTest + */ + +import java.awt.Font; +import java.io.BufferedInputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.InputStream; + +/* + * This test pokes around in platform folders/directories to try + * to find some fonts with which to test. It will do different things + * on different platforms and may not do anything at all if the platform + * directories aren't where it expects. For example if /usr/share/fonts + * is not used on a particular Linux distro or on Windows the fonts are + * not in c:\windows\fonts (which would be the right place on 99.99% of + * systems you will find today. + * It ought to be very reliable but it is not 100% guaranteed. + * Failure to find fonts to test is 'not a product bug'. + * Fonts on a system having different content than we expect based on + * file extension is also 'not a product bug'. + * The former will cause silent success, the latter may cause 'noisy' failure + * and the test would then need to be dialled back to be more cautious. + */ + +public class CreateFontArrayTest { + + public static void main(String[] args) throws Exception { + test(".ttc", 2, -1, true); + test(".ttf", 1, 1, true); + test(".otf", 1, 1, true); + test(".pfa", 0, 0, false); + test(".pfb", 0, 0, false); + } + + static File getPlatformFontFolder(String ext) throws Exception { + boolean recurse = false; + String folder = null; + String os = System.getProperty("os.name"); + if (os.startsWith("Win")) { + folder = "c:\\windows\\fonts"; + } else if (os.startsWith("Linux")) { + folder = "/usr/share/fonts"; + recurse = true; // need to dig to find fonts. + } else if (os.startsWith("Mac")) { + // Disabled until createFont can handle mac font names. + //folder = "/Library/Fonts"; + } + if (folder == null) { + return null; + } + File dir = new File(folder); + if (!dir.exists() || !dir.isDirectory()) { + return null; + } + // Have a root. + if (!recurse) { + return dir; + } + + // If "recurse" is set, try to find a sub-folder which contains + // fonts with the specified extension + return findSubFolder(dir, ext); + } + + static File findSubFolder(File folder, String ext) { + File[] files = + folder.listFiles(f -> f.getName().toLowerCase().endsWith(ext)); + if (files != null && files.length > 0) { + return folder; + } + File[] subdirs = folder.listFiles(f -> f.isDirectory()); + for (File f : subdirs) { + File subfolder = findSubFolder(f, ext); + if (subfolder != null) { + return subfolder; + } + } + return null; + } + + static void test(String ext, int min, int max, + boolean expectSuccess ) throws Exception { + + File dir = getPlatformFontFolder(ext); + if (dir == null) { + System.out.println("No folder to test for " + ext); + return; + } + File[] files = + dir.listFiles(f -> f.getName().toLowerCase().endsWith(ext)); + if (files == null || files.length == 0) { + System.out.println("No files to test for " + ext); + return; + } + System.out.println("Create from file " + files[0]); + Font[] fonts = null; + try { + fonts = Font.createFonts(files[0]); + System.out.println("createFont from file returned " + fonts); + } catch (Exception e) { + if (expectSuccess) { + throw new RuntimeException("Unexpected exception", e); + } else { + System.out.println("Got expected exception " + e); + return; + } + } + for (Font f : fonts) { + System.out.println(ext + " component : " + f); + } + if (fonts.length < min) { + throw new RuntimeException("Expected at least " + min + + " but got " + fonts.length); + } + if (max > 0 && fonts.length > max) { + throw new RuntimeException("Expected no more than " + max + + " but got " + fonts.length); + } + FileInputStream fis = null; + try { + System.out.println("Create from stream " + files[0]); + fis = new FileInputStream(files[0]); + InputStream s = new BufferedInputStream(fis); + fonts = null; + try { + fonts = Font.createFonts(s); + System.out.println("createFont from stream returned " + fonts); + } catch (Exception e) { + if (expectSuccess) { + throw new RuntimeException("Unexpected exception", e); + } else { + System.out.println("Got expected exception " + e); + return; + } + } + for (Font f : fonts) { + System.out.println(ext + " component : " + f); + } + if (fonts.length < min) { + throw new RuntimeException("Expected at least " + min + + " but got " + fonts.length); + } + if (max > 0 && fonts.length > max) { + throw new RuntimeException("Expected no more than " + max + + " but got " + fonts.length); + } + } finally { + if (fis != null) { + fis.close(); + } + } + } +} diff --git a/jdk/test/java/awt/font/FontNames/GetLCIDFromLocale.java b/jdk/test/java/awt/font/FontNames/GetLCIDFromLocale.java index fc5aed23401..ef220b90775 100644 --- a/jdk/test/java/awt/font/FontNames/GetLCIDFromLocale.java +++ b/jdk/test/java/awt/font/FontNames/GetLCIDFromLocale.java @@ -4,9 +4,7 @@ * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. + * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or From c28c517f2e3f639caee764959b28adef88c45690 Mon Sep 17 00:00:00 2001 From: Alexander Scherbatiy Date: Wed, 23 Mar 2016 14:25:22 +0400 Subject: [PATCH 050/162] 8150844: [hidpi] [macosx] -Dsun.java2d.uiScale should be taken into account for OS X Reviewed-by: serb, avstepan --- .../classes/sun/awt/CGraphicsDevice.java | 15 +++++++++++-- ...Test.java => HiDPIPropertiesUnixTest.java} | 18 ++++++---------- .../multiresolution/Corrupted2XImageTest.java | 21 +++---------------- .../MenuMultiresolutionIconTest.java | 15 +++---------- .../MultiresolutionIconTest.java | 21 +++---------------- 5 files changed, 28 insertions(+), 62 deletions(-) rename jdk/test/java/awt/hidpi/properties/{HiDPIPropertiesLinuxTest.java => HiDPIPropertiesUnixTest.java} (85%) diff --git a/jdk/src/java.desktop/macosx/classes/sun/awt/CGraphicsDevice.java b/jdk/src/java.desktop/macosx/classes/sun/awt/CGraphicsDevice.java index 05fe2531c13..823ad8aef10 100644 --- a/jdk/src/java.desktop/macosx/classes/sun/awt/CGraphicsDevice.java +++ b/jdk/src/java.desktop/macosx/classes/sun/awt/CGraphicsDevice.java @@ -32,7 +32,7 @@ import java.awt.GraphicsDevice; import java.awt.Insets; import java.awt.Window; import java.util.Objects; - +import sun.java2d.SunGraphicsEnvironment; import sun.java2d.opengl.CGLGraphicsConfig; public final class CGraphicsDevice extends GraphicsDevice @@ -140,7 +140,7 @@ public final class CGraphicsDevice extends GraphicsDevice public void displayChanged() { xResolution = nativeGetXResolution(displayID); yResolution = nativeGetYResolution(displayID); - scale = (int) nativeGetScaleFactor(displayID); + initScaleFactor(); //TODO configs/fullscreenWindow/modes? } @@ -249,6 +249,17 @@ public final class CGraphicsDevice extends GraphicsDevice return nativeGetDisplayModes(displayID); } + private void initScaleFactor() { + if (SunGraphicsEnvironment.isUIScaleEnabled()) { + double debugScale = SunGraphicsEnvironment.getDebugScale(); + scale = (int) (debugScale >= 1 + ? Math.round(debugScale) + : nativeGetScaleFactor(displayID)); + } else { + scale = 1; + } + } + private static native double nativeGetScaleFactor(int displayID); private static native void nativeSetDisplayMode(int displayID, int w, int h, int bpp, int refrate); diff --git a/jdk/test/java/awt/hidpi/properties/HiDPIPropertiesLinuxTest.java b/jdk/test/java/awt/hidpi/properties/HiDPIPropertiesUnixTest.java similarity index 85% rename from jdk/test/java/awt/hidpi/properties/HiDPIPropertiesLinuxTest.java rename to jdk/test/java/awt/hidpi/properties/HiDPIPropertiesUnixTest.java index aba2dc1f87c..d123398c36e 100644 --- a/jdk/test/java/awt/hidpi/properties/HiDPIPropertiesLinuxTest.java +++ b/jdk/test/java/awt/hidpi/properties/HiDPIPropertiesUnixTest.java @@ -32,27 +32,21 @@ import javax.swing.UIManager; * @bug 8137571 * @summary Linux HiDPI Graphics support * @author Alexander Scherbatiy - * @requires (os.family == "linux") + * @requires (os.family == "linux" | os.family == "mac") * @run main/othervm -Dsun.java2d.uiScale.enabled=false * -Dsun.java2d.uiScale=2 - * HiDPIPropertiesLinuxTest UISCALE_DISABLED - * HiDPIPropertiesTest UISCALE_DISABLED + * HiDPIPropertiesUnixTest UISCALE_DISABLED * @run main/othervm -Dsun.java2d.uiScale.enabled=true * -Dsun.java2d.uiScale=3 - * HiDPIPropertiesLinuxTest UISCALE_3 + * HiDPIPropertiesUnixTest UISCALE_3 * @run main/othervm -Dsun.java2d.uiScale=4 - * HiDPIPropertiesLinuxTest UISCALE_4 + * HiDPIPropertiesUnixTest UISCALE_4 */ -public class HiDPIPropertiesLinuxTest { +public class HiDPIPropertiesUnixTest { public static void main(String[] args) throws Exception { - try { - UIManager.setLookAndFeel( - "com.sun.java.swing.plaf.gtk.GTKLookAndFeel"); - } catch (Exception e) { - return; - } + UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); String testCase = args[0]; switch (testCase) { diff --git a/jdk/test/java/awt/image/multiresolution/Corrupted2XImageTest.java b/jdk/test/java/awt/image/multiresolution/Corrupted2XImageTest.java index e7ef2f125b3..ba0f7b321d6 100644 --- a/jdk/test/java/awt/image/multiresolution/Corrupted2XImageTest.java +++ b/jdk/test/java/awt/image/multiresolution/Corrupted2XImageTest.java @@ -37,7 +37,6 @@ */ import java.awt.*; -import java.awt.geom.AffineTransform; import java.awt.image.*; import java.io.*; @@ -116,25 +115,11 @@ public class Corrupted2XImageTest extends Frame { dispose(); } - private static boolean is2x() { - - AffineTransform tr = GraphicsEnvironment.getLocalGraphicsEnvironment(). - getDefaultScreenDevice().getDefaultConfiguration(). - getDefaultTransform(); - return Math.min(tr.getScaleX(), tr.getScaleY()) > 1.001; - } - public static void main(String[] args) throws Exception { - // TODO: update the test with sun.java2d.uiScale option (remove is2x()) - // after fix of JDK-8150844 enh. to run it on non-HiDPI machines as well - if (is2x()) { - // formats supported by Toolkit.getImage() - for (String format: new String[]{"gif", "jpg", "png"}) { - (new Corrupted2XImageTest(format)).doTest(); - } - } else { - System.out.println("this test is for HiDPI only"); + // formats supported by Toolkit.getImage() + for (String format : new String[]{"gif", "jpg", "png"}) { + (new Corrupted2XImageTest(format)).doTest(); } } } diff --git a/jdk/test/java/awt/image/multiresolution/MenuMultiresolutionIconTest.java b/jdk/test/java/awt/image/multiresolution/MenuMultiresolutionIconTest.java index 332162be952..9a09f5c300f 100644 --- a/jdk/test/java/awt/image/multiresolution/MenuMultiresolutionIconTest.java +++ b/jdk/test/java/awt/image/multiresolution/MenuMultiresolutionIconTest.java @@ -115,13 +115,6 @@ public class MenuMultiresolutionIconTest extends JPanel { } } - private static boolean is2x() { - - return GraphicsEnvironment.getLocalGraphicsEnvironment(). - getDefaultScreenDevice().getDefaultConfiguration(). - getDefaultTransform().getScaleX() > 1.001; - } - private boolean eqColors(Color c1, Color c2) { int tol = 15; @@ -133,7 +126,8 @@ public class MenuMultiresolutionIconTest extends JPanel { private void checkIconColor(Point p, String what) { - Color expected = is2x() ? C2X : C1X; + String scale = System.getProperty(SCALE); + Color expected = "2".equals(scale) ? C2X : C1X; Color c = r.getPixelColor(p.x + SZ / 2, p.y + SZ / 2); if (!eqColors(c, expected)) { frame.dispose(); @@ -177,9 +171,6 @@ public class MenuMultiresolutionIconTest extends JPanel { public static void main(String s[]) throws Exception { - // TODO: remove is2x() after JDK-8150844 fix - if (is2x() == "2".equals(System.getProperty(SCALE))) { - (new MenuMultiresolutionIconTest()).doTest(); - } + (new MenuMultiresolutionIconTest()).doTest(); } } diff --git a/jdk/test/java/awt/image/multiresolution/MultiresolutionIconTest.java b/jdk/test/java/awt/image/multiresolution/MultiresolutionIconTest.java index c8b124d71f0..e35a98a23d4 100644 --- a/jdk/test/java/awt/image/multiresolution/MultiresolutionIconTest.java +++ b/jdk/test/java/awt/image/multiresolution/MultiresolutionIconTest.java @@ -28,8 +28,6 @@ * @summary Check that correct resolution variants are chosen for icons * when multiresolution image is used for their construction. * - * @requires (os.family != "mac") - * * @library ../../../../lib/testlibrary/ * @build ExtendedRobot * @run main/othervm/timeout=240 -Dsun.java2d.uiScale=1 MultiresolutionIconTest @@ -42,7 +40,6 @@ import java.awt.*; import java.awt.event.InputEvent; -import java.awt.geom.AffineTransform; import java.awt.image.BaseMultiResolutionImage; import java.awt.image.BufferedImage; import javax.swing.*; @@ -128,14 +125,6 @@ public class MultiresolutionIconTest extends JFrame { setVisible(true); } - private static boolean is2x() { - - AffineTransform tr = GraphicsEnvironment.getLocalGraphicsEnvironment(). - getDefaultScreenDevice().getDefaultConfiguration(). - getDefaultTransform(); - return (Math.min(tr.getScaleX(), tr.getScaleY()) > 1.001); - } - private boolean checkPressedColor(int x, int y, Color ok) { r.mouseMove(x, y); @@ -175,10 +164,9 @@ public class MultiresolutionIconTest extends JFrame { r.waitForIdle(2000); String scale = System.getProperty(SCALE); - System.out.println("scale = " + scale); - Color - expected = is2x() ? C2X : C1X, - unexpected = is2x() ? C1X : C2X; + boolean is2x = "2".equals(scale); + Color expected = is2x ? C2X : C1X; + Color unexpected = is2x ? C1X : C2X; Point p = lbl.getLocationOnScreen(); int x = p.x + lbl.getWidth() / 2; @@ -227,9 +215,6 @@ public class MultiresolutionIconTest extends JFrame { public static void main(String[] args) throws Exception { - // TODO: remove is2x() check after JDK-8150844 fix - if (is2x() != "2".equals(System.getProperty(SCALE))) { return; } - for (UIManager.LookAndFeelInfo LF: UIManager.getInstalledLookAndFeels()) { System.out.println("\nL&F: " + LF.getName()); (new MultiresolutionIconTest(LF)).doTest(); From d8f82c9477ad19ed21abd73eac9b68002c45ab86 Mon Sep 17 00:00:00 2001 From: Avik Niyogi Date: Wed, 23 Mar 2016 17:25:27 +0530 Subject: [PATCH 051/162] 8151282: [TEST_BUG] javax/swing/JInternalFrame/8146321/JInternalFrameIconTest.java fails with GTK LnF Reviewed-by: serb, alexsch --- .../8146321/JInternalFrameIconTest.java | 33 ++++++++++++++----- 1 file changed, 24 insertions(+), 9 deletions(-) diff --git a/jdk/test/javax/swing/JInternalFrame/8146321/JInternalFrameIconTest.java b/jdk/test/javax/swing/JInternalFrame/8146321/JInternalFrameIconTest.java index 4ff95c5bc30..fb3480d3785 100644 --- a/jdk/test/javax/swing/JInternalFrame/8146321/JInternalFrameIconTest.java +++ b/jdk/test/javax/swing/JInternalFrame/8146321/JInternalFrameIconTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -22,7 +22,7 @@ */ /* @test - * @bug 8146321 + * @bug 8146321 8151282 * @summary verifies JInternalFrame Icon and ImageIcon * @library ../../regtesthelpers * @build Util @@ -53,8 +53,9 @@ public class JInternalFrameIconTest { private static Icon titleIcon; private static BufferedImage imageIconImage; private static BufferedImage iconImage; - private static Robot robot; + private static volatile String errorString = ""; + public static void main(String[] args) throws Exception { robot = new Robot(); @@ -64,6 +65,9 @@ public class JInternalFrameIconTest { for (UIManager.LookAndFeelInfo lookAndFeelItem : lookAndFeelArray) { executeCase(lookAndFeelItem.getClassName()); } + if (!"".equals(errorString)) { + throw new RuntimeException("Error Log:\n" + errorString); + } } @@ -72,17 +76,18 @@ public class JInternalFrameIconTest { createImageIconUI(lookAndFeelString); robot.delay(1000); getImageIconBufferedImage(); - robot.waitForIdle(); + robot.delay(1000); cleanUp(); robot.waitForIdle(); createIconUI(lookAndFeelString); robot.delay(1000); getIconBufferedImage(); - robot.waitForIdle(); + robot.delay(1000); cleanUp(); robot.waitForIdle(); - testIfSame(); + + testIfSame(lookAndFeelString); robot.waitForIdle(); } @@ -198,11 +203,16 @@ public class JInternalFrameIconTest { = robot.createScreenCapture(captureRect); } - private static void testIfSame() throws Exception { + private static void testIfSame(final String lookAndFeelString) + throws Exception { if (!bufferedImagesEqual(imageIconImage, iconImage)) { - System.err.println("ERROR: icon and imageIcon not same."); + String error ="[" + lookAndFeelString + + "] : ERROR: icon and imageIcon not same."; + errorString += error; + System.err.println(error); } else { - System.out.println("SUCCESS: icon and imageIcon same."); + System.out.println("[" + lookAndFeelString + + "] : SUCCESS: icon and imageIcon same."); } } @@ -260,6 +270,11 @@ public class JInternalFrameIconTest { private static boolean tryLookAndFeel(String lookAndFeelString) throws Exception { + //This test case is not applicable for Motif and gtk LAFs + if(lookAndFeelString.contains("motif") + || lookAndFeelString.contains("gtk")) { + return false; + } try { UIManager.setLookAndFeel( lookAndFeelString); From 048ce8be877899d8ad3ebfc73c136c2866bbfaec Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Laurent=20Bourg=C3=A8s?= Date: Wed, 23 Mar 2016 21:20:25 +0100 Subject: [PATCH 052/162] 8144938: Handle properly coordinate overflow in Marlin Renderer Skip point coordinates with NaN/Infinity values Reviewed-by: flar, prr --- .../java2d/marlin/MarlinRenderingEngine.java | 202 +++++++---- .../classes/sun/java2d/marlin/Stroker.java | 5 - .../marlin/TransformingPathConsumer2D.java | 235 +------------ .../classes/sun/java2d/marlin/Version.java | 2 +- .../classes/sun/java2d/pipe/AAShapePipe.java | 1 - jdk/test/sun/java2d/marlin/CrashNaNTest.java | 321 ++++++++++++++++-- 6 files changed, 439 insertions(+), 327 deletions(-) diff --git a/jdk/src/java.desktop/share/classes/sun/java2d/marlin/MarlinRenderingEngine.java b/jdk/src/java.desktop/share/classes/sun/java2d/marlin/MarlinRenderingEngine.java index e01a5e77f9c..b794d8c6004 100644 --- a/jdk/src/java.desktop/share/classes/sun/java2d/marlin/MarlinRenderingEngine.java +++ b/jdk/src/java.desktop/share/classes/sun/java2d/marlin/MarlinRenderingEngine.java @@ -51,6 +51,9 @@ public class MarlinRenderingEngine extends RenderingEngine private static final float MIN_PEN_SIZE = 1f / NORM_SUBPIXELS; + static final float UPPER_BND = Float.MAX_VALUE / 2.0f; + static final float LOWER_BND = -UPPER_BND; + /** * Public constructor */ @@ -279,7 +282,7 @@ public class MarlinRenderingEngine extends RenderingEngine float dashphase, PathConsumer2D pc2d) { - // We use strokerat and outat so that in Stroker and Dasher we can work only + // We use strokerat so that in Stroker and Dasher we can work only // with the pre-transformation coordinates. This will repeat a lot of // computations done in the path iterator, but the alternative is to // work with transformed paths and compute untransformed coordinates @@ -289,15 +292,11 @@ public class MarlinRenderingEngine extends RenderingEngine // However, if a path's width is constant after a transformation, // we can skip all this untransforming. - // If normalization is off we save some transformations by not - // transforming the input to pisces. Instead, we apply the - // transformation after the path processing has been done. - // We can't do this if normalization is on, because it isn't a good - // idea to normalize before the transformation is applied. + // As pathTo() will check transformed coordinates for invalid values + // (NaN / Infinity) to ignore such points, it is necessary to apply the + // transformation before the path processing. AffineTransform strokerat = null; - AffineTransform outat = null; - PathIterator pi; int dashLen = -1; boolean recycleDashes = false; @@ -333,6 +332,7 @@ public class MarlinRenderingEngine extends RenderingEngine // leave a bit of room for error. if (nearZero(a*b + c*d) && nearZero(a*a + c*c - (b*b + d*d))) { final float scale = (float) Math.sqrt(a*a + c*c); + if (dashes != null) { recycleDashes = true; dashLen = dashes.length; @@ -349,48 +349,35 @@ public class MarlinRenderingEngine extends RenderingEngine System.arraycopy(dashes, 0, newDashes, 0, dashLen); dashes = newDashes; for (int i = 0; i < dashLen; i++) { - dashes[i] = scale * dashes[i]; + dashes[i] *= scale; } - dashphase = scale * dashphase; + dashphase *= scale; } - width = scale * width; - pi = getNormalizingPathIterator(rdrCtx, normalize, - src.getPathIterator(at)); + width *= scale; - // by now strokerat == null && outat == null. Input paths to + // by now strokerat == null. Input paths to // stroker (and maybe dasher) will have the full transform at // applied to them and nothing will happen to the output paths. } else { - if (normalize != NormMode.OFF) { - strokerat = at; - pi = getNormalizingPathIterator(rdrCtx, normalize, - src.getPathIterator(at)); + strokerat = at; - // by now strokerat == at && outat == null. Input paths to - // stroker (and maybe dasher) will have the full transform at - // applied to them, then they will be normalized, and then - // the inverse of *only the non translation part of at* will - // be applied to the normalized paths. This won't cause problems - // in stroker, because, suppose at = T*A, where T is just the - // translation part of at, and A is the rest. T*A has already - // been applied to Stroker/Dasher's input. Then Ainv will be - // applied. Ainv*T*A is not equal to T, but it is a translation, - // which means that none of stroker's assumptions about its - // input will be violated. After all this, A will be applied - // to stroker's output. - } else { - outat = at; - pi = src.getPathIterator(null); - // outat == at && strokerat == null. This is because if no - // normalization is done, we can just apply all our - // transformations to stroker's output. - } + // by now strokerat == at. Input paths to + // stroker (and maybe dasher) will have the full transform at + // applied to them, then they will be normalized, and then + // the inverse of *only the non translation part of at* will + // be applied to the normalized paths. This won't cause problems + // in stroker, because, suppose at = T*A, where T is just the + // translation part of at, and A is the rest. T*A has already + // been applied to Stroker/Dasher's input. Then Ainv will be + // applied. Ainv*T*A is not equal to T, but it is a translation, + // which means that none of stroker's assumptions about its + // input will be violated. After all this, A will be applied + // to stroker's output. } } else { // either at is null or it's the identity. In either case // we don't transform the path. - pi = getNormalizingPathIterator(rdrCtx, normalize, - src.getPathIterator(null)); + at = null; } if (useSimplifier) { @@ -399,12 +386,7 @@ public class MarlinRenderingEngine extends RenderingEngine pc2d = rdrCtx.simplifier.init(pc2d); } - // by now, at least one of outat and strokerat will be null. Unless at is not - // a constant multiple of an orthogonal transformation, they will both be - // null. In other cases, outat == at if normalization is off, and if - // normalization is on, strokerat == at. final TransformingPathConsumer2D transformerPC2D = rdrCtx.transformerPC2D; - pc2d = transformerPC2D.transformConsumer(pc2d, outat); pc2d = transformerPC2D.deltaTransformConsumer(pc2d, strokerat); pc2d = rdrCtx.stroker.init(pc2d, width, caps, join, miterlimit); @@ -417,18 +399,22 @@ public class MarlinRenderingEngine extends RenderingEngine recycleDashes); } pc2d = transformerPC2D.inverseDeltaTransformConsumer(pc2d, strokerat); + + final PathIterator pi = getNormalizingPathIterator(rdrCtx, normalize, + src.getPathIterator(at)); + pathTo(rdrCtx, pi, pc2d); /* * Pipeline seems to be: - * shape.getPathIterator - * -> NormalizingPathIterator - * -> inverseDeltaTransformConsumer - * -> Dasher + * shape.getPathIterator(at) + * -> (NormalizingPathIterator) + * -> (inverseDeltaTransformConsumer) + * -> (Dasher) * -> Stroker - * -> deltaTransformConsumer OR transformConsumer + * -> (deltaTransformConsumer) * - * -> CollinearSimplifier to remove redundant segments + * -> (CollinearSimplifier) to remove redundant segments * * -> pc2d = Renderer (bounding box) */ @@ -642,27 +628,109 @@ public class MarlinRenderingEngine extends RenderingEngine private static void pathToLoop(final float[] coords, final PathIterator pi, final PathConsumer2D pc2d) { + // ported from DuctusRenderingEngine.feedConsumer() but simplified: + // - removed skip flag = !subpathStarted + // - removed pathClosed (ie subpathStarted not set to false) + boolean subpathStarted = false; + for (; !pi.isDone(); pi.next()) { switch (pi.currentSegment(coords)) { - case PathIterator.SEG_MOVETO: + case PathIterator.SEG_MOVETO: + /* Checking SEG_MOVETO coordinates if they are out of the + * [LOWER_BND, UPPER_BND] range. This check also handles NaN + * and Infinity values. Skipping next path segment in case of + * invalid data. + */ + if (coords[0] < UPPER_BND && coords[0] > LOWER_BND && + coords[1] < UPPER_BND && coords[1] > LOWER_BND) + { pc2d.moveTo(coords[0], coords[1]); - continue; - case PathIterator.SEG_LINETO: - pc2d.lineTo(coords[0], coords[1]); - continue; - case PathIterator.SEG_QUADTO: - pc2d.quadTo(coords[0], coords[1], - coords[2], coords[3]); - continue; - case PathIterator.SEG_CUBICTO: - pc2d.curveTo(coords[0], coords[1], - coords[2], coords[3], - coords[4], coords[5]); - continue; - case PathIterator.SEG_CLOSE: + subpathStarted = true; + } + break; + case PathIterator.SEG_LINETO: + /* Checking SEG_LINETO coordinates if they are out of the + * [LOWER_BND, UPPER_BND] range. This check also handles NaN + * and Infinity values. Ignoring current path segment in case + * of invalid data. If segment is skipped its endpoint + * (if valid) is used to begin new subpath. + */ + if (coords[0] < UPPER_BND && coords[0] > LOWER_BND && + coords[1] < UPPER_BND && coords[1] > LOWER_BND) + { + if (subpathStarted) { + pc2d.lineTo(coords[0], coords[1]); + } else { + pc2d.moveTo(coords[0], coords[1]); + subpathStarted = true; + } + } + break; + case PathIterator.SEG_QUADTO: + // Quadratic curves take two points + /* Checking SEG_QUADTO coordinates if they are out of the + * [LOWER_BND, UPPER_BND] range. This check also handles NaN + * and Infinity values. Ignoring current path segment in case + * of invalid endpoints's data. Equivalent to the SEG_LINETO + * if endpoint coordinates are valid but there are invalid data + * among other coordinates + */ + if (coords[2] < UPPER_BND && coords[2] > LOWER_BND && + coords[3] < UPPER_BND && coords[3] > LOWER_BND) + { + if (subpathStarted) { + if (coords[0] < UPPER_BND && coords[0] > LOWER_BND && + coords[1] < UPPER_BND && coords[1] > LOWER_BND) + { + pc2d.quadTo(coords[0], coords[1], + coords[2], coords[3]); + } else { + pc2d.lineTo(coords[2], coords[3]); + } + } else { + pc2d.moveTo(coords[2], coords[3]); + subpathStarted = true; + } + } + break; + case PathIterator.SEG_CUBICTO: + // Cubic curves take three points + /* Checking SEG_CUBICTO coordinates if they are out of the + * [LOWER_BND, UPPER_BND] range. This check also handles NaN + * and Infinity values. Ignoring current path segment in case + * of invalid endpoints's data. Equivalent to the SEG_LINETO + * if endpoint coordinates are valid but there are invalid data + * among other coordinates + */ + if (coords[4] < UPPER_BND && coords[4] > LOWER_BND && + coords[5] < UPPER_BND && coords[5] > LOWER_BND) + { + if (subpathStarted) { + if (coords[0] < UPPER_BND && coords[0] > LOWER_BND && + coords[1] < UPPER_BND && coords[1] > LOWER_BND && + coords[2] < UPPER_BND && coords[2] > LOWER_BND && + coords[3] < UPPER_BND && coords[3] > LOWER_BND) + { + pc2d.curveTo(coords[0], coords[1], + coords[2], coords[3], + coords[4], coords[5]); + } else { + pc2d.lineTo(coords[4], coords[5]); + } + } else { + pc2d.moveTo(coords[4], coords[5]); + subpathStarted = true; + } + } + break; + case PathIterator.SEG_CLOSE: + if (subpathStarted) { pc2d.closePath(); - continue; - default: + // do not set subpathStarted to false + // in case of missing moveTo() after close() + } + break; + default: } } pc2d.pathDone(); diff --git a/jdk/src/java.desktop/share/classes/sun/java2d/marlin/Stroker.java b/jdk/src/java.desktop/share/classes/sun/java2d/marlin/Stroker.java index 2946eda28f0..54c7ec32300 100644 --- a/jdk/src/java.desktop/share/classes/sun/java2d/marlin/Stroker.java +++ b/jdk/src/java.desktop/share/classes/sun/java2d/marlin/Stroker.java @@ -338,11 +338,6 @@ final class Stroker implements PathConsumer2D, MarlinConst { } private void drawRoundCap(float cx, float cy, float mx, float my) { - // the first and second arguments of the following two calls - // are really will be ignored by emitCurveTo (because of the false), - // but we put them in anyway, as opposed to just giving it 4 zeroes, - // because it's just 4 additions and it's not good to rely on this - // sort of assumption (right now it's true, but that may change). emitCurveTo(cx+mx-C*my, cy+my+C*mx, cx-my+C*mx, cy+mx+C*my, cx-my, cy+mx); diff --git a/jdk/src/java.desktop/share/classes/sun/java2d/marlin/TransformingPathConsumer2D.java b/jdk/src/java.desktop/share/classes/sun/java2d/marlin/TransformingPathConsumer2D.java index 6258d8dfae6..db8f8dd6391 100644 --- a/jdk/src/java.desktop/share/classes/sun/java2d/marlin/TransformingPathConsumer2D.java +++ b/jdk/src/java.desktop/share/classes/sun/java2d/marlin/TransformingPathConsumer2D.java @@ -35,7 +35,7 @@ final class TransformingPathConsumer2D { // used by RendererContext } - // recycled PathConsumer2D instance from transformConsumer() + // recycled PathConsumer2D instance from wrapPath2d() private final Path2DWrapper wp_Path2DWrapper = new Path2DWrapper(); PathConsumer2D wrapPath2d(Path2D.Float p2d) @@ -43,46 +43,6 @@ final class TransformingPathConsumer2D { return wp_Path2DWrapper.init(p2d); } - // recycled PathConsumer2D instances from transformConsumer() - private final TranslateFilter tx_TranslateFilter = new TranslateFilter(); - private final DeltaScaleFilter tx_DeltaScaleFilter = new DeltaScaleFilter(); - private final ScaleFilter tx_ScaleFilter = new ScaleFilter(); - private final DeltaTransformFilter tx_DeltaTransformFilter = new DeltaTransformFilter(); - private final TransformFilter tx_TransformFilter = new TransformFilter(); - - PathConsumer2D transformConsumer(PathConsumer2D out, - AffineTransform at) - { - if (at == null) { - return out; - } - float mxx = (float) at.getScaleX(); - float mxy = (float) at.getShearX(); - float mxt = (float) at.getTranslateX(); - float myx = (float) at.getShearY(); - float myy = (float) at.getScaleY(); - float myt = (float) at.getTranslateY(); - if (mxy == 0f && myx == 0f) { - if (mxx == 1f && myy == 1f) { - if (mxt == 0f && myt == 0f) { - return out; - } else { - return tx_TranslateFilter.init(out, mxt, myt); - } - } else { - if (mxt == 0f && myt == 0f) { - return tx_DeltaScaleFilter.init(out, mxx, myy); - } else { - return tx_ScaleFilter.init(out, mxx, myy, mxt, myt); - } - } - } else if (mxt == 0f && myt == 0f) { - return tx_DeltaTransformFilter.init(out, mxx, mxy, myx, myy); - } else { - return tx_TransformFilter.init(out, mxx, mxy, mxt, myx, myy, myt); - } - } - // recycled PathConsumer2D instances from deltaTransformConsumer() private final DeltaScaleFilter dt_DeltaScaleFilter = new DeltaScaleFilter(); private final DeltaTransformFilter dt_DeltaTransformFilter = new DeltaTransformFilter(); @@ -97,6 +57,7 @@ final class TransformingPathConsumer2D { float mxy = (float) at.getShearX(); float myx = (float) at.getShearY(); float myy = (float) at.getScaleY(); + if (mxy == 0f && myx == 0f) { if (mxx == 1f && myy == 1f) { return out; @@ -122,6 +83,7 @@ final class TransformingPathConsumer2D { float mxy = (float) at.getShearX(); float myx = (float) at.getShearY(); float myy = (float) at.getScaleY(); + if (mxy == 0f && myx == 0f) { if (mxx == 1f && myy == 1f) { return out; @@ -138,197 +100,6 @@ final class TransformingPathConsumer2D { } } - static final class TranslateFilter implements PathConsumer2D { - private PathConsumer2D out; - private float tx, ty; - - TranslateFilter() {} - - TranslateFilter init(PathConsumer2D out, - float tx, float ty) - { - this.out = out; - this.tx = tx; - this.ty = ty; - return this; // fluent API - } - - @Override - public void moveTo(float x0, float y0) { - out.moveTo(x0 + tx, y0 + ty); - } - - @Override - public void lineTo(float x1, float y1) { - out.lineTo(x1 + tx, y1 + ty); - } - - @Override - public void quadTo(float x1, float y1, - float x2, float y2) - { - out.quadTo(x1 + tx, y1 + ty, - x2 + tx, y2 + ty); - } - - @Override - public void curveTo(float x1, float y1, - float x2, float y2, - float x3, float y3) - { - out.curveTo(x1 + tx, y1 + ty, - x2 + tx, y2 + ty, - x3 + tx, y3 + ty); - } - - @Override - public void closePath() { - out.closePath(); - } - - @Override - public void pathDone() { - out.pathDone(); - } - - @Override - public long getNativeConsumer() { - return 0; - } - } - - static final class ScaleFilter implements PathConsumer2D { - private PathConsumer2D out; - private float sx, sy, tx, ty; - - ScaleFilter() {} - - ScaleFilter init(PathConsumer2D out, - float sx, float sy, - float tx, float ty) - { - this.out = out; - this.sx = sx; - this.sy = sy; - this.tx = tx; - this.ty = ty; - return this; // fluent API - } - - @Override - public void moveTo(float x0, float y0) { - out.moveTo(x0 * sx + tx, y0 * sy + ty); - } - - @Override - public void lineTo(float x1, float y1) { - out.lineTo(x1 * sx + tx, y1 * sy + ty); - } - - @Override - public void quadTo(float x1, float y1, - float x2, float y2) - { - out.quadTo(x1 * sx + tx, y1 * sy + ty, - x2 * sx + tx, y2 * sy + ty); - } - - @Override - public void curveTo(float x1, float y1, - float x2, float y2, - float x3, float y3) - { - out.curveTo(x1 * sx + tx, y1 * sy + ty, - x2 * sx + tx, y2 * sy + ty, - x3 * sx + tx, y3 * sy + ty); - } - - @Override - public void closePath() { - out.closePath(); - } - - @Override - public void pathDone() { - out.pathDone(); - } - - @Override - public long getNativeConsumer() { - return 0; - } - } - - static final class TransformFilter implements PathConsumer2D { - private PathConsumer2D out; - private float mxx, mxy, mxt, myx, myy, myt; - - TransformFilter() {} - - TransformFilter init(PathConsumer2D out, - float mxx, float mxy, float mxt, - float myx, float myy, float myt) - { - this.out = out; - this.mxx = mxx; - this.mxy = mxy; - this.mxt = mxt; - this.myx = myx; - this.myy = myy; - this.myt = myt; - return this; // fluent API - } - - @Override - public void moveTo(float x0, float y0) { - out.moveTo(x0 * mxx + y0 * mxy + mxt, - x0 * myx + y0 * myy + myt); - } - - @Override - public void lineTo(float x1, float y1) { - out.lineTo(x1 * mxx + y1 * mxy + mxt, - x1 * myx + y1 * myy + myt); - } - - @Override - public void quadTo(float x1, float y1, - float x2, float y2) - { - out.quadTo(x1 * mxx + y1 * mxy + mxt, - x1 * myx + y1 * myy + myt, - x2 * mxx + y2 * mxy + mxt, - x2 * myx + y2 * myy + myt); - } - - @Override - public void curveTo(float x1, float y1, - float x2, float y2, - float x3, float y3) - { - out.curveTo(x1 * mxx + y1 * mxy + mxt, - x1 * myx + y1 * myy + myt, - x2 * mxx + y2 * mxy + mxt, - x2 * myx + y2 * myy + myt, - x3 * mxx + y3 * mxy + mxt, - x3 * myx + y3 * myy + myt); - } - - @Override - public void closePath() { - out.closePath(); - } - - @Override - public void pathDone() { - out.pathDone(); - } - - @Override - public long getNativeConsumer() { - return 0; - } - } static final class DeltaScaleFilter implements PathConsumer2D { private PathConsumer2D out; diff --git a/jdk/src/java.desktop/share/classes/sun/java2d/marlin/Version.java b/jdk/src/java.desktop/share/classes/sun/java2d/marlin/Version.java index 1d144169376..9bd0498f7da 100644 --- a/jdk/src/java.desktop/share/classes/sun/java2d/marlin/Version.java +++ b/jdk/src/java.desktop/share/classes/sun/java2d/marlin/Version.java @@ -27,7 +27,7 @@ package sun.java2d.marlin; public final class Version { - private static final String version = "marlin-0.7.3.2-Unsafe-OpenJDK"; + private static final String version = "marlin-0.7.3.3-Unsafe-OpenJDK"; public static String getVersion() { return version; diff --git a/jdk/src/java.desktop/share/classes/sun/java2d/pipe/AAShapePipe.java b/jdk/src/java.desktop/share/classes/sun/java2d/pipe/AAShapePipe.java index 3046ff69c60..0aa5e54195f 100644 --- a/jdk/src/java.desktop/share/classes/sun/java2d/pipe/AAShapePipe.java +++ b/jdk/src/java.desktop/share/classes/sun/java2d/pipe/AAShapePipe.java @@ -28,7 +28,6 @@ import java.awt.BasicStroke; import java.awt.Rectangle; import java.awt.Shape; import java.awt.geom.Rectangle2D; -import java.util.concurrent.ConcurrentLinkedQueue; import sun.awt.SunHints; import sun.java2d.ReentrantContext; import sun.java2d.ReentrantContextProvider; diff --git a/jdk/test/sun/java2d/marlin/CrashNaNTest.java b/jdk/test/sun/java2d/marlin/CrashNaNTest.java index 01e32dd6c11..f25be866f85 100644 --- a/jdk/test/sun/java2d/marlin/CrashNaNTest.java +++ b/jdk/test/sun/java2d/marlin/CrashNaNTest.java @@ -21,14 +21,22 @@ * questions. */ +import java.awt.BasicStroke; import java.awt.Color; import java.awt.Graphics2D; import java.awt.RenderingHints; +import java.awt.Shape; +import java.awt.Stroke; import java.awt.geom.Path2D; +import java.awt.geom.PathIterator; import java.awt.image.BufferedImage; +import java.awt.image.Raster; import java.io.File; import java.io.IOException; +import static java.lang.Double.NEGATIVE_INFINITY; +import static java.lang.Double.POSITIVE_INFINITY; import static java.lang.Double.NaN; +import java.util.Arrays; import java.util.Locale; import java.util.logging.Handler; import java.util.logging.LogRecord; @@ -37,8 +45,9 @@ import javax.imageio.ImageIO; /** * @test - * @bug 8149338 - * @summary Verifies that Marlin supports NaN coordinates and no JVM crash happens ! + * @bug 8149338 8144938 + * @summary Verifies that Marlin supports NaN coordinates (no JVM crash) + * but also it skips properly point coordinates with NaN / Infinity values * @run main CrashNaNTest */ public class CrashNaNTest { @@ -77,23 +86,31 @@ public class CrashNaNTest { System.setProperty("sun.java2d.renderer.useLogger", "true"); System.setProperty("sun.java2d.renderer.doChecks", "true"); + testFillDefaultAt(); + testDrawComplexAt(); + + testPathClosed(); + + testStrokedShapes(); + } + + private static void testFillDefaultAt() { final int width = 400; final int height = 400; final BufferedImage image = new BufferedImage(width, height, - BufferedImage.TYPE_INT_ARGB); + BufferedImage.TYPE_INT_ARGB); final Graphics2D g2d = (Graphics2D) image.getGraphics(); try { g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, - RenderingHints.VALUE_ANTIALIAS_ON); + RenderingHints.VALUE_ANTIALIAS_ON); g2d.setBackground(Color.WHITE); g2d.clearRect(0, 0, width, height); final Path2D.Double path = new Path2D.Double(); - path.moveTo(30, 30); - path.lineTo(100, 100); + path.moveTo(100, 100); for (int i = 0; i < 20000; i++) { path.lineTo(110 + 0.01 * i, 110); @@ -105,39 +122,301 @@ public class CrashNaNTest { path.lineTo(200, NaN); path.lineTo(300, 300); path.lineTo(NaN, NaN); - path.lineTo(100, 100); + path.lineTo(100, 200); path.closePath(); final Path2D.Double path2 = new Path2D.Double(); - path2.moveTo(0,0); - path2.lineTo(width,height); - path2.lineTo(10, 10); + path2.moveTo(0, 0); + path2.lineTo(100, height); + path2.lineTo(0, 200); path2.closePath(); - for (int i = 0; i < 1; i++) { - final long start = System.nanoTime(); - g2d.setColor(Color.BLUE); - g2d.fill(path); + g2d.setColor(Color.BLUE); + g2d.fill(path); + g2d.setColor(Color.GREEN); + g2d.fill(path2); - g2d.fill(path2); - - final long time = System.nanoTime() - start; - System.out.println("paint: duration= " + (1e-6 * time) + " ms."); - } + g2d.setColor(Color.BLACK); + g2d.draw(path); + g2d.draw(path2); if (SAVE_IMAGE) { try { - final File file = new File("CrashNaNTest.png"); + final File file = new File("CrashNaNTest-fill.png"); System.out.println("Writing file: " - + file.getAbsolutePath()); + + file.getAbsolutePath()); ImageIO.write(image, "PNG", file); } catch (IOException ex) { System.out.println("Writing file failure:"); ex.printStackTrace(); } } + + // Check image on few pixels: + final Raster raster = image.getData(); + + checkPixel(raster, 200, 195, Color.BLUE.getRGB()); + checkPixel(raster, 105, 195, Color.BLUE.getRGB()); + checkPixel(raster, 286, 290, Color.BLUE.getRGB()); + + checkPixel(raster, 108, 105, Color.WHITE.getRGB()); + checkPixel(raster, 205, 200, Color.WHITE.getRGB()); + + checkPixel(raster, 5, 200, Color.GREEN.getRGB()); + } finally { g2d.dispose(); } } + + private static void testDrawComplexAt() { + final int width = 400; + final int height = 400; + + final BufferedImage image = new BufferedImage(width, height, + BufferedImage.TYPE_INT_ARGB); + + final Graphics2D g2d = (Graphics2D) image.getGraphics(); + try { + g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, + RenderingHints.VALUE_ANTIALIAS_ON); + g2d.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, + RenderingHints.VALUE_STROKE_PURE); + + g2d.setBackground(Color.WHITE); + g2d.clearRect(0, 0, width, height); + + final Path2D.Double path = new Path2D.Double(); + path.moveTo(100, 100); + + for (int i = 0; i < 20000; i++) { + path.lineTo(110 + 0.01 * i, 110); + path.lineTo(111 + 0.01 * i, 100); + } + + path.lineTo(NaN, 200); + path.lineTo(200, 200); + path.lineTo(200, NaN); + path.lineTo(300, 300); + path.lineTo(NaN, NaN); + path.lineTo(100, 200); + path.closePath(); + + final Path2D.Double path2 = new Path2D.Double(); + path2.moveTo(0, 0); + path2.lineTo(100, height); + path2.lineTo(0, 200); + path2.closePath(); + + // Define an non-uniform transform: + g2d.scale(0.5, 1.0); + g2d.rotate(Math.PI / 31); + + g2d.setColor(Color.BLACK); + g2d.draw(path); + g2d.draw(path2); + + if (SAVE_IMAGE) { + try { + final File file = new File("CrashNaNTest-draw.png"); + System.out.println("Writing file: " + + file.getAbsolutePath()); + ImageIO.write(image, "PNG", file); + } catch (IOException ex) { + System.out.println("Writing file failure:"); + ex.printStackTrace(); + } + } + + // Check image on few pixels: + final Raster raster = image.getData(); + + checkPixelNotWhite(raster, 40, 210); + checkPixelNotWhite(raster, 44, 110); + checkPixelNotWhite(raster, 60, 120); + checkPixelNotWhite(raster, 89, 219); + checkPixelNotWhite(raster, 28, 399); + checkPixelNotWhite(raster, 134, 329); + + } finally { + g2d.dispose(); + } + } + private static void testPathClosed() { + final int width = 100; + final int height = 100; + + final BufferedImage image = new BufferedImage(width, height, + BufferedImage.TYPE_INT_ARGB); + + final Graphics2D g2d = (Graphics2D) image.getGraphics(); + try { + g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, + RenderingHints.VALUE_ANTIALIAS_ON); + + g2d.setBackground(Color.WHITE); + g2d.clearRect(0, 0, width, height); + + final Path2D.Double path = new Path2D.Double(); + path.moveTo(40, 40); + path.lineTo(0, 0); + path.lineTo(80, 0); + path.closePath(); + path.lineTo(80, 80); + path.lineTo(0, 80); + path.closePath(); + + g2d.setColor(Color.BLUE); + g2d.fill(path); + + g2d.setColor(Color.BLACK); + g2d.draw(path); + + if (SAVE_IMAGE) { + try { + final File file = new File("CrashNaNTest-path-closed.png"); + System.out.println("Writing file: " + + file.getAbsolutePath()); + ImageIO.write(image, "PNG", file); + } catch (IOException ex) { + System.out.println("Writing file failure:"); + ex.printStackTrace(); + } + } + + // Check image on few pixels: + final Raster raster = image.getData(); + + checkPixel(raster, 10, 05, Color.BLUE.getRGB()); + checkPixel(raster, 70, 05, Color.BLUE.getRGB()); + checkPixel(raster, 40, 35, Color.BLUE.getRGB()); + + checkPixel(raster, 10, 75, Color.BLUE.getRGB()); + checkPixel(raster, 70, 75, Color.BLUE.getRGB()); + checkPixel(raster, 40, 45, Color.BLUE.getRGB()); + + } finally { + g2d.dispose(); + } + } + + private static void testStrokedShapes() { + final Stroke stroke = new BasicStroke(); + + final Path2D.Double path = new Path2D.Double(); + Shape s; + + // Check filtering NaN values: + path.reset(); + path.moveTo(100, NaN); + path.lineTo(NaN, 100); + path.lineTo(NaN, NaN); + + path.quadTo(NaN, 100, NaN, 100); + path.quadTo(100, NaN, 100, NaN); + path.quadTo(NaN, NaN, NaN, NaN); + + path.curveTo(NaN, 100, NaN, 100, NaN, 100); + path.curveTo(100, NaN, 100, NaN, 100, NaN); + path.curveTo(NaN, NaN, NaN, NaN, NaN, NaN); + path.closePath(); + + s = stroke.createStrokedShape(path); + checkEmptyPath(s); + + // Check filtering +Infinity values: + path.reset(); + path.moveTo(100, POSITIVE_INFINITY); + path.lineTo(POSITIVE_INFINITY, 100); + path.lineTo(POSITIVE_INFINITY, POSITIVE_INFINITY); + + path.quadTo(POSITIVE_INFINITY, 100, + POSITIVE_INFINITY, 100); + path.quadTo(100, POSITIVE_INFINITY, + 100, POSITIVE_INFINITY); + path.quadTo(POSITIVE_INFINITY, POSITIVE_INFINITY, + POSITIVE_INFINITY, POSITIVE_INFINITY); + + path.curveTo(POSITIVE_INFINITY, 100, + POSITIVE_INFINITY, 100, + POSITIVE_INFINITY, 100); + path.curveTo(100, POSITIVE_INFINITY, + 100, POSITIVE_INFINITY, + 100, POSITIVE_INFINITY); + path.curveTo(POSITIVE_INFINITY, POSITIVE_INFINITY, + POSITIVE_INFINITY, POSITIVE_INFINITY, + POSITIVE_INFINITY, POSITIVE_INFINITY); + path.closePath(); + + s = stroke.createStrokedShape(path); + checkEmptyPath(s); + + // Check filtering -Infinity values: + path.reset(); + path.moveTo(100, NEGATIVE_INFINITY); + path.lineTo(NEGATIVE_INFINITY, 100); + path.lineTo(NEGATIVE_INFINITY, NEGATIVE_INFINITY); + + path.quadTo(NEGATIVE_INFINITY, 100, + NEGATIVE_INFINITY, 100); + path.quadTo(100, NEGATIVE_INFINITY, + 100, NEGATIVE_INFINITY); + path.quadTo(NEGATIVE_INFINITY, NEGATIVE_INFINITY, + NEGATIVE_INFINITY, NEGATIVE_INFINITY); + + path.curveTo(NEGATIVE_INFINITY, 100, + NEGATIVE_INFINITY, 100, + NEGATIVE_INFINITY, 100); + path.curveTo(100, NEGATIVE_INFINITY, + 100, NEGATIVE_INFINITY, + 100, NEGATIVE_INFINITY); + path.curveTo(NEGATIVE_INFINITY, NEGATIVE_INFINITY, + NEGATIVE_INFINITY, NEGATIVE_INFINITY, + NEGATIVE_INFINITY, NEGATIVE_INFINITY); + path.closePath(); + + s = stroke.createStrokedShape(path); + checkEmptyPath(s); + } + + private static void checkEmptyPath(final Shape s) { + final float[] coords = new float[6]; + final PathIterator it = s.getPathIterator(null); + + int n = 0; + for (; !it.isDone(); it.next()) { + int type = it.currentSegment(coords); + System.out.println("unexpected segment type= " + type + + " with coords: " + Arrays.toString(coords)); + n++; + } + if (n != 0) { + System.out.println("path elements = " + n); + throw new IllegalStateException("Not empty path: " + + n + " path elements !"); + } + } + + private static void checkPixel(final Raster raster, + final int x, final int y, + final int expected) { + + final int[] rgb = (int[]) raster.getDataElements(x, y, null); + + if (rgb[0] != expected) { + throw new IllegalStateException("bad pixel at (" + x + ", " + y + + ") = " + rgb[0] + " expected: " + expected); + } + } + + private static void checkPixelNotWhite(final Raster raster, + final int x, final int y) { + + final int[] rgb = (int[]) raster.getDataElements(x, y, null); + + if (rgb[0] == Color.WHITE.getRGB()) { + throw new IllegalStateException("bad pixel at (" + x + ", " + y + + ") is white (empty)"); + } + } } From 9dff846b306b36902acc358ad12b3cd867080fd0 Mon Sep 17 00:00:00 2001 From: Martin Doerr Date: Wed, 23 Mar 2016 15:35:38 -0700 Subject: [PATCH 053/162] 8151818: C1: LIRGenerator::move_to_phi can't deal with illegal phi Reviewed-by: iveresov, kvn --- hotspot/src/share/vm/c1/c1_LIRGenerator.cpp | 10 +++++++++- hotspot/src/share/vm/c1/c1_ValueStack.hpp | 6 +++--- 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/hotspot/src/share/vm/c1/c1_LIRGenerator.cpp b/hotspot/src/share/vm/c1/c1_LIRGenerator.cpp index b8df66256b3..03438c5ee8e 100644 --- a/hotspot/src/share/vm/c1/c1_LIRGenerator.cpp +++ b/hotspot/src/share/vm/c1/c1_LIRGenerator.cpp @@ -999,8 +999,16 @@ void LIRGenerator::move_to_phi(PhiResolver* resolver, Value cur_val, Value sux_v Phi* phi = sux_val->as_Phi(); // cur_val can be null without phi being null in conjunction with inlining if (phi != NULL && cur_val != NULL && cur_val != phi && !phi->is_illegal()) { + Phi* cur_phi = cur_val->as_Phi(); + if (cur_phi != NULL && cur_phi->is_illegal()) { + // Phi and local would need to get invalidated + // (which is unexpected for Linear Scan). + // But this case is very rare so we simply bail out. + bailout("propagation of illegal phi"); + return; + } LIR_Opr operand = cur_val->operand(); - if (cur_val->operand()->is_illegal()) { + if (operand->is_illegal()) { assert(cur_val->as_Constant() != NULL || cur_val->as_Local() != NULL, "these can be produced lazily"); operand = operand_for_instruction(cur_val); diff --git a/hotspot/src/share/vm/c1/c1_ValueStack.hpp b/hotspot/src/share/vm/c1/c1_ValueStack.hpp index 8340adbd289..14efe073551 100644 --- a/hotspot/src/share/vm/c1/c1_ValueStack.hpp +++ b/hotspot/src/share/vm/c1/c1_ValueStack.hpp @@ -99,14 +99,14 @@ class ValueStack: public CompilationResourceObj { void clear_locals(); // sets all locals to NULL; void invalidate_local(int i) { - assert(_locals.at(i)->type()->is_single_word() || + assert(!_locals.at(i)->type()->is_double_word() || _locals.at(i + 1) == NULL, "hi-word of doubleword value must be NULL"); _locals.at_put(i, NULL); } Value local_at(int i) const { Value x = _locals.at(i); - assert(x == NULL || x->type()->is_single_word() || + assert(x == NULL || !x->type()->is_double_word() || _locals.at(i + 1) == NULL, "hi-word of doubleword value must be NULL"); return x; } @@ -131,7 +131,7 @@ class ValueStack: public CompilationResourceObj { // stack access Value stack_at(int i) const { Value x = _stack.at(i); - assert(x->type()->is_single_word() || + assert(!x->type()->is_double_word() || _stack.at(i + 1) == NULL, "hi-word of doubleword value must be NULL"); return x; } From 4cc52c4f6e5719bf18b9b95a7b08c6a7b174b48f Mon Sep 17 00:00:00 2001 From: Alexander Zvegintsev Date: Thu, 24 Mar 2016 02:04:14 +0300 Subject: [PATCH 054/162] 8143227: Platform-Specific Desktop Features Reviewed-by: prr, serb --- make/common/CORE_PKGS.gmk | 1 + 1 file changed, 1 insertion(+) diff --git a/make/common/CORE_PKGS.gmk b/make/common/CORE_PKGS.gmk index 850073385a4..3223460f098 100644 --- a/make/common/CORE_PKGS.gmk +++ b/make/common/CORE_PKGS.gmk @@ -82,6 +82,7 @@ CORE_PKGS = \ java.awt \ java.awt.color \ java.awt.datatransfer \ + java.awt.desktop \ java.awt.dnd \ java.awt.event \ java.awt.font \ From c661c227e2077d0b5037e8bdb52e684d64c50f6b Mon Sep 17 00:00:00 2001 From: Alexander Zvegintsev Date: Thu, 24 Mar 2016 02:22:01 +0300 Subject: [PATCH 055/162] 8143227: Platform-Specific Desktop Features Reviewed-by: prr, serb --- jdk/make/mapfiles/libawt_xawt/mapfile-vers | 8 +- .../classes/com/apple/eawt/AppEvent.java | 220 ------- .../classes/com/apple/eawt/Application.java | 199 +----- .../com/apple/eawt/ApplicationAdapter.java | 4 +- .../com/apple/eawt/ApplicationEvent.java | 4 +- .../com/apple/eawt/ApplicationListener.java | 6 +- .../com/apple/eawt/FullScreenAdapter.java | 4 +- .../com/apple/eawt/FullScreenHandler.java | 4 +- .../com/apple/eawt/FullScreenListener.java | 4 +- ...QuitResponse.java => MacQuitResponse.java} | 12 +- .../com/apple/eawt/OpenURIHandler.java | 46 -- .../com/apple/eawt/_AppDockIconHandler.java | 7 +- .../com/apple/eawt/_AppEventHandler.java | 88 ++- .../apple/eawt/_AppEventLegacyHandler.java | 188 ------ .../com/apple/eawt/_AppMenuBarHandler.java | 3 +- .../com/apple/eawt/event/FullScreenEvent.java | 51 ++ .../macosx/classes/sun/lwawt/LWToolkit.java | 7 +- .../sun/lwawt/macosx/CDesktopPeer.java | 105 +++- .../sun/lwawt/macosx/CTaskbarPeer.java | 89 +++ .../classes/sun/lwawt/macosx/LWCToolkit.java | 8 +- .../libawt_lwawt/awt/ApplicationDelegate.h | 6 +- .../libawt_lwawt/awt/ApplicationDelegate.m | 51 +- .../share/classes/java/awt/Desktop.java | 575 +++++++++++++++++- .../share/classes/java/awt/Frame.java | 1 + .../share/classes/java/awt/Taskbar.java | 449 ++++++++++++++ .../classes/java/awt/desktop/AboutEvent.java | 45 ++ .../java/awt/desktop}/AboutHandler.java | 18 +- .../classes/java/awt/desktop/AppEvent.java | 45 ++ .../java/awt/desktop/AppForegroundEvent.java | 47 ++ .../awt/desktop}/AppForegroundListener.java | 27 +- .../java/awt/desktop/AppHiddenEvent.java | 46 ++ .../java/awt/desktop}/AppHiddenListener.java | 28 +- .../java/awt/desktop/AppReopenedEvent.java | 45 ++ .../awt/desktop/AppReopenedListener.java} | 21 +- .../classes/java/awt/desktop/FilesEvent.java | 61 ++ .../java/awt/desktop/OpenFilesEvent.java | 70 +++ .../java/awt/desktop}/OpenFilesHandler.java | 11 +- .../java/awt/desktop/OpenURIEvent.java | 58 ++ .../java/awt/desktop/OpenURIHandler.java | 41 ++ .../java/awt/desktop/PreferencesEvent.java | 45 ++ .../java/awt/desktop}/PreferencesHandler.java | 15 +- .../java/awt/desktop/PrintFilesEvent.java | 50 ++ .../java/awt/desktop}/PrintFilesHandler.java | 11 +- .../classes/java/awt/desktop/QuitEvent.java | 44 ++ .../java/awt/desktop}/QuitHandler.java | 13 +- .../java/awt/desktop/QuitResponse.java | 49 ++ .../java/awt/desktop}/QuitStrategy.java | 19 +- .../java/awt/desktop/ScreenSleepEvent.java | 45 ++ .../awt/desktop}/ScreenSleepListener.java | 18 +- .../awt/desktop/SystemEventListener.java} | 22 +- .../java/awt/desktop/SystemSleepEvent.java | 45 ++ .../awt/desktop}/SystemSleepListener.java | 30 +- .../java/awt/desktop/UserSessionEvent.java | 89 +++ .../awt/desktop}/UserSessionListener.java | 22 +- .../classes/java/awt/desktop/package.html | 36 ++ .../classes/java/awt/peer/DesktopPeer.java | 177 +++++- .../classes/java/awt/peer/TaskbarPeer.java | 136 +++++ .../share/classes/module-info.java | 1 + .../classes/sun/awt/ComponentFactory.java | 18 + .../share/classes/sun/awt/HToolkit.java | 7 +- .../share/classes/sun/awt/SunToolkit.java | 3 +- .../classes/sun/awt/X11/XTaskbarPeer.java | 164 +++++ .../unix/classes/sun/awt/X11/XToolkit.java | 13 +- .../native/libawt_xawt/awt/gtk2_interface.c | 6 +- .../native/libawt_xawt/awt/gtk2_interface.h | 16 +- .../native/libawt_xawt/xawt/awt_Taskbar.c | 260 ++++++++ .../native/libawt_xawt/xawt/awt_Taskbar.h | 58 ++ .../classes/sun/awt/windows/WDesktopPeer.java | 104 +++- .../classes/sun/awt/windows/WTaskbarPeer.java | 152 +++++ .../classes/sun/awt/windows/WToolkit.java | 14 +- .../native/libawt/windows/awt_Desktop.cpp | 83 ++- .../native/libawt/windows/awt_Taskbar.cpp | 128 ++++ .../native/libawt/windows/awt_Taskbar.h | 108 ++++ .../native/libawt/windows/awt_Toolkit.cpp | 120 +++- .../native/libawt/windows/awt_Toolkit.h | 7 +- .../native/libawt/windows/awt_Window.h | 4 +- 76 files changed, 3973 insertions(+), 861 deletions(-) delete mode 100644 jdk/src/java.desktop/macosx/classes/com/apple/eawt/AppEvent.java rename jdk/src/java.desktop/macosx/classes/com/apple/eawt/{QuitResponse.java => MacQuitResponse.java} (86%) delete mode 100644 jdk/src/java.desktop/macosx/classes/com/apple/eawt/OpenURIHandler.java delete mode 100644 jdk/src/java.desktop/macosx/classes/com/apple/eawt/_AppEventLegacyHandler.java create mode 100644 jdk/src/java.desktop/macosx/classes/com/apple/eawt/event/FullScreenEvent.java create mode 100644 jdk/src/java.desktop/macosx/classes/sun/lwawt/macosx/CTaskbarPeer.java create mode 100644 jdk/src/java.desktop/share/classes/java/awt/Taskbar.java create mode 100644 jdk/src/java.desktop/share/classes/java/awt/desktop/AboutEvent.java rename jdk/src/java.desktop/{macosx/classes/com/apple/eawt => share/classes/java/awt/desktop}/AboutHandler.java (74%) create mode 100644 jdk/src/java.desktop/share/classes/java/awt/desktop/AppEvent.java create mode 100644 jdk/src/java.desktop/share/classes/java/awt/desktop/AppForegroundEvent.java rename jdk/src/java.desktop/{macosx/classes/com/apple/eawt => share/classes/java/awt/desktop}/AppForegroundListener.java (64%) create mode 100644 jdk/src/java.desktop/share/classes/java/awt/desktop/AppHiddenEvent.java rename jdk/src/java.desktop/{macosx/classes/com/apple/eawt => share/classes/java/awt/desktop}/AppHiddenListener.java (72%) create mode 100644 jdk/src/java.desktop/share/classes/java/awt/desktop/AppReopenedEvent.java rename jdk/src/java.desktop/{macosx/classes/com/apple/eawt/AppReOpenedListener.java => share/classes/java/awt/desktop/AppReopenedListener.java} (63%) create mode 100644 jdk/src/java.desktop/share/classes/java/awt/desktop/FilesEvent.java create mode 100644 jdk/src/java.desktop/share/classes/java/awt/desktop/OpenFilesEvent.java rename jdk/src/java.desktop/{macosx/classes/com/apple/eawt => share/classes/java/awt/desktop}/OpenFilesHandler.java (78%) create mode 100644 jdk/src/java.desktop/share/classes/java/awt/desktop/OpenURIEvent.java create mode 100644 jdk/src/java.desktop/share/classes/java/awt/desktop/OpenURIHandler.java create mode 100644 jdk/src/java.desktop/share/classes/java/awt/desktop/PreferencesEvent.java rename jdk/src/java.desktop/{macosx/classes/com/apple/eawt => share/classes/java/awt/desktop}/PreferencesHandler.java (74%) create mode 100644 jdk/src/java.desktop/share/classes/java/awt/desktop/PrintFilesEvent.java rename jdk/src/java.desktop/{macosx/classes/com/apple/eawt => share/classes/java/awt/desktop}/PrintFilesHandler.java (83%) create mode 100644 jdk/src/java.desktop/share/classes/java/awt/desktop/QuitEvent.java rename jdk/src/java.desktop/{macosx/classes/com/apple/eawt => share/classes/java/awt/desktop}/QuitHandler.java (87%) create mode 100644 jdk/src/java.desktop/share/classes/java/awt/desktop/QuitResponse.java rename jdk/src/java.desktop/{macosx/classes/com/apple/eawt => share/classes/java/awt/desktop}/QuitStrategy.java (74%) create mode 100644 jdk/src/java.desktop/share/classes/java/awt/desktop/ScreenSleepEvent.java rename jdk/src/java.desktop/{macosx/classes/com/apple/eawt => share/classes/java/awt/desktop}/ScreenSleepListener.java (77%) rename jdk/src/java.desktop/{macosx/classes/com/apple/eawt/AppEventListener.java => share/classes/java/awt/desktop/SystemEventListener.java} (71%) create mode 100644 jdk/src/java.desktop/share/classes/java/awt/desktop/SystemSleepEvent.java rename jdk/src/java.desktop/{macosx/classes/com/apple/eawt => share/classes/java/awt/desktop}/SystemSleepListener.java (66%) create mode 100644 jdk/src/java.desktop/share/classes/java/awt/desktop/UserSessionEvent.java rename jdk/src/java.desktop/{macosx/classes/com/apple/eawt => share/classes/java/awt/desktop}/UserSessionListener.java (74%) create mode 100644 jdk/src/java.desktop/share/classes/java/awt/desktop/package.html create mode 100644 jdk/src/java.desktop/share/classes/java/awt/peer/TaskbarPeer.java create mode 100644 jdk/src/java.desktop/unix/classes/sun/awt/X11/XTaskbarPeer.java create mode 100644 jdk/src/java.desktop/unix/native/libawt_xawt/xawt/awt_Taskbar.c create mode 100644 jdk/src/java.desktop/unix/native/libawt_xawt/xawt/awt_Taskbar.h create mode 100644 jdk/src/java.desktop/windows/classes/sun/awt/windows/WTaskbarPeer.java create mode 100644 jdk/src/java.desktop/windows/native/libawt/windows/awt_Taskbar.cpp create mode 100644 jdk/src/java.desktop/windows/native/libawt/windows/awt_Taskbar.h diff --git a/jdk/make/mapfiles/libawt_xawt/mapfile-vers b/jdk/make/mapfiles/libawt_xawt/mapfile-vers index 42ef24d90a1..2b18bd42e6f 100644 --- a/jdk/make/mapfiles/libawt_xawt/mapfile-vers +++ b/jdk/make/mapfiles/libawt_xawt/mapfile-vers @@ -1,5 +1,5 @@ # -# Copyright (c) 2002, 2014, Oracle and/or its affiliates. All rights reserved. +# Copyright (c) 2002, 2016, Oracle and/or its affiliates. All rights reserved. # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. # # This code is free software; you can redistribute it and/or modify it @@ -150,6 +150,12 @@ SUNWprivate_1.1 { Java_sun_awt_X11_XlibWrapper_XdbeEndIdiom; Java_sun_awt_X11_XDesktopPeer_init; Java_sun_awt_X11_XDesktopPeer_gnome_1url_1show; + Java_sun_awt_X11_XTaskbarPeer_init; + Java_sun_awt_X11_XTaskbarPeer_runloop; + Java_sun_awt_X11_XTaskbarPeer_setBadge; + Java_sun_awt_X11_XTaskbarPeer_setUrgent; + Java_sun_awt_X11_XTaskbarPeer_updateProgress; + Java_sun_awt_X11_XTaskbarPeer_setNativeMenu; Java_sun_awt_X11_XRobotPeer_getRGBPixelsImpl; Java_sun_awt_X11_XRobotPeer_keyPressImpl; Java_sun_awt_X11_XRobotPeer_keyReleaseImpl; diff --git a/jdk/src/java.desktop/macosx/classes/com/apple/eawt/AppEvent.java b/jdk/src/java.desktop/macosx/classes/com/apple/eawt/AppEvent.java deleted file mode 100644 index 643351748cd..00000000000 --- a/jdk/src/java.desktop/macosx/classes/com/apple/eawt/AppEvent.java +++ /dev/null @@ -1,220 +0,0 @@ -/* - * Copyright (c) 2011, 2014, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package com.apple.eawt; - -import java.io.File; -import java.net.URI; -import java.util.*; -import java.awt.Window; - -/** - * AppEvents are sent to listeners and handlers installed on the {@link Application}. - * - * @since Java for Mac OS X 10.6 Update 3 - * @since Java for Mac OS X 10.5 Update 8 - */ -@SuppressWarnings("serial") // JDK implementation class -public abstract class AppEvent extends EventObject { - AppEvent() { - super(Application.getApplication()); - } - - /** - * Contains a list of files. - */ - @SuppressWarnings("serial") // JDK implementation class - public abstract static class FilesEvent extends AppEvent { - final List files; - - FilesEvent(final List files) { - this.files = files; - } - - /** - * @return the list of files - */ - public List getFiles() { - return files; - } - } - - /** - * Event sent when the app is asked to open a list of files. - * - * @see OpenFilesHandler#openFiles(OpenFilesEvent) - */ - @SuppressWarnings("serial") // JDK implementation class - public static class OpenFilesEvent extends FilesEvent { - final String searchTerm; - - OpenFilesEvent(final List files, final String searchTerm) { - super(files); - this.searchTerm = searchTerm; - } - - /** - * If the files were opened using the Spotlight search menu or a Finder search window, this method obtains the search term used to find the files. - * This is useful for highlighting the search term in the documents when they are opened. - * @return the search term used to find the files - */ - public String getSearchTerm() { - return searchTerm; - } - } - - /** - * Event sent when the app is asked to print a list of files. - * - * @see PrintFilesHandler#printFiles(PrintFilesEvent) - */ - @SuppressWarnings("serial") // JDK implementation class - public static class PrintFilesEvent extends FilesEvent { - PrintFilesEvent(final List files) { - super(files); - } - } - - /** - * Event sent when the app is asked to open a URI. - * - * @see OpenURIHandler#openURI(OpenURIEvent) - */ - @SuppressWarnings("serial") // JDK implementation class - public static class OpenURIEvent extends AppEvent { - final URI uri; - - OpenURIEvent(final URI uri) { - this.uri = uri; - } - - /** - * @return the URI the app was asked to open - */ - public URI getURI() { - return uri; - } - } - - /** - * Event sent when the application is asked to open it's about window. - * - * @see AboutHandler#handleAbout() - */ - @SuppressWarnings("serial") // JDK implementation class - public static class AboutEvent extends AppEvent { AboutEvent() { } } - - /** - * Event sent when the application is asked to open it's preferences window. - * - * @see PreferencesHandler#handlePreferences() - */ - @SuppressWarnings("serial") // JDK implementation class - public static class PreferencesEvent extends AppEvent { PreferencesEvent() { } } - - /** - * Event sent when the application is asked to quit. - * - * @see QuitHandler#handleQuitRequestWith(QuitEvent, QuitResponse) - */ - @SuppressWarnings("serial") // JDK implementation class - public static class QuitEvent extends AppEvent { QuitEvent() { } } - - /** - * Event sent when the application is asked to re-open itself. - * - * @see AppReOpenedListener#appReOpened(AppReOpenedEvent) - */ - @SuppressWarnings("serial") // JDK implementation class - public static class AppReOpenedEvent extends AppEvent { AppReOpenedEvent() { } } - - /** - * Event sent when the application has become the foreground app, and when it has resigned being the foreground app. - * - * @see AppForegroundListener#appRaisedToForeground(AppForegroundEvent) - * @see AppForegroundListener#appMovedToBackground(AppForegroundEvent) - */ - @SuppressWarnings("serial") // JDK implementation class - public static class AppForegroundEvent extends AppEvent { AppForegroundEvent() { } } - - /** - * Event sent when the application has been hidden or shown. - * - * @see AppHiddenListener#appHidden(AppHiddenEvent) - * @see AppHiddenListener#appUnhidden(AppHiddenEvent) - */ - @SuppressWarnings("serial") // JDK implementation class - public static class AppHiddenEvent extends AppEvent { AppHiddenEvent() { } } - - /** - * Event sent when the user session has been changed via Fast User Switching. - * - * @see UserSessionListener#userSessionActivated(UserSessionEvent) - * @see UserSessionListener#userSessionDeactivated(UserSessionEvent) - */ - @SuppressWarnings("serial") // JDK implementation class - public static class UserSessionEvent extends AppEvent { UserSessionEvent() { } } - - /** - * Event sent when the displays attached to the system enter and exit power save sleep. - * - * @see ScreenSleepListener#screenAboutToSleep(ScreenSleepEvent) - * @see ScreenSleepListener#screenAwoke(ScreenSleepEvent) - */ - @SuppressWarnings("serial") // JDK implementation class - public static class ScreenSleepEvent extends AppEvent { ScreenSleepEvent() { } } - - /** - * Event sent when the system enters and exits power save sleep. - * - * @see SystemSleepListener#systemAboutToSleep(SystemSleepEvent) - * @see SystemSleepListener#systemAwoke(SystemSleepEvent) - */ - @SuppressWarnings("serial") // JDK implementation class - public static class SystemSleepEvent extends AppEvent { SystemSleepEvent() { } } - - /** - * Event sent when a window is entering/exiting or has entered/exited full screen state. - * - * @see FullScreenUtilities - * - * @since Java for Mac OS X 10.7 Update 1 - */ - @SuppressWarnings("serial") // JDK implementation class - public static class FullScreenEvent extends AppEvent { - final Window window; - - FullScreenEvent(final Window window) { - this.window = window; - } - - /** - * @return window transitioning between full screen states - */ - public Window getWindow() { - return window; - } - } -} diff --git a/jdk/src/java.desktop/macosx/classes/com/apple/eawt/Application.java b/jdk/src/java.desktop/macosx/classes/com/apple/eawt/Application.java index 3535b4ae3d6..8ad28ebb9b7 100644 --- a/jdk/src/java.desktop/macosx/classes/com/apple/eawt/Application.java +++ b/jdk/src/java.desktop/macosx/classes/com/apple/eawt/Application.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2011, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -26,10 +26,10 @@ package com.apple.eawt; import java.awt.Image; -import java.awt.Point; import java.awt.PopupMenu; import java.awt.Toolkit; import java.awt.Window; +import java.awt.desktop.*; import java.beans.Beans; import javax.swing.JMenuBar; @@ -104,38 +104,38 @@ public class Application { } /** - * Adds sub-types of {@link AppEventListener} to listen for notifications from the native Mac OS X system. + * Adds sub-types of {@link SystemEventListener} to listen for notifications from the native Mac OS X system. * * @see AppForegroundListener * @see AppHiddenListener * @see AppReOpenedListener - * @see ScreenSleepListener - * @see SystemSleepListener - * @see UserSessionListener + * @see AppScreenSleepListener + * @see AppSystemSleepListener + * @see AppUserSessionListener * * @param listener * @since Java for Mac OS X 10.6 Update 3 * @since Java for Mac OS X 10.5 Update 8 */ - public void addAppEventListener(final AppEventListener listener) { + public void addAppEventListener(final SystemEventListener listener) { eventHandler.addListener(listener); } /** - * Removes sub-types of {@link AppEventListener} from listening for notifications from the native Mac OS X system. + * Removes sub-types of {@link SystemEventListener} from listening for notifications from the native Mac OS X system. * * @see AppForegroundListener * @see AppHiddenListener * @see AppReOpenedListener - * @see ScreenSleepListener - * @see SystemSleepListener - * @see UserSessionListener + * @see AppScreenSleepListener + * @see AppSystemSleepListener + * @see AppUserSessionListener * * @param listener * @since Java for Mac OS X 10.6 Update 3 * @since Java for Mac OS X 10.5 Update 8 */ - public void removeAppEventListener(final AppEventListener listener) { + public void removeAppEventListener(final SystemEventListener listener) { eventHandler.removeListener(listener); } @@ -367,6 +367,17 @@ public class Application { iconHandler.setDockIconBadge(badge); } + /** + * Displays a progress bar to this application's Dock icon. + * Acceptable values are from 0 to 100, any other disables progress indication. + * + * @param value progress value + * @since 1.9 + */ + public void setDockIconProgress(final int value) { + iconHandler.setDockIconProgress(value); + } + /** * Sets the default menu bar to use when there are no active frames. * Only used when the system property "apple.laf.useScreenMenuBar" is "true", and @@ -397,168 +408,4 @@ public class Application { ((CPlatformWindow)platformWindow).toggleFullScreen(); } - - // -- DEPRECATED API -- - - /** - * Adds the specified ApplicationListener as a receiver of callbacks from this class. - * This method throws a RuntimeException if the newer About, Preferences, Quit, etc handlers are installed. - * - * @param listener an implementation of ApplicationListener that handles ApplicationEvents - * - * @deprecated register individual handlers for each task (About, Preferences, Open, Print, Quit, etc) - * @since 1.4 - */ - @SuppressWarnings("deprecation") - @Deprecated - public void addApplicationListener(final ApplicationListener listener) { - eventHandler.legacyHandler.addLegacyAppListener(listener); - } - - /** - * Removes the specified ApplicationListener from being a receiver of callbacks from this class. - * This method throws a RuntimeException if the newer About, Preferences, Quit, etc handlers are installed. - * - * @param listener an implementation of ApplicationListener that had previously been registered to handle ApplicationEvents - * - * @deprecated unregister individual handlers for each task (About, Preferences, Open, Print, Quit, etc) - * @since 1.4 - */ - @SuppressWarnings("deprecation") - @Deprecated - public void removeApplicationListener(final ApplicationListener listener) { - eventHandler.legacyHandler.removeLegacyAppListener(listener); - } - - /** - * Enables the Preferences item in the application menu. The ApplicationListener receives a callback for - * selection of the Preferences item in the application menu only if this is set to {@code true}. - * - * If a Preferences item isn't present, this method adds and enables it. - * - * @param enable specifies whether the Preferences item in the application menu should be enabled ({@code true}) or not ({@code false}) - * - * @deprecated no replacement - * @since 1.4 - */ - @Deprecated - public void setEnabledPreferencesMenu(final boolean enable) { - menuBarHandler.setPreferencesMenuItemVisible(true); - menuBarHandler.setPreferencesMenuItemEnabled(enable); - } - - /** - * Enables the About item in the application menu. The ApplicationListener receives a callback for - * selection of the About item in the application menu only if this is set to {@code true}. Because AWT supplies - * a standard About window when an application may not, by default this is set to {@code true}. - * - * If the About item isn't present, this method adds and enables it. - * - * @param enable specifies whether the About item in the application menu should be enabled ({@code true}) or not ({@code false}) - * - * @deprecated no replacement - * @since 1.4 - */ - @Deprecated - public void setEnabledAboutMenu(final boolean enable) { - menuBarHandler.setAboutMenuItemEnabled(enable); - } - - /** - * Determines if the Preferences item of the application menu is enabled. - * - * @deprecated no replacement - * @since 1.4 - */ - @Deprecated - public boolean getEnabledPreferencesMenu() { - return menuBarHandler.isPreferencesMenuItemEnabled(); - } - - /** - * Determines if the About item of the application menu is enabled. - * - * @deprecated no replacement - * @since 1.4 - */ - @Deprecated - public boolean getEnabledAboutMenu() { - return menuBarHandler.isAboutMenuItemEnabled(); - } - - /** - * Determines if the About item of the application menu is present. - * - * @deprecated no replacement - * @since 1.4 - */ - @Deprecated - public boolean isAboutMenuItemPresent() { - return menuBarHandler.isAboutMenuItemVisible(); - } - - /** - * Adds the About item to the application menu if the item is not already present. - * - * @deprecated use {@link #setAboutHandler(AboutHandler)} with a non-null {@link AboutHandler} parameter - * @since 1.4 - */ - @Deprecated - public void addAboutMenuItem() { - menuBarHandler.setAboutMenuItemVisible(true); - } - - /** - * Removes the About item from the application menu if the item is present. - * - * @deprecated use {@link #setAboutHandler(AboutHandler)} with a null parameter - * @since 1.4 - */ - @Deprecated - public void removeAboutMenuItem() { - menuBarHandler.setAboutMenuItemVisible(false); - } - - /** - * Determines if the About Preferences of the application menu is present. By default there is no Preferences menu item. - * - * @deprecated no replacement - * @since 1.4 - */ - @Deprecated - public boolean isPreferencesMenuItemPresent() { - return menuBarHandler.isPreferencesMenuItemVisible(); - } - - /** - * Adds the Preferences item to the application menu if the item is not already present. - * - * @deprecated use {@link #setPreferencesHandler(PreferencesHandler)} with a non-null {@link PreferencesHandler} parameter - * @since 1.4 - */ - @Deprecated - public void addPreferencesMenuItem() { - menuBarHandler.setPreferencesMenuItemVisible(true); - } - - /** - * Removes the Preferences item from the application menu if that item is present. - * - * @deprecated use {@link #setPreferencesHandler(PreferencesHandler)} with a null parameter - * @since 1.4 - */ - @Deprecated - public void removePreferencesMenuItem() { - menuBarHandler.setPreferencesMenuItemVisible(false); - } - - /** - * @deprecated Use {@code java.awt.MouseInfo.getPointerInfo().getLocation()}. - * - * @since 1.4 - */ - @Deprecated - public static Point getMouseLocationOnScreen() { - return java.awt.MouseInfo.getPointerInfo().getLocation(); - } } diff --git a/jdk/src/java.desktop/macosx/classes/com/apple/eawt/ApplicationAdapter.java b/jdk/src/java.desktop/macosx/classes/com/apple/eawt/ApplicationAdapter.java index 17339373153..aba03e9f744 100644 --- a/jdk/src/java.desktop/macosx/classes/com/apple/eawt/ApplicationAdapter.java +++ b/jdk/src/java.desktop/macosx/classes/com/apple/eawt/ApplicationAdapter.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2011, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -46,7 +46,7 @@ package com.apple.eawt; * @see ScreenSleepListener * @see SystemSleepListener * - * @deprecated replaced by {@link AboutHandler}, {@link PreferencesHandler}, {@link AppReOpenedListener}, {@link OpenFilesHandler}, {@link PrintFilesHandler}, {@link QuitHandler}, {@link QuitResponse}. + * @deprecated replaced by {@link AboutHandler}, {@link PreferencesHandler}, {@link AppReOpenedListener}, {@link OpenFilesHandler}, {@link PrintFilesHandler}, {@link QuitHandler}, {@link MacQuitResponse}. * @since 1.4 */ @SuppressWarnings("deprecation") diff --git a/jdk/src/java.desktop/macosx/classes/com/apple/eawt/ApplicationEvent.java b/jdk/src/java.desktop/macosx/classes/com/apple/eawt/ApplicationEvent.java index 0cfe0741682..49617f6c852 100644 --- a/jdk/src/java.desktop/macosx/classes/com/apple/eawt/ApplicationEvent.java +++ b/jdk/src/java.desktop/macosx/classes/com/apple/eawt/ApplicationEvent.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2011, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -30,7 +30,7 @@ import java.util.EventObject; /** * The class of events sent to the deprecated ApplicationListener callbacks. * - * @deprecated replaced by {@link AboutHandler}, {@link PreferencesHandler}, {@link AppReOpenedListener}, {@link OpenFilesHandler}, {@link PrintFilesHandler}, {@link QuitHandler}, {@link QuitResponse} + * @deprecated replaced by {@link AboutHandler}, {@link PreferencesHandler}, {@link AppReOpenedListener}, {@link OpenFilesHandler}, {@link PrintFilesHandler}, {@link QuitHandler}, {@link MacQuitResponse} * @since 1.4 */ @Deprecated diff --git a/jdk/src/java.desktop/macosx/classes/com/apple/eawt/ApplicationListener.java b/jdk/src/java.desktop/macosx/classes/com/apple/eawt/ApplicationListener.java index ea2efcf0ede..eabcb92aafe 100644 --- a/jdk/src/java.desktop/macosx/classes/com/apple/eawt/ApplicationListener.java +++ b/jdk/src/java.desktop/macosx/classes/com/apple/eawt/ApplicationListener.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2011, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -47,7 +47,7 @@ import java.util.EventListener; * @see SystemSleepListener * * @since 1.4 - * @deprecated replaced by {@link AboutHandler}, {@link PreferencesHandler}, {@link AppReOpenedListener}, {@link OpenFilesHandler}, {@link PrintFilesHandler}, {@link QuitHandler}, {@link QuitResponse} + * @deprecated replaced by {@link AboutHandler}, {@link PreferencesHandler}, {@link AppReOpenedListener}, {@link OpenFilesHandler}, {@link PrintFilesHandler}, {@link QuitHandler}, {@link MacQuitResponse} */ @SuppressWarnings("deprecation") @Deprecated @@ -134,7 +134,7 @@ public interface ApplicationListener extends EventListener { * {@code event}. To reject the quit, set {@code isHandled(false)}. * * @param event a Quit Application event - * @deprecated use {@link QuitHandler} and {@link QuitResponse} + * @deprecated use {@link QuitHandler} and {@link MacQuitResponse} */ @Deprecated public void handleQuit(ApplicationEvent event); diff --git a/jdk/src/java.desktop/macosx/classes/com/apple/eawt/FullScreenAdapter.java b/jdk/src/java.desktop/macosx/classes/com/apple/eawt/FullScreenAdapter.java index 8e60b7b0e2b..4a124da6e38 100644 --- a/jdk/src/java.desktop/macosx/classes/com/apple/eawt/FullScreenAdapter.java +++ b/jdk/src/java.desktop/macosx/classes/com/apple/eawt/FullScreenAdapter.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2011, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -25,7 +25,7 @@ package com.apple.eawt; -import com.apple.eawt.AppEvent.FullScreenEvent; +import com.apple.eawt.event.FullScreenEvent; /** * Abstract adapter class for receiving fullscreen events. This class is provided diff --git a/jdk/src/java.desktop/macosx/classes/com/apple/eawt/FullScreenHandler.java b/jdk/src/java.desktop/macosx/classes/com/apple/eawt/FullScreenHandler.java index 64e81b08a00..c1d36d8add2 100644 --- a/jdk/src/java.desktop/macosx/classes/com/apple/eawt/FullScreenHandler.java +++ b/jdk/src/java.desktop/macosx/classes/com/apple/eawt/FullScreenHandler.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2011, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -25,13 +25,13 @@ package com.apple.eawt; +import com.apple.eawt.event.FullScreenEvent; import java.awt.*; import java.util.*; import java.util.List; import javax.swing.RootPaneContainer; -import com.apple.eawt.AppEvent.FullScreenEvent; import sun.awt.SunToolkit; import java.lang.annotation.Native; diff --git a/jdk/src/java.desktop/macosx/classes/com/apple/eawt/FullScreenListener.java b/jdk/src/java.desktop/macosx/classes/com/apple/eawt/FullScreenListener.java index 4872ad7646a..737a67f6f83 100644 --- a/jdk/src/java.desktop/macosx/classes/com/apple/eawt/FullScreenListener.java +++ b/jdk/src/java.desktop/macosx/classes/com/apple/eawt/FullScreenListener.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2011, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -25,9 +25,9 @@ package com.apple.eawt; +import com.apple.eawt.event.FullScreenEvent; import java.util.EventListener; -import com.apple.eawt.AppEvent.FullScreenEvent; /** * diff --git a/jdk/src/java.desktop/macosx/classes/com/apple/eawt/QuitResponse.java b/jdk/src/java.desktop/macosx/classes/com/apple/eawt/MacQuitResponse.java similarity index 86% rename from jdk/src/java.desktop/macosx/classes/com/apple/eawt/QuitResponse.java rename to jdk/src/java.desktop/macosx/classes/com/apple/eawt/MacQuitResponse.java index 18b4db5140f..ab37dfc93d9 100644 --- a/jdk/src/java.desktop/macosx/classes/com/apple/eawt/QuitResponse.java +++ b/jdk/src/java.desktop/macosx/classes/com/apple/eawt/MacQuitResponse.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2011, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -25,9 +25,11 @@ package com.apple.eawt; +import java.awt.desktop.QuitResponse; + /** * Used to respond to a request to quit the application. - * The QuitResponse may be used after the {@link QuitHandler#handleQuitRequestWith(AppEvent.QuitEvent, QuitResponse)} method has returned, and may be used from any thread. + * The QuitResponse may be used after the {@link QuitHandler#handleQuitRequestWith(AppEvent.QuitEvent, MacQuitResponse)} method has returned, and may be used from any thread. * * @see Application#setQuitHandler(QuitHandler) * @see QuitHandler @@ -36,16 +38,17 @@ package com.apple.eawt; * @since Java for Mac OS X 10.6 Update 3 * @since Java for Mac OS X 10.5 Update 8 */ -public class QuitResponse { +public class MacQuitResponse implements QuitResponse { final _AppEventHandler appEventHandler; - QuitResponse(final _AppEventHandler appEventHandler) { + MacQuitResponse(final _AppEventHandler appEventHandler) { this.appEventHandler = appEventHandler; } /** * Notifies the external quit requester that the quit will proceed, and performs the default {@link QuitStrategy}. */ + @Override public void performQuit() { if (appEventHandler.currentQuitResponse != this) return; appEventHandler.performQuit(); @@ -55,6 +58,7 @@ public class QuitResponse { * Notifies the external quit requester that the user has explicitly canceled the pending quit, and leaves the application running. * Note: this will cancel a pending log-out, restart, or shutdown. */ + @Override public void cancelQuit() { if (appEventHandler.currentQuitResponse != this) return; appEventHandler.cancelQuit(); diff --git a/jdk/src/java.desktop/macosx/classes/com/apple/eawt/OpenURIHandler.java b/jdk/src/java.desktop/macosx/classes/com/apple/eawt/OpenURIHandler.java deleted file mode 100644 index 1964344f94a..00000000000 --- a/jdk/src/java.desktop/macosx/classes/com/apple/eawt/OpenURIHandler.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright (c) 2011, 2012, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package com.apple.eawt; - -import com.apple.eawt.AppEvent.OpenURIEvent; - -/** - * An implementor is notified when the application is asked to open a URI. - * The application only sends {@link com.apple.eawt.EAWTEvent.OpenURIEvent}s when it has been launched as a bundled Mac application, and it's Info.plist claims URL schemes in it's {@code CFBundleURLTypes} entry. - * See the Info.plist Key Reference for more information about adding a {@code CFBundleURLTypes} key to your app's Info.plist. - * - * @see Application#setOpenURIHandler(OpenURIHandler) - * - * @since Java for Mac OS X 10.6 Update 3 - * @since Java for Mac OS X 10.5 Update 8 - */ -public interface OpenURIHandler { - /** - * Called when the application is asked to open a URI - * @param e the request to open a URI - */ - public void openURI(final OpenURIEvent e); -} diff --git a/jdk/src/java.desktop/macosx/classes/com/apple/eawt/_AppDockIconHandler.java b/jdk/src/java.desktop/macosx/classes/com/apple/eawt/_AppDockIconHandler.java index 4f09f53e930..eab1efb3447 100644 --- a/jdk/src/java.desktop/macosx/classes/com/apple/eawt/_AppDockIconHandler.java +++ b/jdk/src/java.desktop/macosx/classes/com/apple/eawt/_AppDockIconHandler.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2011, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -35,6 +35,7 @@ import sun.lwawt.macosx.CImage.Creator; class _AppDockIconHandler { private static native void nativeSetDockMenu(final long cmenu); private static native void nativeSetDockIconImage(final long image); + private static native void nativeSetDockIconProgress(final int value); private static native long nativeGetDockIconImage(); private static native void nativeSetDockIconBadge(final String badge); @@ -93,6 +94,10 @@ class _AppDockIconHandler { nativeSetDockIconBadge(badge); } + void setDockIconProgress(int value) { + nativeSetDockIconProgress(value); + } + static Creator getCImageCreator() { try { final Method getCreatorMethod = CImage.class.getDeclaredMethod("getCreator", new Class[] {}); diff --git a/jdk/src/java.desktop/macosx/classes/com/apple/eawt/_AppEventHandler.java b/jdk/src/java.desktop/macosx/classes/com/apple/eawt/_AppEventHandler.java index d40b57a31f6..a417f692ab8 100644 --- a/jdk/src/java.desktop/macosx/classes/com/apple/eawt/_AppEventHandler.java +++ b/jdk/src/java.desktop/macosx/classes/com/apple/eawt/_AppEventHandler.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2011, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -25,17 +25,47 @@ package com.apple.eawt; -import java.awt.*; +import java.awt.EventQueue; +import java.awt.Frame; +import java.awt.desktop.AboutEvent; +import java.awt.desktop.AboutHandler; +import java.awt.desktop.AppForegroundEvent; +import java.awt.desktop.AppForegroundListener; +import java.awt.desktop.AppHiddenEvent; +import java.awt.desktop.AppHiddenListener; +import java.awt.desktop.AppReopenedEvent; +import java.awt.desktop.AppReopenedListener; +import java.awt.desktop.OpenFilesEvent; +import java.awt.desktop.OpenFilesHandler; +import java.awt.desktop.OpenURIEvent; +import java.awt.desktop.OpenURIHandler; +import java.awt.desktop.PreferencesEvent; +import java.awt.desktop.PreferencesHandler; +import java.awt.desktop.PrintFilesEvent; +import java.awt.desktop.PrintFilesHandler; +import java.awt.desktop.QuitEvent; +import java.awt.desktop.QuitHandler; +import java.awt.desktop.QuitStrategy; +import java.awt.desktop.ScreenSleepEvent; +import java.awt.desktop.ScreenSleepListener; +import java.awt.desktop.SystemEventListener; +import java.awt.desktop.SystemSleepEvent; +import java.awt.desktop.SystemSleepListener; +import java.awt.desktop.UserSessionEvent; +import java.awt.desktop.UserSessionEvent.Reason; +import java.awt.desktop.UserSessionListener; import java.awt.event.WindowEvent; import java.io.File; -import java.net.*; -import java.util.*; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.ArrayList; +import java.util.IdentityHashMap; +import java.util.LinkedList; import java.util.List; +import java.util.Map; import sun.awt.AppContext; import sun.awt.SunToolkit; -import com.apple.eawt.AppEvent.*; - class _AppEventHandler { private static final int NOTIFY_ABOUT = 1; private static final int NOTIFY_PREFS = 2; @@ -84,9 +114,7 @@ class _AppEventHandler { final _ScreenSleepDispatcher screenSleepDispatcher = new _ScreenSleepDispatcher(); final _SystemSleepDispatcher systemSleepDispatcher = new _SystemSleepDispatcher(); - final _AppEventLegacyHandler legacyHandler = new _AppEventLegacyHandler(this); - - QuitStrategy defaultQuitAction = QuitStrategy.SYSTEM_EXIT_0; + QuitStrategy defaultQuitAction = QuitStrategy.NORMAL_EXIT; _AppEventHandler() { final String strategyProp = System.getProperty("apple.eawt.quitStrategy"); @@ -94,15 +122,16 @@ class _AppEventHandler { if ("CLOSE_ALL_WINDOWS".equals(strategyProp)) { setDefaultQuitStrategy(QuitStrategy.CLOSE_ALL_WINDOWS); - } else if ("SYSTEM_EXIT_O".equals(strategyProp)) { - setDefaultQuitStrategy(QuitStrategy.SYSTEM_EXIT_0); + } else if ("SYSTEM_EXIT_O".equals(strategyProp) + || "NORMAL_EXIT".equals(strategyProp)) { + setDefaultQuitStrategy(QuitStrategy.NORMAL_EXIT); } else { System.err.println("unrecognized apple.eawt.quitStrategy: " + strategyProp); } } - void addListener(final AppEventListener listener) { - if (listener instanceof AppReOpenedListener) reOpenAppDispatcher.addListener((AppReOpenedListener)listener); + void addListener(final SystemEventListener listener) { + if (listener instanceof AppReopenedListener) reOpenAppDispatcher.addListener((AppReopenedListener)listener); if (listener instanceof AppForegroundListener) foregroundAppDispatcher.addListener((AppForegroundListener)listener); if (listener instanceof AppHiddenListener) hiddenAppDispatcher.addListener((AppHiddenListener)listener); if (listener instanceof UserSessionListener) userSessionDispatcher.addListener((UserSessionListener)listener); @@ -110,8 +139,8 @@ class _AppEventHandler { if (listener instanceof SystemSleepListener) systemSleepDispatcher.addListener((SystemSleepListener)listener); } - void removeListener(final AppEventListener listener) { - if (listener instanceof AppReOpenedListener) reOpenAppDispatcher.removeListener((AppReOpenedListener)listener); + void removeListener(final SystemEventListener listener) { + if (listener instanceof AppReopenedListener) reOpenAppDispatcher.removeListener((AppReopenedListener)listener); if (listener instanceof AppForegroundListener) foregroundAppDispatcher.removeListener((AppForegroundListener)listener); if (listener instanceof AppHiddenListener) hiddenAppDispatcher.removeListener((AppHiddenListener)listener); if (listener instanceof UserSessionListener) userSessionDispatcher.removeListener((UserSessionListener)listener); @@ -127,10 +156,10 @@ class _AppEventHandler { this.defaultQuitAction = defaultQuitAction; } - QuitResponse currentQuitResponse; - synchronized QuitResponse obtainQuitResponse() { + MacQuitResponse currentQuitResponse; + synchronized MacQuitResponse obtainQuitResponse() { if (currentQuitResponse != null) return currentQuitResponse; - return currentQuitResponse = new QuitResponse(this); + return currentQuitResponse = new MacQuitResponse(this); } synchronized void cancelQuit() { @@ -142,7 +171,7 @@ class _AppEventHandler { currentQuitResponse = null; try { - if (defaultQuitAction == QuitStrategy.SYSTEM_EXIT_0) System.exit(0); + if (defaultQuitAction == QuitStrategy.NORMAL_EXIT) System.exit(0); if (defaultQuitAction != QuitStrategy.CLOSE_ALL_WINDOWS) { throw new RuntimeException("Unknown quit action"); @@ -270,10 +299,10 @@ class _AppEventHandler { } } - class _AppReOpenedDispatcher extends _AppEventMultiplexor { - void performOnListener(AppReOpenedListener listener, final _NativeEvent event) { - final AppReOpenedEvent e = new AppReOpenedEvent(); - listener.appReOpened(e); + class _AppReOpenedDispatcher extends _AppEventMultiplexor { + void performOnListener(AppReopenedListener listener, final _NativeEvent event) { + final AppReopenedEvent e = new AppReopenedEvent(); + listener.appReopened(e); } } @@ -302,7 +331,9 @@ class _AppEventHandler { } class _UserSessionDispatcher extends _BooleanAppEventMultiplexor { - UserSessionEvent createEvent(final boolean isTrue) { return new UserSessionEvent(); } + UserSessionEvent createEvent(final boolean isTrue) { + return new UserSessionEvent(Reason.UNSPECIFIED); + } void performFalseEventOn(final UserSessionListener listener, final UserSessionEvent e) { listener.userSessionDeactivated(e); @@ -391,7 +422,7 @@ class _AppEventHandler { } void performUsing(final QuitHandler handler, final _NativeEvent event) { - final QuitResponse response = obtainQuitResponse(); // obtains the "current" quit response + final MacQuitResponse response = obtainQuitResponse(); // obtains the "current" quit response handler.handleQuitRequestWith(new QuitEvent(), response); } } @@ -524,9 +555,6 @@ class _AppEventHandler { setHandlerContext(AppContext.getAppContext()); - // if a new handler is installed, block addition of legacy ApplicationListeners - if (handler == legacyHandler) return; - legacyHandler.blockLegacyAPI(); } void performDefaultAction(final _NativeEvent event) { } // by default, do nothing @@ -574,10 +602,6 @@ class _AppEventHandler { } } } - - // if a new handler is installed, block addition of legacy ApplicationListeners - if (handler == legacyHandler) return; - legacyHandler.blockLegacyAPI(); } } } diff --git a/jdk/src/java.desktop/macosx/classes/com/apple/eawt/_AppEventLegacyHandler.java b/jdk/src/java.desktop/macosx/classes/com/apple/eawt/_AppEventLegacyHandler.java deleted file mode 100644 index b0556e3440d..00000000000 --- a/jdk/src/java.desktop/macosx/classes/com/apple/eawt/_AppEventLegacyHandler.java +++ /dev/null @@ -1,188 +0,0 @@ -/* - * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package com.apple.eawt; - -import java.awt.Toolkit; -import java.io.File; -import java.util.*; - -import com.apple.eawt.AppEvent.*; - -@SuppressWarnings("deprecation") -class _AppEventLegacyHandler implements AboutHandler, PreferencesHandler, _OpenAppHandler, AppReOpenedListener, OpenFilesHandler, PrintFilesHandler, QuitHandler { - final _AppEventHandler parent; - final Vector legacyAppListeners = new Vector(); - boolean blockLegacyAPI; - boolean initializedParentDispatchers; - - _AppEventLegacyHandler(final _AppEventHandler parent) { - this.parent = parent; - } - - void blockLegacyAPI() { - blockLegacyAPI = true; - } - - void checkIfLegacyAPIBlocked() { - if (!blockLegacyAPI) return; - throw new IllegalStateException("Cannot add com.apple.eawt.ApplicationListener after installing an app event handler"); - } - - void addLegacyAppListener(final ApplicationListener listener) { - checkIfLegacyAPIBlocked(); - - if (!initializedParentDispatchers) { - final _AppMenuBarHandler menuBarHandler = Application.getApplication().menuBarHandler; - final boolean prefsMenuAlreadyExplicitlySet = menuBarHandler.prefsMenuItemExplicitlySet; - - parent.aboutDispatcher.setHandler(this); - parent.preferencesDispatcher.setHandler(this); - if (!prefsMenuAlreadyExplicitlySet) { - menuBarHandler.setPreferencesMenuItemVisible(false); // default behavior is not to have a preferences item - } - parent.openAppDispatcher.setHandler(this); - parent.reOpenAppDispatcher.addListener(this); - parent.openFilesDispatcher.setHandler(this); - parent.printFilesDispatcher.setHandler(this); - parent.quitDispatcher.setHandler(this); - - initializedParentDispatchers = true; - } - - synchronized (legacyAppListeners) { - legacyAppListeners.addElement(listener); - } - } - - public void removeLegacyAppListener(final ApplicationListener listener) { - checkIfLegacyAPIBlocked(); - - synchronized (legacyAppListeners) { - legacyAppListeners.removeElement(listener); - } - } - - @Override - public void handleAbout(final AboutEvent e) { - final ApplicationEvent ae = new ApplicationEvent(Toolkit.getDefaultToolkit()); - sendEventToEachListenerUntilHandled(ae, new EventDispatcher() { - public void dispatchEvent(final ApplicationListener listener) { - listener.handleAbout(ae); - } - }); - - if (ae.isHandled()) return; - parent.openCocoaAboutWindow(); - } - - @Override - public void handlePreferences(final PreferencesEvent e) { - final ApplicationEvent ae = new ApplicationEvent(Toolkit.getDefaultToolkit()); - sendEventToEachListenerUntilHandled(ae, new EventDispatcher() { - public void dispatchEvent(final ApplicationListener listener) { - listener.handlePreferences(ae); - } - }); - } - - @Override - public void handleOpenApp() { - final ApplicationEvent ae = new ApplicationEvent(Toolkit.getDefaultToolkit()); - sendEventToEachListenerUntilHandled(ae, new EventDispatcher() { - public void dispatchEvent(final ApplicationListener listener) { - listener.handleOpenApplication(ae); - } - }); - } - - @Override - public void appReOpened(final AppReOpenedEvent e) { - final ApplicationEvent ae = new ApplicationEvent(Toolkit.getDefaultToolkit()); - sendEventToEachListenerUntilHandled(ae, new EventDispatcher() { - public void dispatchEvent(final ApplicationListener listener) { - listener.handleReOpenApplication(ae); - } - }); - } - - @Override - public void openFiles(final OpenFilesEvent e) { - final List files = e.getFiles(); - for (final File file : files) { // legacy ApplicationListeners only understood one file at a time - final ApplicationEvent ae = new ApplicationEvent(Toolkit.getDefaultToolkit(), file.getAbsolutePath()); - sendEventToEachListenerUntilHandled(ae, new EventDispatcher() { - public void dispatchEvent(final ApplicationListener listener) { - listener.handleOpenFile(ae); - } - }); - } - } - - @Override - public void printFiles(PrintFilesEvent e) { - final List files = e.getFiles(); - for (final File file : files) { // legacy ApplicationListeners only understood one file at a time - final ApplicationEvent ae = new ApplicationEvent(Toolkit.getDefaultToolkit(), file.getAbsolutePath()); - sendEventToEachListenerUntilHandled(ae, new EventDispatcher() { - public void dispatchEvent(final ApplicationListener listener) { - listener.handlePrintFile(ae); - } - }); - } - } - - @Override - public void handleQuitRequestWith(final QuitEvent e, final QuitResponse response) { - final ApplicationEvent ae = new ApplicationEvent(Toolkit.getDefaultToolkit()); - sendEventToEachListenerUntilHandled(ae, new EventDispatcher() { - public void dispatchEvent(final ApplicationListener listener) { - listener.handleQuit(ae); - } - }); - - if (ae.isHandled()) { - parent.performQuit(); - } else { - parent.cancelQuit(); - } - } - - interface EventDispatcher { - void dispatchEvent(final ApplicationListener listener); - } - - // helper that cycles through the loop and aborts if the event is handled, or there are no listeners - void sendEventToEachListenerUntilHandled(final ApplicationEvent event, final EventDispatcher dispatcher) { - synchronized (legacyAppListeners) { - if (legacyAppListeners.size() == 0) return; - - final Enumeration e = legacyAppListeners.elements(); - while (e.hasMoreElements() && !event.isHandled()) { - dispatcher.dispatchEvent(e.nextElement()); - } - } - } -} diff --git a/jdk/src/java.desktop/macosx/classes/com/apple/eawt/_AppMenuBarHandler.java b/jdk/src/java.desktop/macosx/classes/com/apple/eawt/_AppMenuBarHandler.java index 3ac88f81379..3a132f25595 100644 --- a/jdk/src/java.desktop/macosx/classes/com/apple/eawt/_AppMenuBarHandler.java +++ b/jdk/src/java.desktop/macosx/classes/com/apple/eawt/_AppMenuBarHandler.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2011, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -26,7 +26,6 @@ package com.apple.eawt; import java.awt.Frame; -import java.awt.peer.MenuComponentPeer; import javax.swing.*; import javax.swing.plaf.MenuBarUI; diff --git a/jdk/src/java.desktop/macosx/classes/com/apple/eawt/event/FullScreenEvent.java b/jdk/src/java.desktop/macosx/classes/com/apple/eawt/event/FullScreenEvent.java new file mode 100644 index 00000000000..3ff90ac5e1d --- /dev/null +++ b/jdk/src/java.desktop/macosx/classes/com/apple/eawt/event/FullScreenEvent.java @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package com.apple.eawt.event; + +import com.apple.eawt.Application; +import java.awt.Window; +import java.util.EventObject; + +@SuppressWarnings("serial") // JDK implementation class +public class FullScreenEvent extends EventObject { + + final Window window; + + /** + * @param window window + */ + public FullScreenEvent(final Window window) { + super(Application.getApplication()); + this.window = window; + } + + /** + * @return window transitioning between full screen states + */ + public Window getWindow() { + return window; + } +} diff --git a/jdk/src/java.desktop/macosx/classes/sun/lwawt/LWToolkit.java b/jdk/src/java.desktop/macosx/classes/sun/lwawt/LWToolkit.java index 2870e7ba22b..b74719f149b 100644 --- a/jdk/src/java.desktop/macosx/classes/sun/lwawt/LWToolkit.java +++ b/jdk/src/java.desktop/macosx/classes/sun/lwawt/LWToolkit.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2011, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -370,6 +370,11 @@ public abstract class LWToolkit extends SunToolkit implements Runnable { return true; } + @Override + public final boolean isTaskbarSupported() { + return true; + } + @Override public final KeyboardFocusManagerPeer getKeyboardFocusManagerPeer() { return LWKeyboardFocusManagerPeer.getInstance(); diff --git a/jdk/src/java.desktop/macosx/classes/sun/lwawt/macosx/CDesktopPeer.java b/jdk/src/java.desktop/macosx/classes/sun/lwawt/macosx/CDesktopPeer.java index 1bc37a7aa46..f06865ef9aa 100644 --- a/jdk/src/java.desktop/macosx/classes/sun/lwawt/macosx/CDesktopPeer.java +++ b/jdk/src/java.desktop/macosx/classes/sun/lwawt/macosx/CDesktopPeer.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2011, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -25,9 +25,14 @@ package sun.lwawt.macosx; +import com.apple.eawt.Application; + +import javax.swing.*; import java.awt.Desktop.Action; +import java.awt.desktop.*; import java.awt.peer.DesktopPeer; import java.io.File; +import java.io.FileNotFoundException; import java.io.IOException; import java.net.URI; @@ -37,34 +42,126 @@ import java.net.URI; * * @see DesktopPeer */ -public class CDesktopPeer implements DesktopPeer { +final public class CDesktopPeer implements DesktopPeer { + @Override public boolean isSupported(Action action) { - // OPEN, EDIT, PRINT, MAIL, BROWSE all supported. - // Though we don't really differentiate between OPEN / EDIT return true; } + @Override public void open(File file) throws IOException { this.lsOpenFile(file, false); } + @Override public void edit(File file) throws IOException { this.lsOpenFile(file, false); } + @Override public void print(File file) throws IOException { this.lsOpenFile(file, true); } + @Override public void mail(URI uri) throws IOException { this.lsOpen(uri); } + @Override public void browse(URI uri) throws IOException { this.lsOpen(uri); } + @Override + public void addAppEventListener(SystemEventListener listener) { + Application.getApplication().addAppEventListener(listener); + } + + @Override + public void removeAppEventListener(SystemEventListener listener) { + Application.getApplication().removeAppEventListener(listener); + } + + @Override + public void setAboutHandler(AboutHandler aboutHandler) { + Application.getApplication().setAboutHandler(aboutHandler); + } + + @Override + public void setPreferencesHandler(PreferencesHandler preferencesHandler) { + Application.getApplication().setPreferencesHandler(preferencesHandler); + } + + @Override + public void setOpenFileHandler(OpenFilesHandler openFileHandler) { + Application.getApplication().setOpenFileHandler(openFileHandler); + } + + @Override + public void setPrintFileHandler(PrintFilesHandler printFileHandler) { + Application.getApplication().setPrintFileHandler(printFileHandler); + } + + @Override + public void setOpenURIHandler(OpenURIHandler openURIHandler) { + Application.getApplication().setOpenURIHandler(openURIHandler); + } + + @Override + public void setQuitHandler(QuitHandler quitHandler) { + Application.getApplication().setQuitHandler(quitHandler); + } + + @Override + public void setQuitStrategy(QuitStrategy strategy) { + Application.getApplication().setQuitStrategy(strategy); + } + + @Override + public void enableSuddenTermination() { + Application.getApplication().enableSuddenTermination(); + } + + @Override + public void disableSuddenTermination() { + Application.getApplication().disableSuddenTermination(); + } + + @Override + public void requestForeground(boolean allWindows) { + Application.getApplication().requestForeground(allWindows); + } + + @Override + public void openHelpViewer() { + Application.getApplication().openHelpViewer(); + } + + @Override + public void setDefaultMenuBar(JMenuBar menuBar) { + Application.getApplication().setDefaultMenuBar(menuBar); + } + + @Override + public boolean browseFileDirectory(File file) { + try { + return com.apple.eio.FileManager.revealInFinder(file); + } catch (FileNotFoundException ex) { + return false; //handled in java.awt.Desktop + } + } + + @Override + public boolean moveToTrash(File file) { + try { + return com.apple.eio.FileManager.moveToTrash(file); + } catch (FileNotFoundException ex) { + return false; //handled in java.awt.Desktop + } + } + private void lsOpen(URI uri) throws IOException { int status = _lsOpenURI(uri.toString()); diff --git a/jdk/src/java.desktop/macosx/classes/sun/lwawt/macosx/CTaskbarPeer.java b/jdk/src/java.desktop/macosx/classes/sun/lwawt/macosx/CTaskbarPeer.java new file mode 100644 index 00000000000..df6073e841a --- /dev/null +++ b/jdk/src/java.desktop/macosx/classes/sun/lwawt/macosx/CTaskbarPeer.java @@ -0,0 +1,89 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package sun.lwawt.macosx; + +import com.apple.eawt.Application; +import java.awt.Image; +import java.awt.PopupMenu; +import java.awt.Taskbar.Feature; +import java.awt.peer.TaskbarPeer; + +final public class CTaskbarPeer implements TaskbarPeer { + + CTaskbarPeer() {} + + @Override + public boolean isSupported(Feature feature) { + switch(feature) { + case ICON_BADGE_TEXT: + case ICON_BADGE_NUMBER: + case ICON_IMAGE: + case MENU: + case PROGRESS_VALUE: + case USER_ATTENTION: + return true; + default: + return false; + } + } + + @Override + public void setProgressValue(int value) { + Application.getApplication().setDockIconProgress(value); + } + + @Override + public void setIconBadge(String badge) { + Application.getApplication().setDockIconBadge(badge); + } + + @Override + public Image getIconImage() { + return Application.getApplication().getDockIconImage(); + } + + @Override + public void setIconImage(Image image) { + Application.getApplication().setDockIconImage(image); + } + + @Override + public PopupMenu getMenu() { + return Application.getApplication().getDockMenu(); + } + + @Override + public void setMenu(PopupMenu menu) { + Application.getApplication().setDockMenu(menu); + } + + @Override + public void requestUserAttention(boolean enabled, boolean critical) { + if (enabled) { + Application.getApplication().requestUserAttention(critical); + } + } +} diff --git a/jdk/src/java.desktop/macosx/classes/sun/lwawt/macosx/LWCToolkit.java b/jdk/src/java.desktop/macosx/classes/sun/lwawt/macosx/LWCToolkit.java index b4116a17f3a..f0bf99c7321 100644 --- a/jdk/src/java.desktop/macosx/classes/sun/lwawt/macosx/LWCToolkit.java +++ b/jdk/src/java.desktop/macosx/classes/sun/lwawt/macosx/LWCToolkit.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2011, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -25,6 +25,7 @@ package sun.lwawt.macosx; +import java.awt.peer.TaskbarPeer; import java.awt.*; import java.awt.datatransfer.Clipboard; import java.awt.dnd.*; @@ -293,6 +294,11 @@ public final class LWCToolkit extends LWToolkit { return new CDesktopPeer(); } + @Override + public TaskbarPeer createTaskbarPeer(Taskbar target) { + return new CTaskbarPeer(); + } + @Override public LWCursorManager getCursorManager() { return CCursorManager.getInstance(); diff --git a/jdk/src/java.desktop/macosx/native/libawt_lwawt/awt/ApplicationDelegate.h b/jdk/src/java.desktop/macosx/native/libawt_lwawt/awt/ApplicationDelegate.h index c0a8a7c3b7f..8d0723c555a 100644 --- a/jdk/src/java.desktop/macosx/native/libawt_lwawt/awt/ApplicationDelegate.h +++ b/jdk/src/java.desktop/macosx/native/libawt_lwawt/awt/ApplicationDelegate.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2011, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -40,6 +40,8 @@ NSMenu *fDockMenu; CMenuBar *fDefaultMenuBar; + NSProgressIndicator *fProgressIndicator; + BOOL fHandlesDocumentTypes; BOOL fHandlesURLTypes; } @@ -47,6 +49,8 @@ @property (nonatomic, retain) NSMenuItem *fPreferencesMenu; @property (nonatomic, retain) NSMenuItem *fAboutMenu; +@property (nonatomic, retain) NSProgressIndicator *fProgressIndicator; + @property (nonatomic, retain) NSMenu *fDockMenu; @property (nonatomic, retain) CMenuBar *fDefaultMenuBar; diff --git a/jdk/src/java.desktop/macosx/native/libawt_lwawt/awt/ApplicationDelegate.m b/jdk/src/java.desktop/macosx/native/libawt_lwawt/awt/ApplicationDelegate.m index da48e7351dc..6e9d6a423f2 100644 --- a/jdk/src/java.desktop/macosx/native/libawt_lwawt/awt/ApplicationDelegate.m +++ b/jdk/src/java.desktop/macosx/native/libawt_lwawt/awt/ApplicationDelegate.m @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2011, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -100,6 +100,7 @@ AWT_ASSERT_APPKIT_THREAD; @synthesize fPreferencesMenu; @synthesize fAboutMenu; +@synthesize fProgressIndicator; @synthesize fDockMenu; @synthesize fDefaultMenuBar; @@ -200,6 +201,18 @@ AWT_ASSERT_APPKIT_THREAD; self.fPreferencesMenu = (NSMenuItem*)[appMenu itemWithTag:PREFERENCES_TAG]; self.fAboutMenu = (NSMenuItem*)[appMenu itemAtIndex:0]; + + NSDockTile *dockTile = [NSApp dockTile]; + self.fProgressIndicator = [[NSProgressIndicator alloc] + initWithFrame:NSMakeRect(3.f, 0.f, dockTile.size.width - 6.f, 20.f)]; + + [fProgressIndicator setStyle:NSProgressIndicatorBarStyle]; + [fProgressIndicator setIndeterminate:NO]; + [[dockTile contentView] addSubview:fProgressIndicator]; + [fProgressIndicator setMinValue:0]; + [fProgressIndicator setMaxValue:100]; + [fProgressIndicator setHidden:YES]; + [fProgressIndicator release]; // If the java application has a bundle with an Info.plist file with // a CFBundleDocumentTypes entry, then it is set up to handle Open Doc @@ -252,6 +265,7 @@ AWT_ASSERT_APPKIT_THREAD; self.fAboutMenu = nil; self.fDockMenu = nil; self.fDefaultMenuBar = nil; + self.fProgressIndicator = nil; [super dealloc]; } @@ -468,6 +482,9 @@ AWT_ASSERT_APPKIT_THREAD; [dockImageView setImageScaling:NSImageScaleProportionallyUpOrDown]; [dockImageView setImage:image]; + [[ApplicationDelegate sharedDelegate].fProgressIndicator removeFromSuperview]; + [dockImageView addSubview:[ApplicationDelegate sharedDelegate].fProgressIndicator]; + // add it to the NSDockTile [dockTile setContentView: dockImageView]; [dockTile display]; @@ -475,6 +492,20 @@ AWT_ASSERT_APPKIT_THREAD; [dockImageView release]; } ++ (void)_setDockIconProgress:(NSNumber *)value { +AWT_ASSERT_APPKIT_THREAD; + + ApplicationDelegate *delegate = [ApplicationDelegate sharedDelegate]; + if ([value doubleValue] >= 0 && [value doubleValue] <=100) { + [delegate.fProgressIndicator setDoubleValue:[value doubleValue]]; + [delegate.fProgressIndicator setHidden:NO]; + } else { + [delegate.fProgressIndicator setHidden:YES]; + } + + [[NSApp dockTile] display]; +} + // Obtains the image of the Dock icon, either manually set, a drawn copy, or the default NSApplicationIcon + (NSImage *)_dockIconImage { AWT_ASSERT_APPKIT_THREAD; @@ -608,6 +639,24 @@ JNF_COCOA_ENTER(env); JNF_COCOA_EXIT(env); } +/* + * Class: com_apple_eawt__AppDockIconHandler + * Method: nativeSetDockIconProgress + * Signature: (I)V + */ +JNIEXPORT void JNICALL Java_com_apple_eawt__1AppDockIconHandler_nativeSetDockIconProgress + (JNIEnv *env, jclass clz, jint value) +{ + JNF_COCOA_ENTER(env); + + [ThreadUtilities performOnMainThread:@selector(_setDockIconProgress:) + on:[ApplicationDelegate class] + withObject:[NSNumber numberWithInt:value] + waitUntilDone:NO]; + + JNF_COCOA_EXIT(env); +} + /* * Class: com_apple_eawt__AppDockIconHandler * Method: nativeGetDockIconImage diff --git a/jdk/src/java.desktop/share/classes/java/awt/Desktop.java b/jdk/src/java.desktop/share/classes/java/awt/Desktop.java index 96f3d57e235..2cb38519ed5 100644 --- a/jdk/src/java.desktop/share/classes/java/awt/Desktop.java +++ b/jdk/src/java.desktop/share/classes/java/awt/Desktop.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -25,6 +25,14 @@ package java.awt; +import java.awt.desktop.AboutHandler; +import java.awt.desktop.OpenFilesHandler; +import java.awt.desktop.OpenURIHandler; +import java.awt.desktop.PreferencesHandler; +import java.awt.desktop.PrintFilesHandler; +import java.awt.desktop.QuitHandler; +import java.awt.desktop.QuitStrategy; +import java.awt.desktop.SystemEventListener; import java.awt.peer.DesktopPeer; import java.io.File; import java.io.FilePermission; @@ -35,12 +43,11 @@ import java.net.URISyntaxException; import java.net.URL; import sun.awt.SunToolkit; +import javax.swing.JMenuBar; import sun.security.util.SecurityConstants; /** - * The {@code Desktop} class allows a Java application to launch - * associated applications registered on the native desktop to handle - * a {@link java.net.URI} or a file. + * The {@code Desktop} class allows interact with various desktop capabilities. * *

    Supported operations include: *