summaryrefslogtreecommitdiffstats
path: root/browser/base/content/test/popups/head.js
blob: f72bba7dca42057fb080f6efcf5a50a108ff3077 (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
/* Any copyright is dedicated to the Public Domain.
   http://creativecommons.org/publicdomain/zero/1.0/ */

"use strict";

const gfxInfo = Cc["@mozilla.org/gfx/info;1"].getService(
  SpecialPowers.Ci.nsIGfxInfo
);

async function waitForBlockedPopups(numberOfPopups, { doc }) {
  let toolbarDoc = doc || document;
  let menupopup = toolbarDoc.getElementById("blockedPopupOptions");
  await BrowserTestUtils.waitForCondition(() => {
    let popups = menupopup.querySelectorAll("[popupReportIndex]");
    return popups.length == numberOfPopups;
  }, `Waiting for ${numberOfPopups} popups`);
}

/*
 * Tests that a sequence of size changes ultimately results in the latest
 * requested size. The test also fails when an unexpected window size is
 * observed in a resize event.
 *
 * aPropertyDeltas    List of objects where keys describe the name of a window
 *                    property and the values the difference to its initial
 *                    value.
 *
 * aInstant           Issue changes without additional waiting in between.
 *
 * A brief example of the resutling code that is effectively run for the
 * following list of deltas:
 * [{outerWidth: 5, outerHeight: 10}, {outerWidth: 10}]
 *
 * let initialWidth = win.outerWidth;
 * let initialHeight = win.outerHeight;
 *
 * if (aInstant) {
 *   win.outerWidth = initialWidth + 5;
 *   win.outerHeight = initialHeight + 10;
 *
 *   win.outerWidth = initialWidth + 10;
 * } else {
 *   win.requestAnimationFrame(() => {
 *     win.outerWidth = initialWidth + 5;
 *     win.outerHeight = initialHeight + 10;
 *
 *     win.requestAnimationFrame(() => {
 *        win.outerWidth = initialWidth + 10;
 *     });
 *   });
 * }
 */
async function testPropertyDeltas(
  aPropertyDeltas,
  aInstant,
  aPropInfo,
  aMsg,
  aWaitForCompletion
) {
  let msg = `[${aMsg}]`;

  let win = this.content.popup || this.content.wrappedJSObject;

  // Property names and mapping from ResizeMoveTest
  let {
    sizeProps,
    positionProps /* can be empty/incomplete as workaround on Linux */,
    readonlyProps,
    crossBoundsMapping,
  } = aPropInfo;

  let stringifyState = state => {
    let stateMsg = sizeProps
      .concat(positionProps)
      .filter(prop => state[prop] !== undefined)
      .map(prop => `${prop}: ${state[prop]}`)
      .join(", ");
    return `{ ${stateMsg} }`;
  };

  let initialState = {};
  let finalState = {};

  info("Initializing all values to current state.");
  for (let prop of sizeProps.concat(positionProps)) {
    let value = win[prop];
    initialState[prop] = value;
    finalState[prop] = value;
  }

  // List of potential states during resize events. The current state is also
  // considered valid, as the resize event might still be outstanding.
  let validResizeStates = [initialState];

  let updateFinalState = (aProp, aDelta) => {
    if (
      readonlyProps.includes(aProp) ||
      !sizeProps.concat(positionProps).includes(aProp)
    ) {
      throw new Error(`Unexpected property "${aProp}".`);
    }

    // Update both properties of the same axis.
    let otherProp = crossBoundsMapping[aProp];
    finalState[aProp] = initialState[aProp] + aDelta;
    finalState[otherProp] = initialState[otherProp] + aDelta;

    // Mark size as valid in resize event.
    if (sizeProps.includes(aProp)) {
      let state = {};
      sizeProps.forEach(p => (state[p] = finalState[p]));
      validResizeStates.push(state);
    }
  };

  info("Adding resize event listener.");
  let resizeCount = 0;
  let resizeListener = evt => {
    resizeCount++;

    let currentSizeState = {};
    sizeProps.forEach(p => (currentSizeState[p] = win[p]));

    info(
      `${msg} ${resizeCount}. resize event: ${stringifyState(currentSizeState)}`
    );
    let matchingIndex = validResizeStates.findIndex(state =>
      sizeProps.every(p => state[p] == currentSizeState[p])
    );
    if (matchingIndex < 0) {
      info(`${msg} Size state should have been one of:`);
      for (let state of validResizeStates) {
        info(stringifyState(state));
      }
    }

    if (win.gBrowser && evt.target != win) {
      // Without e10s we receive content resize events in chrome windows.
      todo(false, `${msg} Resize event target is our window.`);
      return;
    }

    ok(
      matchingIndex >= 0,
      `${msg} Valid intermediate state. Current: ` +
        stringifyState(currentSizeState)
    );

    // No longer allow current and preceding states.
    validResizeStates.splice(0, matchingIndex + 1);
  };
  win.addEventListener("resize", resizeListener);

  const useProperties = !Services.prefs.getBoolPref(
    "dom.window_position_size_properties_replaceable.enabled",
    true
  );

  info("Starting property changes.");
  await new Promise(resolve => {
    let index = 0;
    let next = async () => {
      let pre = `${msg} [${index + 1}/${aPropertyDeltas.length}]`;

      let deltaObj = aPropertyDeltas[index];
      for (let prop in deltaObj) {
        updateFinalState(prop, deltaObj[prop]);

        let targetValue = initialState[prop] + deltaObj[prop];
        info(`${pre} Setting ${prop} to ${targetValue}.`);
        if (useProperties) {
          win[prop] = targetValue;
        } else if (sizeProps.includes(prop)) {
          win.resizeTo(finalState.outerWidth, finalState.outerHeight);
        } else {
          win.moveTo(finalState.screenX, finalState.screenY);
        }
        if (aWaitForCompletion) {
          await ContentTaskUtils.waitForCondition(
            () => win[prop] == targetValue,
            `${msg} Waiting for ${prop} to be ${targetValue}.`
          );
        }
      }

      index++;
      if (index < aPropertyDeltas.length) {
        scheduleNext();
      } else {
        resolve();
      }
    };

    let scheduleNext = () => {
      if (aInstant) {
        next();
      } else {
        info(`${msg} Requesting animation frame.`);
        win.requestAnimationFrame(next);
      }
    };
    scheduleNext();
  });

  try {
    info(`${msg} Waiting for window to match the final state.`);
    await ContentTaskUtils.waitForCondition(
      () => sizeProps.concat(positionProps).every(p => win[p] == finalState[p]),
      "Waiting for final state."
    );
  } catch (e) {}

  info(`${msg} Checking final state.`);
  info(`${msg} Exepected: ${stringifyState(finalState)}`);
  info(`${msg} Actual:    ${stringifyState(win)}`);
  for (let prop of sizeProps.concat(positionProps)) {
    is(win[prop], finalState[prop], `${msg} Expected final value for ${prop}`);
  }

  win.removeEventListener("resize", resizeListener);
}

function roundedCenter(aDimension, aOrigin) {
  let center = aOrigin + Math.floor(aDimension / 2);
  return center - (center % 100);
}

class ResizeMoveTest {
  static WindowWidth = 200;
  static WindowHeight = 200;
  static WindowLeft = roundedCenter(screen.availWidth - 200, screen.left);
  static WindowTop = roundedCenter(screen.availHeight - 200, screen.top);

  static PropInfo = {
    sizeProps: ["outerWidth", "outerHeight", "innerWidth", "innerHeight"],
    positionProps: [
      "screenX",
      "screenY",
      /* readonly */ "mozInnerScreenX",
      /* readonly */ "mozInnerScreenY",
    ],
    readonlyProps: ["mozInnerScreenX", "mozInnerScreenY"],
    crossAxisMapping: {
      outerWidth: "outerHeight",
      outerHeight: "outerWidth",
      innerWidth: "innerHeight",
      innerHeight: "innerWidth",
      screenX: "screenY",
      screenY: "screenX",
      mozInnerScreenX: "mozInnerScreenY",
      mozInnerScreenY: "mozInnerScreenX",
    },
    crossBoundsMapping: {
      outerWidth: "innerWidth",
      outerHeight: "innerHeight",
      innerWidth: "outerWidth",
      innerHeight: "outerHeight",
      screenX: "mozInnerScreenX",
      screenY: "mozInnerScreenY",
      mozInnerScreenX: "screenX",
      mozInnerScreenY: "screenY",
    },
  };

  constructor(
    aPropertyDeltas,
    aInstant = false,
    aMsg = "ResizeMoveTest",
    aWaitForCompletion = false
  ) {
    this.propertyDeltas = aPropertyDeltas;
    this.instant = aInstant;
    this.msg = aMsg;
    this.waitForCompletion = aWaitForCompletion;

    // Allows to ignore positions while testing.
    this.ignorePositions = false;
    // Allows to ignore only mozInnerScreenX/Y properties while testing.
    this.ignoreMozInnerScreen = false;
    // Allows to skip checking the restored position after testing.
    this.ignoreRestoredPosition = false;

    if (AppConstants.platform == "linux" && !SpecialPowers.isHeadless) {
      // We can occasionally start the test while nsWindow reports a wrong
      // client offset (gdk origin and root_origin are out of sync). This
      // results in false expectations for the final mozInnerScreenX/Y values.
      this.ignoreMozInnerScreen = !ResizeMoveTest.hasCleanUpTask;

      let { positionProps } = ResizeMoveTest.PropInfo;
      let resizeOnlyTest = aPropertyDeltas.every(deltaObj =>
        positionProps.every(prop => deltaObj[prop] === undefined)
      );

      let isWayland = gfxInfo.windowProtocol == "wayland";
      if (resizeOnlyTest && isWayland) {
        // On Wayland we can't move the window in general. The window also
        // doesn't necessarily open our specified position.
        this.ignoreRestoredPosition = true;
        // We can catch bad screenX/Y at the start of the first test in a
        // window.
        this.ignorePositions = !ResizeMoveTest.hasCleanUpTask;
      }
    }

    if (!ResizeMoveTest.hasCleanUpTask) {
      ResizeMoveTest.hasCleanUpTask = true;
      registerCleanupFunction(ResizeMoveTest.Cleanup);
    }

    add_task(async () => {
      let tab = await ResizeMoveTest.GetOrCreateTab();
      let browsingContext =
        await ResizeMoveTest.GetOrCreatePopupBrowsingContext();
      if (!browsingContext) {
        return;
      }

      info("=== Running in content. ===");
      await this.run(browsingContext, `${this.msg} (content)`);
      await this.restorePopupState(browsingContext);

      info("=== Running in chrome. ===");
      let popupChrome = browsingContext.topChromeWindow;
      await this.run(popupChrome.browsingContext, `${this.msg} (chrome)`);
      await this.restorePopupState(browsingContext);

      info("=== Running in opener. ===");
      await this.run(tab.linkedBrowser, `${this.msg} (opener)`);
      await this.restorePopupState(browsingContext);
    });
  }

  async run(aBrowsingContext, aMsg) {
    let testType = this.instant ? "instant" : "fanned out";
    let msg = `${aMsg} (${testType})`;

    let propInfo = {};
    for (let k in ResizeMoveTest.PropInfo) {
      propInfo[k] = ResizeMoveTest.PropInfo[k];
    }
    if (this.ignoreMozInnerScreen) {
      todo(false, `[${aMsg}] Shouldn't ignore mozInnerScreenX/Y.`);
      propInfo.positionProps = propInfo.positionProps.filter(
        prop => !["mozInnerScreenX", "mozInnerScreenY"].includes(prop)
      );
    }
    if (this.ignorePositions) {
      todo(false, `[${aMsg}] Shouldn't ignore position.`);
      propInfo.positionProps = [];
    }

    info(`${msg}: ` + JSON.stringify(this.propertyDeltas));
    await SpecialPowers.spawn(
      aBrowsingContext,
      [
        this.propertyDeltas,
        this.instant,
        propInfo,
        msg,
        this.waitForCompletion,
      ],
      testPropertyDeltas
    );
  }

  async restorePopupState(aBrowsingContext) {
    info("Restore popup state.");

    let { deltaWidth, deltaHeight } = await SpecialPowers.spawn(
      aBrowsingContext,
      [],
      () => {
        return {
          deltaWidth: this.content.outerWidth - this.content.innerWidth,
          deltaHeight: this.content.outerHeight - this.content.innerHeight,
        };
      }
    );

    let chromeWindow = aBrowsingContext.topChromeWindow;
    let {
      WindowLeft: left,
      WindowTop: top,
      WindowWidth: width,
      WindowHeight: height,
    } = ResizeMoveTest;

    chromeWindow.resizeTo(width + deltaWidth, height + deltaHeight);
    chromeWindow.moveTo(left, top);

    await SpecialPowers.spawn(
      aBrowsingContext,
      [left, top, width, height, this.ignoreRestoredPosition],
      async (aLeft, aTop, aWidth, aHeight, aIgnorePosition) => {
        let win = this.content.wrappedJSObject;

        info("Waiting for restored size.");
        await ContentTaskUtils.waitForCondition(
          () => win.innerWidth == aWidth && win.innerHeight === aHeight,
          "Waiting for restored size."
        );
        is(win.innerWidth, aWidth, "Restored width.");
        is(win.innerHeight, aHeight, "Restored height.");

        if (!aIgnorePosition) {
          info("Waiting for restored position.");
          await ContentTaskUtils.waitForCondition(
            () => win.screenX == aLeft && win.screenY === aTop,
            "Waiting for restored position."
          );
          is(win.screenX, aLeft, "Restored screenX.");
          is(win.screenY, aTop, "Restored screenY.");
        } else {
          todo(false, "Shouldn't ignore restored position.");
        }
      }
    );
  }

  static async GetOrCreateTab() {
    if (ResizeMoveTest.tab) {
      return ResizeMoveTest.tab;
    }

    info("Opening tab.");
    ResizeMoveTest.tab = await BrowserTestUtils.openNewForegroundTab(
      window.gBrowser,
      "https://example.net/browser/browser/base/content/test/popups/popup_blocker_a.html"
    );
    return ResizeMoveTest.tab;
  }

  static async GetOrCreatePopupBrowsingContext() {
    if (ResizeMoveTest.popupBrowsingContext) {
      if (!ResizeMoveTest.popupBrowsingContext.isActive) {
        return undefined;
      }
      return ResizeMoveTest.popupBrowsingContext;
    }

    let tab = await ResizeMoveTest.GetOrCreateTab();
    info("Opening popup.");
    ResizeMoveTest.popupBrowsingContext = await SpecialPowers.spawn(
      tab.linkedBrowser,
      [
        ResizeMoveTest.WindowWidth,
        ResizeMoveTest.WindowHeight,
        ResizeMoveTest.WindowLeft,
        ResizeMoveTest.WindowTop,
      ],
      async (aWidth, aHeight, aLeft, aTop) => {
        let win = this.content.open(
          this.content.document.location.href,
          "_blank",
          `left=${aLeft},top=${aTop},width=${aWidth},height=${aHeight}`
        );
        this.content.popup = win;

        await new Promise(r => (win.onload = r));

        return win.browsingContext;
      }
    );

    return ResizeMoveTest.popupBrowsingContext;
  }

  static async Cleanup() {
    let browsingContext = ResizeMoveTest.popupBrowsingContext;
    if (browsingContext) {
      await SpecialPowers.spawn(browsingContext, [], () => {
        this.content.close();
      });
      delete ResizeMoveTest.popupBrowsingContext;
    }

    let tab = ResizeMoveTest.tab;
    if (tab) {
      await BrowserTestUtils.removeTab(tab);
      delete ResizeMoveTest.tab;
    }
    ResizeMoveTest.hasCleanUpTask = false;
  }
}

function chaosRequestLongerTimeout(aDoRequest) {
  if (aDoRequest && parseInt(Services.env.get("MOZ_CHAOSMODE"), 16)) {
    requestLongerTimeout(2);
  }
}

function createGenericResizeTests(aFirstValue, aSecondValue, aInstant, aMsg) {
  // Runtime almost doubles in chaos mode on Mac.
  chaosRequestLongerTimeout(AppConstants.platform == "macosx");

  let { crossBoundsMapping, crossAxisMapping } = ResizeMoveTest.PropInfo;

  for (let prop of ["innerWidth", "outerHeight"]) {
    // Mixing inner and outer property.
    for (let secondProp of [prop, crossBoundsMapping[prop]]) {
      let first = {};
      first[prop] = aFirstValue;
      let second = {};
      second[secondProp] = aSecondValue;
      new ResizeMoveTest(
        [first, second],
        aInstant,
        `${aMsg} ${prop},${secondProp}`
      );
    }
  }

  for (let prop of ["innerHeight", "outerWidth"]) {
    let first = {};
    first[prop] = aFirstValue;
    let second = {};
    second[prop] = aSecondValue;

    // Setting property of other axis before/between two changes.
    let otherProps = [
      crossAxisMapping[prop],
      crossAxisMapping[crossBoundsMapping[prop]],
    ];
    for (let interferenceProp of otherProps) {
      let interference = {};
      interference[interferenceProp] = 20;
      new ResizeMoveTest(
        [first, interference, second],
        aInstant,
        `${aMsg} ${prop},${interferenceProp},${prop}`
      );
      new ResizeMoveTest(
        [interference, first, second],
        aInstant,
        `${aMsg} ${interferenceProp},${prop},${prop}`
      );
    }
  }
}

function createGenericMoveTests(aInstant, aMsg) {
  // Runtime almost doubles in chaos mode on Mac.
  chaosRequestLongerTimeout(AppConstants.platform == "macosx");

  let { crossAxisMapping } = ResizeMoveTest.PropInfo;

  for (let prop of ["screenX", "screenY"]) {
    for (let [v1, v2, msg] of [
      [9, 10, `${aMsg}`],
      [11, 11, `${aMsg} repeat`],
      [12, 0, `${aMsg} revert`],
    ]) {
      let first = {};
      first[prop] = v1;
      let second = {};
      second[prop] = v2;
      new ResizeMoveTest([first, second], aInstant, `${msg} ${prop},${prop}`);

      let interferenceProp = crossAxisMapping[prop];
      let interference = {};
      interference[interferenceProp] = 20;
      new ResizeMoveTest(
        [first, interference, second],
        aInstant,
        `${aMsg} ${prop},${interferenceProp},${prop}`
      );
      new ResizeMoveTest(
        [interference, first, second],
        aInstant,
        `${msg} ${interferenceProp},${prop},${prop}`
      );
    }
  }
}