summaryrefslogtreecommitdiffstats
path: root/toolkit/content/tests/browser/browser_click_event_during_autoscrolling.js
blob: b47f72ed5b6f5233f32f1e89feef9df4cc85c048 (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
574
575
576
577
/* Any copyright is dedicated to the Public Domain.
   http://creativecommons.org/publicdomain/zero/1.0/ */

"use strict";

add_task(async function () {
  await SpecialPowers.pushPrefEnv({
    set: [
      ["general.autoScroll", true],
      ["middlemouse.contentLoadURL", false],
      ["test.events.async.enabled", false],
    ],
  });

  await BrowserTestUtils.withNewTab(
    "https://example.com/browser/toolkit/content/tests/browser/file_empty.html",
    async function (browser) {
      ok(browser.isRemoteBrowser, "This test passes only in e10s mode");
      await SpecialPowers.spawn(browser, [], () => {
        content.document.body.innerHTML =
          '<div style="height: 10000px;"></div>';
        content.document.documentElement.scrollTop = 500;
        content.document.documentElement.scrollTop; // Flush layout.
        // Prevent to open context menu when testing the secondary button click.
        content.window.addEventListener(
          "contextmenu",
          event => event.preventDefault(),
          { capture: true }
        );
      });

      function promiseFlushLayoutInContent() {
        return SpecialPowers.spawn(browser, [], () => {
          content.document.documentElement.scrollTop; // Flush layout in the remote content.
        });
      }

      function promiseContentTick() {
        return SpecialPowers.spawn(browser, [], async () => {
          await new Promise(r => {
            content.requestAnimationFrame(() => {
              content.requestAnimationFrame(r);
            });
          });
        });
      }

      let autoScroller;
      function promiseWaitForAutoScrollerOpen() {
        if (autoScroller?.state == "open") {
          info("The autoscroller has already been open");
          return Promise.resolve();
        }
        return BrowserTestUtils.waitForEvent(
          window,
          "popupshown",
          { capture: true },
          event => {
            if (event.originalTarget.id != "autoscroller") {
              return false;
            }
            autoScroller = event.originalTarget;
            info('"popupshown" event is fired');
            autoScroller.getBoundingClientRect(); // Flush layout of the autoscroller
            return true;
          }
        );
      }

      function promiseWaitForAutoScrollerClosed() {
        if (!autoScroller || autoScroller.state == "closed") {
          info("The autoscroller has already been closed");
          return Promise.resolve();
        }
        return BrowserTestUtils.waitForEvent(
          autoScroller,
          "popuphidden",
          { capture: true },
          () => {
            info('"popuphidden" event is fired');
            return true;
          }
        );
      }

      // Unfortunately, we cannot use synthesized mouse events for starting and
      // stopping autoscrolling because they may run different path from user
      // operation especially when there is a popup.

      /**
       * Instead of using `waitForContentEvent`, we use `addContentEventListener`
       * for checking which events are fired because `waitForContentEvent` cannot
       * detect redundant event since it's removed automatically at first event
       * or timeout if the expected count is 0.
       */
      class ContentEventCounter {
        constructor(aBrowser, aEventTypes) {
          this.eventData = new Map();
          for (let eventType of aEventTypes) {
            const removeEventListener =
              BrowserTestUtils.addContentEventListener(
                aBrowser,
                eventType,
                () => {
                  let eventData = this.eventData.get(eventType);
                  eventData.count++;
                },
                { capture: true }
              );
            this.eventData.set(eventType, {
              count: 0, // how many times the event fired.
              removeEventListener, // function to remove the event listener.
            });
          }
        }

        getCountAndRemoveEventListener(aEventType) {
          let eventData = this.eventData.get(aEventType);
          if (eventData.removeEventListener) {
            eventData.removeEventListener();
            eventData.removeEventListener = null;
          }
          return eventData.count;
        }

        promiseMouseEvents(aEventTypes, aMessage) {
          let needsToWait = [];
          for (const eventType of aEventTypes) {
            let eventData = this.eventData.get(eventType);
            if (eventData.count > 0) {
              info(`${aMessage}: Waiting "${eventType}" event in content...`);
              needsToWait.push(
                // Let's use `waitForCondition` here.  "timeout" is not worthwhile
                // to debug this test.  We want clearer failure log.
                TestUtils.waitForCondition(
                  () => eventData.count > 0,
                  `${aMessage}: "${eventType}" should be fired, but timed-out`
                )
              );
              break;
            }
          }
          return Promise.all(needsToWait);
        }
      }

      await SpecialPowers.pushPrefEnv({ set: [["middlemouse.paste", true]] });
      await (async function testMouseEventsAtStartingAutoScrolling() {
        info(
          "Waiting autoscroller popup for testing mouse events at starting autoscrolling"
        );
        await promiseFlushLayoutInContent();
        let eventsInContent = new ContentEventCounter(browser, [
          "click",
          "auxclick",
          "mousedown",
          "mouseup",
          "paste",
        ]);
        // Ensure that the event listeners added in the content with accessing
        // the remote content.
        await promiseFlushLayoutInContent();
        await EventUtils.promiseNativeMouseEvent({
          type: "mousemove",
          target: browser,
          atCenter: true,
        });
        const waitForOpenAutoScroll = promiseWaitForAutoScrollerOpen();
        await EventUtils.promiseNativeMouseEvent({
          type: "mousedown",
          target: browser,
          atCenter: true,
          button: 1, // middle button
        });
        await waitForOpenAutoScroll;
        // In the wild, native "mouseup" event occurs after the popup is open.
        await EventUtils.promiseNativeMouseEvent({
          type: "mouseup",
          target: browser,
          atCenter: true,
          button: 1, // middle button
        });
        await promiseFlushLayoutInContent();
        await promiseContentTick();
        await eventsInContent.promiseMouseEvents(
          ["mouseup"],
          "At starting autoscrolling"
        );
        for (let eventType of ["click", "auxclick", "paste"]) {
          is(
            eventsInContent.getCountAndRemoveEventListener(eventType),
            0,
            `"${eventType}" event shouldn't be fired in the content when a middle click starts autoscrolling`
          );
        }
        for (let eventType of ["mousedown", "mouseup"]) {
          is(
            eventsInContent.getCountAndRemoveEventListener(eventType),
            1,
            `"${eventType}" event should be fired in the content when a middle click starts autoscrolling`
          );
        }
        info("Waiting autoscroller close for preparing the following tests");
        let waitForAutoScrollEnd = promiseWaitForAutoScrollerClosed();
        EventUtils.synthesizeKey("KEY_Escape");
        await waitForAutoScrollEnd;
      })();

      if (
        // Bug 1693240: We don't support setting modifiers while posting a mouse event on Windows.
        !navigator.platform.includes("Win") &&
        // Bug 1693237: We don't support setting modifiers on Android.
        !navigator.appVersion.includes("Android") &&
        // In Headless mode, modifiers are not supported by this kind of APIs.
        !Cc["@mozilla.org/gfx/info;1"].getService(Ci.nsIGfxInfo).isHeadless
      ) {
        await SpecialPowers.pushPrefEnv({
          set: [
            ["general.autoscroll.prevent_to_start.shiftKey", true],
            ["general.autoscroll.prevent_to_start.altKey", true],
            ["general.autoscroll.prevent_to_start.ctrlKey", true],
            ["general.autoscroll.prevent_to_start.metaKey", true],
          ],
        });
        for (const modifier of ["Shift", "Control", "Alt", "Meta"]) {
          if (modifier == "Meta" && !navigator.platform.includes("Mac")) {
            continue; // Delete this after fixing bug 1232918.
          }
          await (async function modifiersPreventToStartAutoScrolling() {
            info(
              `Waiting to check not to open autoscroller popup with middle button click with ${modifier}`
            );
            await promiseFlushLayoutInContent();
            let eventsInContent = new ContentEventCounter(browser, [
              "click",
              "auxclick",
              "mousedown",
              "mouseup",
              "paste",
            ]);
            // Ensure that the event listeners added in the content with accessing
            // the remote content.
            await promiseFlushLayoutInContent();
            await EventUtils.promiseNativeMouseEvent({
              type: "mousemove",
              target: browser,
              atCenter: true,
            });
            info(
              `Waiting to MozAutoScrollNoStart event for the middle button click with ${modifier}`
            );
            await EventUtils.promiseNativeMouseEvent({
              type: "mousedown",
              target: browser,
              atCenter: true,
              button: 1, // middle button
              modifiers: {
                altKey: modifier == "Alt",
                ctrlKey: modifier == "Control",
                metaKey: modifier == "Meta",
                shiftKey: modifier == "Shift",
              },
            });
            try {
              await TestUtils.waitForCondition(
                () => autoScroller?.state == "open",
                `Waiting to check not to open autoscroller popup with ${modifier}`,
                100,
                10
              );
              ok(
                false,
                `The autoscroller popup shouldn't be opened by middle click with ${modifier}`
              );
            } catch (ex) {
              ok(
                true,
                `The autoscroller popup was not open as expected after middle click with ${modifier}`
              );
            }
            // In the wild, native "mouseup" event occurs after the popup is open.
            await EventUtils.promiseNativeMouseEvent({
              type: "mouseup",
              target: browser,
              atCenter: true,
              button: 1, // middle button
            });
            await promiseFlushLayoutInContent();
            await promiseContentTick();
            await eventsInContent.promiseMouseEvents(
              ["paste"],
              `At middle clicking with ${modifier}`
            );
            for (let eventType of [
              "mousedown",
              "mouseup",
              "click",
              "auxclick",
              "paste",
            ]) {
              is(
                eventsInContent.getCountAndRemoveEventListener(eventType),
                1,
                `"${eventType}" event should be fired in the content when a middle click with ${modifier}`
              );
            }
            info(
              "Waiting autoscroller close for preparing the following tests"
            );
          })();
        }
      }

      async function doTestMouseEventsAtStoppingAutoScrolling({
        aButton = 0,
        aClickOutsideAutoScroller = false,
        aDescription = "Unspecified",
      }) {
        info(
          `Starting autoscrolling for testing to stop autoscrolling with ${aDescription}`
        );
        await promiseFlushLayoutInContent();
        await EventUtils.promiseNativeMouseEvent({
          type: "mousemove",
          target: browser,
          atCenter: true,
        });
        const waitForOpenAutoScroll = promiseWaitForAutoScrollerOpen();
        await EventUtils.promiseNativeMouseEvent({
          type: "mousedown",
          target: browser,
          atCenter: true,
          button: 1, // middle button
        });
        // In the wild, native "mouseup" event occurs after the popup is open.
        await waitForOpenAutoScroll;
        await EventUtils.promiseNativeMouseEvent({
          type: "mouseup",
          target: browser,
          atCenter: true,
          button: 1, // middle button
        });
        await promiseFlushLayoutInContent();
        // Just to be sure, wait for a tick for wait APZ stable.
        await TestUtils.waitForTick();

        let eventsInContent = new ContentEventCounter(browser, [
          "click",
          "auxclick",
          "mousedown",
          "mouseup",
          "paste",
          "contextmenu",
        ]);
        // Ensure that the event listeners added in the content with accessing
        // the remote content.
        await promiseFlushLayoutInContent();

        aDescription = `Stop autoscrolling with ${aDescription}`;
        info(
          `${aDescription}: Synthesizing primary mouse button event on the autoscroller`
        );
        const autoScrollerRect = autoScroller.getOuterScreenRect();
        info(
          `${aDescription}: autoScroller: { left: ${autoScrollerRect.left}, top: ${autoScrollerRect.top}, width: ${autoScrollerRect.width}, height: ${autoScrollerRect.height} }`
        );
        const waitForCloseAutoScroller = promiseWaitForAutoScrollerClosed();
        if (aClickOutsideAutoScroller) {
          info(
            `${aDescription}: Synthesizing mousemove move cursor outside the autoscroller...`
          );
          await EventUtils.promiseNativeMouseEvent({
            type: "mousemove",
            target: autoScroller,
            offsetX: -10,
            offsetY: -10,
            elementOnWidget: browser, // use widget for the parent window of the autoscroller
          });
          info(
            `${aDescription}: Synthesizing mousedown to stop autoscrolling...`
          );
          await EventUtils.promiseNativeMouseEvent({
            type: "mousedown",
            target: autoScroller,
            offsetX: -10,
            offsetY: -10,
            button: aButton,
            elementOnWidget: browser, // use widget for the parent window of the autoscroller
          });
        } else {
          info(
            `${aDescription}: Synthesizing mousemove move cursor onto the autoscroller...`
          );
          await EventUtils.promiseNativeMouseEvent({
            type: "mousemove",
            target: autoScroller,
            atCenter: true,
            elementOnWidget: browser, // use widget for the parent window of the autoscroller
          });
          info(
            `${aDescription}: Synthesizing mousedown to stop autoscrolling...`
          );
          await EventUtils.promiseNativeMouseEvent({
            type: "mousedown",
            target: autoScroller,
            atCenter: true,
            button: aButton,
            elementOnWidget: browser, // use widget for the parent window of the autoscroller
          });
        }
        // In the wild, native "mouseup" event occurs after the popup is closed.
        await waitForCloseAutoScroller;
        info(
          `${aDescription}: Synthesizing mouseup event for preceding mousedown which is for stopping autoscrolling`
        );
        await EventUtils.promiseNativeMouseEvent({
          type: "mouseup",
          target: browser,
          atCenter: true,
          button: aButton,
        });
        await promiseFlushLayoutInContent();
        await promiseContentTick();
        await eventsInContent.promiseMouseEvents(
          aButton != 2 ? ["mouseup"] : ["mouseup", "contextmenu"],
          aDescription
        );
        is(
          autoScroller.state,
          "closed",
          `${aDescription}: The autoscroller should've been closed`
        );
        // - On macOS, when clicking outside autoscroller, nsChildView
        // intentionally blocks both "mousedown" and "mouseup" events in the
        // case of the primary button click, and only "mousedown" for the
        // middle button when the "mousedown".  I'm not sure how it should work
        // on macOS for conforming to the platform manner.  Note that autoscroll
        // isn't available on the other browsers on macOS.  So, there is no
        // reference, but for consistency between platforms, it may be better
        // to ignore the platform manner.
        // - On Windows, when clicking outside autoscroller, nsWindow
        // intentionally blocks only "mousedown" events for the primary button
        // and the middle button.  But this behavior is different from Chrome
        // so that we need to fix this in the future.
        // - On Linux, when clicking outside autoscroller, nsWindow
        // intentionally blocks only "mousedown" events for any buttons.  But
        // on Linux, autoscroll isn't available by the default settings.  So,
        // not so urgent, but should be fixed in the future for consistency
        // between platforms and compatibility with Chrome on Windows.
        const rollingUpPopupConsumeMouseDown =
          aClickOutsideAutoScroller &&
          (aButton != 2 || navigator.platform.includes("Linux"));
        const rollingUpPopupConsumeMouseUp =
          aClickOutsideAutoScroller &&
          aButton == 0 &&
          navigator.platform.includes("Mac");
        const checkFuncForClick =
          aClickOutsideAutoScroller &&
          aButton == 2 &&
          !navigator.platform.includes("Linux")
            ? todo_is
            : is;
        for (let eventType of ["click", "auxclick"]) {
          checkFuncForClick(
            eventsInContent.getCountAndRemoveEventListener(eventType),
            0,
            `${aDescription}: "${eventType}" event shouldn't be fired in the remote content`
          );
        }
        is(
          eventsInContent.getCountAndRemoveEventListener("paste"),
          0,
          `${aDescription}: "paste" event shouldn't be fired in the remote content`
        );
        const checkFuncForMouseDown = rollingUpPopupConsumeMouseDown
          ? todo_is
          : is;
        checkFuncForMouseDown(
          eventsInContent.getCountAndRemoveEventListener("mousedown"),
          1,
          `${aDescription}: "mousedown" event should be fired in the remote content`
        );
        const checkFuncForMouseUp = rollingUpPopupConsumeMouseUp ? todo_is : is;
        checkFuncForMouseUp(
          eventsInContent.getCountAndRemoveEventListener("mouseup"),
          1,
          `${aDescription}: "mouseup" event should be fired in the remote content`
        );
        const checkFuncForContextMenu =
          aButton == 2 &&
          aClickOutsideAutoScroller &&
          navigator.platform.includes("Linux")
            ? todo_is
            : is;
        checkFuncForContextMenu(
          eventsInContent.getCountAndRemoveEventListener("contextmenu"),
          aButton == 2 ? 1 : 0,
          `${aDescription}: "contextmenu" event should${
            aButton != 2 ? " not" : ""
          } be fired in the remote content`
        );

        const promiseClickEvent = BrowserTestUtils.waitForContentEvent(
          browser,
          "click",
          {
            capture: true,
          }
        );
        await promiseFlushLayoutInContent();
        info(`${aDescription}: Waiting for click event in the remote content`);
        EventUtils.synthesizeNativeMouseEvent({
          type: "click",
          target: browser,
          atCenter: true,
        });
        await promiseClickEvent;
        ok(
          true,
          `${aDescription}: click event is fired in the remote content after stopping autoscrolling`
        );
      }

      // Clicking the primary button to stop autoscrolling.
      await doTestMouseEventsAtStoppingAutoScrolling({
        aButton: 0,
        aClickOutsideAutoScroller: false,
        aDescription: "a primary button click on autoscroller",
      });
      await doTestMouseEventsAtStoppingAutoScrolling({
        aButton: 0,
        aClickOutsideAutoScroller: true,
        aDescription: "a primary button click outside autoscroller",
      });

      // Clicking the secondary button to stop autoscrolling.
      await doTestMouseEventsAtStoppingAutoScrolling({
        aButton: 2,
        aClickOutsideAutoScroller: false,
        aDescription: "a secondary button click on autoscroller",
      });
      await doTestMouseEventsAtStoppingAutoScrolling({
        aButton: 2,
        aClickOutsideAutoScroller: true,
        aDescription: "a secondary button click outside autoscroller",
      });

      // Clicking the middle button to stop autoscrolling.
      await SpecialPowers.pushPrefEnv({ set: [["middlemouse.paste", true]] });
      await doTestMouseEventsAtStoppingAutoScrolling({
        aButton: 1,
        aClickOutsideAutoScroller: false,
        aDescription:
          "a middle button click on autoscroller (middle click paste enabled)",
      });
      await doTestMouseEventsAtStoppingAutoScrolling({
        aButton: 1,
        aClickOutsideAutoScroller: true,
        aDescription:
          "a middle button click outside autoscroller (middle click paste enabled)",
      });
      await SpecialPowers.pushPrefEnv({ set: [["middlemouse.paste", false]] });
      await doTestMouseEventsAtStoppingAutoScrolling({
        aButton: 1,
        aClickOutsideAutoScroller: false,
        aDescription:
          "a middle button click on autoscroller (middle click paste disabled)",
      });
      await doTestMouseEventsAtStoppingAutoScrolling({
        aButton: 1,
        aClickOutsideAutoScroller: true,
        aDescription:
          "a middle button click outside autoscroller (middle click paste disabled)",
      });
    }
  );
});