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