File: TestMainKeyWindow.java

package info (click to toggle)
openjdk-11 11.0.4%2B11-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 757,028 kB
  • sloc: java: 5,016,041; xml: 1,191,974; cpp: 934,731; ansic: 555,697; sh: 24,299; objc: 12,703; python: 3,602; asm: 3,415; makefile: 2,772; awk: 351; sed: 172; perl: 114; jsp: 24; csh: 3
file content (409 lines) | stat: -rw-r--r-- 13,666 bytes parent folder | download | duplicates (6)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
/*
 * Copyright (c) 2018, 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
 * @key headful
 * @bug 8194327
 * @summary [macosx] AWT windows have incorrect main/key window behaviors
 * @author Alan Snyder
 * @run main/othervm/native TestMainKeyWindow
 * @requires (os.family == "mac")
 */

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Objects;
import javax.swing.*;

public class TestMainKeyWindow
{
    static TestMainKeyWindow theTest;

    KeyStroke commandT = KeyStroke.getKeyStroke(KeyEvent.VK_T, KeyEvent.META_DOWN_MASK);

    int nextX = 130;

    private final MyFrame frame1;
    private final MyFrame frame2;
    private final Object COLOR_PANEL = "Color Panel";
    private final Object NATIVE_WINDOW = "Native Window";

    // these bounds must agree with the native code that creates the windows
    private Rectangle colorPanelBounds = new Rectangle(130, 300, 225, 400);  // approximate is OK
    private Rectangle nativeWindowBounds = new Rectangle(130, 200, 200, 100);

    private Robot robot;

    private int actionCounter;
    private Object actionTarget;

    private int failureCount;
    private boolean isApplicationOpened;

    public TestMainKeyWindow()
    {
        System.loadLibrary("testMainKeyWindow");

        JMenuBar defaultMenuBar = createMenuBar("Application", true);
        Desktop.getDesktop().setDefaultMenuBar(defaultMenuBar);

        setup();

        frame1 = new MyFrame("Frame 1");
        frame2 = new MyFrame("Frame 2");
        frame1.setVisible(true);
        frame2.setVisible(true);

        try {
            robot = new Robot();
            robot.setAutoDelay(50);
        } catch (AWTException ex) {
            throw new RuntimeException(ex);
        }
    }

    class MyFrame
        extends JFrame
    {
        public MyFrame(String title)
            throws HeadlessException
        {
            super(title);

            JMenuBar mainMenuBar = createMenuBar(title, true);
            setJMenuBar(mainMenuBar);
            setBounds(nextX, 60, 200, 90);
            nextX += 250;
            JComponent contentPane = new JPanel();
            setContentPane(contentPane);
            contentPane.setLayout(new FlowLayout());
            contentPane.add(new JCheckBox("foo", true));
            InputMap inputMap = contentPane.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
            inputMap.put(commandT, "test");
            ActionMap actionMap = contentPane.getActionMap();
            actionMap.put("test", new MyAction(title + " Key"));
        }
    }

    private void runTest()
    {
        failureCount = 0;
        robot.waitForIdle();
        performTest(frame1, false);
        performTest(frame1, true);
        performTest(frame2, false);
        performTest(frame2, true);
        performTest(NATIVE_WINDOW, false);
        performTest(NATIVE_WINDOW, true);
        performTest(COLOR_PANEL, false);
        if (failureCount > 0) {
            throw new RuntimeException("Test failed: " + failureCount + " failure(s)");
        }
    }

    private void performTest(Object windowIdentification, boolean selectColorPanel)
    {
        setupWindows(windowIdentification, selectColorPanel);

        performMenuShortcutTest(windowIdentification, selectColorPanel);
        performMenuItemTest(windowIdentification, selectColorPanel);

        // test deactivating and reactivating the application
        // the window state and behavior should be restored

        openOtherApplication();
        activateApplication();
        robot.delay(1000);

        performMenuShortcutTest(windowIdentification, selectColorPanel);
        performMenuItemTest(windowIdentification, selectColorPanel);
    }

    private void openOtherApplication() {
        try {
            String[] cmd = { "/usr/bin/open", "/Applications/System Preferences.app" };
            Runtime.getRuntime().exec(cmd);
            if (!isApplicationOpened) {
                String[] cmd2 = { "/usr/bin/osascript", "-e",
                    "tell application \"System Preferences\" to set bounds of window 1 to {400, 180, 1068, 821}" };
                Runtime.getRuntime().exec(cmd2);
            }
            isApplicationOpened = true;
        } catch (IOException ex) {
            throw new RuntimeException("Unable to deactivate test application");
        }
        robot.delay(1000);
    }

    private void performMenuShortcutTest(Object windowIdentification, boolean selectColorPanel)
    {
        int currentActionCount = actionCounter;

        // Perform the menu shortcut
        robot.keyPress(KeyEvent.VK_META);
        robot.keyPress(KeyEvent.VK_T);
        robot.keyRelease(KeyEvent.VK_T);
        robot.keyRelease(KeyEvent.VK_META);
        robot.waitForIdle();

        Object target = waitForAction(currentActionCount + 1);
        boolean isDirectKey = windowIdentification instanceof Window && !selectColorPanel;
        Object expectedTarget = getExpectedTarget(windowIdentification, isDirectKey);
        if (!Objects.equals(target, expectedTarget)) {
            failureCount++;
            String configuration = getConfigurationName(windowIdentification, selectColorPanel);
            System.err.println("***** Menu shortcut test failed for " + configuration + ". Expected: " + expectedTarget + ", Actual: " + target);
        }
    }

