1 /*
   2  * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  */
  23 
  24 
  25 import java.awt.*;
  26 import java.awt.event.InputEvent;
  27 import javax.swing.*;
  28 import java.io.*;
  29 import test.java.awt.regtesthelpers.Util;
  30 
  31 /**
  32  * AWT/Swing overlapping test for Panel and JPanel behavior during resizing.
  33  * <p>See <a href="https://bugs.openjdk.java.net/browse/JDK-6786219">JDK-6786219</a> for details
  34  */
  35 /*
  36 @test
  37 @bug 6786219
  38 @summary Issues when resizing the frame after mixing of heavy weight & light weight components
  39 @author sergey.grinev@oracle.com: area=awt.mixing
  40 @library ../../regtesthelpers
  41 @build Util
  42 @build FrameBorderCounter
  43 @run main MixingPanelsResizing
  44  */
  45 public class MixingPanelsResizing {
  46 
  47     static volatile boolean failed = false;
  48 
  49     private static JFrame frame;
  50     private static JButton jbutton;
  51     private static Button awtButton;
  52     private static JButton jbutton2;
  53     private static Button awtButton2;
  54     private static final Color jbColor = Color.RED;
  55     private static final Color awtColor = Color.ORANGE;
  56     private static final Color jb2Color = Color.BLUE;
  57     private static final Color awt2Color = Color.CYAN;
  58     private static final int ROBOT_DELAY = 500;
  59 
  60     private static Point lLoc;
  61     private static int borderShift;
  62 
  63     private static int frameBorderCounter() {
  64         String JAVA_HOME = System.getProperty("java.home");
  65         try {
  66             Process p = Runtime.getRuntime().exec(JAVA_HOME + "/bin/java FrameBorderCounter");
  67             try {
  68                 p.waitFor();
  69             } catch (InterruptedException e) {
  70                 e.printStackTrace();
  71                 throw new RuntimeException(e);
  72             }
  73             if (p.exitValue() != 0) {
  74                 throw new RuntimeException("FrameBorderCounter exited with not null code!\n" + readInputStream(p.getErrorStream()));
  75             }
  76             return Integer.parseInt(readInputStream(p.getInputStream()).trim());
  77         } catch (IOException e) {
  78             e.printStackTrace();
  79             throw new RuntimeException(e);
  80         }
  81     }
  82 
  83     private static String readInputStream(InputStream is) throws IOException {
  84         byte[] buffer = new byte[4096];
  85         int len = 0;
  86         StringBuilder sb = new StringBuilder();
  87         try (InputStreamReader isr = new InputStreamReader(is)) {
  88             while ((len = is.read(buffer)) > 0) {
  89                 sb.append(new String(buffer, 0, len));
  90             }
  91         }
  92         return sb.toString();
  93     }
  94 
  95     private static void init() throws Exception {
  96         //*** Create instructions for the user here ***
  97 
  98         borderShift = frameBorderCounter();
  99         borderShift = Math.abs(borderShift) == 1 ? borderShift : (borderShift / 2);
 100         String[] instructions = {
 101             "This is an AUTOMATIC test, simply wait until it is done.",
 102             "The result (passed or failed) will be shown in the",
 103             "message window below."
 104         };
 105         SwingUtilities.invokeAndWait(new Runnable() {
 106             public void run() {
 107                 Sysout.createDialog();
 108                 Sysout.printInstructions(instructions);
 109 
 110                 // prepare controls
 111 
 112                 frame = new JFrame();
 113 
 114                 Panel awtPanel = new Panel();
 115                 awtPanel.setBackground(Color.GREEN);
 116                 awtButton = new Button("AWTButton");
 117                 awtPanel.add(awtButton);
 118                 awtButton.setForeground(awtColor);
 119                 awtButton.setBackground(awtColor);
 120                 jbutton = new JButton("SwingButton");
 121                 awtPanel.add(jbutton);
 122                 jbutton.setForeground(jbColor);
 123                 jbutton.setBackground(jbColor);
 124 
 125                 JPanel jPanel = new JPanel();
 126                 jbutton2 = new JButton("SwingButton2");
 127                 jPanel.add(jbutton2);
 128                 jbutton2.setForeground(jb2Color);
 129                 jbutton2.setBackground(jb2Color);
 130                 awtButton2 = new Button("AWT Button2");
 131                 jPanel.add(awtButton2);
 132                 awtButton2.setForeground(awt2Color);
 133                 awtButton2.setBackground(awt2Color);
 134                 jPanel.setBackground(Color.YELLOW);
 135 
 136                 frame.add(awtPanel, BorderLayout.SOUTH);
 137                 frame.add(jPanel, BorderLayout.NORTH);
 138 
 139                 frame.pack();
 140                 frame.setVisible(true);
 141             }
 142         });
 143 
 144         /////////////////////////
 145 
 146         final Robot robot = Util.createRobot();
 147         robot.setAutoDelay(ROBOT_DELAY);
 148 
 149         Util.waitForIdle(robot);
 150 
 151         SwingUtilities.invokeAndWait(new Runnable() {
 152             public void run() {
 153                 lLoc = frame.getLocationOnScreen();
 154                 lLoc.translate(frame.getWidth() + borderShift, frame.getHeight() + borderShift);
 155             }
 156         });
 157 
 158         //grow
 159         robot.mouseMove(lLoc.x, lLoc.y);
 160         robot.mousePress(InputEvent.BUTTON1_MASK);
 161 
 162         Runnable test = new Runnable() {
 163 
 164             public void run() {
 165                 Point btnLoc = jbutton.getLocationOnScreen();
 166                 Color c = robot.getPixelColor(btnLoc.x + 5, btnLoc.y + 5);
 167                 if (!c.equals(jbColor)) {
 168                     fail("JButton was not redrawn properly on AWT Panel during move");
 169                 }
 170 
 171                 btnLoc = awtButton.getLocationOnScreen();
 172                 c = robot.getPixelColor(btnLoc.x + 5, btnLoc.y + 5);
 173                 if (!c.equals(awtColor)) {
 174                     fail("AWT Button was not redrawn properly on AWT Panel during move");
 175                 }
 176 
 177                 btnLoc = jbutton2.getLocationOnScreen();
 178                 c = robot.getPixelColor(btnLoc.x + 5, btnLoc.y + 5);
 179                 if (!c.equals(jb2Color)) {
 180                     fail("JButton was not redrawn properly on JPanel during move");
 181                 }
 182 
 183                 btnLoc = awtButton2.getLocationOnScreen();
 184                 c = robot.getPixelColor(btnLoc.x + 5, btnLoc.y + 5);
 185                 if (!c.equals(awt2Color)) {
 186                     fail("ATW Button was not redrawn properly on JPanel during move");
 187                 }
 188             }
 189         };
 190 
 191         for (int i = 0; i < 30; i++) {
 192             test.run();
 193             robot.mouseMove(lLoc.x + 20 * i, lLoc.y + 10 * i);
 194         }
 195         robot.mouseRelease(InputEvent.BUTTON1_MASK);
 196 
 197         //back
 198         System.out.println("fast back");
 199         robot.mousePress(InputEvent.BUTTON1_MASK);
 200         for (int i = 5; i >= 0; i--) {
 201             test.run();
 202             robot.mouseMove(lLoc.x + 120 * i, lLoc.y + 60 * i);
 203         }
 204         robot.mouseRelease(InputEvent.BUTTON1_MASK);
 205 
 206         pass();
 207     }//End  init()
 208     /*****************************************************
 209      * Standard Test Machinery Section
 210      * DO NOT modify anything in this section -- it's a
 211      * standard chunk of code which has all of the
 212      * synchronisation necessary for the test harness.
 213      * By keeping it the same in all tests, it is easier
 214      * to read and understand someone else's test, as
 215      * well as insuring that all tests behave correctly
 216      * with the test harness.
 217      * There is a section following this for test-
 218      * classes
 219      ******************************************************/
 220     private static boolean theTestPassed = false;
 221     private static boolean testGeneratedInterrupt = false;
 222     private static String failureMessage = "";
 223     private static Thread mainThread = null;
 224     private static int sleepTime = 300000;
 225 
 226     // Not sure about what happens if multiple of this test are
 227     //  instantiated in the same VM.  Being static (and using
 228     //  static vars), it aint gonna work.  Not worrying about
 229     //  it for now.
 230     public static void main(String args[]) throws Exception {
 231         if (!Toolkit.getDefaultToolkit().isDynamicLayoutActive()) {
 232             System.out.println("Dynamic layout is not active. Test passes.");
 233             return;
 234         }
 235         mainThread = Thread.currentThread();
 236         try {
 237             init();
 238         } catch (TestPassedException e) {
 239             //The test passed, so just return from main and harness will
 240             // interepret this return as a pass
 241             return;
 242         }
 243         //At this point, neither test pass nor test fail has been
 244         // called -- either would have thrown an exception and ended the
 245         // test, so we know we have multiple threads.
 246 
 247         //Test involves other threads, so sleep and wait for them to
 248         // called pass() or fail()
 249         try {
 250             Thread.sleep(sleepTime);
 251             //Timed out, so fail the test
 252             throw new RuntimeException("Timed out after " + sleepTime / 1000 + " seconds");
 253         } catch (InterruptedException e) {
 254             //The test harness may have interrupted the test.  If so, rethrow the exception
 255             // so that the harness gets it and deals with it.
 256             if (!testGeneratedInterrupt) {
 257                 throw e;
 258             }
 259 
 260             //reset flag in case hit this code more than once for some reason (just safety)
 261             testGeneratedInterrupt = false;
 262 
 263             if (theTestPassed == false) {
 264                 throw new RuntimeException(failureMessage);
 265             }
 266         }
 267 
 268     }//main
 269 
 270     public static synchronized void setTimeoutTo(int seconds) {
 271         sleepTime = seconds * 1000;
 272     }
 273 
 274     public static synchronized void pass() {
 275         Sysout.println("The test passed.");
 276         Sysout.println("The test is over, hit  Ctl-C to stop Java VM");
 277         //first check if this is executing in main thread
 278         if (mainThread == Thread.currentThread()) {
 279             //Still in the main thread, so set the flag just for kicks,
 280             // and throw a test passed exception which will be caught
 281             // and end the test.
 282             theTestPassed = true;
 283             throw new TestPassedException();
 284         }
 285         theTestPassed = true;
 286         testGeneratedInterrupt = true;
 287         mainThread.interrupt();
 288     }//pass()
 289 
 290     public static synchronized void fail() {
 291         //test writer didn't specify why test failed, so give generic
 292         fail("it just plain failed! :-)");
 293     }
 294 
 295     public static synchronized void fail(String whyFailed) {
 296         Sysout.println("The test failed: " + whyFailed);
 297         Sysout.println("The test is over, hit  Ctl-C to stop Java VM");
 298         //check if this called from main thread
 299         if (mainThread == Thread.currentThread()) {
 300             //If main thread, fail now 'cause not sleeping
 301             throw new RuntimeException(whyFailed);
 302         }
 303         theTestPassed = false;
 304         testGeneratedInterrupt = true;
 305         failureMessage = whyFailed;
 306         mainThread.interrupt();
 307     }//fail()
 308 }// class JButtonInGlassPane
 309 class TestPassedException extends RuntimeException {
 310 }
 311 
 312 //*********** End Standard Test Machinery Section **********
 313 //************ Begin classes defined for the test ****************
 314 // if want to make listeners, here is the recommended place for them, then instantiate
 315 //  them in init()
 316 
 317 /* Example of a class which may be written as part of a test
 318 class NewClass implements anInterface
 319 {
 320 static int newVar = 0;
 321 
 322 public void eventDispatched(AWTEvent e)
 323 {
 324 //Counting events to see if we get enough
 325 eventCount++;
 326 
 327 if( eventCount == 20 )
 328 {
 329 //got enough events, so pass
 330 
 331 JButtonInGlassPane.pass();
 332 }
 333 else if( tries == 20 )
 334 {
 335 //tried too many times without getting enough events so fail
 336 
 337 JButtonInGlassPane.fail();
 338 }
 339 
 340 }// eventDispatched()
 341 
 342 }// NewClass class
 343 
 344  */
 345 //************** End classes defined for the test *******************
 346 /****************************************************
 347 Standard Test Machinery
 348 DO NOT modify anything below -- it's a standard
 349 chunk of code whose purpose is to make user
 350 interaction uniform, and thereby make it simpler
 351 to read and understand someone else's test.
 352  ****************************************************/
 353 /**
 354 This is part of the standard test machinery.
 355 It creates a dialog (with the instructions), and is the interface
 356 for sending text messages to the user.
 357 To print the instructions, send an array of strings to Sysout.createDialog
 358 WithInstructions method.  Put one line of instructions per array entry.
 359 To display a message for the tester to see, simply call Sysout.println
 360 with the string to be displayed.
 361 This mimics System.out.println but works within the test harness as well
 362 as standalone.
 363  */
 364 class Sysout {
 365 
 366     private static TestDialog dialog;
 367 
 368     public static void createDialogWithInstructions(String[] instructions) {
 369         dialog = new TestDialog(new Frame(), "Instructions");
 370         dialog.printInstructions(instructions);
 371         //dialog.setVisible(true);
 372         println("Any messages for the tester will display here.");
 373     }
 374 
 375     public static void createDialog() {
 376         dialog = new TestDialog(new Frame(), "Instructions");
 377         String[] defInstr = {"Instructions will appear here. ", ""};
 378         dialog.printInstructions(defInstr);
 379         //dialog.setVisible(true);
 380         println("Any messages for the tester will display here.");
 381     }
 382 
 383     public static void printInstructions(String[] instructions) {
 384         dialog.printInstructions(instructions);
 385     }
 386 
 387     public static void println(String messageIn) {
 388         dialog.displayMessage(messageIn);
 389         System.out.println(messageIn);
 390     }
 391 }// Sysout  class
 392 
 393 /**
 394 This is part of the standard test machinery.  It provides a place for the
 395 test instructions to be displayed, and a place for interactive messages
 396 to the user to be displayed.
 397 To have the test instructions displayed, see Sysout.
 398 To have a message to the user be displayed, see Sysout.
 399 Do not call anything in this dialog directly.
 400  */
 401 class TestDialog extends Dialog {
 402 
 403     TextArea instructionsText;
 404     TextArea messageText;
 405     int maxStringLength = 80;
 406 
 407     //DO NOT call this directly, go through Sysout
 408     public TestDialog(Frame frame, String name) {
 409         super(frame, name);
 410         int scrollBoth = TextArea.SCROLLBARS_BOTH;
 411         instructionsText = new TextArea("", 15, maxStringLength, scrollBoth);
 412         add("North", instructionsText);
 413 
 414         messageText = new TextArea("", 5, maxStringLength, scrollBoth);
 415         add("Center", messageText);
 416 
 417         pack();
 418 
 419         //setVisible(true);
 420     }// TestDialog()
 421 
 422     //DO NOT call this directly, go through Sysout
 423     public void printInstructions(String[] instructions) {
 424         //Clear out any current instructions
 425         instructionsText.setText("");
 426 
 427         //Go down array of instruction strings
 428 
 429         String printStr, remainingStr;
 430         for (int i = 0; i < instructions.length; i++) {
 431             //chop up each into pieces maxSringLength long
 432             remainingStr = instructions[i];
 433             while (remainingStr.length() > 0) {
 434                 //if longer than max then chop off first max chars to print
 435                 if (remainingStr.length() >= maxStringLength) {
 436                     //Try to chop on a word boundary
 437                     int posOfSpace = remainingStr.lastIndexOf(' ', maxStringLength - 1);
 438 
 439                     if (posOfSpace <= 0) {
 440                         posOfSpace = maxStringLength - 1;
 441                     }
 442 
 443                     printStr = remainingStr.substring(0, posOfSpace + 1);
 444                     remainingStr = remainingStr.substring(posOfSpace + 1);
 445                 } //else just print
 446                 else {
 447                     printStr = remainingStr;
 448                     remainingStr = "";
 449                 }
 450 
 451                 instructionsText.append(printStr + "\n");
 452 
 453             }// while
 454 
 455         }// for
 456 
 457     }//printInstructions()
 458 
 459     //DO NOT call this directly, go through Sysout
 460     public void displayMessage(String messageIn) {
 461         messageText.append(messageIn + "\n");
 462         System.out.println(messageIn);
 463     }
 464 }// TestDialog  class
 465