aboutsummaryrefslogtreecommitdiff
;;; GNU Guix --- Functional package management for GNU ;;; Copyright © 2019, 2020 L p R n d n <guix@lprndn.info> ;;; Copyright © 2020 Ricardo Wurmus <rekado@elephly.net> ;;; Copyright © 2022 Maxim Cournoyer <maxim.cournoyer@gmail.com> ;;; ;;; This file is part of GNU Guix. ;;; ;;; GNU Guix is free software; you can redistribute it and/or modify it ;;; under the terms of the GNU General Public License as published by ;;; the Free Software Foundation; either version 3 of the License, or (at ;;; your option) any later version. ;;; ;;; GNU Guix is distributed in the hope that it will be useful, but ;;; WITHOUT ANY WARRANTY; without even the implied warranty of ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;;; GNU General Public License for more details. ;;; ;;; You should have received a copy of the GNU General Public License ;;; along with GNU Guix. If not, see <http://www.gnu.org/licenses/>. (define-module (gnu services lightdm) #:use-module (gnu artwork) #:use-module (gnu packages admin) #:use-module (gnu packages display-managers) #:use-module (gnu packages freedesktop) #:use-module (gnu packages gnome) #:use-module (gnu packages vnc) #:use-module (gnu packages xorg) #:use-module (gnu services configuration) #:use-module (gnu services dbus) #:use-module (gnu services desktop) #:use-module (gnu services shepherd) #:use-module (gnu services xorg) #:use-module (gnu services) #:use-module (gnu system pam) #:use-module (gnu system shadow) #:use-module (guix diagnostics) #:use-module (guix gexp) #:use-module (guix i18n) #:use-module (guix records) #:use-module (ice-9 format) #:use-module (ice-9 match) #:use-module (srfi srfi-1) #:use-module (srfi srfi-26) #:export (lightdm-seat-configuration lightdm-seat-configuration? lightdm-seat-configuration-name lightdm-seat-configuration-type lightdm-seat-configuration-user-session lightdm-seat-configuration-autologin-user lightdm-seat-configuration-greeter-session lightdm-seat-configuration-xserver-command lightdm-seat-configuration-session-wrapper lightdm-seat-configuration-extra-config lightdm-gtk-greeter-configuration lightdm-gtk-greeter-configuration? lightdm-gtk-greeter-configuration-lightdm-gtk-greeter lightdm-gtk-greeter-configuration-assets lightdm-gtk-greeter-configuration-theme-name lightdm-gtk-greeter-configuration-icon-theme-name lightdm-gtk-greeter-configuration-cursor-theme-name lightdm-gtk-greeter-configuration-allow-debug lightdm-gtk-greeter-configuration-background lightdm-gtk-greeter-configuration-a11y-states lightdm-gtk-greeter-configuration-reader lightdm-gtk-greeter-configuration-extra-config lightdm-configuration lightdm-configuration? lightdm-configuration-lightdm lightdm-configuration-allow-empty-passwords? lightdm-configuration-xorg-configuration lightdm-configuration-greeters lightdm-configuration-seats lightdm-configuration-xdmcp? lightdm-configuration-xdmcp-listen-address lightdm-configuration-vnc-server? lightdm-configuration-vnc-server-command lightdm-configuration-vnc-server-listen-address lightdm-configuration-vnc-server-port lightdm-configuration-extra-config lightdm-service-type)) ;;; ;;; Greeters. ;;; (define list-of-file-likes? (list-of file-like?)) (define %a11y-states '(contrast font keyboard reader)) (define (a11y-state? value) (memq value %a11y-states)) (define list-of-a11y-states? (list-of a11y-state?)) (define-maybe boolean) (define (serialize-boolean name value) (define (strip-trailing-? name) ;; field? -> field (let ((str (symbol->string name))) (if (string-suffix? "?" str) (string-drop-right str 1) str))) (format #f "~a=~:[false~;true~]~%" (strip-trailing-? name) value)) (define-maybe file-like) (define (serialize-file-like name value) #~(format #f "~a=~a~%" '#$name #$value)) (define (serialize-list-of-a11y-states name value) (format #f "~a=~a~%" name (string-join (map symbol->string value) ";"))) (define (serialize-string name value) (format #f "~a=~a~%" name value)) (define (serialize-number name value) (format #f "~a=~a~%" name value)) (define (serialize-list-of-strings _ value) (string-join value "\n")) (define-configuration lightdm-gtk-greeter-configuration (lightdm-gtk-greeter (file-like lightdm-gtk-greeter) "The lightdm-gtk-greeter package to use." empty-serializer) (assets (list-of-file-likes (list adwaita-icon-theme gnome-themes-extra ;; FIXME: hicolor-icon-theme should be in the ;; packages of the desktop templates. hicolor-icon-theme)) "The list of packages complementing the greeter, such as package providing icon themes." empty-serializer) (theme-name (string "Adwaita") "The name of the theme to use.") (icon-theme-name (string "Adwaita") "The name of the icon theme to use.") (cursor-theme-name (string "Adwaita") "The name of the cursor theme to use.") (cursor-theme-size (number 16) "The size to use for the cursor theme.") (allow-debugging? maybe-boolean "Set to #t to enable debug log level.") (background (file-like (file-append %artwork-repository "/backgrounds/guix-checkered-16-9.svg")) "The background image to use.") ;; FIXME: This should be enabled by default, but it currently doesn't work, ;; failing to connect to D-Bus, causing the login to fail. (at-spi-enabled? (boolean #f) "Enable accessibility support through the Assistive Technology Service Provider Interface (AT-SPI).") (a11y-states (list-of-a11y-states %a11y-states) "The accessibility features to enable, given as list of symbols.") (reader maybe-file-like "The command to use to launch a screen reader.") (extra-config (list-of-strings '()) "Extra configuration values to append to the LightDM GTK Greeter configuration file.")) (define (strip-record-type-name-brackets name) "Remove the '<' and '>' brackets from NAME, a symbol." (let ((name (symbol->string name))) (if (and (string-prefix? "<" name) (string-suffix? ">" name)) (string->symbol (string-drop (string-drop-right name 1) 1)) (error "unexpected record type name" name)))) (define (config->name config) "Return the constructor name (a symbol) from CONFIG." (strip-record-type-name-brackets (record-type-name (struct-vtable config)))) (define (greeter-configuration->greeter-fields config) "Return the fields of CONFIG, a greeter configuration." (match config ;; Note: register any new greeter configuration here. ((? lightdm-gtk-greeter-configuration?) lightdm-gtk-greeter-configuration-fields))) (define (greeter-configuration->packages config) "Return the list of greeter packages, including assets, used by CONFIG, a greeter configuration." (match config ;; Note: register any new greeter configuration here. ((? lightdm-gtk-greeter-configuration?) (cons (lightdm-gtk-greeter-configuration-lightdm-gtk-greeter config) (lightdm-gtk-greeter-configuration-assets config))))) ;;; TODO: Implement directly in (gnu services configuration), perhaps by ;;; making the FIELDS argument optional. (define (serialize-configuration* config) "Like `serialize-configuration', but not requiring to provide a FIELDS argument." (define fields (greeter-configuration->greeter-fields config)) (serialize-configuration config fields)) (define (greeter-configuration->conf-name config) "Return the file name of CONFIG, a greeter configuration." (format #f "~a.conf" (greeter-configuration->greeter-session config))) (define (greeter-configuration->file config) "Serialize CONFIG into a file under the output directory, so that it can be easily added to XDG_CONF_DIRS." (computed-file (greeter-configuration->conf-name config) #~(begin (call-with-output-file #$output (lambda (port) (format port (string-append "[greeter]\n" #$(serialize-configuration* config)))))))) ;;; ;;; Seats. ;;; (define seat-name? string?) (define (serialize-seat-name _ value) (format #f "[Seat:~a]~%" value)) (define (seat-type? type) (memq type '(local xremote))) (define (serialize-seat-type name value) (format #f "~a=~a~%" name value)) (define-maybe seat-type) (define (greeter-session? value) (memq value '(lightdm-gtk-greeter))) (define (serialize-greeter-session name value) (format #f "~a=~a~%" name value)) (define-maybe greeter-session) (define-maybe string) ;;; Note: all the fields except for the seat name should be 'maybe's, since ;;; the real default value is set by the %lightdm-seat-default define later, ;;; and this avoids repeating ourselves in the serialized configuration file. (define-configuration lightdm-seat-configuration (name seat-name "The name of the seat. An asterisk (*) can be used in the name to apply the seat configuration to all the seat names it matches.") (user-session maybe-string "The session to use by default. The session name must be provided as a lowercase string, such as @code{\"gnome\"}, @code{\"ratpoison\"}, etc.") (type (seat-type 'local) "The type of the seat, either the @code{local} or @code{xremote} symbol.") (autologin-user maybe-string "The username to automatically log in with by default.") (greeter-session (greeter-session 'lightdm-gtk-greeter) "The greeter session to use, specified as a symbol. Currently, only @code{lightdm-gtk-greeter} is supported.") ;; Note: xserver-command must be lazily computed, so that it can be ;; overridden via 'lightdm-configuration-xorg-configuration'. (xserver-command maybe-file-like "The Xorg server command to run.") (session-wrapper (file-like (xinitrc)) "The xinitrc session wrapper to use.") (extra-config (list-of-strings '()) "Extra configuration values to append to the seat configuration section.")) (define (greeter-session->greater-configuration-pred identifier) "Return the predicate to check if a configuration is of the type specifying a greeter identified by IDENTIFIER." (match identifier ;; Note: register any new greeter identifier here. ('lightdm-gtk-greeter lightdm-gtk-greeter-configuration?))) (define (greeter-configuration->greeter-session config) "Given CONFIG, a greeter configuration object, return its identifier, a symbol." (let ((suffix "-configuration") (greeter-conf-name (config->name config))) (string->symbol (string-drop-right (symbol->string greeter-conf-name) (string-length suffix))))) (define list-of-seat-configurations? (list-of lightdm-seat-configuration?)) ;;; ;;; LightDM. ;;; (define (greeter-configuration? config) (or (lightdm-gtk-greeter-configuration? config) ;; Note: register any new greeter configuration here. )) (define (list-of-greeter-configurations? greeter-configs) (and ((list-of greeter-configuration?) greeter-configs) ;; Greeter configurations must also not be provided more than once. (let* ((types (map (compose record-type-name struct-vtable) greeter-configs)) (dupes (filter (lambda (type) (< 1 (count (cut eq? type <>) types))) types))) (unless (null? dupes) (leave (G_ "duplicate greeter configurations: ~a~%") dupes))))) (define-configuration/no-serialization lightdm-configuration (lightdm (file-like lightdm) "The lightdm package to use.") (allow-empty-passwords? (boolean #f) "Whether users not having a password set can login.") (debug? (boolean #f) "Enable verbose output.") (xorg-configuration (xorg-configuration (xorg-configuration)) "The default Xorg server configuration to use to generate the Xorg server start script. It can be refined per seat via the @code{xserver-command} of the @code{<lightdm-seat-configuration>} record, if desired.") (greeters (list-of-greeter-configurations (list (lightdm-gtk-greeter-configuration))) "The LightDM greeter configurations specifying the greeters to use.") (seats (list-of-seat-configurations (list (lightdm-seat-configuration (name "*")))) "The seat configurations to use. A LightDM seat is akin to a user.") (xdmcp? (boolean #f) "Whether a XDMCP server should listen on port UDP 177.") (xdmcp-listen-address maybe-string "The host or IP address the XDMCP server listens for incoming connections. When unspecified, listen on for any hosts/IP addresses.") (vnc-server? (boolean #f) "Whether a VNC server is started.") (vnc-server-command (file-like (file-append tigervnc-server "/bin/Xvnc")) "The Xvnc command to use for the VNC server, it's possible to provide extra options not otherwise exposed along the command, for example to disable security: @lisp (vnc-server-command (file-append tigervnc-server \"/bin/Xvnc\" \" -SecurityTypes None\" )) @end lisp Or to set a PasswordFile for the classic (unsecure) VncAuth mechanism: @lisp (vnc-server-command (file-append tigervnc-server \"/bin/Xvnc\" \" -PasswordFile /var/lib/lightdm/.vnc/passwd\")) @end lisp The password file should be manually created using the @command{vncpasswd} command. Note that LightDM will create new sessions for VNC users, which means they need to authenticate in the same way as local users would. ") (vnc-server-listen-address maybe-string "The host or IP address the VNC server listens for incoming connections. When unspecified, listen for any hosts/IP addresses.") (vnc-server-port (number 5900) "The TCP port the VNC server should listen to.") (extra-config (list-of-strings '()) "Extra configuration values to append to the LightDM configuration file.")) (define (lightdm-configuration->packages config) "Return all the greeter packages and their assets defined in CONFIG, a <lightdm-configuration> object, as well as the lightdm package itself." (cons (lightdm-configuration-lightdm config) (append-map greeter-configuration->packages (lightdm-configuration-greeters config)))) (define (validate-lightdm-configuration config) "Sanity check CONFIG, a <lightdm-configuration> record instance." ;; This is required to make inter-field validations, such as between the ;; seats and greeters. (let* ((seats (lightdm-configuration-seats config)) (greeter-sessions (delete-duplicates (map lightdm-seat-configuration-greeter-session seats) eq?)) (greeter-configurations (lightdm-configuration-greeters config)) (missing-greeters (filter-map (lambda (id) (define pred (greeter-session->greater-configuration-pred id)) (if (find pred greeter-configurations) #f ;happy path id)) greeter-sessions))) (unless (null? missing-greeters) (leave (G_ "no greeter configured for seat greeter sessions: ~a~%") missing-greeters)))) (define (lightdm-configuration-file config) (match-record config <lightdm-configuration> (xorg-configuration seats xdmcp? xdmcp-listen-address vnc-server? vnc-server-command vnc-server-listen-address vnc-server-port extra-config) (apply mixed-text-file "lightdm.conf" " # # General configuration # [LightDM] greeter-user=lightdm sessions-directory=/run/current-system/profile/share/xsessions\ :/run/current-system/profile/share/wayland-sessions remote-sessions-directory=/run/current-system/profile/share/remote-sessions " #~(string-join '#$extra-config "\n") " # # XDMCP Server configuration # [XDMCPServer] enabled=" (if xdmcp? "true" "false") "\n" (if (maybe-value-set? xdmcp-listen-address) (format #f "xdmcp-listen-address=~a" xdmcp-listen-address) "") " # # VNC Server configuration # [VNCServer] enabled=" (if vnc-server? "true" "false") " command=" vnc-server-command " port=" (number->string vnc-server-port) "\n" (if (maybe-value-set? vnc-server-listen-address) (format #f "vnc-server-listen-address=~a" vnc-server-listen-address) "") " # # Seat configuration. # " (map (lambda (seat) ;; This complication exists to propagate a default value for ;; the 'xserver-command' field of the seats. Having a ;; 'xorg-configuration' field at the root of the ;; lightdm-configuration enables the use of ;; 'set-xorg-configuration' and can be more convenient. (let ((seat* (if (maybe-value-set? (lightdm-seat-configuration-xserver-command seat)) seat (lightdm-seat-configuration (inherit seat) (xserver-command (xorg-start-command xorg-configuration)))))) (serialize-configuration seat* lightdm-seat-configuration-fields))) seats)))) (define (lightdm-configuration-directory config) "Return a directory containing the serialized lightdm configuration and all the serialized greeter configurations from CONFIG." (file-union "etc-lightdm" (cons `("lightdm.conf" ,(lightdm-configuration-file config)) (map (lambda (g) `(,(greeter-configuration->conf-name g) ,(greeter-configuration->file g))) (lightdm-configuration-greeters config))))) (define %lightdm-accounts (list (user-group (name "lightdm") (system? #t)) (user-account (name "lightdm") (group "lightdm") (system? #t) (comment "LightDM user") (home-directory "/var/lib/lightdm") (shell (file-append shadow "/sbin/nologin"))))) (define %lightdm-activation ;; Ensure /var/lib/lightdm is owned by the "lightdm" user. Adapted from the ;; %gdm-activation. (with-imported-modules '((guix build utils)) #~(begin (use-modules (guix build utils)) (define (ensure-ownership directory) (let* ((lightdm (getpwnam "lightdm")) (uid (passwd:uid lightdm)) (gid (passwd:gid lightdm)) (st (stat directory #f))) ;; Recurse into directory only if it has wrong ownership. (when (and st (or (not (= uid (stat:uid st))) (not (= gid (stat:gid st))))) (for-each (lambda (file) (chown file uid gid)) (find-files directory #:directories? #t))))) (when (not (stat "/var/lib/lightdm-data" #f)) (mkdir-p "/var/lib/lightdm-data")) (for-each ensure-ownership '("/var/lib/lightdm" "/var/lib/lightdm-data"))))) (define (lightdm-pam-service config) "Return a PAM service for @command{lightdm}." (unix-pam-service "lightdm" #:login-uid? #t #:allow-empty-passwords? (lightdm-configuration-allow-empty-passwords? config))) (define (lightdm-greeter-pam-service) "Return a PAM service for @command{lightdm-greeter}." (pam-service (name "lightdm-greeter") (auth (list ;; Load environment from /etc/environment and ~/.pam_environment. (pam-entry (control "required") (module "pam_env.so")) ;; Always let the greeter start without authentication. (pam-entry (control "required") (module "pam_permit.so")))) ;; No action required for account management (account (list (pam-entry (control "required") (module "pam_permit.so")))) ;; Prohibit changing password. (password (list (pam-entry (control "required") (module "pam_deny.so")))) ;; Setup session. (session (list (pam-entry (control "required") (module "pam_unix.so")))))) (define (lightdm-autologin-pam-service) "Return a PAM service for @command{lightdm-autologin}}." (pam-service (name "lightdm-autologin") (auth (list ;; Block login if user is globally disabled. (pam-entry (control "required") (module "pam_nologin.so")) (pam-entry (control "required") (module "pam_succeed_if.so") (arguments (list "uid >= 1000"))) ;; Allow access without authentication. (pam-entry (control "required") (module "pam_permit.so")))) ;; Stop autologin if account requires action. (account (list (pam-entry (control "required") (module "pam_unix.so")))) ;; Prohibit changing password. (password (list (pam-entry (control "required") (module "pam_deny.so")))) ;; Setup session. (session (list (pam-entry (control "required") (module "pam_unix.so")))))) (define (lightdm-pam-services config) (list (lightdm-pam-service config) (lightdm-greeter-pam-service) (lightdm-autologin-pam-service))) (define (lightdm-shepherd-service config) "Return a <lightdm-service> for LightDM using CONFIG." (validate-lightdm-configuration config) (define lightdm-command #~(list #$(file-append (lightdm-configuration-lightdm config) "/sbin/lightdm") #$@(if (lightdm-configuration-debug? config) #~("--debug") #~()))) (define lightdm-paths (let ((lightdm (lightdm-configuration-lightdm config))) #~(string-join '#$(map (lambda (dir) (file-append lightdm dir)) '("/bin" "/sbin" "/libexec")) ":"))) (define data-dirs ;; LightDM itself needs to be in XDG_DATA_DIRS for the accountsservice ;; interface it provides to be picked up. The greeters must also be in ;; XDG_DATA_DIRS to be found. (let ((packages (lightdm-configuration->packages config))) #~(string-join '#$(map (cut file-append <> "/share") packages) ":"))) (list (shepherd-service (documentation "LightDM display manager") (requirement '(pam dbus-system user-processes host-name)) (provision '(lightdm display-manager xorg-server)) (respawn? #f) (start ;; Note: sadly, environment variables defined for 'lightdm' are ;; cleared and/or overridden by /etc/profile by its spawned greeters, ;; so an out-of-band means such as /etc is required. #~(make-forkexec-constructor #$lightdm-command ;; Lightdm needs itself in its PATH. #:environment-variables (list ;; It looks for greeter .desktop files as ;; well as lightdm accountsservice ;; interface in XDG_DATA_DIRS. (string-append "XDG_DATA_DIRS=" #$data-dirs) (string-append "PATH=" #$lightdm-paths)))) (stop #~(make-kill-destructor))))) (define (lightdm-etc-service config) "Return a list of FILES for @var{etc-service-type} to build the /etc/lightdm directory using CONFIG" (list `("lightdm" ,(lightdm-configuration-directory config)))) (define lightdm-service-type (handle-xorg-configuration lightdm-configuration (service-type (name 'lightdm) (default-value (lightdm-configuration)) (extensions (list (service-extension pam-root-service-type lightdm-pam-services) (service-extension shepherd-root-service-type lightdm-shepherd-service) (service-extension activation-service-type (const %lightdm-activation)) (service-extension dbus-root-service-type (compose list lightdm-configuration-lightdm)) (service-extension polkit-service-type (compose list lightdm-configuration-lightdm)) (service-extension account-service-type (const %lightdm-accounts)) ;; Add 'lightdm' to the system profile, so that its ;; 'share/accountsservice' D-Bus service extension directory can be ;; found via the 'XDG_DATA_DIRS=/run/current-system/profile/share' ;; environment variable set in the wrapper of the ;; libexec/accounts-daemon binary of the accountsservice package. ;; This daemon is spawned by D-Bus, and there's little we can do to ;; affect its environment. For more reading, see: ;; https://github.com/NixOS/nixpkgs/issues/45059. (service-extension profile-service-type lightdm-configuration->packages) ;; This is needed for lightdm and greeter ;; to find their configuration (service-extension etc-service-type lightdm-etc-service))) (description "Run @code{lightdm}, the LightDM graphical login manager.")))) ;;; ;;; Generate documentation. ;;; (define (generate-doc) (configuration->documentation 'lightdm-configuration) (configuration->documentation 'lightdm-gtk-greeter-configuration) (configuration->documentation 'lightdm-seat-configuration)) ef='#n824'>824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952
;;; guix-list.el --- List buffers for displaying entries   -*- lexical-binding: t -*-

