1# This module declares the options to define a *display manager*, the
2# program responsible for handling X logins (such as LightDM, GDM, or SDDM).
3# The display manager allows the user to select a *session
4# type*. When the user logs in, the display manager starts the
5# *session script* ("xsession" below) to launch the selected session
6# type. The session type defines two things: the *desktop manager*
7# (e.g., KDE, Gnome or a plain xterm), and optionally the *window
8# manager* (e.g. kwin or twm).
9
10{
11 config,
12 lib,
13 options,
14 pkgs,
15 ...
16}:
17
18let
19 inherit (lib)
20 mkOption
21 types
22 literalExpression
23 optionalString
24 ;
25
26 cfg = config.services.xserver;
27 xorg = pkgs.xorg;
28
29 fontconfig = config.fonts.fontconfig;
30 xresourcesXft = pkgs.writeText "Xresources-Xft" ''
31 Xft.antialias: ${if fontconfig.antialias then "1" else "0"}
32 Xft.rgba: ${fontconfig.subpixel.rgba}
33 Xft.lcdfilter: lcd${fontconfig.subpixel.lcdfilter}
34 Xft.hinting: ${if fontconfig.hinting.enable then "1" else "0"}
35 Xft.autohint: ${if fontconfig.hinting.autohint then "1" else "0"}
36 Xft.hintstyle: ${fontconfig.hinting.style}
37 '';
38
39 # FIXME: this is an ugly hack.
40 # Some sessions (read: most WMs) don't activate systemd's `graphical-session.target`.
41 # Other sessions (read: most non-WMs) expect `graphical-session.target` to be reached
42 # when the entire session is actually ready. We used to just unconditionally force
43 # `graphical-session.target` to be activated in the session wrapper so things like
44 # xdg-autostart-generator work on sessions that are wrong, but this broke sessions
45 # that do things right. So, preserve this behavior (with some extra steps) by matching
46 # on XDG_CURRENT_DESKTOP and deliberately ignoring sessions we know can do the right thing.
47 fakeSession = action: ''
48 session_is_systemd_aware=$(
49 IFS=:
50 for i in $XDG_CURRENT_DESKTOP; do
51 case $i in
52 KDE|GNOME|Pantheon|X-NIXOS-SYSTEMD-AWARE) echo "1"; exit; ;;
53 *) ;;
54 esac
55 done
56 )
57
58 if [ -z "$session_is_systemd_aware" ]; then
59 /run/current-system/systemd/bin/systemctl --user ${action} nixos-fake-graphical-session.target
60 fi
61 '';
62
63 # file provided by services.xserver.displayManager.sessionData.wrapper
64 xsessionWrapper = pkgs.writeScript "xsession-wrapper" ''
65 #! ${pkgs.bash}/bin/bash
66
67 # Shared environment setup for graphical sessions.
68
69 . /etc/profile
70 if test -f ~/.profile; then
71 source ~/.profile
72 fi
73
74 cd "$HOME"
75
76 # Allow the user to execute commands at the beginning of the X session.
77 if test -f ~/.xprofile; then
78 source ~/.xprofile
79 fi
80
81 ${optionalString config.services.displayManager.logToJournal ''
82 if [ -z "$_DID_SYSTEMD_CAT" ]; then
83 export _DID_SYSTEMD_CAT=1
84 exec ${config.systemd.package}/bin/systemd-cat -t xsession "$0" "$@"
85 fi
86 ''}
87
88 ${optionalString config.services.displayManager.logToFile ''
89 exec &> >(tee ~/.xsession-errors)
90 ''}
91
92 # Load X defaults. This should probably be safe on wayland too.
93 ${xorg.xrdb}/bin/xrdb -merge ${xresourcesXft}
94 if test -e ~/.Xresources; then
95 ${xorg.xrdb}/bin/xrdb -merge ~/.Xresources
96 elif test -e ~/.Xdefaults; then
97 ${xorg.xrdb}/bin/xrdb -merge ~/.Xdefaults
98 fi
99
100 # Import environment variables into the systemd user environment.
101 ${optionalString (cfg.displayManager.importedVariables != [ ]) (
102 "/run/current-system/systemd/bin/systemctl --user import-environment "
103 + toString (lib.unique cfg.displayManager.importedVariables)
104 )}
105
106 # Speed up application start by 50-150ms according to
107 # https://kdemonkey.blogspot.com/2008/04/magic-trick.html
108 compose_cache="''${XCOMPOSECACHE:-$HOME/.compose-cache}"
109 mkdir -p "$compose_cache"
110 # To avoid accidentally deleting a wrongly set up XCOMPOSECACHE directory,
111 # defensively try to delete cache *files* only, following the file format specified in
112 # https://gitlab.freedesktop.org/xorg/lib/libx11/-/blob/master/modules/im/ximcp/imLcIm.c#L353-358
113 # sprintf (*res, "%s/%c%d_%03x_%08x_%08x", dir, _XimGetMyEndian(), XIM_CACHE_VERSION, (unsigned int)sizeof (DefTree), hash, hash2);
114 ${pkgs.findutils}/bin/find "$compose_cache" -maxdepth 1 -regextype posix-extended -regex '.*/[Bl][0-9]+_[0-9a-f]{3}_[0-9a-f]{8}_[0-9a-f]{8}' -delete
115 unset compose_cache
116
117 # Work around KDE errors when a user first logs in and
118 # .local/share doesn't exist yet.
119 mkdir -p "''${XDG_DATA_HOME:-$HOME/.local/share}"
120
121 unset _DID_SYSTEMD_CAT
122
123 ${cfg.displayManager.sessionCommands}
124
125 ${fakeSession "start"}
126
127 # Allow the user to setup a custom session type.
128 if test -x ~/.xsession; then
129 eval exec ~/.xsession "$@"
130 fi
131
132 if test "$1"; then
133 # Run the supplied session command. Remove any double quotes with eval.
134 eval exec "$@"
135 else
136 # TODO: Do we need this? Should not the session always exist?
137 echo "error: unknown session $1" 1>&2
138 exit 1
139 fi
140 '';
141in
142
143{
144 options = {
145
146 services.xserver.displayManager = {
147
148 xauthBin = mkOption {
149 internal = true;
150 default = "${xorg.xauth}/bin/xauth";
151 defaultText = literalExpression ''"''${pkgs.xorg.xauth}/bin/xauth"'';
152 description = "Path to the {command}`xauth` program used by display managers.";
153 };
154
155 xserverBin = mkOption {
156 type = types.path;
157 description = "Path to the X server used by display managers.";
158 };
159
160 xserverArgs = mkOption {
161 type = types.listOf types.str;
162 default = [ ];
163 example = [
164 "-ac"
165 "-logverbose"
166 "-verbose"
167 "-nolisten tcp"
168 ];
169 description = "List of arguments for the X server.";
170 };
171
172 setupCommands = mkOption {
173 type = types.lines;
174 default = "";
175 description = ''
176 Shell commands executed just after the X server has started.
177
178 This option is only effective for display managers for which this feature
179 is supported; currently these are LightDM, GDM and SDDM.
180 '';
181 };
182
183 sessionCommands = mkOption {
184 type = types.lines;
185 default = "";
186 example = ''
187 xmessage "Hello World!" &
188 '';
189 description = ''
190 Shell commands executed just before the window or desktop manager is
191 started. These commands are not currently sourced for Wayland sessions.
192 '';
193 };
194
195 session = mkOption {
196 default = [ ];
197 type = types.listOf types.attrs;
198 example = literalExpression ''
199 [ { manage = "desktop";
200 name = "xterm";
201 start = '''
202 ''${pkgs.xterm}/bin/xterm -ls &
203 waitPID=$!
204 ''';
205 }
206 ]
207 '';
208 description = ''
209 List of sessions supported with the command used to start each
210 session. Each session script can set the
211 {var}`waitPID` shell variable to make this script
212 wait until the end of the user session. Each script is used
213 to define either a window manager or a desktop manager. These
214 can be differentiated by setting the attribute
215 {var}`manage` either to `"window"`
216 or `"desktop"`.
217
218 The list of desktop manager and window manager should appear
219 inside the display manager with the desktop manager name
220 followed by the window manager name.
221 '';
222 };
223
224 importedVariables = mkOption {
225 type = types.listOf (types.strMatching "[a-zA-Z_][a-zA-Z0-9_]*");
226 visible = false;
227 description = ''
228 Environment variables to import into the systemd user environment.
229 '';
230 };
231
232 };
233
234 };
235
236 config = {
237 services.displayManager.sessionData.wrapper = xsessionWrapper;
238
239 services.xserver.displayManager.xserverBin = "${xorg.xorgserver.out}/bin/X";
240
241 services.xserver.displayManager.importedVariables = [
242 # This is required by user units using the session bus.
243 "DBUS_SESSION_BUS_ADDRESS"
244 # These are needed by the ssh-agent unit.
245 "DISPLAY"
246 "XAUTHORITY"
247 # This is required to specify session within user units (e.g. loginctl lock-session).
248 "XDG_SESSION_ID"
249 ];
250
251 systemd.user.targets.nixos-fake-graphical-session = {
252 unitConfig = {
253 Description = "Fake graphical-session target for non-systemd-aware sessions";
254 BindsTo = "graphical-session.target";
255 };
256 };
257
258 # Create desktop files and scripts for starting sessions for WMs/DMs
259 # that do not have upstream session files (those defined using services.{display,desktop,window}Manager.session options).
260 services.displayManager.sessionPackages =
261 let
262 dms = lib.filter (s: s.manage == "desktop") cfg.displayManager.session;
263 wms = lib.filter (s: s.manage == "window") cfg.displayManager.session;
264
265 # Script responsible for starting the window manager and the desktop manager.
266 xsession =
267 dm: wm:
268 pkgs.writeScript "xsession" ''
269 #! ${pkgs.bash}/bin/bash
270
271 # Legacy session script used to construct .desktop files from
272 # `services.xserver.displayManager.session` entries. Called from
273 # `sessionWrapper`.
274
275 # Start the window manager.
276 ${wm.start}
277
278 # Start the desktop manager.
279 ${dm.start}
280
281 ${optionalString cfg.updateDbusEnvironment ''
282 ${lib.getBin pkgs.dbus}/bin/dbus-update-activation-environment --systemd --all
283 ''}
284
285 test -n "$waitPID" && wait "$waitPID"
286
287 ${fakeSession "stop"}
288
289 exit 0
290 '';
291 in
292 # We will generate every possible pair of WM and DM.
293 lib.concatLists (
294 lib.mapCartesianProduct
295 (
296 { dm, wm }:
297 let
298 sessionName = "${dm.name}${optionalString (wm.name != "none") ("+" + wm.name)}";
299 prettyName =
300 if dm.name != "none" then
301 "${dm.prettyName or dm.name}${
302 optionalString (wm.name != "none") (" (" + (wm.prettyName or wm.name) + ")")
303 }"
304 else
305 (wm.prettyName or wm.name);
306 script = xsession dm wm;
307 desktopNames = if dm ? desktopNames then lib.concatStringsSep ";" dm.desktopNames else sessionName;
308 in
309 lib.optional (dm.name != "none" || wm.name != "none") (
310 pkgs.writeTextFile {
311 name = "${sessionName}-xsession";
312 destination = "/share/xsessions/${sessionName}.desktop";
313 # Desktop Entry Specification:
314 # - https://standards.freedesktop.org/desktop-entry-spec/latest/
315 # - https://standards.freedesktop.org/desktop-entry-spec/latest/ar01s06.html
316 text = ''
317 [Desktop Entry]
318 Version=1.0
319 Type=XSession
320 TryExec=${script}
321 Exec=${script}
322 Name=${prettyName}
323 DesktopNames=${desktopNames}
324 '';
325 }
326 // {
327 providedSessions = [ sessionName ];
328 }
329 )
330 )
331 {
332 dm = dms;
333 wm = wms;
334 }
335 );
336 };
337
338 imports = [
339 (lib.mkRemovedOptionModule
340 [ "services" "xserver" "displayManager" "desktopManagerHandlesLidAndPower" ]
341 "The option is no longer necessary because all display managers have already delegated lid management to systemd."
342 )
343 (lib.mkRenamedOptionModule
344 [ "services" "xserver" "displayManager" "job" "logsXsession" ]
345 [ "services" "displayManager" "logToFile" ]
346 )
347 (lib.mkRenamedOptionModule
348 [ "services" "xserver" "displayManager" "logToJournal" ]
349 [ "services" "displayManager" "logToJournal" ]
350 )
351 (lib.mkRenamedOptionModule
352 [ "services" "xserver" "displayManager" "extraSessionFilesPackages" ]
353 [ "services" "displayManager" "sessionPackages" ]
354 )
355 ];
356
357}