summaryrefslogtreecommitdiffstats
path: root/uriloader/exthandler/tests/mochitest/browser_download_open_with_internal_handler.js
blob: e39d9ff04ff42efa6958984d7009e3de0beabe1f (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
/* Any copyright is dedicated to the Public Domain.
   http://creativecommons.org/publicdomain/zero/1.0/ */

"use strict";

requestLongerTimeout(2);

const { Downloads } = ChromeUtils.importESModule(
  "resource://gre/modules/Downloads.sys.mjs"
);
const { DownloadIntegration } = ChromeUtils.importESModule(
  "resource://gre/modules/DownloadIntegration.sys.mjs"
);

const TEST_PATH = getRootDirectory(gTestPath).replace(
  "chrome://mochitests/content",
  "https://example.com"
);

const MimeSvc = Cc["@mozilla.org/mime;1"].getService(Ci.nsIMIMEService);
const HandlerSvc = Cc["@mozilla.org/uriloader/handler-service;1"].getService(
  Ci.nsIHandlerService
);

let MockFilePicker = SpecialPowers.MockFilePicker;
MockFilePicker.init(window);

function waitForAcceptButtonToGetEnabled(doc) {
  let dialog = doc.querySelector("#unknownContentType");
  let button = dialog.getButton("accept");
  return TestUtils.waitForCondition(
    () => !button.disabled,
    "Wait for Accept button to get enabled"
  );
}

async function waitForPdfJS(browser, url) {
  await SpecialPowers.pushPrefEnv({
    set: [["pdfjs.eventBusDispatchToDOM", true]],
  });
  // Runs tests after all "load" event handlers have fired off
  let loadPromise = BrowserTestUtils.waitForContentEvent(
    browser,
    "documentloaded",
    false,
    null,
    true
  );
  BrowserTestUtils.loadURIString(browser, url);
  return loadPromise;
}

/**
 * This test covers which choices are presented for downloaded files and how
 * those choices are handled. Unless a pref is enabled
 * (browser.download.always_ask_before_handling_new_types) the unknown content
 * dialog will be skipped altogether by default when downloading.
 * To retain coverage for the non-default scenario, each task sets `alwaysAskBeforeHandling`
 * to true for the relevant mime-type and extensions.
 */
function alwaysAskForHandlingTypes(typeExtensions, ask = true) {
  let mimeInfos = [];
  for (let [type, ext] of Object.entries(typeExtensions)) {
    const mimeInfo = MimeSvc.getFromTypeAndExtension(type, ext);
    mimeInfo.alwaysAskBeforeHandling = ask;
    if (!ask) {
      mimeInfo.preferredAction = mimeInfo.handleInternally;
    }
    HandlerSvc.store(mimeInfo);
    mimeInfos.push(mimeInfo);
  }
  return mimeInfos;
}

add_setup(async function () {
  // Remove the security delay for the dialog during the test.
  await SpecialPowers.pushPrefEnv({
    set: [
      ["security.dialog_enable_delay", 0],
      ["browser.helperApps.showOpenOptionForPdfJS", true],
      ["browser.helperApps.showOpenOptionForViewableInternally", true],
    ],
  });

  // Restore handlers after the whole test has run
  const registerRestoreHandler = function (type, ext) {
    const mimeInfo = MimeSvc.getFromTypeAndExtension(type, ext);
    const existed = HandlerSvc.exists(mimeInfo);

    registerCleanupFunction(() => {
      if (existed) {
        HandlerSvc.store(mimeInfo);
      } else {
        HandlerSvc.remove(mimeInfo);
      }
    });
  };
  registerRestoreHandler("application/pdf", "pdf");
  registerRestoreHandler("binary/octet-stream", "pdf");
  registerRestoreHandler("application/unknown", "pdf");
  registerRestoreHandler("image/webp", "webp");
});

/**
 * Check that loading a PDF file with content-disposition: attachment
 * shows an option to open with the internal handler, and that the
 * internal option handler is not present when the download button
 * is clicked from pdf.js.
 */
add_task(async function test_check_open_with_internal_handler() {
  const mimeInfosToRestore = alwaysAskForHandlingTypes({
    "application/pdf": "pdf",
    "binary/octet-stream": "pdf",
  });

  for (let file of [
    "file_pdf_application_pdf.pdf",
    "file_pdf_binary_octet_stream.pdf",
  ]) {
    info("Testing with " + file);
    let publicList = await Downloads.getList(Downloads.PUBLIC);
    registerCleanupFunction(async () => {
      await publicList.removeFinished();
    });
    let dialogWindowPromise = BrowserTestUtils.domWindowOpenedAndLoaded();
    let loadingTab = await BrowserTestUtils.openNewForegroundTab({
      gBrowser,
      opening: TEST_PATH + file,
      waitForLoad: false,
      waitForStateStop: true,
    });
    // Add an extra tab after the loading tab so we can test that
    // pdf.js is opened in the adjacent tab and not at the end of
    // the tab strip.
    let extraTab = await BrowserTestUtils.addTab(gBrowser, "about:blank");
    let dialogWindow = await dialogWindowPromise;
    is(
      dialogWindow.location.href,
      "chrome://mozapps/content/downloads/unknownContentType.xhtml",
      "Should have seen the unknown content dialogWindow."
    );
    let doc = dialogWindow.document;
    let internalHandlerRadio = doc.querySelector("#handleInternally");

    await waitForAcceptButtonToGetEnabled(doc);

    ok(!internalHandlerRadio.hidden, "The option should be visible for PDF");
    ok(internalHandlerRadio.selected, "The option should be selected");

    let downloadFinishedPromise = promiseDownloadFinished(publicList);
    let newTabPromise = BrowserTestUtils.waitForNewTab(gBrowser);
    let dialog = doc.querySelector("#unknownContentType");
    let button = dialog.getButton("accept");
    button.disabled = false;
    dialog.acceptDialog();
    info("waiting for new tab to open");
    let newTab = await newTabPromise;

    is(
      newTab._tPos - 1,
      loadingTab._tPos,
      "pdf.js should be opened in an adjacent tab"
    );

    await ContentTask.spawn(newTab.linkedBrowser, null, async () => {
      await ContentTaskUtils.waitForCondition(
        () => content.document.readyState == "complete"
      );
    });

    let publicDownloads = await publicList.getAll();
    is(
      publicDownloads.length,
      1,
      "download should appear in publicDownloads list"
    );

    let download = await downloadFinishedPromise;

    let subdialogPromise = BrowserTestUtils.domWindowOpenedAndLoaded();
    // Current tab has file: URI and TEST_PATH is http uri, so uri will be different
    BrowserTestUtils.loadURIString(newTab.linkedBrowser, TEST_PATH + file);
    let subDialogWindow = await subdialogPromise;
    let subDoc = subDialogWindow.document;

    // Prevent racing with initialization of the dialog and make sure that
    // the final state of the dialog has the correct visibility of the internal-handler option.
    await waitForAcceptButtonToGetEnabled(subDoc);
    let subInternalHandlerRadio = subDoc.querySelector("#handleInternally");
    ok(
      !subInternalHandlerRadio.hidden,
      "This option should be shown when the dialog is shown for another PDF"
    );
    // Cancel dialog
    subDoc.querySelector("#unknownContentType").cancelDialog();

    let filepickerPromise = new Promise(resolve => {
      MockFilePicker.showCallback = function (fp) {
        setTimeout(() => {
          resolve(fp.defaultString);
        }, 0);
        return Ci.nsIFilePicker.returnCancel;
      };
    });

    subdialogPromise = BrowserTestUtils.domWindowOpenedAndLoaded();
    await SpecialPowers.spawn(newTab.linkedBrowser, [], async () => {
      let downloadButton;
      await ContentTaskUtils.waitForCondition(() => {
        downloadButton = content.document.querySelector("#download");
        return !!downloadButton;
      });
      ok(downloadButton, "Download button should be present in pdf.js");
      downloadButton.click();
    });
    info(
      "Waiting for unknown content type dialog to appear from pdf.js download button click"
    );
    let filename = await filepickerPromise;
    is(filename, file, "filename was set in filepicker");

    // Remove the first file (can't do this sooner or the second load fails):
    if (download?.target.exists) {
      try {
        info("removing " + download.target.path);
        await IOUtils.remove(download.target.path);
      } catch (ex) {
        /* ignore */
      }
    }

    BrowserTestUtils.removeTab(loadingTab);
    BrowserTestUtils.removeTab(newTab);
    BrowserTestUtils.removeTab(extraTab);

    await publicList.removeFinished();
  }
  for (let mimeInfo of mimeInfosToRestore) {
    HandlerSvc.remove(mimeInfo);
  }
});

/**
 * Test that choosing to open in an external application doesn't
 * open the PDF into pdf.js
 */
add_task(async function test_check_open_with_external_application() {
  const mimeInfosToRestore = alwaysAskForHandlingTypes({
    "application/pdf": "pdf",
    "binary/octet-stream": "pdf",
  });

  for (let file of [
    "file_pdf_application_pdf.pdf",
    "file_pdf_binary_octet_stream.pdf",
  ]) {
    info("Testing with " + file);
    let publicList = await Downloads.getList(Downloads.PUBLIC);
    registerCleanupFunction(async () => {
      await publicList.removeFinished();
    });
    let dialogWindowPromise = BrowserTestUtils.domWindowOpenedAndLoaded();
    let loadingTab = await BrowserTestUtils.openNewForegroundTab({
      gBrowser,
      opening: TEST_PATH + file,
      waitForLoad: false,
      waitForStateStop: true,
    });
    let dialogWindow = await dialogWindowPromise;
    is(
      dialogWindow.location.href,
      "chrome://mozapps/content/downloads/unknownContentType.xhtml",
      "Should have seen the unknown content dialogWindow."
    );

    let oldLaunchFile = DownloadIntegration.launchFile;
    let waitForLaunchFileCalled = new Promise(resolve => {
      DownloadIntegration.launchFile = () => {
        ok(true, "The file should be launched with an external application");
        resolve();
      };
    });

    let doc = dialogWindow.document;
    await waitForAcceptButtonToGetEnabled(doc);
    let dialog = doc.querySelector("#unknownContentType");
    doc.querySelector("#open").click();
    let button = dialog.getButton("accept");
    button.disabled = false;
    info("Accepting the dialog");
    dialog.acceptDialog();
    info("Waiting until DownloadIntegration.launchFile is called");
    await waitForLaunchFileCalled;
    DownloadIntegration.launchFile = oldLaunchFile;

    let publicDownloads = await publicList.getAll();
    is(
      publicDownloads.length,
      1,
      "download should appear in publicDownloads list"
    );
    let download = publicDownloads[0];
    ok(
      !download.launchWhenSucceeded,
      "launchWhenSucceeded should be false after launchFile is called"
    );

    BrowserTestUtils.removeTab(loadingTab);
    if (download?.target.exists) {
      try {
        info("removing " + download.target.path);
        await IOUtils.remove(download.target.path);
      } catch (ex) {
        /* ignore */
      }
    }
    await publicList.removeFinished();
  }
  for (let mimeInfo of mimeInfosToRestore) {
    HandlerSvc.remove(mimeInfo);
  }
});

/**
 * Test that choosing to open a PDF with an external application works and
 * then downloading the same file again and choosing Open with Firefox opens
 * the download in Firefox.
 */
add_task(async function test_check_open_with_external_then_internal() {
  // This test only runs on Windows because appPicker.xhtml is only used on Windows.
  if (AppConstants.platform != "win") {
    return;
  }

  // This test covers a bug that only occurs when the mimeInfo is set to Always Ask
  const mimeInfo = MimeSvc.getFromTypeAndExtension("application/pdf", "pdf");
  console.log(
    "mimeInfo.preferredAction is currently:",
    mimeInfo.preferredAction
  );
  mimeInfo.preferredAction = mimeInfo.alwaysAsk;
  mimeInfo.alwaysAskBeforeHandling = true;
  HandlerSvc.store(mimeInfo);

  for (let [file, mimeType] of [
    ["file_pdf_application_pdf.pdf", "application/pdf"],
    ["file_pdf_binary_octet_stream.pdf", "binary/octet-stream"],
    ["file_pdf_application_unknown.pdf", "application/unknown"],
  ]) {
    info("Testing with " + file);
    let originalMimeInfo = MimeSvc.getFromTypeAndExtension(mimeType, "pdf");

    let publicList = await Downloads.getList(Downloads.PUBLIC);
    registerCleanupFunction(async () => {
      await publicList.removeFinished();
    });
    let dialogWindowPromise = BrowserTestUtils.domWindowOpenedAndLoaded();
    // Open a new tab to the PDF file which will trigger the Unknown Content Type dialog
    // and choose to open the PDF with an external application.
    let loadingTab = await BrowserTestUtils.openNewForegroundTab({
      gBrowser,
      opening: TEST_PATH + file,
      waitForLoad: false,
      waitForStateStop: true,
    });
    let dialogWindow = await dialogWindowPromise;
    is(
      dialogWindow.location.href,
      "chrome://mozapps/content/downloads/unknownContentType.xhtml",
      "Should have seen the unknown content dialogWindow."
    );

    let oldLaunchFile = DownloadIntegration.launchFile;
    let waitForLaunchFileCalled = new Promise(resolve => {
      DownloadIntegration.launchFile = () => {
        ok(true, "The file should be launched with an external application");
        resolve();
      };
    });

    let doc = dialogWindow.document;
    await waitForAcceptButtonToGetEnabled(doc);
    let dialog = doc.querySelector("#unknownContentType");
    let openHandlerMenulist = doc.querySelector("#openHandler");
    let originalDefaultHandler = openHandlerMenulist.label;
    doc.querySelector("#open").click();
    doc.querySelector("#openHandlerPopup").click();
    let oldOpenDialog = dialogWindow.openDialog;
    dialogWindow.openDialog = (location, unused2, unused3, params) => {
      is(location, "chrome://global/content/appPicker.xhtml", "app picker");
      let handlerApp = params.mimeInfo.possibleLocalHandlers.queryElementAt(
        0,
        Ci.nsILocalHandlerApp
      );
      ok(handlerApp.executable, "handlerApp should be executable");
      ok(handlerApp.executable.isFile(), "handlerApp should be a file");
      params.handlerApp = handlerApp;
    };
    doc.querySelector("#choose").click();
    dialogWindow.openDialog = oldOpenDialog;
    await TestUtils.waitForCondition(
      () => originalDefaultHandler != openHandlerMenulist.label,
      "waiting for openHandler to get updated"
    );
    let newDefaultHandler = openHandlerMenulist.label;
    info(`was ${originalDefaultHandler}, now ${newDefaultHandler}`);
    let button = dialog.getButton("accept");
    button.disabled = false;
    info("Accepting the dialog");
    dialog.acceptDialog();
    info("Waiting until DownloadIntegration.launchFile is called");
    await waitForLaunchFileCalled;
    BrowserTestUtils.removeTab(loadingTab);

    // Now, open a new tab to the PDF file which will trigger the Unknown Content Type dialog
    // and choose to open the PDF internally. The previously used external application should be shown as
    // the external option.
    dialogWindowPromise = BrowserTestUtils.domWindowOpenedAndLoaded();
    loadingTab = await BrowserTestUtils.openNewForegroundTab({
      gBrowser,
      opening: TEST_PATH + file,
      waitForLoad: false,
      waitForStateStop: true,
    });
    dialogWindow = await dialogWindowPromise;
    is(
      dialogWindow.location.href,
      "chrome://mozapps/content/downloads/unknownContentType.xhtml",
      "Should have seen the unknown content dialogWindow."
    );

    DownloadIntegration.launchFile = () => {
      ok(false, "The file should not be launched with an external application");
    };

    doc = dialogWindow.document;
    await waitForAcceptButtonToGetEnabled(doc);
    openHandlerMenulist = doc.querySelector("#openHandler");
    is(openHandlerMenulist.label, newDefaultHandler, "'new' handler");
    dialog = doc.querySelector("#unknownContentType");
    doc.querySelector("#handleInternally").click();
    info("Accepting the dialog");
    button = dialog.getButton("accept");
    button.disabled = false;
    let newTabPromise = BrowserTestUtils.waitForNewTab(gBrowser);
    dialog.acceptDialog();

    info("waiting for new tab to open");
    let newTab = await newTabPromise;

    await ContentTask.spawn(newTab.linkedBrowser, null, async () => {
      await ContentTaskUtils.waitForCondition(
        () => content.document.readyState == "complete"
      );
    });

    is(
      newTab.linkedBrowser.contentPrincipal.origin,
      "resource://pdf.js",
      "PDF should be opened with pdf.js"
    );

    BrowserTestUtils.removeTab(loadingTab);
    BrowserTestUtils.removeTab(newTab);

    // Now trigger the dialog again and select the system
    // default option to reset the state for the next iteration of the test.
    // Reset the state for the next iteration of the test.
    HandlerSvc.store(originalMimeInfo);
    DownloadIntegration.launchFile = oldLaunchFile;
    let [download] = await publicList.getAll();
    if (download?.target.exists) {
      try {
        info("removing " + download.target.path);
        await IOUtils.remove(download.target.path);
      } catch (ex) {
        /* ignore */
      }
    }
    await publicList.removeFinished();
  }
});

/**
 * Check that the "Open with internal handler" option is presented
 * for other viewable internally types.
 */
add_task(
  async function test_internal_handler_hidden_with_viewable_internally_type() {
    await SpecialPowers.pushPrefEnv({
      set: [["image.webp.enabled", true]],
    });

    const mimeInfosToRestore = alwaysAskForHandlingTypes({
      "binary/octet-stream": "xml",
      "image/webp": "webp",
    });

    for (let [file, checkDefault] of [
      // The default for binary/octet-stream is changed by the PDF tests above,
      // this may change given bug 1659008, so I'm just ignoring the default for now.
      ["file_xml_attachment_binary_octet_stream.xml", false],
      ["file_green.webp", true],
    ]) {
      let dialogWindowPromise = BrowserTestUtils.domWindowOpenedAndLoaded();
      let loadingTab = await BrowserTestUtils.openNewForegroundTab({
        gBrowser,
        opening: TEST_PATH + file,
        waitForLoad: false,
        waitForStateStop: true,
      });
      let dialogWindow = await dialogWindowPromise;
      is(
        dialogWindow.location.href,
        "chrome://mozapps/content/downloads/unknownContentType.xhtml",
        "Should have seen the unknown content dialogWindow."
      );
      let doc = dialogWindow.document;
      let internalHandlerRadio = doc.querySelector("#handleInternally");

      // Prevent racing with initialization of the dialog and make sure that
      // the final state of the dialog has the correct visibility of the internal-handler option.
      await waitForAcceptButtonToGetEnabled(doc);

      let fileDesc = file.substring(file.lastIndexOf(".") + 1);

      ok(
        !internalHandlerRadio.hidden,
        `The option should be visible for ${fileDesc}`
      );
      if (checkDefault) {
        ok(
          internalHandlerRadio.selected,
          `The option should be selected for ${fileDesc}`
        );
      }

      let dialog = doc.querySelector("#unknownContentType");
      dialog.cancelDialog();
      BrowserTestUtils.removeTab(loadingTab);
    }
    for (let mimeInfo of mimeInfosToRestore) {
      HandlerSvc.remove(mimeInfo);
    }
  }
);

/**
 * Check that the "Open with internal handler" option is not presented
 * for non-PDF, non-viewable-internally types.
 */
add_task(async function test_internal_handler_hidden_with_other_type() {
  const mimeInfosToRestore = alwaysAskForHandlingTypes({
    "text/plain": "txt",
  });

  let dialogWindowPromise = BrowserTestUtils.domWindowOpenedAndLoaded();
  let loadingTab = await BrowserTestUtils.openNewForegroundTab({
    gBrowser,
    opening: TEST_PATH + "file_txt_attachment_test.txt",
    waitForLoad: false,
    waitForStateStop: true,
  });
  let dialogWindow = await dialogWindowPromise;
  is(
    dialogWindow.location.href,
    "chrome://mozapps/content/downloads/unknownContentType.xhtml",
    "Should have seen the unknown content dialogWindow."
  );
  let doc = dialogWindow.document;

  // Prevent racing with initialization of the dialog and make sure that
  // the final state of the dialog has the correct visibility of the internal-handler option.
  await waitForAcceptButtonToGetEnabled(doc);

  let internalHandlerRadio = doc.querySelector("#handleInternally");
  ok(
    internalHandlerRadio.hidden,
    "The option should be hidden for unknown file type"
  );

  let dialog = doc.querySelector("#unknownContentType");
  dialog.cancelDialog();
  BrowserTestUtils.removeTab(loadingTab);
  for (let mimeInfo of mimeInfosToRestore) {
    HandlerSvc.remove(mimeInfo);
  }
});

/**
 * Check that the "Open with internal handler" option is not presented
 * when the feature is disabled for PDFs.
 */
add_task(async function test_internal_handler_hidden_with_pdf_pref_disabled() {
  const mimeInfosToRestore = alwaysAskForHandlingTypes({
    "application/pdf": "pdf",
    "binary/octet-stream": "pdf",
  });
  await SpecialPowers.pushPrefEnv({
    set: [["browser.helperApps.showOpenOptionForPdfJS", false]],
  });
  for (let file of [
    "file_pdf_application_pdf.pdf",
    "file_pdf_binary_octet_stream.pdf",
  ]) {
    let dialogWindowPromise = BrowserTestUtils.domWindowOpenedAndLoaded();
    let loadingTab = await BrowserTestUtils.openNewForegroundTab({
      gBrowser,
      opening: TEST_PATH + file,
      waitForLoad: false,
      waitForStateStop: true,
    });
    let dialogWindow = await dialogWindowPromise;
    is(
      dialogWindow.location.href,
      "chrome://mozapps/content/downloads/unknownContentType.xhtml",
      "Should have seen the unknown content dialogWindow."
    );
    let doc = dialogWindow.document;

    await waitForAcceptButtonToGetEnabled(doc);

    let internalHandlerRadio = doc.querySelector("#handleInternally");
    ok(
      internalHandlerRadio.hidden,
      "The option should be hidden for PDF when the pref is false"
    );

    let dialog = doc.querySelector("#unknownContentType");
    dialog.cancelDialog();
    BrowserTestUtils.removeTab(loadingTab);
  }
  for (let mimeInfo of mimeInfosToRestore) {
    HandlerSvc.remove(mimeInfo);
  }
});

/**
 * Check that the "Open with internal handler" option is not presented
 * for other viewable internally types when disabled.
 */
add_task(
  async function test_internal_handler_hidden_with_viewable_internally_pref_disabled() {
    const mimeInfosToRestore = alwaysAskForHandlingTypes({
      "text/xml": "xml",
    });
    await SpecialPowers.pushPrefEnv({
      set: [["browser.helperApps.showOpenOptionForViewableInternally", false]],
    });
    let dialogWindowPromise = BrowserTestUtils.domWindowOpenedAndLoaded();
    let loadingTab = await BrowserTestUtils.openNewForegroundTab({
      gBrowser,
      opening: TEST_PATH + "file_xml_attachment_test.xml",
      waitForLoad: false,
      waitForStateStop: true,
    });
    let dialogWindow = await dialogWindowPromise;
    is(
      dialogWindow.location.href,
      "chrome://mozapps/content/downloads/unknownContentType.xhtml",
      "Should have seen the unknown content dialogWindow."
    );
    let doc = dialogWindow.document;

    await waitForAcceptButtonToGetEnabled(doc);

    let internalHandlerRadio = doc.querySelector("#handleInternally");
    ok(
      internalHandlerRadio.hidden,
      "The option should be hidden for XML when the pref is false"
    );

    let dialog = doc.querySelector("#unknownContentType");
    dialog.cancelDialog();
    BrowserTestUtils.removeTab(loadingTab);
    for (let mimeInfo of mimeInfosToRestore) {
      HandlerSvc.remove(mimeInfo);
    }
  }
);

/*
 * This test sets the action to internal. The files should open directly without asking.
 */
add_task(async function test_check_open_with_internal_handler_noask() {
  const mimeInfosToRestore = alwaysAskForHandlingTypes(
    {
      "application/pdf": "pdf",
      "binary/octet-stream": "pdf",
      "application/octet-stream": "pdf",
    },
    false
  );

  // Build the matrix of tests to perform.
  let matrix = {
    alwaysOpenPDFInline: [false, true],
    file: [
      "file_pdf_application_pdf.pdf",
      "file_pdf_binary_octet_stream.pdf",
      "file_pdf_application_octet_stream.pdf",
    ],
    where: ["top", "popup", "frame"],
  };
  let tests = [{}];
  for (let [key, values] of Object.entries(matrix)) {
    tests = tests.flatMap(test =>
      values.map(value => ({ [key]: value, ...test }))
    );
  }

  for (let test of tests) {
    info(`test case: ${JSON.stringify(test)}`);
    let { alwaysOpenPDFInline, file, where } = test;

    // These are the cases that can be opened inline. binary/octet-stream
    // isn't handled by pdfjs.
    let canHandleInline =
      file == "file_pdf_application_pdf.pdf" ||
      (file == "file_pdf_application_octet_stream.pdf" && where != "frame");

    await SpecialPowers.pushPrefEnv({
      set: [
        ["browser.helperApps.showOpenOptionForPdfJS", true],
        ["browser.helperApps.showOpenOptionForViewableInternally", true],
        ["browser.download.open_pdf_attachments_inline", alwaysOpenPDFInline],
      ],
    });

    async function doNavigate(browser) {
      await SpecialPowers.spawn(
        browser,
        [TEST_PATH + file, where],
        async (contentUrl, where_) => {
          switch (where_) {
            case "top":
              content.location = contentUrl;
              break;
            case "popup":
              content.open(contentUrl);
              break;
            case "frame":
              let frame = content.document.createElement("iframe");
              frame.setAttribute("src", contentUrl);
              content.document.body.appendChild(frame);
              break;
            default:
              ok(false, "Unknown where value");
              break;
          }
        }
      );
    }

    // If this is true, the pdf is opened directly without downloading it.
    // Otherwise, it must first be downloaded and optionally displayed in
    // a tab with a file url.
    let openPDFDirectly = alwaysOpenPDFInline && canHandleInline;

    await BrowserTestUtils.withNewTab(
      { gBrowser, url: TEST_PATH + "blank.html" },
      async browser => {
        let readyPromise = BrowserTestUtils.waitForNewTab(
          gBrowser,
          null,
          false,
          !openPDFDirectly
        );

        await doNavigate(browser);

        await readyPromise;

        is(
          gBrowser.selectedBrowser.currentURI.scheme,
          openPDFDirectly ? "https" : "file",
          "Loaded PDF uri has the correct scheme"
        );

        // intentionally don't bother checking session history without ship to
        // keep complexity down.
        if (Services.appinfo.sessionHistoryInParent) {
          let shistory = browser.browsingContext.sessionHistory;
          is(shistory.count, 1, "should a single shentry");
          is(shistory.index, 0, "should be on the first entry");
          let shentry = shistory.getEntryAtIndex(shistory.index);
          is(shentry.URI.spec, TEST_PATH + "blank.html");
        }

        await SpecialPowers.spawn(
          browser,
          [TEST_PATH + "blank.html"],
          async blankUrl => {
            ok(
              !docShell.isAttemptingToNavigate,
              "should not still be attempting to navigate"
            );
            is(
              content.location.href,
              blankUrl,
              "original browser hasn't navigated"
            );
          }
        );

        await BrowserTestUtils.removeTab(gBrowser.selectedTab);
      }
    );
  }

  for (let mimeInfo of mimeInfosToRestore) {
    HandlerSvc.remove(mimeInfo);
  }
});

add_task(async () => {
  MockFilePicker.cleanup();
});