    private void performMenuItemTest(Object windowIdentification, boolean selectColorPanel)
    {
        int currentActionCount = actionCounter;

        // Find the menu on the screen menu bar
        // The location depends upon the application name which is the name of the first menu.
        // Unfortunately, the application name can vary based on how the application is run.
        // The work around is to make the menu and the menu item names very long.

        int menuBarX = 250;
        int menuBarY = 11;
        int menuItemX = menuBarX;
        int menuItemY = 34;

        robot.mouseMove(menuBarX, menuBarY);
        robot.delay(100);
        robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
        robot.delay(100);
        robot.mouseMove(menuItemX, menuItemY);
        robot.delay(100);
        robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
        robot.waitForIdle();

        Object target = waitForAction(currentActionCount + 1);
        Object expectedTarget = getExpectedTarget(windowIdentification, false);
        if (!Objects.equals(target, expectedTarget)) {
            failureCount++;
            String configuration = getConfigurationName(windowIdentification, selectColorPanel);
            System.err.println("***** Menu item test failed for " + configuration + ". Expected: " + expectedTarget + ", Actual: " + target);
        }
    }

    private String getConfigurationName(Object windowIdentification, boolean selectColorPanel)
    {
        String name = "Unknown";
        if (windowIdentification instanceof Window) {
            Window w = (Window) windowIdentification;
            name = getWindowTitle(w);
        } else if (windowIdentification == NATIVE_WINDOW) {
            name = "Native Window";
        } else if (windowIdentification == COLOR_PANEL) {
            name = "Color Panel";
        }
        if (selectColorPanel) {
            return name + " with color panel";
        } else {
            return name;
        }
    }

    private Object getExpectedTarget(Object windowIdentification, boolean isDirectKey)
    {
        if (windowIdentification instanceof Window) {
            Window w = (Window) windowIdentification;
            String title = getWindowTitle(w);
            if (isDirectKey) {
                title = title + " Key";
            }
            return title;
        }
        return "Application";
    }

    private String getWindowTitle(Window w)
    {
        if (w instanceof Frame) {
            Frame f = (Frame) w;
            return f.getTitle();
        }
        if (w instanceof Dialog) {
            Dialog d = (Dialog) w;
            return d.getTitle();
        }
        throw new IllegalStateException();
    }

    private synchronized void registerAction(Object target)
    {
        actionCounter++;
        actionTarget = target;
    }

    private synchronized Object waitForAction(int count)
    {
        try {
            for (int i = 0; i < 10; i++) {
                if (actionCounter == count) {
                    return actionTarget;
                }
                if (actionCounter > count) {
                    throw new IllegalStateException();
                }
                wait(100);
            }
        } catch (InterruptedException ex) {
        }
        return "No Action";
    }

    private void setupWindows(Object windowIdentification, boolean selectColorPanel)
    {
        clickOnWindowTitleBar(windowIdentification);
        if (selectColorPanel) {
            clickOnWindowTitleBar(COLOR_PANEL);
        }
    }

    private void clickOnWindowTitleBar(Object windowIdentification)
    {
        Rectangle bounds = getWindowBounds(windowIdentification);
        int x = bounds.x + 70;  // to the right of the stoplight buttons
        int y = bounds.y + 12;  // in the title bar
        robot.mouseMove(x, y);
        robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
        robot.waitForIdle();
        robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
        robot.waitForIdle();
    }

    private Rectangle getWindowBounds(Object windowIdentification)
    {
        if (windowIdentification instanceof Window) {
            Window w = (Window) windowIdentification;
            return w.getBounds();
        }
        if (windowIdentification == COLOR_PANEL) {
            return colorPanelBounds;
        }
        if (windowIdentification == NATIVE_WINDOW) {
            return nativeWindowBounds;
        }
        throw new IllegalArgumentException();
    }

    JMenuBar createMenuBar(String text, boolean isEnabled)
    {
        JMenuBar mb = new JMenuBar();
        // A very long name makes it more likely that the robot will hit the menu
        JMenu menu = new JMenu("TestTestTestTestTestTestTestTestTestTest");
        mb.add(menu);
        JMenuItem item = new JMenuItem("TestTestTestTestTestTestTestTestTestTest");
        item.setAccelerator(commandT);
        item.setEnabled(isEnabled);
        item.addActionListener(ev -> {
            registerAction(text);
        });
        menu.add(item);
        return mb;
    }

    void dispose()
    {
        frame1.setVisible(false);
        frame2.setVisible(false);
        frame1.dispose();
        frame2.dispose();
        takedown();
        Desktop.getDesktop().setDefaultMenuBar(null);
        if (isApplicationOpened) {
            try {
                String[] cmd = { "/usr/bin/osascript", "-e", "tell application \"System Preferences\" to close window 1" };
                Process p = Runtime.getRuntime().exec(cmd);
                p.waitFor();
            } catch (IOException | InterruptedException ex) {
            }
        }
    }

    class MyAction
        extends AbstractAction
    {
        String text;

        public MyAction(String text)
        {
            super("Test");

            this.text = text;
        }

        @Override
        public void actionPerformed(ActionEvent e)
        {
            registerAction(text);
        }
    }

    private static native void setup();
    private static native void takedown();
    private static native void activateApplication();

    public static void main(String[] args)
    {
        if (!System.getProperty("os.name").contains("OS X")) {
            System.out.println("This test is for MacOS only. Automatically passed on other platforms.");
            return;
        }

        System.setProperty("apple.laf.useScreenMenuBar", "true");

        try {
            runSwing(() -> {
                theTest = new TestMainKeyWindow();
            });
            theTest.runTest();
        } finally {
            if (theTest != null) {
                runSwing(() -> {
                    theTest.dispose();
                });
            }
        }
    }

    private static void runSwing(Runnable r)
    {
        try {
            SwingUtilities.invokeAndWait(r);
        } catch (InterruptedException e) {
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        }
    }
}