Files
MacNix-config/modules/darwin/dock/default.nix
T

129 lines
3.5 KiB
Nix

{
config,
pkgs,
lib,
...
}:
# Original source: https://gist.github.com/antifuchs/10138c4d838a63c0a05e725ccd7bccdd
with lib;
let
cfg = config.local.dock;
inherit (pkgs) stdenv dockutil;
user = "olaf";
in
{
options = {
local.dock.enable = mkOption {
description = "Enable dock";
default = stdenv.isDarwin;
example = false;
};
local.dock.entries = mkOption {
description = "Entries on the Dock";
type =
with types;
listOf (submodule {
options = {
path = lib.mkOption { type = str; };
section = lib.mkOption {
type = str;
default = "apps";
};
options = lib.mkOption {
type = str;
default = "";
};
};
});
readOnly = true;
};
};
config = mkIf cfg.enable (
let
normalize = path: if hasSuffix ".app" path then path + "/" else path;
entryURI =
path:
"file://"
+ (builtins.replaceStrings
[
" "
"!"
"\""
"#"
"$"
"%"
"&"
"'"
"("
")"
]
[
"%20"
"%21"
"%22"
"%23"
"%24"
"%25"
"%26"
"%27"
"%28"
"%29"
]
(normalize path)
);
wantURIs = concatMapStrings (entry: "${entryURI entry.path}\n") cfg.entries;
createEntries = concatMapStrings (
entry:
''
if [ -e ${escapeShellArg entry.path} ]; then
runDockutil --no-restart --add ${escapeShellArg entry.path} --section ${escapeShellArg entry.section} ${entry.options} /Users/${user} || exit 1
fi
''
) cfg.entries;
in
{
system.activationScripts.postActivation.text = ''
echo >&2 "Setting up the Dock for ${user}..."
if [ "$(/usr/bin/stat -f %Su /dev/console)" = ${escapeShellArg user} ]; then
dockUid="$(/usr/bin/id -u ${escapeShellArg user})"
runDockutil() {
# Avoid dockutil's root-only defaults-export pipe deadlock.
local status
if ${pkgs.coreutils}/bin/timeout --kill-after=5s 30s \
/bin/launchctl asuser "$dockUid" \
/usr/bin/sudo -H -n -u ${escapeShellArg user} \
${dockutil}/bin/dockutil "$@"; then
return 0
else
status=$?
echo >&2 "Dock setup failed: dockutil $* exited with status $status (timeout: 30s)."
return "$status"
fi
}
dockListing="$(runDockutil --list /Users/${user})" || exit 1
haveURIs="$(printf '%s\n' "$dockListing" | ${pkgs.coreutils}/bin/cut -f2)"
if ! diff -wu <(echo "$haveURIs") <(echo -n ${escapeShellArg wantURIs}) >&2; then
echo >&2 "Resetting Dock."
runDockutil --no-restart --remove all /Users/${user} || exit 1
${createEntries}
if ! ${pkgs.coreutils}/bin/timeout --kill-after=5s 30s \
/bin/launchctl kickstart -k "gui/$dockUid/com.apple.Dock.agent"; then
echo >&2 "Dock setup failed: could not restart the Dock for ${user}."
exit 1
fi
fi
echo >&2 "Dock setup complete."
else
echo >&2 "Skipping Dock setup: ${user} is not the active console user. Re-run activation after logging in."
fi
'';
}
);
}