fork/home-manager

git clone https://git.julia.blue/fork/home-manager

Simone Ragusafirefox: set ADD_DATE and LAST_MODIFIED of bookmarks to 168f7d8c0

master
25.7 KiB697 linesraw
1{ config, lib, pkgs, ... }:
2
3with lib;
4
5let
6
7  inherit (pkgs.stdenv.hostPlatform) isDarwin;
8
9  cfg = config.programs.firefox;
10
11  jsonFormat = pkgs.formats.json { };
12
13  mozillaConfigPath =
14    if isDarwin then "Library/Application Support/Mozilla" else ".mozilla";
15
16  firefoxConfigPath = if isDarwin then
17    "Library/Application Support/Firefox"
18  else
19    "${mozillaConfigPath}/firefox";
20
21  profilesPath =
22    if isDarwin then "${firefoxConfigPath}/Profiles" else firefoxConfigPath;
23
24  # The extensions path shared by all profiles; will not be supported
25  # by future Firefox versions.
26  extensionPath = "extensions/{ec8030f7-c20a-464f-9b0e-13a3a9e97384}";
27
28  profiles = flip mapAttrs' cfg.profiles (_: profile:
29    nameValuePair "Profile${toString profile.id}" {
30      Name = profile.name;
31      Path = if isDarwin then "Profiles/${profile.path}" else profile.path;
32      IsRelative = 1;
33      Default = if profile.isDefault then 1 else 0;
34    }) // {
35      General = { StartWithLastProfile = 1; };
36    };
37
38  profilesIni = generators.toINI { } profiles;
39
40  userPrefValue = pref:
41    builtins.toJSON (if isBool pref || isInt pref || isString pref then
42      pref
43    else
44      builtins.toJSON pref);
45
46  mkUserJs = prefs: extraPrefs: bookmarks:
47    let
48      prefs' = lib.optionalAttrs ([ ] != bookmarks) {
49        "browser.bookmarks.file" = toString (firefoxBookmarksFile bookmarks);
50        "browser.places.importBookmarksHTML" = true;
51      } // prefs;
52    in ''
53      // Generated by Home Manager.
54
55      ${concatStrings (mapAttrsToList (name: value: ''
56        user_pref("${name}", ${userPrefValue value});
57      '') prefs')}
58
59      ${extraPrefs}
60    '';
61
62  firefoxBookmarksFile = bookmarks:
63    let
64      indent = level:
65        lib.concatStringsSep "" (map (lib.const "  ") (lib.range 1 level));
66
67      bookmarkToHTML = indentLevel: bookmark:
68        ''
69          ${indent indentLevel}<DT><A HREF="${
70            escapeXML bookmark.url
71          }" ADD_DATE="1" LAST_MODIFIED="1"${
72            lib.optionalString (bookmark.keyword != null)
73            " SHORTCUTURL=\"${escapeXML bookmark.keyword}\""
74          }${
75            lib.optionalString (bookmark.tags != [ ])
76            " TAGS=\"${escapeXML (concatStringsSep "," bookmark.tags)}\""
77          }>${escapeXML bookmark.name}</A>'';
78
79      directoryToHTML = indentLevel: directory: ''
80        ${indent indentLevel}<DT>${
81          if directory.toolbar then
82            ''<H3 PERSONAL_TOOLBAR_FOLDER="true">Bookmarks Toolbar''
83          else
84            "<H3>${escapeXML directory.name}"
85        }</H3>
86        ${indent indentLevel}<DL><p>
87        ${allItemsToHTML (indentLevel + 1) directory.bookmarks}
88        ${indent indentLevel}</p></DL>'';
89
90      itemToHTMLOrRecurse = indentLevel: item:
91        if item ? "url" then
92          bookmarkToHTML indentLevel item
93        else
94          directoryToHTML indentLevel item;
95
96      allItemsToHTML = indentLevel: bookmarks:
97        lib.concatStringsSep "\n"
98        (map (itemToHTMLOrRecurse indentLevel) bookmarks);
99
100      bookmarkEntries = allItemsToHTML 1 bookmarks;
101    in pkgs.writeText "firefox-bookmarks.html" ''
102      <!DOCTYPE NETSCAPE-Bookmark-file-1>
103      <!-- This is an automatically generated file.
104        It will be read and overwritten.
105        DO NOT EDIT! -->
106      <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=UTF-8">
107      <TITLE>Bookmarks</TITLE>
108      <H1>Bookmarks Menu</H1>
109      <DL><p>
110      ${bookmarkEntries}
111      </p></DL>
112    '';
113
114in {
115  meta.maintainers = [ maintainers.rycee maintainers.kira-bruneau ];
116
117  imports = [
118    (mkRemovedOptionModule [ "programs" "firefox" "extensions" ] ''
119
120      Extensions are now managed per-profile. That is, change from
121
122        programs.firefox.extensions = [ foo bar ];
123
124      to
125
126        programs.firefox.profiles.myprofile.extensions = [ foo bar ];'')
127    (mkRemovedOptionModule [ "programs" "firefox" "enableAdobeFlash" ]
128      "Support for this option has been removed.")
129    (mkRemovedOptionModule [ "programs" "firefox" "enableGoogleTalk" ]
130      "Support for this option has been removed.")
131    (mkRemovedOptionModule [ "programs" "firefox" "enableIcedTea" ]
132      "Support for this option has been removed.")
133  ];
134
135  options = {
136    programs.firefox = {
137      enable = mkEnableOption "Firefox";
138
139      package = mkOption {
140        type = with types; nullOr package;
141        default = if versionAtLeast config.home.stateVersion "19.09" then
142          pkgs.firefox
143        else
144          pkgs.firefox-unwrapped;
145        defaultText = literalExpression "pkgs.firefox";
146        example = literalExpression ''
147          pkgs.firefox.override {
148            # See nixpkgs' firefox/wrapper.nix to check which options you can use
149            cfg = {
150              # Gnome shell native connector
151              enableGnomeExtensions = true;
152              # Tridactyl native connector
153              enableTridactylNative = true;
154            };
155          }
156        '';
157        description = ''
158          The Firefox package to use. If state version ≥ 19.09 then
159          this should be a wrapped Firefox package. For earlier state
160          versions it should be an unwrapped Firefox package.
161          Set to <literal>null</literal> to disable installing Firefox.
162        '';
163      };
164
165      profiles = mkOption {
166        type = types.attrsOf (types.submodule ({ config, name, ... }: {
167          options = {
168            name = mkOption {
169              type = types.str;
170              default = name;
171              description = "Profile name.";
172            };
173
174            id = mkOption {
175              type = types.ints.unsigned;
176              default = 0;
177              description = ''
178                Profile ID. This should be set to a unique number per profile.
179              '';
180            };
181
182            settings = mkOption {
183              type = types.attrsOf (jsonFormat.type // {
184                description =
185                  "Firefox preference (int, bool, string, and also attrs, list, float as a JSON string)";
186              });
187              default = { };
188              example = literalExpression ''
189                {
190                  "browser.startup.homepage" = "https://nixos.org";
191                  "browser.search.region" = "GB";
192                  "browser.search.isUS" = false;
193                  "distribution.searchplugins.defaultLocale" = "en-GB";
194                  "general.useragent.locale" = "en-GB";
195                  "browser.bookmarks.showMobileBookmarks" = true;
196                  "browser.newtabpage.pinned" = [{
197                    title = "NixOS";
198                    url = "https://nixos.org";
199                  }];
200                }
201              '';
202              description = ''
203                Attribute set of Firefox preferences.
204
205                Firefox only supports int, bool, and string types for
206                preferences, but home-manager will automatically
207                convert all other JSON-compatible values into strings.
208              '';
209            };
210
211            extraConfig = mkOption {
212              type = types.lines;
213              default = "";
214              description = ''
215                Extra preferences to add to {file}`user.js`.
216              '';
217            };
218
219            userChrome = mkOption {
220              type = types.lines;
221              default = "";
222              description = "Custom Firefox user chrome CSS.";
223              example = ''
224                /* Hide tab bar in FF Quantum */
225                @-moz-document url("chrome://browser/content/browser.xul") {
226                  #TabsToolbar {
227                    visibility: collapse !important;
228                    margin-bottom: 21px !important;
229                  }
230
231                  #sidebar-box[sidebarcommand="treestyletab_piro_sakura_ne_jp-sidebar-action"] #sidebar-header {
232                    visibility: collapse !important;
233                  }
234                }
235              '';
236            };
237
238            userContent = mkOption {
239              type = types.lines;
240              default = "";
241              description = "Custom Firefox user content CSS.";
242              example = ''
243                /* Hide scrollbar in FF Quantum */
244                *{scrollbar-width:none !important}
245              '';
246            };
247
248            bookmarks = mkOption {
249              type = let
250                bookmarkSubmodule = types.submodule ({ config, name, ... }: {
251                  options = {
252                    name = mkOption {
253                      type = types.str;
254                      default = name;
255                      description = "Bookmark name.";
256                    };
257
258                    tags = mkOption {
259                      type = types.listOf types.str;
260                      default = [ ];
261                      description = "Bookmark tags.";
262                    };
263
264                    keyword = mkOption {
265                      type = types.nullOr types.str;
266                      default = null;
267                      description = "Bookmark search keyword.";
268                    };
269
270                    url = mkOption {
271                      type = types.str;
272                      description = "Bookmark url, use %s for search terms.";
273                    };
274                  };
275                }) // {
276                  description = "bookmark submodule";
277                };
278
279                bookmarkType = types.addCheck bookmarkSubmodule (x: x ? "url");
280
281                directoryType = types.submodule ({ config, name, ... }: {
282                  options = {
283                    name = mkOption {
284                      type = types.str;
285                      default = name;
286                      description = "Directory name.";
287                    };
288
289                    bookmarks = mkOption {
290                      type = types.listOf nodeType;
291                      default = [ ];
292                      description = "Bookmarks within directory.";
293                    };
294
295                    toolbar = mkOption {
296                      type = types.bool;
297                      default = false;
298                      description = "If directory should be shown in toolbar.";
299                    };
300                  };
301                }) // {
302                  description = "directory submodule";
303                };
304
305                nodeType = types.either bookmarkType directoryType;
306              in with types;
307              coercedTo (attrsOf nodeType) attrValues (listOf nodeType);
308              default = [ ];
309              example = literalExpression ''
310                [
311                  {
312                    name = "wikipedia";
313                    tags = [ "wiki" ];
314                    keyword = "wiki";
315                    url = "https://en.wikipedia.org/wiki/Special:Search?search=%s&go=Go";
316                  }
317                  {
318                    name = "kernel.org";
319                    url = "https://www.kernel.org";
320                  }
321                  {
322                    name = "Nix sites";
323                    toolbar = true;
324                    bookmarks = [
325                      {
326                        name = "homepage";
327                        url = "https://nixos.org/";
328                      }
329                      {
330                        name = "wiki";
331                        tags = [ "wiki" "nix" ];
332                        url = "https://nixos.wiki/";
333                      }
334                    ];
335                  }
336                ]
337              '';
338              description = ''
339                Preloaded bookmarks. Note, this may silently overwrite any
340                previously existing bookmarks!
341              '';
342            };
343
344            path = mkOption {
345              type = types.str;
346              default = name;
347              description = "Profile path.";
348            };
349
350            isDefault = mkOption {
351              type = types.bool;
352              default = config.id == 0;
353              defaultText = "true if profile ID is 0";
354              description = "Whether this is a default profile.";
355            };
356
357            search = {
358              force = mkOption {
359                type = with types; bool;
360                default = false;
361                description = ''
362                  Whether to force replace the existing search
363                  configuration. This is recommended since Firefox will
364                  replace the symlink for the search configuration on every
365                  launch, but note that you'll lose any existing
366                  configuration by enabling this.
367                '';
368              };
369
370              default = mkOption {
371                type = with types; nullOr str;
372                default = null;
373                example = "DuckDuckGo";
374                description = ''
375                  The default search engine used in the address bar and search bar.
376                '';
377              };
378
379              order = mkOption {
380                type = with types; uniq (listOf str);
381                default = [ ];
382                example = [ "DuckDuckGo" "Google" ];
383                description = ''
384                  The order the search engines are listed in. Any engines
385                  that aren't included in this list will be listed after
386                  these in an unspecified order.
387                '';
388              };
389
390              engines = mkOption {
391                type = with types; attrsOf (attrsOf jsonFormat.type);
392                default = { };
393                example = literalExpression ''
394                  {
395                    "Nix Packages" = {
396                      urls = [{
397                        template = "https://search.nixos.org/packages";
398                        params = [
399                          { name = "type"; value = "packages"; }
400                          { name = "query"; value = "{searchTerms}"; }
401                        ];
402                      }];
403
404                      icon = "''${pkgs.nixos-icons}/share/icons/hicolor/scalable/apps/nix-snowflake.svg";
405                      definedAliases = [ "@np" ];
406                    };
407
408                    "NixOS Wiki" = {
409                      urls = [{ template = "https://nixos.wiki/index.php?search={searchTerms}"; }];
410                      iconUpdateURL = "https://nixos.wiki/favicon.png";
411                      updateInterval = 24 * 60 * 60 * 1000; # every day
412                      definedAliases = [ "@nw" ];
413                    };
414
415                    "Bing".metaData.hidden = true;
416                    "Google".metaData.alias = "@g"; # builtin engines only support specifying one additional alias
417                  }
418                '';
419                description = ''
420                  Attribute set of search engine configurations. Engines
421                  that only have {var}`metaData` specified will
422                  be treated as builtin to Firefox.
423
424                  See [SearchEngine.jsm](https://searchfox.org/mozilla-central/rev/669329e284f8e8e2bb28090617192ca9b4ef3380/toolkit/components/search/SearchEngine.jsm#1138-1177)
425                  in Firefox's source for available options. We maintain a
426                  mapping to let you specify all options in the referenced
427                  link without underscores, but it may fall out of date with
428                  future options.
429
430                  Note, {var}`icon` is also a special option
431                  added by Home Manager to make it convenient to specify
432                  absolute icon paths.
433                '';
434              };
435            };
436
437            extensions = mkOption {
438              type = types.listOf types.package;
439              default = [ ];
440              example = literalExpression ''
441                with pkgs.nur.repos.rycee.firefox-addons; [
442                  privacy-badger
443                ]
444              '';
445              description = ''
446                List of Firefox add-on packages to install for this profile.
447                Some pre-packaged add-ons are accessible from the
448                [Nix User Repository](https://github.com/nix-community/NUR).
449                Once you have NUR installed run
450
451                ```console
452                $ nix-env -f '<nixpkgs>' -qaP -A nur.repos.rycee.firefox-addons
453                ```
454
455                to list the available Firefox add-ons.
456
457                Note that it is necessary to manually enable these extensions
458                inside Firefox after the first installation.
459              '';
460            };
461
462          };
463        }));
464        default = { };
465        description = "Attribute set of Firefox profiles.";
466      };
467
468      enableGnomeExtensions = mkOption {
469        type = types.bool;
470        default = false;
471        description = ''
472          Whether to enable the GNOME Shell native host connector. Note, you
473          also need to set the NixOS option
474          `services.gnome.gnome-browser-connector.enable` to
475          `true`.
476        '';
477      };
478    };
479  };
480
481  config = mkIf cfg.enable {
482    assertions = [
483      (let
484        defaults =
485          catAttrs "name" (filter (a: a.isDefault) (attrValues cfg.profiles));
486      in {
487        assertion = cfg.profiles == { } || length defaults == 1;
488        message = "Must have exactly one default Firefox profile but found "
489          + toString (length defaults) + optionalString (length defaults > 1)
490          (", namely " + concatStringsSep ", " defaults);
491      })
492
493      (let
494        duplicates = filterAttrs (_: v: length v != 1) (zipAttrs
495          (mapAttrsToList (n: v: { "${toString v.id}" = n; }) (cfg.profiles)));
496
497        mkMsg = n: v: "  - ID ${n} is used by ${concatStringsSep ", " v}";
498      in {
499        assertion = duplicates == { };
500        message = ''
501          Must not have Firefox profiles with duplicate IDs but
502        '' + concatStringsSep "\n" (mapAttrsToList mkMsg duplicates);
503      })
504    ];
505
506    warnings = optional (cfg.enableGnomeExtensions or false) ''
507      Using 'programs.firefox.enableGnomeExtensions' has been deprecated and
508      will be removed in the future. Please change to overriding the package
509      configuration using 'programs.firefox.package' instead. You can refer to
510      its example for how to do this.
511    '';
512
513    home.packages = let
514      # The configuration expected by the Firefox wrapper.
515      fcfg = { enableGnomeExtensions = cfg.enableGnomeExtensions; };
516
517      # A bit of hackery to force a config into the wrapper.
518      browserName = cfg.package.browserName or (builtins.parseDrvName
519        cfg.package.name).name;
520
521      # The configuration expected by the Firefox wrapper builder.
522      bcfg = setAttrByPath [ browserName ] fcfg;
523
524      package = if isDarwin then
525        cfg.package
526      else if versionAtLeast config.home.stateVersion "19.09" then
527        cfg.package.override (old: { cfg = old.cfg or { } // fcfg; })
528      else
529        (pkgs.wrapFirefox.override { config = bcfg; }) cfg.package { };
530    in lib.optional (cfg.package != null) package;
531
532    home.file = mkMerge ([{
533      "${firefoxConfigPath}/profiles.ini" =
534        mkIf (cfg.profiles != { }) { text = profilesIni; };
535    }] ++ flip mapAttrsToList cfg.profiles (_: profile: {
536      "${profilesPath}/${profile.path}/.keep".text = "";
537
538      "${profilesPath}/${profile.path}/chrome/userChrome.css" =
539        mkIf (profile.userChrome != "") { text = profile.userChrome; };
540
541      "${profilesPath}/${profile.path}/chrome/userContent.css" =
542        mkIf (profile.userContent != "") { text = profile.userContent; };
543
544      "${profilesPath}/${profile.path}/user.js" = mkIf (profile.settings != { }
545        || profile.extraConfig != "" || profile.bookmarks != [ ]) {
546          text =
547            mkUserJs profile.settings profile.extraConfig profile.bookmarks;
548        };
549
550      "${profilesPath}/${profile.path}/search.json.mozlz4" = mkIf
551        (profile.search.default != null || profile.search.order != [ ]
552          || profile.search.engines != { }) {
553            force = profile.search.force;
554            source = let
555              settings = {
556                version = 6;
557                engines = let
558                  # Map of nice field names to internal field names.
559                  # This is intended to be exhaustive and should be
560                  # updated at every version bump.
561                  internalFieldNames = (genAttrs [
562                    "name"
563                    "isAppProvided"
564                    "loadPath"
565                    "hasPreferredIcon"
566                    "updateInterval"
567                    "updateURL"
568                    "iconUpdateURL"
569                    "iconURL"
570                    "iconMapObj"
571                    "metaData"
572                    "orderHint"
573                    "definedAliases"
574                    "urls"
575                  ] (name: "_${name}")) // {
576                    searchForm = "__searchForm";
577                  };
578
579                  processCustomEngineInput = input:
580                    (removeAttrs input [ "icon" ])
581                    // optionalAttrs (input ? icon) {
582                      # Convenience to specify absolute path to icon
583                      iconURL = "file://${input.icon}";
584                    } // (optionalAttrs (input ? iconUpdateURL) {
585                      # Convenience to default iconURL to iconUpdateURL so
586                      # the icon is immediately downloaded from the URL
587                      iconURL = input.iconURL or input.iconUpdateURL;
588                    } // {
589                      # Required for custom engine configurations, loadPaths
590                      # are unique identifiers that are generally formatted
591                      # like: [source]/path/to/engine.xml
592                      loadPath = ''
593                        [home-manager]/programs.firefox.profiles.${profile.name}.search.engines."${
594                          replaceStrings [ "\\" ] [ "\\\\" ] input.name
595                        }"'';
596                    });
597
598                  processEngineInput = name: input:
599                    let
600                      requiredInput = {
601                        inherit name;
602                        isAppProvided = input.isAppProvided or removeAttrs input
603                          [ "metaData" ] == { };
604                        metaData = input.metaData or { };
605                      };
606                    in if requiredInput.isAppProvided then
607                      requiredInput
608                    else
609                      processCustomEngineInput (input // requiredInput);
610
611                  buildEngineConfig = name: input:
612                    mapAttrs' (name: value: {
613                      name = internalFieldNames.${name} or name;
614                      inherit value;
615                    }) (processEngineInput name input);
616
617                  sortEngineConfigs = configs:
618                    let
619                      buildEngineConfigWithOrder = order: name:
620                        let
621                          config = configs.${name} or {
622                            _name = name;
623                            _isAppProvided = true;
624                            _metaData = { };
625                          };
626                        in config // {
627                          _metaData = config._metaData // { inherit order; };
628                        };
629
630                      engineConfigsWithoutOrder =
631                        attrValues (removeAttrs configs profile.search.order);
632
633                      sortedEngineConfigs =
634                        (imap buildEngineConfigWithOrder profile.search.order)
635                        ++ engineConfigsWithoutOrder;
636                    in sortedEngineConfigs;
637
638                  engineInput = profile.search.engines // {
639                    # Infer profile.search.default as an app provided
640                    # engine if it's not in profile.search.engines
641                    ${profile.search.default} =
642                      profile.search.engines.${profile.search.default} or { };
643                  };
644                in sortEngineConfigs (mapAttrs buildEngineConfig engineInput);
645
646                metaData = optionalAttrs (profile.search.default != null) {
647                  current = profile.search.default;
648                  hash = "@hash@";
649                } // {
650                  useSavedOrder = profile.search.order != [ ];
651                };
652              };
653
654              # Home Manager doesn't circumvent user consent and isn't acting
655              # maliciously. We're modifying the search outside of Firefox, but
656              # a claim by Mozilla to remove this would be very anti-user, and
657              # is unlikely to be an issue for our use case.
658              disclaimer = appName:
659                "By modifying this file, I agree that I am doing so "
660                + "only within ${appName} itself, using official, user-driven search "
661                + "engine selection processes, and in a way which does not circumvent "
662                + "user consent. I acknowledge that any attempt to change this file "
663                + "from outside of ${appName} is a malicious act, and will be responded "
664                + "to accordingly.";
665
666              salt = if profile.search.default != null then
667                profile.path + profile.search.default + disclaimer "Firefox"
668              else
669                null;
670            in pkgs.runCommand "search.json.mozlz4" {
671              nativeBuildInputs = with pkgs; [ mozlz4a openssl ];
672              json = builtins.toJSON settings;
673              inherit salt;
674            } ''
675              if [[ -n $salt ]]; then
676                export hash=$(echo -n "$salt" | openssl dgst -sha256 -binary | base64)
677                mozlz4a <(substituteStream json search.json.in --subst-var hash) "$out"
678              else
679                mozlz4a <(echo "$json") "$out"
680              fi
681            '';
682          };
683
684      "${profilesPath}/${profile.path}/extensions" =
685        mkIf (profile.extensions != [ ]) {
686          source = let
687            extensionsEnvPkg = pkgs.buildEnv {
688              name = "hm-firefox-extensions";
689              paths = profile.extensions;
690            };
691          in "${extensionsEnvPkg}/share/mozilla/${extensionPath}";
692          recursive = true;
693          force = true;
694        };
695    }));
696  };
697}