WindowOpacity.java revision 14851:980da45565c8
1/*
2 * Copyright (c) 2008, 2016, 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 %W% %E%
26  @key headful
27  @bug 6594131
28  @summary Tests the AWTUtilities.get/setWindowOpacity() methods
29  @author anthony.petrov@...: area=awt.toplevel
30  @modules java.desktop/com.sun.awt
31  @run main WindowOpacity
32*/
33
34import java.awt.*;
35import java.awt.event.*;
36
37import com.sun.awt.AWTUtilities;
38
39public class WindowOpacity
40{
41    //*** test-writer defined static variables go here ***
42
43   private static Robot robot;
44
45
46    private static void init()
47    {
48        //*** Create instructions for the user here ***
49        String[] instructions =
50        {
51            "This is an AUTOMATIC test, simply wait until it is done.",
52            "The result (passed or failed) will be shown in the",
53            "message window below."
54        };
55        Sysout.createDialog( );
56        Sysout.printInstructions( instructions );
57
58        if (!AWTUtilities.isTranslucencySupported(AWTUtilities.Translucency.TRANSLUCENT)) {
59            System.out.println("Either the Toolkit or the native system does not support controlling the window opacity level.");
60            pass();
61        }
62        try {
63            robot = new Robot();
64        }catch(Exception ex) {
65            ex.printStackTrace();
66            throw new RuntimeException ("Unexpected failure");
67        }
68
69        boolean passed;
70
71        Frame f = new Frame("Opacity test");
72        f.setUndecorated(true);
73
74        passed = false;
75        try {
76            AWTUtilities.getWindowOpacity(null);
77        } catch (NullPointerException e) {
78            passed = true;
79        }
80        if (!passed) {
81            fail("getWindowOpacity() allows passing null.");
82        }
83
84
85        passed = false;
86        try {
87            AWTUtilities.setWindowOpacity(null, 0.5f);
88        } catch (NullPointerException e) {
89            passed = true;
90        }
91        if (!passed) {
92            fail("setWindowOpacity() allows passing null.");
93        }
94
95
96        float curOpacity = AWTUtilities.getWindowOpacity(f);
97        if (curOpacity < 1.0f || curOpacity > 1.0f) {
98            fail("getWindowOpacity() reports the initial opacity level other than 1.0: " + curOpacity);
99        }
100
101
102
103        passed = false;
104        try {
105            AWTUtilities.setWindowOpacity(f, -0.5f);
106        } catch (IllegalArgumentException e) {
107            passed = true;
108        }
109        if (!passed) {
110            fail("setWindowOpacity() allows passing negative opacity level.");
111        }
112
113
114
115        passed = false;
116        try {
117            AWTUtilities.setWindowOpacity(f, 1.5f);
118        } catch (IllegalArgumentException e) {
119            passed = true;
120        }
121        if (!passed) {
122            fail("setWindowOpacity() allows passing opacity level greater than 1.0.");
123        }
124
125
126        AWTUtilities.setWindowOpacity(f, 0.5f);
127
128        curOpacity = AWTUtilities.getWindowOpacity(f);
129        if (curOpacity < 0.5f || curOpacity > 0.5f) {
130            fail("getWindowOpacity() reports the opacity level that differs from the value set with setWindowOpacity: " + curOpacity);
131        }
132
133
134        AWTUtilities.setWindowOpacity(f, 0.75f);
135
136        curOpacity = AWTUtilities.getWindowOpacity(f);
137        if (curOpacity < 0.75f || curOpacity > 0.75f) {
138            fail("getWindowOpacity() reports the opacity level that differs from the value set with setWindowOpacity the second time: " + curOpacity);
139        }
140
141
142        f.setBounds(100, 100, 300, 200);
143        f.setVisible(true);
144
145        robot.waitForIdle();
146
147        curOpacity = AWTUtilities.getWindowOpacity(f);
148        if (curOpacity < 0.75f || curOpacity > 0.75f) {
149            fail("getWindowOpacity() reports the opacity level that differs from the value set with setWindowOpacity before showing the frame: " + curOpacity);
150        }
151
152
153
154        AWTUtilities.setWindowOpacity(f, 0.5f);
155        robot.waitForIdle();
156
157        curOpacity = AWTUtilities.getWindowOpacity(f);
158        if (curOpacity < 0.5f || curOpacity > 0.5f) {
159            fail("getWindowOpacity() reports the opacity level that differs from the value set with setWindowOpacity after showing the frame: " + curOpacity);
160        }
161
162        WindowOpacity.pass();
163
164    }//End  init()
165
166
167
168    /*****************************************************
169     * Standard Test Machinery Section
170     * DO NOT modify anything in this section -- it's a
171     * standard chunk of code which has all of the
172     * synchronisation necessary for the test harness.
173     * By keeping it the same in all tests, it is easier
174     * to read and understand someone else's test, as
175     * well as insuring that all tests behave correctly
176     * with the test harness.
177     * There is a section following this for test-
178     * classes
179     ******************************************************/
180    private static boolean theTestPassed = false;
181    private static boolean testGeneratedInterrupt = false;
182    private static String failureMessage = "";
183
184    private static Thread mainThread = null;
185
186    private static int sleepTime = 300000;
187
188    // Not sure about what happens if multiple of this test are
189    //  instantiated in the same VM.  Being static (and using
190    //  static vars), it aint gonna work.  Not worrying about
191    //  it for now.
192    public static void main( String args[] ) throws InterruptedException
193    {
194        mainThread = Thread.currentThread();
195        try
196        {
197            init();
198        }
199        catch( TestPassedException e )
200        {
201            //The test passed, so just return from main and harness will
202            // interepret this return as a pass
203            return;
204        }
205        //At this point, neither test pass nor test fail has been
206        // called -- either would have thrown an exception and ended the
207        // test, so we know we have multiple threads.
208
209        //Test involves other threads, so sleep and wait for them to
210        // called pass() or fail()
211        try
212        {
213            Thread.sleep( sleepTime );
214            //Timed out, so fail the test
215            throw new RuntimeException( "Timed out after " + sleepTime/1000 + " seconds" );
216        }
217        catch (InterruptedException e)
218        {
219            //The test harness may have interrupted the test.  If so, rethrow the exception
220            // so that the harness gets it and deals with it.
221            if( ! testGeneratedInterrupt ) throw e;
222
223            //reset flag in case hit this code more than once for some reason (just safety)
224            testGeneratedInterrupt = false;
225
226            if ( theTestPassed == false )
227            {
228                throw new RuntimeException( failureMessage );
229            }
230        }
231
232    }//main
233
234    public static synchronized void setTimeoutTo( int seconds )
235    {
236        sleepTime = seconds * 1000;
237    }
238
239    public static synchronized void pass()
240    {
241        Sysout.println( "The test passed." );
242        Sysout.println( "The test is over, hit  Ctl-C to stop Java VM" );
243        //first check if this is executing in main thread
244        if ( mainThread == Thread.currentThread() )
245        {
246            //Still in the main thread, so set the flag just for kicks,
247            // and throw a test passed exception which will be caught
248            // and end the test.
249            theTestPassed = true;
250            throw new TestPassedException();
251        }
252        theTestPassed = true;
253        testGeneratedInterrupt = true;
254        mainThread.interrupt();
255    }//pass()
256
257    public static synchronized void fail()
258    {
259        //test writer didn't specify why test failed, so give generic
260        fail( "it just plain failed! :-)" );
261    }
262
263    public static synchronized void fail( String whyFailed )
264    {
265        Sysout.println( "The test failed: " + whyFailed );
266        Sysout.println( "The test is over, hit  Ctl-C to stop Java VM" );
267        //check if this called from main thread
268        if ( mainThread == Thread.currentThread() )
269        {
270            //If main thread, fail now 'cause not sleeping
271            throw new RuntimeException( whyFailed );
272        }
273        theTestPassed = false;
274        testGeneratedInterrupt = true;
275        failureMessage = whyFailed;
276        mainThread.interrupt();
277    }//fail()
278
279}// class WindowOpacity
280
281//This exception is used to exit from any level of call nesting
282// when it's determined that the test has passed, and immediately
283// end the test.
284class TestPassedException extends RuntimeException
285{
286}
287
288//*********** End Standard Test Machinery Section **********
289
290
291//************ Begin classes defined for the test ****************
292
293// if want to make listeners, here is the recommended place for them, then instantiate
294//  them in init()
295
296/* Example of a class which may be written as part of a test
297class NewClass implements anInterface
298 {
299   static int newVar = 0;
300
301   public void eventDispatched(AWTEvent e)
302    {
303      //Counting events to see if we get enough
304      eventCount++;
305
306      if( eventCount == 20 )
307       {
308         //got enough events, so pass
309
310         WindowOpacity.pass();
311       }
312      else if( tries == 20 )
313       {
314         //tried too many times without getting enough events so fail
315
316         WindowOpacity.fail();
317       }
318
319    }// eventDispatched()
320
321 }// NewClass class
322
323*/
324
325
326//************** End classes defined for the test *******************
327
328
329
330
331/****************************************************
332 Standard Test Machinery
333 DO NOT modify anything below -- it's a standard
334  chunk of code whose purpose is to make user
335  interaction uniform, and thereby make it simpler
336  to read and understand someone else's test.
337 ****************************************************/
338
339/**
340 This is part of the standard test machinery.
341 It creates a dialog (with the instructions), and is the interface
342  for sending text messages to the user.
343 To print the instructions, send an array of strings to Sysout.createDialog
344  WithInstructions method.  Put one line of instructions per array entry.
345 To display a message for the tester to see, simply call Sysout.println
346  with the string to be displayed.
347 This mimics System.out.println but works within the test harness as well
348  as standalone.
349 */
350
351class Sysout
352{
353    private static TestDialog dialog;
354
355    public static void createDialogWithInstructions( String[] instructions )
356    {
357        dialog = new TestDialog( new Frame(), "Instructions" );
358        dialog.printInstructions( instructions );
359        dialog.setVisible(true);
360        println( "Any messages for the tester will display here." );
361    }
362
363    public static void createDialog( )
364    {
365        dialog = new TestDialog( new Frame(), "Instructions" );
366        String[] defInstr = { "Instructions will appear here. ", "" } ;
367        dialog.printInstructions( defInstr );
368        dialog.setVisible(true);
369        println( "Any messages for the tester will display here." );
370    }
371
372
373    public static void printInstructions( String[] instructions )
374    {
375        dialog.printInstructions( instructions );
376    }
377
378
379    public static void println( String messageIn )
380    {
381        dialog.displayMessage( messageIn );
382        System.out.println(messageIn);
383    }
384
385}// Sysout  class
386
387/**
388  This is part of the standard test machinery.  It provides a place for the
389   test instructions to be displayed, and a place for interactive messages
390   to the user to be displayed.
391  To have the test instructions displayed, see Sysout.
392  To have a message to the user be displayed, see Sysout.
393  Do not call anything in this dialog directly.
394  */
395class TestDialog extends Dialog
396{
397
398    TextArea instructionsText;
399    TextArea messageText;
400    int maxStringLength = 80;
401
402    //DO NOT call this directly, go through Sysout
403    public TestDialog( Frame frame, String name )
404    {
405        super( frame, name );
406        int scrollBoth = TextArea.SCROLLBARS_BOTH;
407        instructionsText = new TextArea( "", 15, maxStringLength, scrollBoth );
408        add( "North", instructionsText );
409
410        messageText = new TextArea( "", 5, maxStringLength, scrollBoth );
411        add("Center", messageText);
412
413        pack();
414
415        setVisible(true);
416    }// TestDialog()
417
418    //DO NOT call this directly, go through Sysout
419    public void printInstructions( String[] instructions )
420    {
421        //Clear out any current instructions
422        instructionsText.setText( "" );
423
424        //Go down array of instruction strings
425
426        String printStr, remainingStr;
427        for( int i=0; i < instructions.length; i++ )
428        {
429            //chop up each into pieces maxSringLength long
430            remainingStr = instructions[ i ];
431            while( remainingStr.length() > 0 )
432            {
433                //if longer than max then chop off first max chars to print
434                if( remainingStr.length() >= maxStringLength )
435                {
436                    //Try to chop on a word boundary
437                    int posOfSpace = remainingStr.
438                        lastIndexOf( ' ', maxStringLength - 1 );
439
440                    if( posOfSpace <= 0 ) posOfSpace = maxStringLength - 1;
441
442                    printStr = remainingStr.substring( 0, posOfSpace + 1 );
443                    remainingStr = remainingStr.substring( posOfSpace + 1 );
444                }
445                //else just print
446                else
447                {
448                    printStr = remainingStr;
449                    remainingStr = "";
450                }
451
452                instructionsText.append( printStr + "\n" );
453
454            }// while
455
456        }// for
457
458    }//printInstructions()
459
460    //DO NOT call this directly, go through Sysout
461    public void displayMessage( String messageIn )
462    {
463        messageText.append( messageIn + "\n" );
464        System.out.println(messageIn);
465    }
466
467}// TestDialog  class
468