aboutsummaryrefslogtreecommitdiff
path: root/java_tests/tests/detailed/ui/MenuBar.java
blob: f92741ae08c6516bc793928f3c9404bc98d39e89 (plain)
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
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
// Copyright (c) 2014 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.

package tests.detailed.ui;

import org.cef.CefApp;
import org.cef.CefClient;
import org.cef.OS;
import org.cef.browser.CefBrowser;
import org.cef.callback.CefPdfPrintCallback;
import org.cef.callback.CefRunFileDialogCallback;
import org.cef.callback.CefStringVisitor;
import org.cef.handler.CefDialogHandler.FileDialogMode;
import org.cef.misc.CefPdfPrintSettings;
import org.cef.network.CefCookieManager;
import org.cef.network.CefRequest;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.Vector;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JLayeredPane;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRootPane;
import javax.swing.SwingUtilities;

import tests.detailed.BrowserFrame;
import tests.detailed.MainFrame;
import tests.detailed.dialog.CookieManagerDialog;
import tests.detailed.dialog.DevToolsDialog;
import tests.detailed.dialog.DownloadDialog;
import tests.detailed.dialog.SearchDialog;
import tests.detailed.dialog.ShowTextDialog;
import tests.detailed.dialog.UrlRequestDialog;
import tests.detailed.dialog.WebPluginManagerDialog;
import tests.detailed.util.DataUri;

@SuppressWarnings("serial")
public class MenuBar extends JMenuBar {
    class SaveAs implements CefStringVisitor {
        private PrintWriter fileWriter_;

        public SaveAs(String fName) throws FileNotFoundException, UnsupportedEncodingException {
            fileWriter_ = new PrintWriter(fName, "UTF-8");
        }

        @Override
        public void visit(String string) {
            fileWriter_.write(string);
            fileWriter_.close();
        }
    }

    private final MainFrame owner_;
    private final CefBrowser browser_;
    private String last_selected_file_ = "";
    private final JMenu bookmarkMenu_;
    private final ControlPanel control_pane_;
    private final DownloadDialog downloadDialog_;
    private final CefCookieManager cookieManager_;
    private boolean reparentPending_ = false;

