1 /*
   2  * Copyright (c) 2006, 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   @test
  26   @bug 6378278
  27   @summary Apparent missing key events causing Bugster to break
  28   @author oleg.sukhodolsky: area=awt.focus
  29   @run main InputVerifierTest
  30 */
  31 
  32 /**
  33  * InputVerifierTest.java
  34  *
  35  * summary: Apparent missing key events causing Bugster to break
  36  */
  37 
  38 import java.awt.AWTException;
  39 import java.awt.BorderLayout;
  40 import java.awt.Component;
  41 import java.awt.Dialog;
  42 import java.awt.Frame;
  43 import java.awt.Point;
  44 import java.awt.Robot;
  45 import java.awt.TextArea;
  46 
  47 import java.awt.event.InputEvent;
  48 import java.awt.event.KeyEvent;
  49 
  50 import javax.swing.InputVerifier;
  51 import javax.swing.JComponent;
  52 import javax.swing.JFrame;
  53 import javax.swing.JTextField;
  54 
  55 public class InputVerifierTest
  56 {
  57 
  58     //*** test-writer defined static variables go here ***
  59     static volatile boolean ivWasCalled = false;
  60 
  61     private static void init()
  62     {
  63         //*** Create instructions for the user here ***
  64         String[] instructions =
  65         {
  66             "This is an AUTOMATIC test, simply wait until it is done.",
  67             "The result (passed or failed) will be shown in the",
  68             "message window below."
  69         };
  70         Sysout.createDialog( );
  71         Sysout.printInstructions( instructions );
  72 
  73         JFrame frame = new JFrame();
  74         JTextField t1 = new JTextField();
  75         t1.setInputVerifier(new InputVerifier() {
  76             public boolean verify(JComponent input) {
  77                 Sysout.println("verify(" + input + ")");
  78                 ivWasCalled = true;
  79                 return true;
  80             }
  81         });
  82         JTextField t2 = new JTextField();
  83 
  84         frame.getContentPane().add(t1, BorderLayout.NORTH);
  85         frame.getContentPane().add(t2, BorderLayout.SOUTH);
  86         frame.setSize(200, 200);
  87         frame.setVisible(true);
  88 
  89         Robot r = null;
  90         try {
  91             r = new Robot();
  92         } catch (AWTException e) {
  93             e.printStackTrace();
  94             InputVerifierTest.fail(e.toString());
  95         }
  96 
  97         try {
  98             r.waitForIdle();
  99 
 100             mouseClickOnComp(r, t1);
 101             r.waitForIdle();
 102 
 103             if (!t1.isFocusOwner()) {
 104                 throw new RuntimeException("t1 is not a focus owner");
 105             }
 106             ivWasCalled = false;
 107             r.keyPress(KeyEvent.VK_TAB);
 108             r.delay(10);
 109             r.keyRelease(KeyEvent.VK_TAB);
 110             r.waitForIdle();
 111 
 112             if (!t2.isFocusOwner()) {
 113                 throw new RuntimeException("t2 is not a focus owner");
 114             }
 115             if (!ivWasCalled) {
 116                 throw new RuntimeException("InputVerifier was not called after tabbing");
 117             }
 118 
 119             mouseClickOnComp(r, t1);
 120             r.waitForIdle();
 121 
 122             if (!t1.isFocusOwner()) {
 123                 throw new RuntimeException("t1 is not a focus owner");
 124             }
 125 
 126             ivWasCalled = false;
 127             mouseClickOnComp(r, t2);
 128             r.waitForIdle();
 129             if (!t2.isFocusOwner()) {
 130                 throw new RuntimeException("t2 is not a focus owner");
 131             }
 132             if (!ivWasCalled) {
 133                 throw new RuntimeException("InputVErifier was not called after mouse press");
 134             }
 135         } catch (Exception e) {
 136             e.printStackTrace();
 137             InputVerifierTest.fail(e.toString());
 138         }
 139 
 140         InputVerifierTest.pass();
 141 
 142     }//End  init()
 143 
 144     static void mouseClickOnComp(Robot r, Component comp) {
 145         Point loc = comp.getLocationOnScreen();
 146         loc.x += comp.getWidth() / 2;
 147         loc.y += comp.getHeight() / 2;
 148         r.mouseMove(loc.x, loc.y);
 149         r.delay(10);
 150         r.mousePress(InputEvent.BUTTON1_MASK);
 151         r.delay(10);
 152         r.mouseRelease(InputEvent.BUTTON1_MASK);
 153     }
 154 
 155     /*****************************************************
 156      * Standard Test Machinery Section
 157      * DO NOT modify anything in this section -- it's a
 158      * standard chunk of code which has all of the
 159      * synchronisation necessary for the test harness.
 160      * By keeping it the same in all tests, it is easier
 161      * to read and understand someone else's test, as
 162      * well as insuring that all tests behave correctly
 163      * with the test harness.
 164      * There is a section following this for test-
 165      * classes
 166      ******************************************************/
 167     private static boolean theTestPassed = false;
 168     private static boolean testGeneratedInterrupt = false;
 169     private static String failureMessage = "";
 170 
 171     private static Thread mainThread = null;
 172 
 173     private static int sleepTime = 300000;
 174 
 175     // Not sure about what happens if multiple of this test are
 176     //  instantiated in the same VM.  Being static (and using
 177     //  static vars), it aint gonna work.  Not worrying about
 178     //  it for now.
 179     public static void main( String args[] ) throws InterruptedException
 180     {
 181         mainThread = Thread.currentThread();
 182         try
 183         {
 184             init();
 185         }
 186         catch( TestPassedException e )
 187         {
 188             //The test passed, so just return from main and harness will
 189             // interepret this return as a pass
 190             return;
 191         }
 192         //At this point, neither test pass nor test fail has been
 193         // called -- either would have thrown an exception and ended the
 194         // test, so we know we have multiple threads.
 195 
 196         //Test involves other threads, so sleep and wait for them to
 197         // called pass() or fail()
 198         try
 199         {
 200             Thread.sleep( sleepTime );
 201             //Timed out, so fail the test
 202             throw new RuntimeException( "Timed out after " + sleepTime/1000 + " seconds" );
 203         }
 204         catch (InterruptedException e)
 205         {
 206             //The test harness may have interrupted the test.  If so, rethrow the exception
 207             // so that the harness gets it and deals with it.
 208             if( ! testGeneratedInterrupt ) throw e;
 209 
 210             //reset flag in case hit this code more than once for some reason (just safety)
 211             testGeneratedInterrupt = false;
 212 
 213             if ( theTestPassed == false )
 214             {
 215                 throw new RuntimeException( failureMessage );
 216             }
 217         }
 218 
 219     }//main
 220 
 221     public static synchronized void setTimeoutTo( int seconds )
 222     {
 223         sleepTime = seconds * 1000;
 224     }
 225 
 226     public static synchronized void pass()
 227     {
 228         Sysout.println( "The test passed." );
 229         Sysout.println( "The test is over, hit  Ctl-C to stop Java VM" );
 230         //first check if this is executing in main thread
 231         if ( mainThread == Thread.currentThread() )
 232         {
 233             //Still in the main thread, so set the flag just for kicks,
 234             // and throw a test passed exception which will be caught
 235             // and end the test.
 236             theTestPassed = true;
 237             throw new TestPassedException();
 238         }
 239         theTestPassed = true;
 240         testGeneratedInterrupt = true;
 241         mainThread.interrupt();
 242     }//pass()
 243 
 244     public static synchronized void fail()
 245     {
 246         //test writer didn't specify why test failed, so give generic
 247         fail( "it just plain failed! :-)" );
 248     }
 249 
 250     public static synchronized void fail( String whyFailed )
 251     {
 252         Sysout.println( "The test failed: " + whyFailed );
 253         Sysout.println( "The test is over, hit  Ctl-C to stop Java VM" );
 254         //check if this called from main thread
 255         if ( mainThread == Thread.currentThread() )
 256         {
 257             //If main thread, fail now 'cause not sleeping
 258             throw new RuntimeException( whyFailed );
 259         }
 260         theTestPassed = false;
 261         testGeneratedInterrupt = true;
 262         failureMessage = whyFailed;
 263         mainThread.interrupt();
 264     }//fail()
 265 
 266 }// class InputVerifierTest
 267 
 268 //This exception is used to exit from any level of call nesting
 269 // when it's determined that the test has passed, and immediately
 270 // end the test.
 271 class TestPassedException extends RuntimeException
 272 {
 273 }
 274 
 275 //*********** End Standard Test Machinery Section **********
 276 
 277 /****************************************************
 278  Standard Test Machinery
 279  DO NOT modify anything below -- it's a standard
 280   chunk of code whose purpose is to make user
 281   interaction uniform, and thereby make it simpler
 282   to read and understand someone else's test.
 283  ****************************************************/
 284 
 285 /**
 286  This is part of the standard test machinery.
 287  It creates a dialog (with the instructions), and is the interface
 288   for sending text messages to the user.
 289  To print the instructions, send an array of strings to Sysout.createDialog
 290   WithInstructions method.  Put one line of instructions per array entry.
 291  To display a message for the tester to see, simply call Sysout.println
 292   with the string to be displayed.
 293  This mimics System.out.println but works within the test harness as well
 294   as standalone.
 295  */
 296 
 297 class Sysout
 298 {
 299     private static TestDialog dialog;
 300 
 301     public static void createDialogWithInstructions( String[] instructions )
 302     {
 303         dialog = new TestDialog( new Frame(), "Instructions" );
 304         dialog.printInstructions( instructions );
 305         dialog.setVisible(true);
 306         println( "Any messages for the tester will display here." );
 307     }
 308 
 309     public static void createDialog( )
 310     {
 311         dialog = new TestDialog( new Frame(), "Instructions" );
 312         String[] defInstr = { "Instructions will appear here. ", "" } ;
 313         dialog.printInstructions( defInstr );
 314         dialog.setVisible(true);
 315         println( "Any messages for the tester will display here." );
 316     }
 317 
 318 
 319     public static void printInstructions( String[] instructions )
 320     {
 321         dialog.printInstructions( instructions );
 322     }
 323 
 324 
 325     public static void println( String messageIn )
 326     {
 327         dialog.displayMessage( messageIn );
 328         System.out.println(messageIn);
 329     }
 330 
 331 }// Sysout  class
 332 
 333 /**
 334   This is part of the standard test machinery.  It provides a place for the
 335    test instructions to be displayed, and a place for interactive messages
 336    to the user to be displayed.
 337   To have the test instructions displayed, see Sysout.
 338   To have a message to the user be displayed, see Sysout.
 339   Do not call anything in this dialog directly.
 340   */
 341 class TestDialog extends Dialog
 342 {
 343 
 344     TextArea instructionsText;
 345     TextArea messageText;
 346     int maxStringLength = 80;
 347 
 348     //DO NOT call this directly, go through Sysout
 349     public TestDialog( Frame frame, String name )
 350     {
 351         super( frame, name );
 352         int scrollBoth = TextArea.SCROLLBARS_BOTH;
 353         instructionsText = new TextArea( "", 15, maxStringLength, scrollBoth );
 354         add( "North", instructionsText );
 355 
 356         messageText = new TextArea( "", 5, maxStringLength, scrollBoth );
 357         add("Center", messageText);
 358 
 359         pack();
 360 
 361         setVisible(true);
 362     }// TestDialog()
 363 
 364     //DO NOT call this directly, go through Sysout
 365     public void printInstructions( String[] instructions )
 366     {
 367         //Clear out any current instructions
 368         instructionsText.setText( "" );
 369 
 370         //Go down array of instruction strings
 371 
 372         String printStr, remainingStr;
 373         for( int i=0; i < instructions.length; i++ )
 374         {
 375             //chop up each into pieces maxSringLength long
 376             remainingStr = instructions[ i ];
 377             while( remainingStr.length() > 0 )
 378             {
 379                 //if longer than max then chop off first max chars to print
 380                 if( remainingStr.length() >= maxStringLength )
 381                 {
 382                     //Try to chop on a word boundary
 383                     int posOfSpace = remainingStr.
 384                         lastIndexOf( ' ', maxStringLength - 1 );
 385 
 386                     if( posOfSpace <= 0 ) posOfSpace = maxStringLength - 1;
 387 
 388                     printStr = remainingStr.substring( 0, posOfSpace + 1 );
 389                     remainingStr = remainingStr.substring( posOfSpace + 1 );
 390                 }
 391                 //else just print
 392                 else
 393                 {
 394                     printStr = remainingStr;
 395                     remainingStr = "";
 396                 }
 397 
 398                 instructionsText.append( printStr + "\n" );
 399 
 400             }// while
 401 
 402         }// for
 403 
 404     }//printInstructions()
 405 
 406     //DO NOT call this directly, go through Sysout
 407     public void displayMessage( String messageIn )
 408     {
 409         messageText.append( messageIn + "\n" );
 410         System.out.println(messageIn);
 411     }
 412 
 413 }// TestDialog  class