1 /*
2  * Copyright (c) 2008, 2013, 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%  %I%, %G%
26   @bug 6315717
27   @summary  manual control over the Robot
28   @author Andrei Dmitriev : area=awt.robot
29   @run applet/manual=yesno ManualInstructions.html
30 */
31 
32 import java.applet.Applet;
33 import java.awt.*;
34 import java.awt.event.*;
35 import java.util.Timer;
36 import java.util.TimerTask;
37 
38 public class ManualInstructions extends Applet
39 {
40     final static long SEND_DELAY = 1000;
41 
main(String s[])42     public static void main(String s[]){
43         ManualInstructions mi = new ManualInstructions();
44         mi.init();
45         mi.start();
46     }
47 
48     static Robot robot;
49     Point mouseLocation; //where mouse should be pressed each time
50     Panel target = new Panel();
51     Button pressOn = new Button("press on ...");
52     Button releaseOn = new Button("release on ...");
53     Button clickOn = new Button("click on ...");
54     Choice buttonNumber = new Choice();
55 
init()56     public void init()
57     {
58         try {
59             robot = new Robot();
60         } catch (AWTException ex) {
61             ex.printStackTrace();
62             throw new RuntimeException(ex);
63         }
64         this.setLayout (new BorderLayout ());
65 
66         target.setBackground(Color.green);
67         target.setName("GreenBox");//for the ease of debug
68         target.setPreferredSize(new Dimension(100, 100));
69         String toolkit = Toolkit.getDefaultToolkit().getClass().getName();
70 
71         // on X systems two buttons are reserved for wheel though they are countable by MouseInfo.
72         int buttonsNumber = toolkit.equals("sun.awt.windows.WToolkit")?MouseInfo.getNumberOfButtons():MouseInfo.getNumberOfButtons()-2;
73 
74         for (int i = 0; i < 8; i++){
75             buttonNumber.add("BUTTON"+(i+1)+"_MASK");
76         }
77 
78         pressOn.addActionListener(new ActionListener(){
79                 public void actionPerformed(ActionEvent e){
80                     System.out.println("Now pressing : " + (buttonNumber.getSelectedIndex()+1));
81 
82                     Timer timer = new Timer();
83                     TimerTask robotInteraction = new TimerTask(){
84                             public void run(){
85                                 robot.mouseMove(updateTargetLocation().x, updateTargetLocation().y);
86                                 robot.mousePress(getMask(buttonNumber.getSelectedIndex()+1));
87                             }
88                         };
89                     timer.schedule(robotInteraction, SEND_DELAY);
90                 }
91             });
92 
93         releaseOn.addActionListener(new ActionListener(){
94             public void actionPerformed(ActionEvent e){
95                 System.out.println("Now releasing : " + (buttonNumber.getSelectedIndex()+1));
96                 Timer timer = new Timer();
97                 TimerTask robotInteraction = new TimerTask(){
98                         public void run(){
99                             robot.mouseMove(updateTargetLocation().x, updateTargetLocation().y);
100                             robot.mouseRelease(getMask(buttonNumber.getSelectedIndex()+1));
101                         }
102                     };
103                 timer.schedule(robotInteraction, SEND_DELAY);
104             }
105         });
106 
107         clickOn.addActionListener(new ActionListener(){
108             public void actionPerformed(ActionEvent e){
109                 System.out.println("Now clicking : " + (buttonNumber.getSelectedIndex()+1));
110                 Timer timer = new Timer();
111                 TimerTask robotInteraction = new TimerTask(){
112                         public void run(){
113                             robot.mouseMove(updateTargetLocation().x, updateTargetLocation().y);
114                             robot.mousePress(getMask(buttonNumber.getSelectedIndex()+1));
115                             robot.mouseRelease(getMask(buttonNumber.getSelectedIndex()+1));
116                         }
117                     };
118                 timer.schedule(robotInteraction, SEND_DELAY);
119             }
120 
121         });
122         target.addMouseListener(new MouseAdapter(){
123            public void mousePressed(MouseEvent e){
124                 Sysout.println(""+e);
125            }
126            public void mouseReleased(MouseEvent e){
127                 Sysout.println(""+e);
128            }
129            public void mouseClicked(MouseEvent e){
130                 Sysout.println(""+e);
131            }
132         });
133 
134         String[] instructions =
135         {
136             "Do provide an instruction to the robot by",
137             "choosing the button number to act and ",
138             "pressing appropriate java.awt.Button on the left.",
139             "Inspect an output in the TextArea below.",
140             "Please don't generate non-natural sequences like Release-Release, etc.",
141             "If you use keyboard be sure that you released the keyboard shortly.",
142             "If events are generated well press Pass, otherwise Fail."
143         };
144         Sysout.createDialogWithInstructions( instructions );
145 
146     }//End  init()
147 
getMask(int button)148     private int getMask(int button){
149         return InputEvent.getMaskForButton(button);
150 
151         /*
152             //this only works for standard buttons and for old JDK builds
153         int mask = 0;
154         switch (button){
155         case 1: {
156             mask = InputEvent.BUTTON1_MASK;
157             break;
158         }
159         case 2: {
160             mask = InputEvent.BUTTON2_MASK;
161             break;
162         }
163         case 3: {
164             mask = InputEvent.BUTTON3_MASK;
165             break;
166         }
167         }
168         return mask;
169         */
170     }
171 
updateTargetLocation()172     private Point updateTargetLocation() {
173         return new Point(target.getLocationOnScreen().x + target.getWidth()/2, target.getLocationOnScreen().y + target.getHeight()/2);
174     }
175 
start()176     public void start ()
177     {
178         //Get things going.  Request focus, set size, et cetera
179         setSize (200,200);
180         setVisible(true);
181         validate();
182         Frame f = new Frame ("Set action for Robot here.");
183         f.setLayout(new FlowLayout());
184         f.add(buttonNumber);
185         f.add(pressOn);
186         f.add(releaseOn);
187         f.add(clickOn);
188         f.add(target);
189         f.pack();
190         f.setVisible(true);
191      }// start()
192 }// class
193 
194 /* Place other classes related to the test after this line */
195 
196 
197 /****************************************************
198  Standard Test Machinery
199  DO NOT modify anything below -- it's a standard
200   chunk of code whose purpose is to make user
201   interaction uniform, and thereby make it simpler
202   to read and understand someone else's test.
203  ****************************************************/
204 
205 /**
206  This is part of the standard test machinery.
207  It creates a dialog (with the instructions), and is the interface
208   for sending text messages to the user.
209  To print the instructions, send an array of strings to Sysout.createDialog
210   WithInstructions method.  Put one line of instructions per array entry.
211  To display a message for the tester to see, simply call Sysout.println
212   with the string to be displayed.
213  This mimics System.out.println but works within the test harness as well
214   as standalone.
215  */
216 
217 class Sysout
218 {
219     private static TestDialog dialog;
220 
createDialogWithInstructions( String[] instructions )221     public static void createDialogWithInstructions( String[] instructions )
222     {
223         dialog = new TestDialog( new Frame(), "Instructions" );
224         dialog.printInstructions( instructions );
225         dialog.setVisible(true);
226         println( "Any messages for the tester will display here." );
227     }
228 
createDialog( )229     public static void createDialog( )
230     {
231         dialog = new TestDialog( new Frame(), "Instructions" );
232         String[] defInstr = { "Instructions will appear here. ", "" } ;
233         dialog.printInstructions( defInstr );
234         dialog.setVisible(true);
235         println( "Any messages for the tester will display here." );
236     }
237 
printInstructions( String[] instructions )238     public static void printInstructions( String[] instructions )
239     {
240         dialog.printInstructions( instructions );
241     }
242 
243 
println( String messageIn )244     public static void println( String messageIn )
245     {
246         dialog.displayMessage( messageIn );
247     }
248 
249 }// Sysout  class
250 
251 /**
252   This is part of the standard test machinery.  It provides a place for the
253    test instructions to be displayed, and a place for interactive messages
254    to the user to be displayed.
255   To have the test instructions displayed, see Sysout.
256   To have a message to the user be displayed, see Sysout.
257   Do not call anything in this dialog directly.
258   */
259 class TestDialog extends Dialog
260 {
261 
262     TextArea instructionsText;
263     TextArea messageText;
264     int maxStringLength = 120;
265 
266     //DO NOT call this directly, go through Sysout
TestDialog( Frame frame, String name )267     public TestDialog( Frame frame, String name )
268     {
269         super( frame, name );
270         int scrollBoth = TextArea.SCROLLBARS_BOTH;
271         instructionsText = new TextArea( "", 15, maxStringLength, scrollBoth );
272         add( "North", instructionsText );
273 
274         messageText = new TextArea( "", 5, maxStringLength, scrollBoth );
275         add("Center", messageText);
276 
277         pack();
278 
279         setVisible(true);
280     }// TestDialog()
281 
282     //DO NOT call this directly, go through Sysout
printInstructions( String[] instructions )283     public void printInstructions( String[] instructions )
284     {
285         //Clear out any current instructions
286         instructionsText.setText( "" );
287 
288         //Go down array of instruction strings
289 
290         String printStr, remainingStr;
291         for( int i=0; i < instructions.length; i++ )
292         {
293             //chop up each into pieces maxSringLength long
294             remainingStr = instructions[ i ];
295             while( remainingStr.length() > 0 )
296             {
297                 //if longer than max then chop off first max chars to print
298                 if( remainingStr.length() >= maxStringLength )
299                 {
300                     //Try to chop on a word boundary
301                     int posOfSpace = remainingStr.
302                         lastIndexOf( ' ', maxStringLength - 1 );
303 
304                     if( posOfSpace <= 0 ) posOfSpace = maxStringLength - 1;
305 
306                     printStr = remainingStr.substring( 0, posOfSpace + 1 );
307                     remainingStr = remainingStr.substring( posOfSpace + 1 );
308                 }
309                 //else just print
310                 else
311                 {
312                     printStr = remainingStr;
313                     remainingStr = "";
314                 }
315 
316                 instructionsText.append( printStr + "\n" );
317             }// while
318         }// for
319     }//printInstructions()
320 
321     //DO NOT call this directly, go through Sysout
displayMessage( String messageIn )322     public void displayMessage( String messageIn )
323     {
324         messageText.append( messageIn + "\n" );
325         System.out.println(messageIn);
326     }
327 
328 }// TestDialog  class
329