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

"use strict";

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 {
  handleInternally,
  saveToDisk,
  useSystemDefault,
  alwaysAsk,
  useHelperApp,
} = Ci.nsIHandlerInfo;

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"
  );
}

add_setup(async function () {
  await SpecialPowers.pushPrefEnv({
    set: [
      // Remove the security delay for the dialog during the test.
      ["security.dialog_enable_delay", 0],
      ["browser.helperApps.showOpenOptionForViewableInternally", true],
      // Make sure we don't open a file picker dialog somehow.
      ["browser.download.useDownloadDir", true],
    ],
  });

  // Restore handlers after the whole test has run
  const registerRestoreHandler = function (type, ext) {
    const mimeInfo = gMimeSvc.getFromTypeAndExtension(type, ext);
    const existed = gHandlerSvc.exists(mimeInfo);
    registerCleanupFunction(() => {
      if (existed) {
        gHandlerSvc.store(mimeInfo);
      } else {
        gHandlerSvc.remove(mimeInfo);
      }
    });
  };
  registerRestoreHandler("image/svg+xml", "svg");
});

function ensureMIMEState({ preferredAction, alwaysAskBeforeHandling }) {
  const mimeInfo = gMimeSvc.getFromTypeAndExtension("image/svg+xml", "svg");
  mimeInfo.preferredAction = preferredAction;
  mimeInfo.alwaysAskBeforeHandling = alwaysAskBeforeHandling;
  gHandlerSvc.store(mimeInfo);
}

function waitDelay(delay) {
  return new Promise(resolve => {
    /* eslint-disable mozilla/no-arbitrary-setTimeout */
    window.setTimeout(resolve, delay);
  });
}

function promisePanelOpened() {
  if (DownloadsPanel.panel && DownloadsPanel.panel.state == "open") {
    return Promise.resolve();
  }
  return BrowserTestUtils.waitForEvent(DownloadsPanel.panel, "popupshown");
}

const kTestCasesPrefEnabled = [
  {
    description:
      "Pref enabled - internal handling as default should not change prefs",
    preDialogState: {
      preferredAction: handleInternally,
      alwaysAskBeforeHandling: false,
    },
    expectTab: true,
    expectLaunch: false,
    expectedPreferredAction: handleInternally,
    expectedAlwaysAskBeforeHandling: false,
    expectUCT: false,
  },
  {
    description:
      "Pref enabled - external handling as default should not change prefs",
    preDialogState: {
      preferredAction: useSystemDefault,
      alwaysAskBeforeHandling: false,
    },
    expectTab: false,
    expectLaunch: true,
    expectedPreferredAction: useSystemDefault,
    expectedAlwaysAskBeforeHandling: false,
    expectUCT: false,
  },
  {
    description: "Pref enabled - saveToDisk as default should not change prefs",
    preDialogState: {
      preferredAction: saveToDisk,
      alwaysAskBeforeHandling: false,
    },
    expectTab: false,
    expectLaunch: false,
    expectedPreferredAction: saveToDisk,
    expectedAlwaysAskBeforeHandling: false,
    expectUCT: false,
  },
  {
    description:
      "Pref enabled - choose internal + alwaysAsk default + checkbox should update persisted default",
    preDialogState: {
      preferredAction: alwaysAsk,
      alwaysAskBeforeHandling: false,
    },
    dialogActions(doc) {
      let handleItem = doc.querySelector("#handleInternally");
      handleItem.click();
      ok(handleItem.selected, "The 'open' option should now be selected");
      let checkbox = doc.querySelector("#rememberChoice");
      checkbox.checked = true;
      checkbox.doCommand();
    },
    // new tab will not launch in test environment when alwaysAsk is preferredAction
    expectTab: false,
    expectLaunch: false,
    expectedPreferredAction: handleInternally,
    expectedAlwaysAskBeforeHandling: false,
    expectUCT: true,
  },
  {
    description:
      "Pref enabled - saveToDisk with alwaysAsk default should update persisted default",
    preDialogState: {
      preferredAction: alwaysAsk,
      alwaysAskBeforeHandling: false,
    },
    dialogActions(doc) {
      let saveItem = doc.querySelector("#save");
      saveItem.click();
      ok(saveItem.selected, "The 'save' option should now be selected");
    },
    expectTab: false,
    expectLaunch: false,
    expectedPreferredAction: saveToDisk,
    expectedAlwaysAskBeforeHandling: false,
    expectUCT: true,
  },
];