;; Copyright © 2014, 2015 Alex Kost <alezost@gmail.com>

;; This file is part of GNU Guix.

;; GNU Guix is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.

;; GNU Guix is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;; GNU General Public License for more details.

;; You should have received a copy of the GNU General Public License
;; along with this program.  If not, see <http://www.gnu.org/licenses/>.

;;; Commentary:

;; This file provides a list-like buffer for displaying information
;; about Guix packages and generations.

;;; Code:

(require 'cl-lib)
(require 'tabulated-list)
(require 'guix-info)
(require 'guix-base)
(require 'guix-entry)
(require 'guix-utils)

(defgroup guix-list nil
  "General settings for list buffers."
  :prefix "guix-list-"
  :group 'guix)

(defgroup guix-list-faces nil
  "Faces for list buffers."
  :group 'guix-list
  :group 'guix-faces)

(defface guix-list-file-path
  '((t :inherit guix-info-file-path))
  "Face used for file paths."
  :group 'guix-list-faces)

(defface guix-list-time
  '((t :inherit guix-info-time))
  "Face used for time stamps."
  :group 'guix-list-faces)

(defvar guix-list-format
  `((package
     (name guix-package-list-get-name 20 t)
     (version nil 10 nil)
     (outputs nil 13 t)
     (installed guix-package-list-get-installed-outputs 13 t)
     (synopsis guix-list-get-one-line 30 nil))
    (output
     (name guix-package-list-get-name 20 t)
     (version nil 10 nil)
     (output nil 9 t)
     (installed nil 12 t)
     (synopsis guix-list-get-one-line 30 nil))
    (generation
     (number nil 5 guix-list-sort-numerically-0 :right-align t)
     (current guix-generation-list-get-current 10 t)
     (time guix-list-get-time 20 t)
     (path guix-list-get-file-path 30 t)))
  "List of format values of the displayed columns.
Each element of the list has a form:

  (ENTRY-TYPE . ((PARAM VALUE-FUN WIDTH SORT . PROPS) ...))

PARAM is the name of an entry parameter of ENTRY-TYPE.

VALUE-FUN may be either nil or a function returning a value that
will be inserted.  The function is called with 2 arguments: the
first one is the value of the parameter; the second one is an
entry (alist of parameter names and values).

For the meaning of WIDTH, SORT and PROPS, see
`tabulated-list-format'.")

(defvar guix-list-column-titles
  '((generation
     (number . "N.")))
  "Column titles for list buffers.
Has the same structure as `guix-param-titles', but titles from
this list have a priority.")

(defun guix-list-describe (&optional mark-names)
  "Describe entries marked with a general mark.
'Describe' means display entries in 'info' buffer.
If no entries are marked, describe the current entry.
With prefix argument, describe entries marked with any mark."
  (interactive (list (unless current-prefix-arg '(general))))
  (let* ((ids        (or (apply #'guix-list-get-marked-id-list mark-names)
                         (list (guix-list-current-id))))
         (count      (length ids))
         (entry-type guix-entry-type))
    (when (or (<= count (guix-list-describe-warning-count entry-type))
              (y-or-n-p (format "Do you really want to describe %d entries? "
                                count)))
      (guix-list-describe-entries entry-type ids))))

(defun guix-list-describe-ids (ids)
  "Describe entries with IDS (list of identifiers)."
  (apply #'guix-get-show-entries
         guix-profile 'info guix-entry-type 'id ids))


;;; Wrappers for 'list' variables

(defvar guix-list-data nil
  "Alist with 'list' data.
This alist is filled by `guix-list-define-entry-type' macro.")

(defun guix-list-value (entry-type symbol)
  "Return SYMBOL's value for ENTRY-TYPE from `guix-list-data'."
  (symbol-value (guix-assq-value guix-list-data entry-type symbol)))

(defun guix-list-param-title (entry-type param)
  "Return column title of an ENTRY-TYPE parameter PARAM."
  (or (guix-assq-value guix-list-column-titles
                       entry-type param)
      (guix-get-param-title entry-type param)))

(defun guix-list-format (entry-type)
  "Return column format for ENTRY-TYPE."
  (guix-assq-value guix-list-format entry-type))

(defun guix-list-displayed-params (entry-type)
  "Return a list of ENTRY-TYPE parameters that should be displayed."
  (mapcar #'car (guix-list-format entry-type)))

(defun guix-list-sort-key (entry-type)
  "Return sort key for ENTRY-TYPE."
  (guix-list-value entry-type 'sort-key))

(defun guix-list-additional-marks (entry-type)
  "Return alist of additional marks for ENTRY-TYPE."
  (guix-list-value entry-type 'marks))

(defun guix-list-describe-warning-count (entry-type)
  "Return the maximum number of ENTRY-TYPE entries to describe."
  (guix-list-value entry-type 'describe-count))

(defun guix-list-describe-entries (entry-type ids)
  "Describe ENTRY-TYPE entries with IDS in 'info' buffer"
  (funcall (guix-list-value entry-type 'describe)
           ids))


;;; Tabulated list internals

(defun guix-list-sort-numerically (column a b)
  "Compare COLUMN of tabulated entries A and B numerically.
This function is used for sort predicates for `tabulated-list-format'.
Return non-nil, if B is bigger than A."
  (cl-flet ((num (entry)
              (string-to-number (aref (cadr entry) column))))
    (> (num b) (num a))))

(defmacro guix-list-define-numerical-sorter (column)
  "Define numerical sort predicate for COLUMN.
See `guix-list-sort-numerically' for details."
  (let ((name (intern (format "guix-list-sort-numerically-%d" column)))
        (doc  (format "\
Predicate to sort tabulated list by column %d numerically.
See `guix-list-sort-numerically' for details."
                      column)))
    `(defun ,name (a b)
       ,doc
       (guix-list-sort-numerically ,column a b))))

(defmacro guix-list-define-numerical-sorters (n)
  "Define numerical sort predicates for columns from 0 to N.
See `guix-list-define-numerical-sorter' for details."
  `(progn
     ,@(mapcar (lambda (i)
                 `(guix-list-define-numerical-sorter ,i))
               (number-sequence 0 n))))

(guix-list-define-numerical-sorters 9)

(defun guix-list-tabulated-sort-key (entry-type)
  "Return ENTRY-TYPE sort key for `tabulated-list-sort-key'."
  (let ((sort-key (guix-list-sort-key entry-type)))
    (and sort-key
         (cons (guix-list-param-title entry-type (car sort-key))
               (cdr sort-key)))))

(defun guix-list-tabulated-vector (entry-type fun)
  "Call FUN on each column specification for ENTRY-TYPE.

FUN is applied to column specification as arguments (see
`guix-list-format').

Return a vector made of values of FUN calls."
  (apply #'vector
         (mapcar (lambda (col-spec)
                   (apply fun col-spec))
                 (guix-list-format entry-type))))

(defun guix-list-tabulated-format (entry-type)
  "Return ENTRY-TYPE list specification for `tabulated-list-format'."
  (guix-list-tabulated-vector
   entry-type
   (lambda (param _ &rest rest-spec)
     (cons (guix-list-param-title entry-type param)
           rest-spec))))

(defun guix-list-insert-entries (entries entry-type)
  "Display ENTRIES of ENTRY-TYPE in the current list buffer.
ENTRIES should have a form of `guix-entries'."
  (setq tabulated-list-entries
        (guix-list-tabulated-entries entries entry-type))
  (tabulated-list-print))

(defun guix-list-tabulated-entries (entries entry-type)
  "Return a list of ENTRY-TYPE values for `tabulated-list-entries'."
  (mapcar (lambda (entry)
            (list (guix-entry-id entry)
                  (guix-list-tabulated-entry entry entry-type)))
          entries))

(defun guix-list-tabulated-entry (entry entry-type)
  "Return array of values for `tabulated-list-entries'.
Parameters are taken from ENTRY-TYPE ENTRY."
  (guix-list-tabulated-vector
   entry-type
   (lambda (param fun &rest _)
     (let ((val (guix-entry-value entry param)))
       (if fun
           (funcall fun val entry)
         (guix-get-string val))))))

(defun guix-list-get-one-line (val &optional _)
  "Return one-line string from a multi-line string VAL.
VAL may be nil."
  (if val
      (guix-get-one-line val)
    (guix-get-string nil)))

(defun guix-list-get-time (seconds &optional _)
  "Return formatted time string from SECONDS."
  (guix-get-string (guix-get-time-string seconds)
                   'guix-list-time))

(defun guix-list-get-file-path (path &optional _)
  "Return PATH button specification for `tabulated-list-entries'."
  (list path
        'face 'guix-list-file-path
        'action (lambda (btn) (find-file (button-label btn)))
        'follow-link t
        'help-echo "Find file"))

(defun guix-list-current-id ()
  "Return ID of the current entry."
  (or (tabulated-list-get-id)
      (user-error "No entry here")))

(defun guix-list-current-entry ()
  "Return alist of the current entry info."
  (guix-entry-by-id (guix-list-current-id) guix-entries))

(defun guix-list-current-package-id ()
  "Return ID of the current package."
  (cl-ecase major-mode
    (guix-package-list-mode
     (guix-list-current-id))
    (guix-output-list-mode
     (guix-entry-value (guix-list-current-entry) 'package-id))))

(defun guix-list-for-each-line (fun &rest args)
  "Call FUN with ARGS for each entry line."
  (or (derived-mode-p 'guix-list-mode)
      (error "The current buffer is not in Guix List mode"))
  (save-excursion
    (goto-char (point-min))
    (while (not (eobp))
      (apply fun args)
      (forward-line))))

(defun guix-list-fold-lines (fun init)
  "Fold over entry lines in the current list buffer.
Call FUN with RESULT as argument for each line, using INIT as
the initial value of RESULT.  Return the final result."
  (let ((res init))
    (guix-list-for-each-line
     (lambda () (setq res (funcall fun res))))
    res))


;;; Marking and sorting

(defvar-local guix-list-marked nil
  "List of the marked entries.
Each element of the list has a form:

  (ID MARK-NAME . ARGS)

ID is an entry ID.
MARK-NAME is a symbol from `guix-list-marks'.
ARGS is a list of additional values.")

(defvar-local guix-list-marks nil
  "Alist of available mark names and mark characters.")

(defvar guix-list-default-marks
  '((empty   . ?\s)
    (general . ?*))
  "Alist of default mark names and mark characters.")

(defun guix-list-marks (entry-type)
  "Return alist of available marks for ENTRY-TYPE."
  (append guix-list-default-marks
          (guix-list-additional-marks entry-type)))

(defun guix-list-get-mark (name)
  "Return mark character by its NAME."
  (or (guix-assq-value guix-list-marks name)
      (error "Mark '%S' not found" name)))

(defun guix-list-get-mark-string (name)
  "Return mark string by its NAME."
  (string (guix-list-get-mark name)))

(defun guix-list-current-mark ()
  "Return mark character of the current line."
  (char-after (line-beginning-position)))

(defun guix-list-get-marked (&rest mark-names)
  "Return list of specs of entries marked with any mark from MARK-NAMES.
Entry specs are elements from `guix-list-marked' list.
If MARK-NAMES are not specified, use all marks from
`guix-list-marks' except the `empty' one."
  (or mark-names
      (setq mark-names
            (delq 'empty
                  (mapcar #'car guix-list-marks))))
  (cl-remove-if-not (lambda (assoc)
                      (memq (cadr assoc) mark-names))
                    guix-list-marked))

(defun guix-list-get-marked-args (mark-name)
  "Return list of (ID . ARGS) elements from lines marked with MARK-NAME.
See `guix-list-marked' for the meaning of ARGS."
  (mapcar (lambda (spec)
            (let ((id (car spec))
                  (args (cddr spec)))
              (cons id args)))
          (guix-list-get-marked mark-name)))

(defun guix-list-get-marked-id-list (&rest mark-names)
  "Return list of IDs of entries marked with any mark from MARK-NAMES.
See `guix-list-get-marked' for details."
  (mapcar #'car (apply #'guix-list-get-marked mark-names)))

(defun guix-list--mark (mark-name &optional advance &rest args)
  "Put a mark on the current line.
Also add the current entry to `guix-list-marked' using its ID and ARGS.
MARK-NAME is a symbol from `guix-list-marks'.
If ADVANCE is non-nil, move forward by one line after marking."
  (let ((id (guix-list-current-id)))
    (if (eq mark-name 'empty)
        (setq guix-list-marked (assq-delete-all id guix-list-marked))
      (let ((assoc (assq id guix-list-marked))
            (val (cons mark-name args)))
        (if assoc
            (setcdr assoc val)
          (push (cons id val) guix-list-marked)))))
  (tabulated-list-put-tag (guix-list-get-mark-string mark-name)
                          advance))

(defun guix-list-mark (&optional arg)
  "Mark the current line and move to the next line.
With ARG, mark all lines."
  (interactive "P")
  (if arg
      (guix-list-mark-all)
    (guix-list--mark 'general t)))

(defun guix-list-mark-all (&optional mark-name)
  "Mark all lines with MARK-NAME mark.
MARK-NAME is a symbol from `guix-list-marks'.
Interactively, put a general mark on all lines."
  (interactive)
  (or mark-name (setq mark-name 'general))
  (guix-list-for-each-line #'guix-list--mark mark-name))

(defun guix-list-unmark (&optional arg)
  "Unmark the current line and move to the next line.
With ARG, unmark all lines."
  (interactive "P")
  (if arg
      (guix-list-unmark-all)
    (guix-list--mark 'empty t)))

(defun guix-list-unmark-backward ()
  "Move up one line and unmark it."
  (interactive)
  (forward-line -1)
  (guix-list--mark 'empty))

(defun guix-list-unmark-all ()
  "Unmark all lines."
  (interactive)
  (guix-list-mark-all 'empty))

(defun guix-list-restore-marks ()
  "Put marks according to `guix-list-marked'."
  (guix-list-for-each-line
   (lambda ()
     (let ((mark-name (car (guix-assq-value guix-list-marked
                                            (guix-list-current-id)))))
       (tabulated-list-put-tag
        (guix-list-get-mark-string (or mark-name 'empty)))))))

(defun guix-list-sort (&optional n)
  "Sort guix list entries by the column at point.
With a numeric prefix argument N, sort the Nth column.
Same as `tabulated-list-sort', but also restore marks after sorting."
  (interactive "P")
  (tabulated-list-sort n)
  (guix-list-restore-marks))


;;; Major mode and interface definer

(defvar guix-list-mode-map
  (let ((map (make-sparse-keymap)))
    (set-keymap-parent
     map (make-composed-keymap guix-root-map
                               tabulated-list-mode-map))
    (define-key map (kbd "RET") 'guix-list-describe)
    (define-key map (kbd "i")   'guix-list-describe)
    (define-key map (kbd "m")   'guix-list-mark)
    (define-key map (kbd "*")   'guix-list-mark)
    (define-key map (kbd "u")   'guix-list-unmark)
    (define-key map (kbd "DEL") 'guix-list-unmark-backward)
    (define-key map [remap tabulated-list-sort] 'guix-list-sort)
    map)
  "Keymap for `guix-list-mode' buffers.")

(define-derived-mode guix-list-mode tabulated-list-mode "Guix-List"
  "Parent mode for displaying data in 'list' form.")

(defun guix-list-mode-initialize (entry-type)
  "Set up the current 'list' buffer for displaying ENTRY-TYPE entries."
  (setq tabulated-list-padding  2
        tabulated-list-format   (guix-list-tabulated-format entry-type)
        tabulated-list-sort-key (guix-list-tabulated-sort-key entry-type))
  (setq-local guix-list-marks   (guix-list-marks entry-type))
  (tabulated-list-init-header))

(defmacro guix-list-define-entry-type (entry-type &rest args)
  "Define common stuff for displaying ENTRY-TYPE entries in list buffers.

Remaining argument (ARGS) should have a form [KEYWORD VALUE] ...  The
following keywords are available:

  - `:sort-key' - default value of the generated
    `guix-ENTRY-TYPE-list-sort-key' variable.

  - `:describe-function' - default value of the generated
    `guix-ENTRY-TYPE-describe-function' variable.

  - `:marks' - default value of the generated
    `guix-ENTRY-TYPE-list-marks' variable.
"
  (let* ((entry-type-str     (symbol-name entry-type))
         (prefix             (concat "guix-" entry-type-str "-list"))
         (group              (intern prefix))
         (mode-str           (concat prefix "-mode"))
         (init-fun           (intern (concat prefix "-mode-initialize")))
         (describe-var       (intern (concat prefix "-describe-function")))
         (describe-count-var (intern (concat prefix
                                             "-describe-warning-count")))
         (sort-key-var       (intern (concat prefix "-sort-key")))
         (marks-var          (intern (concat prefix "-marks"))))
    (guix-keyword-args-let args
        ((describe-val       :describe-function)
         (describe-count-val :describe-count 10)
         (sort-key-val       :sort-key)
         (marks-val          :marks))
      `(progn
         (defcustom ,sort-key-var ,sort-key-val
           ,(format "\
Default sort key for 'list' buffer with '%s' entries.
Should be nil (no sort) or have a form:

  (PARAM . FLIP)

PARAM is the name of '%s' entry parameter.  For the meaning of
FLIP, see `tabulated-list-sort-key'."
                    entry-type-str entry-type-str)
           :type '(choice (const :tag "No sort" nil)
                          (cons symbol boolean))
           :group ',group)

         (defvar ,marks-var ,marks-val
           ,(format "\
Alist of additional marks for 'list' buffer with '%s' entries.
Marks from this list are used along with `guix-list-default-marks'."
                    entry-type-str))

         (defcustom ,describe-count-var ,describe-count-val
           ,(format "\
The maximum number of '%s' entries to describe without a warning.
If a user wants to describe more than this number of marked
entries, he will be prompted for confirmation.
See also `guix-list-describe'."
                    entry-type-str)
           :type 'integer
           :group ',group)

         (defvar ,describe-var ,describe-val
           ,(format "Function used to describe '%s' entries."
                    entry-type-str))

         (defun ,init-fun ()
           ,(concat "Initial settings for `" mode-str "'.")
           (guix-list-mode-initialize ',entry-type))

         (guix-alist-put!
          '((describe       . ,describe-var)
            (describe-count . ,describe-count-var)
            (sort-key       . ,sort-key-var)
            (marks          . ,marks-var))
          'guix-list-data ',entry-type)))))

(put 'guix-list-define-entry-type 'lisp-indent-function 'defun)

(defun guix-list-edit-package ()
  "Go to the location of the current package."
  (interactive)
  (guix-edit (guix-list-current-package-id)))


;;; Displaying packages

(guix-define-buffer-type list package)

(guix-list-define-entry-type package
  :describe-function 'guix-list-describe-ids
  :sort-key '(name)
  :marks '((install . ?I)
           (upgrade . ?U)
           (delete  . ?D)))

(defface guix-package-list-installed
  '((t :inherit guix-package-info-installed-outputs))
  "Face used if there are installed outputs for the current package."
  :group 'guix-package-list-faces)

(defface guix-package-list-obsolete
  '((t :inherit guix-package-info-obsolete))
  "Face used if a package is obsolete."
  :group 'guix-package-list-faces)

(defcustom guix-package-list-generation-marking-enabled nil
  "If non-nil, allow putting marks in a list with 'generation packages'.

By default this is disabled, because it may be confusing.  For
example a package is installed in some generation, so a user can
mark it for deletion in the list of packages from this
generation, but the package may not be installed in the latest
generation, so actually it cannot be deleted.

If you managed to understand the explanation above or if you
really know what you do or if you just don't care, you can set
this variable to t.  It should not do much harm anyway (most
likely)."
  :type 'boolean
  :group 'guix-package-list)

(let ((map guix-package-list-mode-map))
  (define-key map (kbd "e")   'guix-list-edit-package)
  (define-key map (kbd "x")   'guix-package-list-execute)
  (define-key map (kbd "i")   'guix-package-list-mark-install)
  (define-key map (kbd "d")   'guix-package-list-mark-delete)
  (define-key map (kbd "U")   'guix-package-list-mark-upgrade)
  (define-key map (kbd "^")   'guix-package-list-mark-upgrades))

(defun guix-package-list-get-name (name entry)
  "Return NAME of the package ENTRY.
Colorize it with `guix-package-list-installed' or
`guix-package-list-obsolete' if needed."
  (guix-get-string name
                   (cond ((guix-entry-value entry 'obsolete)
                          'guix-package-list-obsolete)
                         ((guix-entry-value entry 'installed)
                          'guix-package-list-installed))))

(defun guix-package-list-get-installed-outputs (installed &optional _)
  "Return string with outputs from INSTALLED entries."
  (guix-get-string
   (mapcar (lambda (entry)
             (guix-entry-value entry 'output))
           installed)))

(defun guix-package-list-marking-check ()
  "Signal an error if marking is disabled for the current buffer."
  (when (and (not guix-package-list-generation-marking-enabled)
             (or (derived-mode-p 'guix-package-list-mode)
                 (derived-mode-p 'guix-output-list-mode))
             (eq guix-search-type 'generation))
    (error "Action marks are disabled for lists of 'generation packages'")))

(defun guix-package-list-mark-outputs (mark default
                                       &optional prompt available)
  "Mark the current package with MARK and move to the next line.
If PROMPT is non-nil, use it to ask a user for outputs from
AVAILABLE list, otherwise mark all DEFAULT outputs."
  (let ((outputs (if prompt
                     (guix-completing-read-multiple
                      prompt available nil t)
                   default)))
    (apply #'guix-list--mark mark t outputs)))

(defun guix-package-list-mark-install (&optional arg)
  "Mark the current package for installation and move to the next line.
With ARG, prompt for the outputs to install (several outputs may
be separated with \",\")."
  (interactive "P")
  (guix-package-list-marking-check)
  (let* ((entry     (guix-list-current-entry))
         (all       (guix-entry-value entry 'outputs))
         (installed (guix-package-installed-outputs entry))
         (available (cl-set-difference all installed :test #'string=)))
    (or available
        (user-error "This package is already installed"))
    (guix-package-list-mark-outputs
     'install '("out")
     (and arg "Output(s) to install: ")
     available)))

(defun guix-package-list-mark-delete (&optional arg)
  "Mark the current package for deletion and move to the next line.
With ARG, prompt for the outputs to delete (several outputs may
be separated with \",\")."
  (interactive "P")
  (guix-package-list-marking-check)
  (let* ((entry (guix-list-current-entry))
         (installed (guix-package-installed-outputs entry)))
    (or installed
        (user-error "This package is not installed"))
    (guix-package-list-mark-outputs
     'delete installed
     (and arg "Output(s) to delete: ")
     installed)))

(defun guix-package-list-mark-upgrade (&optional arg)
  "Mark the current package for upgrading and move to the next line.
With ARG, prompt for the outputs to upgrade (several outputs may
be separated with \",\")."
  (interactive "P")
  (guix-package-list-marking-check)
  (let* ((entry (guix-list-current-entry))
         (installed (guix-package-installed-outputs entry)))
    (or installed
        (user-error "This package is not installed"))
    (when (or (guix-entry-value entry 'obsolete)
              (y-or-n-p "This package is not obsolete.  Try to upgrade it anyway? "))
      (guix-package-list-mark-outputs
       'upgrade installed
       (and arg "Output(s) to upgrade: ")
       installed))))

(defun guix-list-mark-package-upgrades (fun)
  "Mark all obsolete packages for upgrading.
Use FUN to perform marking of the current line.  FUN should
accept an entry as argument."
  (guix-package-list-marking-check)
  (let ((obsolete (cl-remove-if-not
                   (lambda (entry)
                     (guix-entry-value entry 'obsolete))
                   guix-entries)))
    (guix-list-for-each-line
     (lambda ()
       (let* ((id (guix-list-current-id))
              (entry (cl-find-if
                      (lambda (entry)
                        (equal id (guix-entry-id entry)))
                      obsolete)))
         (when entry
           (funcall fun entry)))))))

(defun guix-package-list-mark-upgrades ()
  "Mark all obsolete packages for upgrading."
  (interactive)
  (guix-list-mark-package-upgrades
   (lambda (entry)
     (apply #'guix-list--mark
            'upgrade nil
            (guix-package-installed-outputs entry)))))

(defun guix-list-execute-package-actions (fun)
  "Perform actions on the marked packages.
Use FUN to define actions suitable for `guix-process-package-actions'.
FUN should accept action-type as argument."
  (let ((actions (delq nil
                       (mapcar fun '(install delete upgrade)))))
    (if actions
        (guix-process-package-actions
         guix-profile actions (current-buffer))
      (user-error "No operations specified"))))

(defun guix-package-list-execute ()
  "Perform actions on the marked packages."
  (interactive)
  (guix-list-execute-package-actions #'guix-package-list-make-action))

(defun guix-package-list-make-action (action-type)
  "Return action specification for the packages marked with ACTION-TYPE.
Return nil, if there are no packages marked with ACTION-TYPE.
The specification is suitable for `guix-process-package-actions'."
  (let ((specs (guix-list-get-marked-args action-type)))
    (and specs (cons action-type specs))))


;;; Displaying outputs

(guix-define-buffer-type list output
  :buffer-name "*Guix Package List*"
  :required (package-id))

(guix-list-define-entry-type output
  :describe-function 'guix-output-list-describe
  :sort-key '(name)
  :marks '((install . ?I)
           (upgrade . ?U)
           (delete  . ?D)))

(let ((map guix-output-list-mode-map))
  (define-key map (kbd "e")   'guix-list-edit-package)
  (define-key map (kbd "x")   'guix-output-list-execute)
  (define-key map (kbd "i")   'guix-output-list-mark-install)
  (define-key map (kbd "d")   'guix-output-list-mark-delete)
  (define-key map (kbd "U")   'guix-output-list-mark-upgrade)
  (define-key map (kbd "^")   'guix-output-list-mark-upgrades))

(defun guix-output-list-mark-install ()
  "Mark the current output for installation and move to the next line."
  (interactive)
  (guix-package-list-marking-check)
  (let* ((entry     (guix-list-current-entry))
         (installed (guix-entry-value entry 'installed)))
    (if installed
        (user-error "This output is already installed")
      (guix-list--mark 'install t))))

(defun guix-output-list-mark-delete ()
  "Mark the current output for deletion and move to the next line."
  (interactive)
  (guix-package-list-marking-check)
  (let* ((entry     (guix-list-current-entry))
         (installed (guix-entry-value entry 'installed)))
    (if installed
        (guix-list--mark 'delete t)
      (user-error "This output is not installed"))))

(defun guix-output-list-mark-upgrade ()
  "Mark the current output for deletion and move to the next line."
  (interactive)
  (guix-package-list-marking-check)
  (let* ((entry     (guix-list-current-entry))
         (installed (guix-entry-value entry 'installed)))
    (or installed
        (user-error "This output is not installed"))
    (when (or (guix-entry-value entry 'obsolete)
              (y-or-n-p "This output is not obsolete.  Try to upgrade it anyway? "))
      (guix-list--mark 'upgrade t))))

(defun guix-output-list-mark-upgrades ()
  "Mark all obsolete package outputs for upgrading."
  (interactive)
  (guix-list-mark-package-upgrades
   (lambda (_) (guix-list--mark 'upgrade))))

(defun guix-output-list-execute ()
  "Perform actions on the marked outputs."
  (interactive)
  (guix-list-execute-package-actions #'guix-output-list-make-action))

(defun guix-output-list-make-action (action-type)
  "Return action specification for the outputs marked with ACTION-TYPE.
Return nil, if there are no outputs marked with ACTION-TYPE.
The specification is suitable for `guix-process-output-actions'."
  (let ((ids (guix-list-get-marked-id-list action-type)))
    (and ids (cons action-type
                   (mapcar #'guix-package-id-and-output-by-output-id
                           ids)))))

(defun guix-output-list-describe (ids)
  "Describe outputs with IDS (list of output identifiers).
See `guix-package-info-type'."
  (if (eq guix-package-info-type 'output)
      (apply #'guix-get-show-entries
             guix-profile 'info 'output 'id ids)
    (let ((pids (mapcar (lambda (oid)
                          (car (guix-package-id-and-output-by-output-id
                                oid)))
                        ids)))
      (apply #'guix-get-show-entries
             guix-profile 'info 'package 'id
             (cl-remove-duplicates pids)))))


;;; Displaying generations

(guix-define-buffer-type list generation)

(guix-list-define-entry-type generation
  :describe-function 'guix-list-describe-ids
  :sort-key '(number . t)
  :marks '((delete . ?D)))

(let ((map guix-generation-list-mode-map))
  (define-key map (kbd "RET") 'guix-generation-list-show-packages)
  (define-key map (kbd "+")   'guix-generation-list-show-added-packages)
  (define-key map (kbd "-")   'guix-generation-list-show-removed-packages)
  (define-key map (kbd "=")   'guix-generation-list-diff)
  (define-key map (kbd "D")   'guix-generation-list-diff)
  (define-key map (kbd "e")   'guix-generation-list-ediff)
  (define-key map (kbd "x")   'guix-generation-list-execute)
  (define-key map (kbd "s")   'guix-generation-list-switch)
  (define-key map (kbd "d")   'guix-generation-list-mark-delete))

(defun guix-generation-list-get-current (val &optional _)
  "Return string from VAL showing whether this generation is current.
VAL is a boolean value."
  (if val "(current)" ""))

(defun guix-generation-list-switch ()
  "Switch current profile to the generation at point."
  (interactive)
  (let* ((entry   (guix-list-current-entry))
         (current (guix-entry-value entry 'current))
         (number  (guix-entry-value entry 'number)))
    (if current
        (user-error "This generation is already the current one")
      (guix-switch-to-generation guix-profile number (current-buffer)))))

(defun guix-generation-list-show-packages ()
  "List installed packages for the generation at point."
  (interactive)
  (guix-get-show-entries guix-profile 'list guix-package-list-type
                         'generation (guix-list-current-id)))

(defun guix-generation-list-generations-to-compare ()
  "Return a sorted list of 2 marked generations for comparing."
  (let ((numbers (guix-list-get-marked-id-list 'general)))
    (if (/= (length numbers) 2)
        (user-error "2 generations should be marked for comparing")
      (sort numbers #'<))))

(defun guix-generation-list-show-added-packages ()
  "List package outputs added to the latest marked generation.
If 2 generations are marked with \\[guix-list-mark], display
outputs installed in the latest marked generation that were not
installed in the other one."
  (interactive)
  (apply #'guix-get-show-entries
         guix-profile 'list 'output 'generation-diff
         (reverse (guix-generation-list-generations-to-compare))))

(defun guix-generation-list-show-removed-packages ()
  "List package outputs removed from the latest marked generation.
If 2 generations are marked with \\[guix-list-mark], display
outputs not installed in the latest marked generation that were
installed in the other one."
  (interactive)
  (apply #'guix-get-show-entries
         guix-profile 'list 'output 'generation-diff
         (guix-generation-list-generations-to-compare)))

(defun guix-generation-list-compare (diff-fun gen-fun)
  "Run GEN-FUN on the 2 marked generations and run DIFF-FUN on the results."
  (cl-multiple-value-bind (gen1 gen2)
      (guix-generation-list-generations-to-compare)
    (funcall diff-fun
             (funcall gen-fun gen1)
             (funcall gen-fun gen2))))

(defun guix-generation-list-ediff-manifests ()
  "Run Ediff on manifests of the 2 marked generations."
  (interactive)
  (guix-generation-list-compare
   #'ediff-files
   #'guix-profile-generation-manifest-file))

(defun guix-generation-list-diff-manifests ()
  "Run Diff on manifests of the 2 marked generations."
  (interactive)
  (guix-generation-list-compare
   #'guix-diff
   #'guix-profile-generation-manifest-file))

(defun guix-generation-list-ediff-packages ()
  "Run Ediff on package outputs installed in the 2 marked generations."
  (interactive)
  (guix-generation-list-compare
   #'ediff-buffers
   #'guix-profile-generation-packages-buffer))

(defun guix-generation-list-diff-packages ()
  "Run Diff on package outputs installed in the 2 marked generations."
  (interactive)
  (guix-generation-list-compare
   #'guix-diff
   #'guix-profile-generation-packages-buffer))

(defun guix-generation-list-ediff (arg)
  "Run Ediff on package outputs installed in the 2 marked generations.
With ARG, run Ediff on manifests of the marked generations."
  (interactive "P")
  (if arg
      (guix-generation-list-ediff-manifests)
    (guix-generation-list-ediff-packages)))

(defun guix-generation-list-diff (arg)
  "Run Diff on package outputs installed in the 2 marked generations.
With ARG, run Diff on manifests of the marked generations."
  (interactive "P")
  (if arg
      (guix-generation-list-diff-manifests)
    (guix-generation-list-diff-packages)))

(defun guix-generation-list-mark-delete (&optional arg)
  "Mark the current generation for deletion and move to the next line.
With ARG, mark all generations for deletion."
  (interactive "P")
  (if arg
      (guix-list-mark-all 'delete)
    (guix-list--mark 'delete t)))

(defun guix-generation-list-execute ()
  "Delete marked generations."
  (interactive)
  (let ((marked (guix-list-get-marked-id-list 'delete)))
    (or marked
        (user-error "No generations marked for deletion"))
    (guix-delete-generations guix-profile marked (current-buffer))))

(provide 'guix-list)

;;; guix-list.el ends here