    public MenuBar(MainFrame owner, CefBrowser browser, ControlPanel control_pane,
            DownloadDialog downloadDialog, CefCookieManager cookieManager) {
        owner_ = owner;
        browser_ = browser;
        control_pane_ = control_pane;
        downloadDialog_ = downloadDialog;
        cookieManager_ = cookieManager;

        setEnabled(browser_ != null);

        JMenu fileMenu = new JMenu("File");

        JMenuItem openFileItem = new JMenuItem("Open file...");
        openFileItem.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent arg0) {
                JFileChooser fc = new JFileChooser(new File(last_selected_file_));
                // Show open dialog; this method does not return until the dialog is closed.
                fc.showOpenDialog(owner_);
                File selectedFile = fc.getSelectedFile();
                if (selectedFile != null) {
                    last_selected_file_ = selectedFile.getAbsolutePath();
                    browser_.loadURL("file:///" + selectedFile.getAbsolutePath());
                }
            }
        });
        fileMenu.add(openFileItem);

        JMenuItem openFileDialog = new JMenuItem("Save as...");
        openFileDialog.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                CefRunFileDialogCallback callback = new CefRunFileDialogCallback() {
                    @Override
                    public void onFileDialogDismissed(
                            int selectedAcceptFilter, Vector<String> filePaths) {
                        if (!filePaths.isEmpty()) {
                            try {
                                SaveAs saveContent = new SaveAs(filePaths.get(0));
                                browser_.getSource(saveContent);
                            } catch (FileNotFoundException | UnsupportedEncodingException e) {
                                browser_.executeJavaScript("alert(\"Can't save file\");",
                                        control_pane_.getAddress(), 0);
                            }
                        }
                    }
                };
                browser_.runFileDialog(FileDialogMode.FILE_DIALOG_SAVE, owner_.getTitle(),
                        "index.html", null, 0, callback);
            }
        });
        fileMenu.add(openFileDialog);

        JMenuItem printItem = new JMenuItem("Print...");
        printItem.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                browser_.print();
            }
        });
        fileMenu.add(printItem);

        JMenuItem printToPdfItem = new JMenuItem("Print to PDF");
        printToPdfItem.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JFileChooser fc = new JFileChooser();
                fc.showSaveDialog(owner_);
                File selectedFile = fc.getSelectedFile();
                if (selectedFile != null) {
                    CefPdfPrintSettings pdfSettings = new CefPdfPrintSettings();
                    pdfSettings.header_footer_enabled = true;
                    // A4 page size
                    pdfSettings.page_width = 210000;
                    pdfSettings.page_height = 297000;
                    browser.printToPDF(
                            selectedFile.getAbsolutePath(), pdfSettings, new CefPdfPrintCallback() {
                                @Override
                                public void onPdfPrintFinished(String path, boolean ok) {
                                    SwingUtilities.invokeLater(new Runnable() {
                                        @Override
                                        public void run() {
                                            if (ok) {
                                                JOptionPane.showMessageDialog(owner_,
                                                        "PDF saved to " + path, "Success",
                                                        JOptionPane.INFORMATION_MESSAGE);
                                            } else {
                                                JOptionPane.showMessageDialog(owner_, "PDF failed",
                                                        "Failed", JOptionPane.ERROR_MESSAGE);
                                            }
                                        }
                                    });
                                }
                            });
                }
            }
        });
        fileMenu.add(printToPdfItem);

        JMenuItem searchItem = new JMenuItem("Search...");
        searchItem.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                new SearchDialog(owner_, browser_).setVisible(true);
            }
        });
        fileMenu.add(searchItem);

        fileMenu.addSeparator();

        JMenuItem viewSource = new JMenuItem("View source");
        viewSource.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                browser_.viewSource();
            }
        });
        fileMenu.add(viewSource);

        JMenuItem getSource = new JMenuItem("Get source...");
        getSource.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                ShowTextDialog visitor = new ShowTextDialog(
                        owner_, "Source of \"" + control_pane_.getAddress() + "\"");
                browser_.getSource(visitor);
            }
        });
        fileMenu.add(getSource);

        JMenuItem getText = new JMenuItem("Get text...");
        getText.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                ShowTextDialog visitor = new ShowTextDialog(
                        owner_, "Content of \"" + control_pane_.getAddress() + "\"");
                browser_.getText(visitor);
            }
        });
        fileMenu.add(getText);

        fileMenu.addSeparator();

        JMenuItem showDownloads = new JMenuItem("Show Downloads");
        showDownloads.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                downloadDialog_.setVisible(true);
            }
        });
        fileMenu.add(showDownloads);

        JMenuItem showCookies = new JMenuItem("Show Cookies");
        showCookies.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                CookieManagerDialog cookieManager =
                        new CookieManagerDialog(owner_, "Cookie Manager", cookieManager_);
                cookieManager.setVisible(true);
            }
        });
        fileMenu.add(showCookies);

        JMenuItem showPlugins = new JMenuItem("Show Plugins");
        showPlugins.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                WebPluginManagerDialog pluginManager =
                        new WebPluginManagerDialog(owner_, "Plugin Manager");
                pluginManager.setVisible(true);
            }
        });
        fileMenu.add(showPlugins);

        fileMenu.addSeparator();

        JMenuItem exitItem = new JMenuItem("Exit");
        exitItem.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                owner_.dispatchEvent(new WindowEvent(owner_, WindowEvent.WINDOW_CLOSING));
            }
        });
        fileMenu.add(exitItem);

        bookmarkMenu_ = new JMenu("Bookmarks");

        JMenuItem addBookmarkItem = new JMenuItem("Add bookmark");
        addBookmarkItem.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                addBookmark(owner_.getTitle(), control_pane_.getAddress());
            }
        });
        bookmarkMenu_.add(addBookmarkItem);
        bookmarkMenu_.addSeparator();

        JMenu testMenu = new JMenu("Tests");

        JMenuItem testJSItem = new JMenuItem("JavaScript alert");
        testJSItem.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                browser_.executeJavaScript("alert('Hello World');", control_pane_.getAddress(), 1);
            }
        });
        testMenu.add(testJSItem);

        JMenuItem jsAlertItem = new JMenuItem("JavaScript alert (will be suppressed)");
        jsAlertItem.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                browser_.executeJavaScript("alert('Never displayed');", "http://dontshow.me", 1);
            }
        });
        testMenu.add(jsAlertItem);

        JMenuItem testShowText = new JMenuItem("Show Text");
        testShowText.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                browser_.loadURL(DataUri.create(
                        "text/html", "<html><body><h1>Hello World</h1></body></html>"));
            }
        });
        testMenu.add(testShowText);

        JMenuItem showForm = new JMenuItem("RequestHandler Test");
        showForm.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String form = "<html><head><title>RequestHandler test</title></head>";
                form += "<body><h1>RequestHandler test</h1>";
                form += "<form action=\"http://www.google.com/\" method=\"post\">";
                form += "<input type=\"text\" name=\"searchFor\"/>";
                form += "<input type=\"submit\"/><br/>";
                form += "<input type=\"checkbox\" name=\"sendAsGet\"> Use GET instead of POST";
                form += "<p>This form tries to send the content of the text field as HTTP-POST request to http://www.google.com.</p>";
                form += "<h2>Testcase 1</h2>";
                form += "Try to enter the word <b>\"ignore\"</b> into the text field and press \"submit\".<br />";
                form += "The request will be rejected by the application.";
                form += "<p>See implementation of <u>tests.RequestHandler.onBeforeBrowse(CefBrowser, CefRequest, boolean)</u> for details</p>";
                form += "<h2>Testcase 2</h2>";
                form += "Due Google doesn't allow the POST method, the server replies with a 405 error.</br>";
                form += "If you activate the checkbox \"Use GET instead of POST\", the application will change the POST request into a GET request.";
                form += "<p>See implementation of <u>tests.RequestHandler.onBeforeResourceLoad(CefBrowser, CefRequest)</u> for details</p>";
                form += "</form>";
                form += "</body></html>";
                browser_.loadURL(DataUri.create("text/html", form));
            }
        });
        testMenu.add(showForm);

        JMenuItem httpRequest = new JMenuItem("Manual HTTP request");
        httpRequest.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String searchFor = JOptionPane.showInputDialog(owner_, "Search on google:");
                if (searchFor != null && !searchFor.isEmpty()) {
                    CefRequest myRequest = CefRequest.create();
                    myRequest.setMethod("GET");
                    myRequest.setURL("http://www.google.com/#q=" + searchFor);
                    myRequest.setFirstPartyForCookies("http://www.google.com/#q=" + searchFor);
                    browser_.loadRequest(myRequest);
                }
            }
        });
        testMenu.add(httpRequest);

        JMenuItem showInfo = new JMenuItem("Show Info");
        showInfo.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String info = "<html><head><title>Browser status</title></head>";
                info += "<body><h1>Browser status</h1><table border=\"0\">";
                info += "<tr><td>CanGoBack</td><td>" + browser_.canGoBack() + "</td></tr>";
                info += "<tr><td>CanGoForward</td><td>" + browser_.canGoForward() + "</td></tr>";
                info += "<tr><td>IsLoading</td><td>" + browser_.isLoading() + "</td></tr>";
                info += "<tr><td>isPopup</td><td>" + browser_.isPopup() + "</td></tr>";
                info += "<tr><td>hasDocument</td><td>" + browser_.hasDocument() + "</td></tr>";
                info += "<tr><td>Url</td><td>" + browser_.getURL() + "</td></tr>";
                info += "<tr><td>Zoom-Level</td><td>" + browser_.getZoomLevel() + "</td></tr>";
                info += "</table></body></html>";
                String js = "var x=window.open(); x.document.open(); x.document.write('" + info
                        + "'); x.document.close();";
                browser_.executeJavaScript(js, "", 0);

                String jsFunc = "cef_query_" + MainFrame.queryCounter;
                String jsQuery = "window." + jsFunc + "({request: '" + jsFunc + "'});";
                browser_.executeJavaScript(jsQuery, "", 0);
            }
        });
        testMenu.add(showInfo);

        final JMenuItem showDevTools = new JMenuItem("Show DevTools");
        showDevTools.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                DevToolsDialog devToolsDlg = new DevToolsDialog(owner_, "DEV Tools", browser_);
                devToolsDlg.addComponentListener(new ComponentAdapter() {
                    @Override
                    public void componentHidden(ComponentEvent e) {
                        showDevTools.setEnabled(true);
                    }
                });
                devToolsDlg.setVisible(true);
                showDevTools.setEnabled(false);
            }
        });
        testMenu.add(showDevTools);

        JMenuItem testURLRequest = new JMenuItem("URL Request");
        testURLRequest.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                UrlRequestDialog dlg = new UrlRequestDialog(owner_, "URL Request Test");
                dlg.setVisible(true);
            }
        });
        testMenu.add(testURLRequest);

        JMenuItem reparent = new JMenuItem("Reparent");
        reparent.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                final BrowserFrame newFrame = new BrowserFrame("New Window");
                newFrame.setLayout(new BorderLayout());
                final JButton reparentButton = new JButton("Reparent <");
                reparentButton.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        if (reparentPending_) return;
                        reparentPending_ = true;

                        if (reparentButton.getText().equals("Reparent <")) {
                            owner_.removeBrowser(new Runnable() {
                                public void run() {
                                    newFrame.add(browser_.getUIComponent(), BorderLayout.CENTER);
                                    newFrame.setBrowser(browser_);
                                    reparentButton.setText("Reparent >");
                                    reparentPending_ = false;
                                }
                            });
                        } else {
                            newFrame.removeBrowser(new Runnable() {
                                public void run() {
                                    JRootPane rootPane = (JRootPane) owner_.getComponent(0);
                                    Container container = rootPane.getContentPane();
                                    JPanel panel = (JPanel) container.getComponent(0);
                                    panel.add(browser_.getUIComponent());
                                    owner_.setBrowser(browser_);
                                    owner_.revalidate();
                                    reparentButton.setText("Reparent <");
                                    reparentPending_ = false;
                                }
                            });
                        }
                    }
                });
                newFrame.add(reparentButton, BorderLayout.NORTH);
                newFrame.setSize(400, 400);
                newFrame.setVisible(true);
            }
        });
        testMenu.add(reparent);

        JMenuItem newwindow = new JMenuItem("New window");
        newwindow.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                final MainFrame frame = new MainFrame(OS.isLinux(), false, false, null);
                frame.setSize(800, 600);
                frame.setVisible(true);
            }
        });
        testMenu.add(newwindow);

        JMenuItem screenshotSync = new JMenuItem("Screenshot (on AWT thread, native res)");
        screenshotSync.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                long start = System.nanoTime();
                CompletableFuture<BufferedImage> shot = browser.createScreenshot(true);
                System.out.println("Took screenshot from the AWT event thread in "
                        + TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start) + " msecs");
                try {
                    displayScreenshot(shot.get());
                } catch (InterruptedException | ExecutionException exc) {
                    // cannot happen, future is already resolved in this case
                }
            }
        });
        screenshotSync.setEnabled(owner.isOsrEnabled());
        testMenu.add(screenshotSync);

        JMenuItem screenshotSyncScaled = new JMenuItem("Screenshot (on AWT thread, scaled)");
        screenshotSyncScaled.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                long start = System.nanoTime();
                CompletableFuture<BufferedImage> shot = browser.createScreenshot(false);
                System.out.println("Took screenshot from the AWT event thread in "
                        + TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start) + " msecs");
                try {
                    displayScreenshot(shot.get());
                } catch (InterruptedException | ExecutionException exc) {
                    // cannot happen, future is already resolved in this case
                }
            }
        });
        screenshotSyncScaled.setEnabled(owner.isOsrEnabled());
        testMenu.add(screenshotSyncScaled);

        JMenuItem screenshotAsync = new JMenuItem("Screenshot (from other thread, scaled)");
        screenshotAsync.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                long start = System.nanoTime();
                CompletableFuture<BufferedImage> shot = browser.createScreenshot(false);
                shot.thenAccept((image) -> {
                    System.out.println("Took screenshot asynchronously in "
                            + TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start)
                            + " msecs");
                    SwingUtilities.invokeLater(new Runnable() {
                        @Override
                        public void run() {
                            displayScreenshot(image);
                        }
                    });
                });
            }
        });
        screenshotAsync.setEnabled(owner.isOsrEnabled());
        testMenu.add(screenshotAsync);

        add(fileMenu);
        add(bookmarkMenu_);
        add(testMenu);
    }

    public void addBookmark(String name, String URL) {
        if (bookmarkMenu_ == null) return;

        // Test if the bookmark already exists. If yes, update URL
        Component[] entries = bookmarkMenu_.getMenuComponents();
        for (Component itemEntry : entries) {
            if (!(itemEntry instanceof JMenuItem)) continue;

            JMenuItem item = (JMenuItem) itemEntry;
            if (item.getText().equals(name)) {
                item.setActionCommand(URL);
                return;
            }
        }

        JMenuItem menuItem = new JMenuItem(name);
        menuItem.setActionCommand(URL);
        menuItem.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                browser_.loadURL(e.getActionCommand());
            }
        });
        bookmarkMenu_.add(menuItem);
        validate();
    }

    private void displayScreenshot(BufferedImage aScreenshot) {
        JFrame frame = new JFrame("Screenshot");
        ImageIcon image = new ImageIcon();
        image.setImage(aScreenshot);
        frame.setLayout(new FlowLayout());
        JLabel label = new JLabel(image);
        label.setPreferredSize(new Dimension(aScreenshot.getWidth(), aScreenshot.getHeight()));
        frame.add(label);
        frame.setVisible(true);
        frame.pack();
    }

    public void addBookmarkSeparator() {
        bookmarkMenu_.addSeparator();
    }
}