add_task(
  async function test_check_saving_handler_choices_with_always_ask_before_handling_new_types_pref_enabled() {
    SpecialPowers.pushPrefEnv({
      set: [["browser.download.always_ask_before_handling_new_types", false]],
    });

    let publicList = await Downloads.getList(Downloads.PUBLIC);
    registerCleanupFunction(async () => {
      await publicList.removeFinished();
    });
    let file = "file_image_svgxml.svg";

    for (let testCase of kTestCasesPrefEnabled) {
      info("Testing with " + file + "; " + testCase.description);
      ensureMIMEState(testCase.preDialogState);
      const { expectTab, expectLaunch, description, expectUCT } = testCase;

      let oldLaunchFile = DownloadIntegration.launchFile;
      let fileLaunched = Promise.withResolvers();
      DownloadIntegration.launchFile = () => {
        ok(
          expectLaunch,
          `The file should ${
            expectLaunch ? "" : "not "
          }be launched with an external application - ${description}`
        );
        fileLaunched.resolve();
      };

      info("Load window and tabs");
      let dialogWindowPromise = BrowserTestUtils.domWindowOpenedAndLoaded();
      let loadingTab = await BrowserTestUtils.openNewForegroundTab({
        gBrowser,
        opening: TEST_PATH + file,
        waitForLoad: false,
        waitForStateStop: true,
      });

      // See if UCT window appears in loaded tab.
      let dialogWindow = await Promise.race([
        waitDelay(1000),
        dialogWindowPromise,
      ]);

      is(
        !!dialogWindow,
        expectUCT,
        `UCT window should${expectUCT ? "" : " not"} have appeared`
      );

      let download;

      if (dialogWindow) {
        is(
          dialogWindow.location.href,
          "chrome://mozapps/content/downloads/unknownContentType.xhtml",
          "Unknown content dialogWindow should be loaded correctly."
        );
        let doc = dialogWindow.document;
        let internalHandlerRadio = doc.querySelector("#handleInternally");

        info("Waiting for accept button to get enabled");
        await waitForAcceptButtonToGetEnabled(doc);

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

        info("Running UCT dialog options before downloading file");
        await testCase.dialogActions(doc);

        let dialog = doc.querySelector("#unknownContentType");
        dialog.acceptDialog();

        info("Waiting for downloads to finish");
        let downloadFinishedPromise = promiseDownloadFinished(publicList);
        download = await downloadFinishedPromise;
      } else {
        let downloadPanelPromise = promisePanelOpened();
        await downloadPanelPromise;
        is(
          DownloadsPanel.isPanelShowing,
          true,
          "DownloadsPanel should be open"
        );

        info("Skipping UCT dialog options");
        info("Waiting for downloads to finish");
        // Unlike when the UCT window opens, the download immediately starts.
        let downloadList = await publicList;
        [download] = downloadList._downloads;
      }

      if (expectLaunch) {
        info("Waiting for launch to finish");
        await fileLaunched.promise;
      }
      DownloadIntegration.launchFile = oldLaunchFile;

      is(
        download.contentType,
        "image/svg+xml",
        "File contentType should be correct"
      );
      is(
        download.source.url,
        `${TEST_PATH + file}`,
        "File name should be correct."
      );
      is(
        (await publicList.getAll()).length,
        1,
        "download should appear in public list"
      );

      // Check mime info:
      const mimeInfo = gMimeSvc.getFromTypeAndExtension("image/svg+xml", "svg");
      gHandlerSvc.fillHandlerInfo(mimeInfo, "");
      is(
        mimeInfo.preferredAction,
        testCase.expectedPreferredAction,
        "preferredAction - " + description
      );
      is(
        mimeInfo.alwaysAskBeforeHandling,
        testCase.expectedAlwaysAskBeforeHandling,
        "alwaysAskBeforeHandling - " + description
      );

      info("Cleaning up");
      BrowserTestUtils.removeTab(loadingTab);
      // By default, if internal is default with pref enabled, we view the svg file in
      // in a new tab. Close this tab in order for the test case to pass.
      if (expectTab && testCase.preferredAction !== alwaysAsk) {
        BrowserTestUtils.removeTab(gBrowser.selectedTab);
      }
      await publicList.removeFinished();
      if (download?.target.exists) {
        try {
          await IOUtils.remove(download.target.path);
        } catch (ex) {
          /* ignore */
        }
      }
    }
  }
);