Bug 1880550 - Propagate explicit heights to scrolled table cells as min-heights....
[gecko.git] / toolkit / components / downloads / DownloadPaths.sys.mjs
blobf1e0a080c27c0cc9a1d6940ea2da1b63cd3bdcad
1 /* This Source Code Form is subject to the terms of the Mozilla Public
2  * License, v. 2.0. If a copy of the MPL was not distributed with this
3  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
5 /**
6  * Provides methods for giving names and paths to files being downloaded.
7  */
9 export var DownloadPaths = {
10   /**
11    * Sanitizes an arbitrary string via mimeSvc.validateFileNameForSaving.
12    *
13    * If the filename being validated is one that was returned from a
14    * file picker, pass false for compressWhitespaces and true for
15    * allowInvalidFilenames. Otherwise, the default values of the arguments
16    * should generally be used.
17    *
18    * @param {string} leafName The full leaf name to sanitize
19    * @param {boolean} [compressWhitespaces] Whether consecutive whitespaces
20    *        should be compressed. The default value is true.
21    * @param {boolean} [allowInvalidFilenames] Allow invalid and dangerous
22    *        filenames and extensions as is.
23    */
24   sanitize(
25     leafName,
26     { compressWhitespaces = true, allowInvalidFilenames = false } = {}
27   ) {
28     const mimeSvc = Cc["@mozilla.org/mime;1"].getService(Ci.nsIMIMEService);
30     let flags = mimeSvc.VALIDATE_SANITIZE_ONLY | mimeSvc.VALIDATE_DONT_TRUNCATE;
31     if (!compressWhitespaces) {
32       flags |= mimeSvc.VALIDATE_DONT_COLLAPSE_WHITESPACE;
33     }
34     if (allowInvalidFilenames) {
35       flags |= mimeSvc.VALIDATE_ALLOW_INVALID_FILENAMES;
36     }
37     return mimeSvc.validateFileNameForSaving(leafName, "", flags);
38   },
40   /**
41    * Creates a uniquely-named file starting from the name of the provided file.
42    * If a file with the provided name already exists, the function attempts to
43    * create nice alternatives, like "base(1).ext" (instead of "base-1.ext").
44    *
45    * If a unique name cannot be found, the function throws the XPCOM exception
46    * NS_ERROR_FILE_TOO_BIG. Other exceptions, like NS_ERROR_FILE_ACCESS_DENIED,
47    * can also be expected.
48    *
49    * @param templateFile
50    *        nsIFile whose leaf name is going to be used as a template. The
51    *        provided object is not modified.
52    *
53    * @return A new instance of an nsIFile object pointing to the newly created
54    *         empty file. On platforms that support permission bits, the file is
55    *         created with permissions 644.
56    */
57   createNiceUniqueFile(templateFile) {
58     // Work on a clone of the provided template file object.
59     let curFile = templateFile.clone().QueryInterface(Ci.nsIFile);
60     let [base, ext] = DownloadPaths.splitBaseNameAndExtension(curFile.leafName);
61     // Try other file names, for example "base(1).txt" or "base(1).tar.gz",
62     // only if the file name initially set already exists.
63     for (let i = 1; i < 10000 && curFile.exists(); i++) {
64       curFile.leafName = base + "(" + i + ")" + ext;
65     }
66     // At this point we hand off control to createUnique, which will create the
67     // file with the name we chose, if it is valid. If not, createUnique will
68     // attempt to modify it again, for example it will shorten very long names
69     // that can't be created on some platforms, and for which a normal call to
70     // nsIFile.create would result in NS_ERROR_FILE_NOT_FOUND. This can result
71     // very rarely in strange names like "base(9999).tar-1.gz" or "ba-1.gz".
72     curFile.createUnique(Ci.nsIFile.NORMAL_FILE_TYPE, 0o644);
73     return curFile;
74   },
76   /**
77    * Separates the base name from the extension in a file name, recognizing some
78    * double extensions like ".tar.gz".
79    *
80    * @param leafName
81    *        The full leaf name to be parsed. Be careful when processing names
82    *        containing leading or trailing dots or spaces.
83    *
84    * @return [base, ext]
85    *         The base name of the file, which can be empty, and its extension,
86    *         which always includes the leading dot unless it's an empty string.
87    *         Concatenating the two items always results in the original name.
88    */
89   splitBaseNameAndExtension(leafName) {
90     // The following regular expression is built from these key parts:
91     //  .*?                      Matches the base name non-greedily.
92     //  \.[A-Z0-9]{1,3}          Up to three letters or numbers preceding a
93     //                           double extension.
94     //  \.(?:gz|bz2|Z)           The second part of common double extensions.
95     //  \.[^.]*                  Matches any extension or a single trailing dot.
96     let [, base, ext] = /(.*?)(\.[A-Z0-9]{1,3}\.(?:gz|bz2|Z)|\.[^.]*)?$/i.exec(
97       leafName
98     );
99     // Return an empty string instead of undefined if no extension is found.
100     return [base, ext || ""];
101   },