summaryrefslogtreecommitdiffstats
path: root/browser/components/urlbar/tests/browser-tips/browser_searchTips_interaction.js
blob: 7e4f0bbc65595fadc372d8c4048f5e5263e6d180 (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
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
/* Any copyright is dedicated to the Public Domain.
 * http://creativecommons.org/publicdomain/zero/1.0/ */

// Tests the Search Tips feature, which displays a prompt to use the Urlbar on
// the newtab page and on the user's default search engine's homepage.
// Specifically, it tests that the Tips appear when they should be appearing.
// This doesn't test the max-shown-count limit because it requires restarting
// the browser.

"use strict";

ChromeUtils.defineESModuleGetters(this, {
  AppMenuNotifications: "resource://gre/modules/AppMenuNotifications.sys.mjs",
  ProfileAge: "resource://gre/modules/ProfileAge.sys.mjs",
  UrlbarPrefs: "resource:///modules/UrlbarPrefs.sys.mjs",
  UrlbarProviderSearchTips:
    "resource:///modules/UrlbarProviderSearchTips.sys.mjs",
  UrlbarUtils: "resource:///modules/UrlbarUtils.sys.mjs",
});

XPCOMUtils.defineLazyModuleGetters(this, {
  HttpServer: "resource://testing-common/httpd.js",
});

XPCOMUtils.defineLazyServiceGetter(
  this,
  "clipboardHelper",
  "@mozilla.org/widget/clipboardhelper;1",
  "nsIClipboardHelper"
);

// These should match the same consts in UrlbarProviderSearchTips.jsm.
const MAX_SHOWN_COUNT = 4;
const LAST_UPDATE_THRESHOLD_MS = 24 * 60 * 60 * 1000;

// We test some of the bigger Google domains.
const GOOGLE_DOMAINS = [
  "www.google.com",
  "www.google.ca",
  "www.google.co.uk",
  "www.google.com.au",
  "www.google.co.nz",
];

// In order for the persist tip to appear, the scheme of the
// search engine has to be the same as the scheme of the SERP url.
// withDNSRedirect() loads an http: url while the searchform
// of the default engine uses https. To enable the search term
// to be shown, we use the Example engine because it doesn't require
// a redirect.
const SEARCH_TERM = "chocolate";
const SEARCH_SERP_URL = `https://example.com/?q=${SEARCH_TERM}`;

add_setup(async function() {
  await PlacesUtils.history.clear();
  await PlacesUtils.bookmarks.eraseEverything();

  await SpecialPowers.pushPrefEnv({
    set: [
      [
        `browser.urlbar.tipShownCount.${UrlbarProviderSearchTips.TIP_TYPE.ONBOARD}`,
        0,
      ],
      [
        `browser.urlbar.tipShownCount.${UrlbarProviderSearchTips.TIP_TYPE.PERSIST}`,
        0,
      ],
      [
        `browser.urlbar.tipShownCount.${UrlbarProviderSearchTips.TIP_TYPE.REDIRECT}`,
        0,
      ],
    ],
  });

  // Write an old profile age so tips are actually shown.
  let age = await ProfileAge();
  let originalTimes = age._times;
  let date = Date.now() - LAST_UPDATE_THRESHOLD_MS - 30000;
  age._times = { created: date, firstUse: date };
  await age.writeTimes();

  // Remove update history and the current active update so tips are shown.
  let updateRootDir = Services.dirsvc.get("UpdRootD", Ci.nsIFile);
  let updatesFile = updateRootDir.clone();
  updatesFile.append("updates.xml");
  let activeUpdateFile = updateRootDir.clone();
  activeUpdateFile.append("active-update.xml");
  try {
    updatesFile.remove(false);
  } catch (e) {}
  try {
    activeUpdateFile.remove(false);
  } catch (e) {}

  let defaultEngine = await Services.search.getDefault();
  let defaultEngineName = defaultEngine.name;
  Assert.equal(defaultEngineName, "Google", "Default engine should be Google.");

  // Add a mock engine so we don't hit the network loading the SERP.
  await SearchTestUtils.installSearchExtension();

  registerCleanupFunction(async () => {
    let age2 = await ProfileAge();
    age2._times = originalTimes;
    await age2.writeTimes();
    await setDefaultEngine(defaultEngineName);
    resetSearchTipsProvider();
  });
});

// Picking the tip's button should cause the Urlbar to blank out and the tip to
// be not to be shown again in any session. Telemetry should be updated.
add_task(async function pickButton_onboard() {
  UrlbarProviderSearchTips.disableTipsForCurrentSession = false;
  await SpecialPowers.pushPrefEnv({
    set: [["browser.urlbar.eventTelemetry.enabled", true]],
  });

  Services.telemetry.clearEvents();
  let tab = await BrowserTestUtils.openNewForegroundTab({
    gBrowser,
    url: "about:newtab",
    waitForLoad: false,
  });
  await checkTip(window, UrlbarProviderSearchTips.TIP_TYPE.ONBOARD, false);

  // Click the tip button.
  let result = await UrlbarTestUtils.getDetailsOfResultAt(window, 0);
  let button = result.element.row._buttons.get("0");
  await UrlbarTestUtils.promisePopupClose(window, () => {
    EventUtils.synthesizeMouseAtCenter(button, {});
  });
  gURLBar.blur();

  // Check telemetry.
  const scalars = TelemetryTestUtils.getProcessScalars("parent", true, true);
  TelemetryTestUtils.assertKeyedScalar(
    scalars,
    "urlbar.tips",
    `${UrlbarProviderSearchTips.TIP_TYPE.ONBOARD}-picked`,
    1
  );
  TelemetryTestUtils.assertEvents(
    [
      {
        category: "urlbar",
        method: "engagement",
        object: "click",
        value: "typed",
      },
    ],
    { category: "urlbar" }
  );

  Assert.equal(
    UrlbarPrefs.get(
      `tipShownCount.${UrlbarProviderSearchTips.TIP_TYPE.ONBOARD}`
    ),
    MAX_SHOWN_COUNT,
    "Onboarding tips are disabled after tip button is picked."
  );
  Assert.equal(gURLBar.value, "", "The Urlbar should be empty.");
  resetSearchTipsProvider();

  BrowserTestUtils.removeTab(tab);
  await SpecialPowers.popPrefEnv();
});

// Picking the tip's button should cause the Urlbar to blank out and the tip to
// be not to be shown again in any session. Telemetry should be updated.
add_task(async function pickButton_redirect() {
  UrlbarProviderSearchTips.disableTipsForCurrentSession = false;
  await SpecialPowers.pushPrefEnv({
    set: [["browser.urlbar.eventTelemetry.enabled", true]],
  });
  Services.telemetry.clearEvents();

  await setDefaultEngine("Google");
  await BrowserTestUtils.withNewTab("about:blank", async () => {
    await withDNSRedirect("www.google.com", "/", async url => {
      BrowserTestUtils.loadURI(gBrowser.selectedBrowser, url);
      await BrowserTestUtils.browserLoaded(gBrowser.selectedBrowser);
      await checkTip(window, UrlbarProviderSearchTips.TIP_TYPE.REDIRECT, false);

      // Click the tip button.
      let result = await UrlbarTestUtils.getDetailsOfResultAt(window, 0);
      let button = result.element.row._buttons.get("0");
      await UrlbarTestUtils.promisePopupClose(window, () => {
        EventUtils.synthesizeMouseAtCenter(button, {});
      });
      gURLBar.blur();
    });
  });

  // Check telemetry.
  const scalars = TelemetryTestUtils.getProcessScalars("parent", true, true);
  TelemetryTestUtils.assertKeyedScalar(
    scalars,
    "urlbar.tips",
    `${UrlbarProviderSearchTips.TIP_TYPE.REDIRECT}-picked`,
    1
  );
  TelemetryTestUtils.assertEvents(
    [
      {
        category: "urlbar",
        method: "engagement",
        object: "click",
        value: "typed",
      },
    ],
    { category: "urlbar" }
  );

  Assert.equal(
    UrlbarPrefs.get(
      `tipShownCount.${UrlbarProviderSearchTips.TIP_TYPE.REDIRECT}`
    ),
    MAX_SHOWN_COUNT,
    "Redirect tips are disabled after tip button is picked."
  );
  Assert.equal(gURLBar.value, "", "The Urlbar should be empty.");
  resetSearchTipsProvider();
  await SpecialPowers.popPrefEnv();
});

// Picking the tip's button should cause the Urlbar to keep its current
// value and the tip to be not to be shown again in any session.
// Telemetry should be updated.
add_task(async function pickButton_persist() {
  UrlbarProviderSearchTips.disableTipsForCurrentSession = false;
  await SpecialPowers.pushPrefEnv({
    set: [
      ["browser.urlbar.eventTelemetry.enabled", true],
      ["browser.urlbar.showSearchTerms.featureGate", true],
    ],
  });
  Services.telemetry.clearEvents();

  await setDefaultEngine("Example");

  await BrowserTestUtils.withNewTab("about:blank", async () => {
    let browserLoadedPromise = BrowserTestUtils.browserLoaded(
      gBrowser.selectedBrowser,
      false,
      SEARCH_SERP_URL
    );
    BrowserTestUtils.loadURI(gBrowser.selectedBrowser, SEARCH_SERP_URL);
    await browserLoadedPromise;
    await checkTip(window, UrlbarProviderSearchTips.TIP_TYPE.PERSIST, false);

    let result = await UrlbarTestUtils.getDetailsOfResultAt(window, 0);
    let button = result.element.row._buttons.get("0");

    await UrlbarTestUtils.promisePopupClose(window, () => {
      EventUtils.synthesizeMouseAtCenter(button, {});
    });
    gURLBar.blur();

    Assert.equal(
      gURLBar.value,
      SEARCH_TERM,
      "The Urlbar should keep its existing value."
    );
  });

  // Check telemetry.
  const scalars = TelemetryTestUtils.getProcessScalars("parent", true, true);
  TelemetryTestUtils.assertKeyedScalar(
    scalars,
    "urlbar.tips",
    `${UrlbarProviderSearchTips.TIP_TYPE.PERSIST}-picked`,
    1
  );
  TelemetryTestUtils.assertEvents(
    [
      {
        category: "urlbar",
        method: "engagement",
        object: "click",
        value: "typed",
      },
    ],
    { category: "urlbar" }
  );

  Assert.equal(
    UrlbarPrefs.get(
      `tipShownCount.${UrlbarProviderSearchTips.TIP_TYPE.PERSIST}`
    ),
    MAX_SHOWN_COUNT,
    "Persist tips are disabled after tip button is picked."
  );
  Assert.equal(gURLBar.value, "", "The Urlbar should be empty.");
  resetSearchTipsProvider();
  await SpecialPowers.popPrefEnv();
});

// Clicking in the input while the onboard tip is showing should have the same
// effect as picking the tip.
add_task(async function clickInInput_onboard() {
  UrlbarProviderSearchTips.disableTipsForCurrentSession = false;
  await SpecialPowers.pushPrefEnv({
    set: [["browser.urlbar.eventTelemetry.enabled", true]],
  });
  Services.telemetry.clearEvents();

  await setDefaultEngine("Google");
  let tab = await BrowserTestUtils.openNewForegroundTab({
    gBrowser,
    url: "about:newtab",
    waitForLoad: false,
  });
  await checkTip(window, UrlbarProviderSearchTips.TIP_TYPE.ONBOARD, false);

  // Click in the input.
  await UrlbarTestUtils.promisePopupClose(window, () => {
    EventUtils.synthesizeMouseAtCenter(gURLBar.textbox.parentNode, {});
  });
  gURLBar.blur();

  // Check telemetry.
  const scalars = TelemetryTestUtils.getProcessScalars("parent", true, true);
  TelemetryTestUtils.assertKeyedScalar(
    scalars,
    "urlbar.tips",
    `${UrlbarProviderSearchTips.TIP_TYPE.ONBOARD}-picked`,
    1
  );
  TelemetryTestUtils.assertEvents(
    [
      {
        category: "urlbar",
        method: "engagement",
        object: "click",
        value: "typed",
      },
    ],
    { category: "urlbar" }
  );

  Assert.equal(
    UrlbarPrefs.get(
      `tipShownCount.${UrlbarProviderSearchTips.TIP_TYPE.ONBOARD}`
    ),
    MAX_SHOWN_COUNT,
    "Onboarding tips are disabled after tip button is picked."
  );
  Assert.equal(gURLBar.value, "", "The Urlbar should be empty.");
  resetSearchTipsProvider();

  BrowserTestUtils.removeTab(tab);
  await SpecialPowers.popPrefEnv();
});

// Pressing Ctrl+L (the open location command) while the onboard tip is showing
// should have the same effect as picking the tip.
add_task(async function openLocation_onboard() {
  UrlbarProviderSearchTips.disableTipsForCurrentSession = false;
  await SpecialPowers.pushPrefEnv({
    set: [["browser.urlbar.eventTelemetry.enabled", true]],
  });
  Services.telemetry.clearEvents();

  await setDefaultEngine("Google");
  let tab = await BrowserTestUtils.openNewForegroundTab({
    gBrowser,
    url: "about:newtab",
    waitForLoad: false,
  });
  await checkTip(window, UrlbarProviderSearchTips.TIP_TYPE.ONBOARD, false);

  // Trigger the open location command.
  await UrlbarTestUtils.promisePopupClose(window, () => {
    document.getElementById("Browser:OpenLocation").doCommand();
  });
  gURLBar.blur();

  // Check telemetry.
  const scalars = TelemetryTestUtils.getProcessScalars("parent", true, true);
  TelemetryTestUtils.assertKeyedScalar(
    scalars,
    "urlbar.tips",
    `${UrlbarProviderSearchTips.TIP_TYPE.ONBOARD}-picked`,
    1
  );
  TelemetryTestUtils.assertEvents(
    [
      {
        category: "urlbar",
        method: "engagement",
        object: "enter",
        value: "typed",
      },
    ],
    { category: "urlbar" }
  );

  Assert.equal(
    UrlbarPrefs.get(
      `tipShownCount.${UrlbarProviderSearchTips.TIP_TYPE.ONBOARD}`
    ),
    MAX_SHOWN_COUNT,
    "Onboarding tips are disabled after tip button is picked."
  );
  Assert.equal(gURLBar.value, "", "The Urlbar should be empty.");
  resetSearchTipsProvider();

  BrowserTestUtils.removeTab(tab);
  await SpecialPowers.popPrefEnv();
});

// Clicking in the input while the redirect tip is showing should have the same
// effect as picking the tip.
add_task(async function clickInInput_redirect() {
  UrlbarProviderSearchTips.disableTipsForCurrentSession = false;
  await SpecialPowers.pushPrefEnv({
    set: [["browser.urlbar.eventTelemetry.enabled", true]],
  });
  Services.telemetry.clearEvents();

  await setDefaultEngine("Google");
  await BrowserTestUtils.withNewTab("about:blank", async () => {
    await withDNSRedirect("www.google.com", "/", async url => {
      BrowserTestUtils.loadURI(gBrowser.selectedBrowser, url);
      await BrowserTestUtils.browserLoaded(gBrowser.selectedBrowser);
      await checkTip(window, UrlbarProviderSearchTips.TIP_TYPE.REDIRECT, false);

      // Click in the input.
      await UrlbarTestUtils.promisePopupClose(window, () => {
        EventUtils.synthesizeMouseAtCenter(gURLBar.textbox.parentNode, {});
      });
      gURLBar.blur();
    });
  });

  // Check telemetry.
  const scalars = TelemetryTestUtils.getProcessScalars("parent", true, true);
  TelemetryTestUtils.assertKeyedScalar(
    scalars,
    "urlbar.tips",
    `${UrlbarProviderSearchTips.TIP_TYPE.REDIRECT}-picked`,
    1
  );
  TelemetryTestUtils.assertEvents(
    [
      {
        category: "urlbar",
        method: "engagement",
        object: "click",
        value: "typed",
      },
    ],
    { category: "urlbar" }
  );

  Assert.equal(
    UrlbarPrefs.get(
      `tipShownCount.${UrlbarProviderSearchTips.TIP_TYPE.REDIRECT}`
    ),
    MAX_SHOWN_COUNT,
    "Redirect tips are disabled after tip button is picked."
  );
  Assert.equal(gURLBar.value, "", "The Urlbar should be empty.");
  resetSearchTipsProvider();
  await SpecialPowers.popPrefEnv();
});

// Clicking in the input while the persist tip is showing should have the same
// effect as picking the tip.
add_task(async function clickInInput_persist() {
  UrlbarProviderSearchTips.disableTipsForCurrentSession = false;
  await SpecialPowers.pushPrefEnv({
    set: [
      ["browser.urlbar.eventTelemetry.enabled", true],
      ["browser.urlbar.showSearchTerms.featureGate", true],
    ],
  });
  Services.telemetry.clearEvents();

  await setDefaultEngine("Example");
  await BrowserTestUtils.withNewTab("about:blank", async () => {
    let browserLoadedPromise = BrowserTestUtils.browserLoaded(
      gBrowser.selectedBrowser,
      false,
      SEARCH_SERP_URL
    );
    BrowserTestUtils.loadURI(gBrowser.selectedBrowser, SEARCH_SERP_URL);
    await browserLoadedPromise;
    await checkTip(window, UrlbarProviderSearchTips.TIP_TYPE.PERSIST, false);

    // Click in the input.
    // The popup should be shown because the search term shouldn't be
    // cleared when the user focuses on the urlbar.
    await UrlbarTestUtils.promisePopupOpen(window, () => {
      EventUtils.synthesizeMouseAtCenter(gURLBar.textbox.parentNode, {});
    });
    gURLBar.blur();
    Assert.equal(
      gURLBar.value,
      SEARCH_TERM,
      "The Urlbar should keep its existing value."
    );
  });

  // Check telemetry.
  const scalars = TelemetryTestUtils.getProcessScalars("parent", true, true);
  TelemetryTestUtils.assertKeyedScalar(
    scalars,
    "urlbar.tips",
    `${UrlbarProviderSearchTips.TIP_TYPE.PERSIST}-picked`,
    1
  );
  // This includes the abandonment engagement event whereas the others don't.
  // It might be because the persist tip keeps the existing search term
  // whereas onboard and redirect don't.
  TelemetryTestUtils.assertEvents(
    [
      {
        category: "urlbar",
        method: "engagement",
        object: "click",
        value: "typed",
      },
      {
        category: "urlbar",
        method: "abandonment",
        object: "blur",
        value: "returned",
      },
    ],
    { category: "urlbar" }
  );

  Assert.equal(
    UrlbarPrefs.get(
      `tipShownCount.${UrlbarProviderSearchTips.TIP_TYPE.PERSIST}`
    ),
    MAX_SHOWN_COUNT,
    "Persist tips are disabled after tip button is picked."
  );
  Assert.equal(gURLBar.value, "", "The Urlbar should be empty.");
  resetSearchTipsProvider();
  await SpecialPowers.popPrefEnv();
});

// Pressing Ctrl+L (the open location command) while the redirect tip is showing
// should have the same effect as picking the tip.
add_task(async function openLocation_redirect() {
  UrlbarProviderSearchTips.disableTipsForCurrentSession = false;
  await SpecialPowers.pushPrefEnv({
    set: [["browser.urlbar.eventTelemetry.enabled", true]],
  });
  Services.telemetry.clearEvents();

  await setDefaultEngine("Google");
  await BrowserTestUtils.withNewTab("about:blank", async () => {
    await withDNSRedirect("www.google.com", "/", async url => {
      BrowserTestUtils.loadURI(gBrowser.selectedBrowser, url);
      await BrowserTestUtils.browserLoaded(gBrowser.selectedBrowser);
      await checkTip(window, UrlbarProviderSearchTips.TIP_TYPE.REDIRECT, false);

      // Trigger the open location command.
      await UrlbarTestUtils.promisePopupClose(window, () => {
        document.getElementById("Browser:OpenLocation").doCommand();
      });
      gURLBar.blur();
    });
  });

  // Check telemetry.
  const scalars = TelemetryTestUtils.getProcessScalars("parent", true, true);
  TelemetryTestUtils.assertKeyedScalar(
    scalars,
    "urlbar.tips",
    `${UrlbarProviderSearchTips.TIP_TYPE.REDIRECT}-picked`,
    1
  );
  TelemetryTestUtils.assertEvents(
    [
      {
        category: "urlbar",
        method: "engagement",
        object: "enter",
        value: "typed",
      },
    ],
    { category: "urlbar" }
  );

  Assert.equal(
    UrlbarPrefs.get(
      `tipShownCount.${UrlbarProviderSearchTips.TIP_TYPE.REDIRECT}`
    ),
    MAX_SHOWN_COUNT,
    "Redirect tips are disabled after tip button is picked."
  );
  Assert.equal(gURLBar.value, "", "The Urlbar should be empty.");
  resetSearchTipsProvider();
  await SpecialPowers.popPrefEnv();
});

// Pressing Ctrl+L (the open location command) while the persist tip is showing
// should have the same effect as picking the tip.
add_task(async function openLocation_persist() {
  UrlbarProviderSearchTips.disableTipsForCurrentSession = false;
  await SpecialPowers.pushPrefEnv({
    set: [
      ["browser.urlbar.eventTelemetry.enabled", true],
      ["browser.urlbar.showSearchTerms.featureGate", true],
    ],
  });
  Services.telemetry.clearEvents();

  await setDefaultEngine("Example");
  await BrowserTestUtils.withNewTab("about:blank", async () => {
    let browserLoadedPromise = BrowserTestUtils.browserLoaded(
      gBrowser.selectedBrowser,
      false,
      SEARCH_SERP_URL
    );
    BrowserTestUtils.loadURI(gBrowser.selectedBrowser, SEARCH_SERP_URL);
    await browserLoadedPromise;
    await checkTip(window, UrlbarProviderSearchTips.TIP_TYPE.PERSIST, false);

    // Trigger the open location command.
    await UrlbarTestUtils.promisePopupClose(window, () => {
      document.getElementById("Browser:OpenLocation").doCommand();
    });
    gURLBar.blur();
    Assert.equal(
      gURLBar.value,
      SEARCH_TERM,
      "The Urlbar should keep its existing value."
    );
  });

  // Check telemetry.
  const scalars = TelemetryTestUtils.getProcessScalars("parent", true, true);
  TelemetryTestUtils.assertKeyedScalar(
    scalars,
    "urlbar.tips",
    `${UrlbarProviderSearchTips.TIP_TYPE.PERSIST}-picked`,
    1
  );
  TelemetryTestUtils.assertEvents(
    [
      {
        category: "urlbar",
        method: "engagement",
        object: "enter",
        value: "typed",
      },
    ],
    { category: "urlbar" }
  );

  Assert.equal(
    UrlbarPrefs.get(
      `tipShownCount.${UrlbarProviderSearchTips.TIP_TYPE.PERSIST}`
    ),
    MAX_SHOWN_COUNT,
    "Persist tips are disabled after tip button is picked."
  );
  Assert.equal(gURLBar.value, "", "The Urlbar should be empty.");
  resetSearchTipsProvider();
  await SpecialPowers.popPrefEnv();
});

add_task(async function pickingTipDoesNotDisableOtherKinds() {
  UrlbarProviderSearchTips.disableTipsForCurrentSession = false;
  await setDefaultEngine("Google");
  let tab = await BrowserTestUtils.openNewForegroundTab({
    gBrowser,
    url: "about:newtab",
    waitForLoad: false,
  });
  await checkTip(window, UrlbarProviderSearchTips.TIP_TYPE.ONBOARD, false);

  // Click the tip button.
  let result = await UrlbarTestUtils.getDetailsOfResultAt(window, 0);
  let button = result.element.row._buttons.get("0");
  await UrlbarTestUtils.promisePopupClose(window, () => {
    EventUtils.synthesizeMouseAtCenter(button, {});
  });

  gURLBar.blur();
  Assert.equal(
    UrlbarPrefs.get(
      `tipShownCount.${UrlbarProviderSearchTips.TIP_TYPE.ONBOARD}`
    ),
    MAX_SHOWN_COUNT,
    "Onboarding tips are disabled after tip button is picked."
  );

  BrowserTestUtils.removeTab(tab);

  // Simulate a new session.
  UrlbarProviderSearchTips.disableTipsForCurrentSession = false;

  // Onboarding tips should no longer be shown.
  let tab2 = await BrowserTestUtils.openNewForegroundTab({
    gBrowser,
    url: "about:newtab",
    waitForLoad: false,
  });
  await checkTip(window, UrlbarProviderSearchTips.TIP_TYPE.NONE);

  // We should still show redirect tips.
  await withDNSRedirect("www.google.com", "/", async url => {
    await checkTab(window, url, UrlbarProviderSearchTips.TIP_TYPE.REDIRECT);
  });

  BrowserTestUtils.removeTab(tab2);
  resetSearchTipsProvider();
});

// The tip shouldn't be shown when there's another notification present.
add_task(async function notification() {
  await BrowserTestUtils.withNewTab("about:blank", async () => {
    let box = gBrowser.getNotificationBox();
    let note = box.appendNotification("urlbar-test", {
      label: "Test",
      priority: box.PRIORITY_INFO_HIGH,
    });
    // Give it a big persistence so it doesn't go away on page load.
    note.persistence = 100;
    await withDNSRedirect("www.google.com", "/", async url => {
      BrowserTestUtils.loadURI(gBrowser.selectedBrowser, url);
      await BrowserTestUtils.browserLoaded(gBrowser.selectedBrowser);
      await checkTip(window, UrlbarProviderSearchTips.TIP_TYPE.NONE);
      box.removeNotification(note, true);
    });
  });
  resetSearchTipsProvider();
});

// The tip should be shown when switching to a tab where it should be shown.
add_task(async function tabSwitch() {
  let tab = BrowserTestUtils.addTab(gBrowser, "about:newtab");
  UrlbarProviderSearchTips.disableTipsForCurrentSession = false;
  Services.telemetry.clearScalars();
  await BrowserTestUtils.switchTab(gBrowser, tab);
  await checkTip(window, UrlbarProviderSearchTips.TIP_TYPE.ONBOARD);
  BrowserTestUtils.removeTab(tab);
  resetSearchTipsProvider();
});

// The engagement event should be ended if the user ignores a tip.
// See bug 1610024.
add_task(async function ignoreEndsEngagement() {
  await setDefaultEngine("Google");
  await BrowserTestUtils.withNewTab("about:blank", async () => {
    await withDNSRedirect("www.google.com", "/", async url => {
      BrowserTestUtils.loadURI(gBrowser.selectedBrowser, url);
      await BrowserTestUtils.browserLoaded(gBrowser.selectedBrowser);
      await checkTip(window, UrlbarProviderSearchTips.TIP_TYPE.REDIRECT, false);
      // We're just looking for any target outside the Urlbar.
      let spring = gURLBar.inputField
        .closest("#nav-bar")
        .querySelector("toolbarspring");
      await UrlbarTestUtils.promisePopupClose(window, async () => {
        await EventUtils.synthesizeMouseAtCenter(spring, {});
      });
      Assert.ok(
        UrlbarProviderSearchTips.showedTipTypeInCurrentEngagement ==
          UrlbarProviderSearchTips.TIP_TYPE.NONE,
        "The engagement should have ended after the tip was ignored."
      );
    });
  });
  resetSearchTipsProvider();
});

add_task(async function pasteAndGo_url() {
  await doPasteAndGoTest("http://example.com/", "http://example.com/");
});

add_task(async function pasteAndGo_nonURL() {
  await setDefaultEngine("Example");
  await doPasteAndGoTest(
    "pasteAndGo_nonURL",
    "https://example.com/?q=pasteAndGo_nonURL"
  );
  await setDefaultEngine("Google");
});

async function doPasteAndGoTest(searchString, expectedURL) {
  UrlbarProviderSearchTips.disableTipsForCurrentSession = false;
  let tab = await BrowserTestUtils.openNewForegroundTab({
    gBrowser,
    url: "about:newtab",
    waitForLoad: false,
  });
  await checkTip(window, UrlbarProviderSearchTips.TIP_TYPE.ONBOARD, false);

  await SimpleTest.promiseClipboardChange(searchString, () => {
    clipboardHelper.copyString(searchString);
  });

  let textBox = gURLBar.querySelector("moz-input-box");
  let cxmenu = textBox.menupopup;
  let cxmenuPromise = BrowserTestUtils.waitForEvent(cxmenu, "popupshown");
  EventUtils.synthesizeMouseAtCenter(gURLBar.inputField, {
    type: "contextmenu",
    button: 2,
  });
  await cxmenuPromise;
  let menuitem = textBox.getMenuItem("paste-and-go");

  let browserLoadedPromise = BrowserTestUtils.browserLoaded(
    gBrowser.selectedBrowser,
    false,
    expectedURL
  );
  cxmenu.activateItem(menuitem);
  await browserLoadedPromise;
  BrowserTestUtils.removeTab(tab);
  resetSearchTipsProvider();
}

// Since we coupled the logic that decides whether to show the tip with our
// gURLBar.search call, we should make sure search isn't called when
// the conditions for a tip are met but the provider is disabled.
add_task(async function noActionWhenDisabled() {
  await setDefaultEngine("Bing");
  await withDNSRedirect("www.bing.com", "/", async url => {
    await checkTab(window, url, UrlbarProviderSearchTips.TIP_TYPE.REDIRECT);
  });

  await SpecialPowers.pushPrefEnv({
    set: [
      [
        "browser.newtabpage.activity-stream.asrouter.userprefs.cfr.features",
        false,
      ],
    ],
  });

  await withDNSRedirect("www.bing.com", "/", async url => {
    Assert.ok(
      !UrlbarTestUtils.isPopupOpen(window),
      "The UrlbarView should not be open."
    );
  });

  await SpecialPowers.popPrefEnv();
});