code:
;;; GNU Guix --- Functional package management for GNU
;;; Copyright © 2018, 2019 Mathieu Othacehe <m.othacehe@gmail.com>
;;; Copyright © 2019, 2020 Ludovic Courtès <ludo@gnu.org>
;;; Copyright © 2020 Tobias Geerinckx-Rice <me@tobias.gr>
;;;
;;; 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 installer newt partition)
  #:use-module (gnu installer parted)
  #:use-module (gnu installer steps)
  #:use-module (gnu installer utils)
  #:use-module (gnu installer newt page)
  #:use-module (gnu installer newt utils)
  #:use-module (guix i18n)
  #:use-module (ice-9 match)
  #:use-module (srfi srfi-1)
  #:use-module (srfi srfi-26)
  #:use-module (srfi srfi-34)
  #:use-module (srfi srfi-35)
  #:use-module (newt)
  #:use-module (parted)
  #:export (run-partioning-page))

(define (button-exit-action)
  "Raise the &installer-step-abort condition."
  (raise
   (condition
    (&installer-step-abort))))

(define (run-scheme-page)
  "Run a page asking the user for a partitioning scheme."
  (let* ((items
          `((root . ,(G_ "Everything is one partition"))
            (root-home . ,(G_ "Separate /home partition"))))
         (result (run-listbox-selection-page
                  #:info-text (G_ "Please select a partitioning scheme.")
                  #:title (G_ "Partition scheme")
                  #:listbox-items items
                  #:listbox-item->text cdr
                  #:listbox-height 4
                  #:sort-listbox-items? #f       ;keep the 'root' option first
                  #:button-text (G_ "Exit")
                  #:button-callback-procedure button-exit-action)))
    (car result)))

(define (draw-formatting-page)
  "Draw a page asking for confirmation, and then indicating that partitions
are being formatted."
  (run-confirmation-page (G_ "We are about to format your hard disk.  All \
its data will be lost.  Do you wish to continue?")
                         (G_ "Format disk?")
                         #:exit-button-procedure button-exit-action)
  (draw-info-page
   (format #f (G_ "Partition formatting is in progress, please wait."))
   (G_ "Preparing partitions")))

(define (run-device-page devices)
  "Run a page asking the user to select a device among those in the given
DEVICES list."
  (define (device-items)
    (map (lambda (device)
           `(,device . ,(device-description device)))
         devices))

  (let* ((result (run-listbox-selection-page
                  #:info-text (G_ "Please select a disk.")
                  #:title (G_ "Disk")
                  #:listbox-items (device-items)
                  #:listbox-item->text cdr
                  #:listbox-height 10
                  #:button-text (G_ "Exit")
                  #:button-callback-procedure button-exit-action))
         (device (car result)))
    device))

(define (run-label-page button-text button-callback)
  "Run a page asking the user to select a partition table label."
  (run-listbox-selection-page
   #:info-text (G_ "Select a new partition table type. \
Be careful, all data on the disk will be lost.")
   #:title (G_ "Partition table")
   #:listbox-items '("msdos" "gpt")
   #:listbox-item->text identity
   #:button-text button-text
   #:button-callback-procedure button-callback))

(define (run-type-page partition)
  "Run a page asking the user to select a partition type."
  (let* ((disk (partition-disk partition))
         (partitions (disk-partitions disk))
         (other-extended-partitions?
          (any extended-partition? partitions))
         (items
          `(normal ,@(if other-extended-partitions?
                         '()
                         '(extended)))))
    (run-listbox-selection-page
     #:info-text (G_ "Please select a partition type.")
     #:title (G_ "Partition type")
     #:listbox-items items
     #:listbox-item->text symbol->string
     #:sort-listbox-items? #f
     #:button-text (G_ "Exit")
     #:button-callback-procedure button-exit-action)))

(define (run-fs-type-page)
  "Run a page asking the user to select a file-system type."
  (run-listbox-selection-page
   #:info-text (G_ "Please select the file-system type for this partition.")
   #:title (G_ "File-system type")
   #:listbox-items '(ext4 btrfs fat16 fat32 jfs ntfs swap)
   #:listbox-item->text user-fs-type-name
   #:sort-listbox-items? #f
   #:button-text (G_ "Exit")
   #:button-callback-procedure button-exit-action))

(define (inform-can-create-partition? user-partition)
  "Return #t if it is possible to create USER-PARTITION. This is determined by
calling CAN-CREATE-PARTITION? procedure. If an exception is raised, catch it
an inform the user with an appropriate error-page and return #f."
  (guard (c ((max-primary-exceeded? c)
            (run-error-page
             (G_ "Primary partitions count exceeded.")
             (G_ "Creation error"))
            #f)
           ((extended-creation-error? c)
            (run-error-page
             (G_ "Extended partition creation error.")
             (G_ "Creation error"))
            #f)
           ((logical-creation-error? c)
            (run-error-page
             (G_ "Logical partition creation error.")
             (G_ "Creation error"))
            #f))
    (can-create-partition? user-partition)))

(define (prompt-luks-passwords user-partitions)
  "Prompt for the luks passwords of the encrypted partitions in
USER-PARTITIONS list. Return this list with password fields filled-in."
  (map (lambda (user-part)
         (let* ((crypt-label (user-partition-crypt-label user-part))
                (file-name (user-partition-file-name user-part))
                (password-page
                 (lambda ()
                   (run-input-page
                    (format #f (G_ "Please enter the password for the \
encryption of partition ~a (label: ~a).") file-name crypt-label)
                    (G_ "Password required")
                    #:input-visibility-checkbox? #t)))
                (password-confirm-page
                 (lambda ()
                   (run-input-page
                    (format #f (G_ "Please confirm the password for the \
encryption of partition ~a (label: ~a).") file-name crypt-label)
                    (G_ "Password confirmation required")
                    #:input-visibility-checkbox? #t))))
           (if crypt-label
               (let loop ()
                 (let ((password (password-page))
                       (confirmation (password-confirm-page)))
                   (if (string=? password confirmation)
                       (user-partition
                        (inherit user-part)
                        (crypt-password password))
                       (begin
                         (run-error-page
                          (G_ "Password mismatch, please try again.")
                          (G_ "Password error"))
                         (loop)))))
               user-part)))
       user-partitions))

(define* (run-partition-page target-user-partition
                             #:key
                             (default-item #f))
  "Run a page allowing the user to edit the given TARGET-USER-PARTITION
record. If the argument DEFAULT-ITEM is passed, use it to select the current
listbox item. This is used to avoid the focus to switch back to the first
listbox entry while calling this procedure recursively."

  (define (numeric-size device size)
    "Parse the given SIZE on DEVICE and return it."
    (call-with-values
        (lambda ()
          (unit-parse size device))
      (lambda (value range)
        value)))

  (define (numeric-size-range device size)
    "Parse the given SIZE on DEVICE and return the associated RANGE."
    (call-with-values
        (lambda ()
          (unit-parse size device))
      (lambda (value range)
        range)))

  (define* (fill-user-partition-geom user-part
                                     #:key
                                     device (size #f) start end)
    "Return the given USER-PART with the START, END and SIZE fields set to the
eponym arguments. Use UNIT-FORMAT-CUSTOM to format START and END arguments as
sectors on DEVICE."
    (user-partition
     (inherit user-part)
     (size size)
     (start (unit-format-custom device start UNIT-SECTOR))
     (end (unit-format-custom device end UNIT-SECTOR))))

  (define (apply-user-partition-changes user-part)
    "Set the name, file-system type and boot flag on the partition specified
by USER-PART, if it is applicable for the partition type."
    (let* ((partition (user-partition-parted-object user-part))
           (disk (partition-disk partition))
           (disk-type (disk-disk-type disk))
           (device (disk-device disk))
           (has-name? (disk-type-check-feature
                       disk-type
                       DISK-TYPE-FEATURE-PARTITION-NAME))
           (name (user-partition-name user-part))
           (fs-type (filesystem-type-get
                     (user-fs-type-name
                      (user-partition-fs-type user-part))))
           (bootable? (user-partition-bootable? user-part))
           (esp? (user-partition-esp? user-part))
           (flag-bootable?
            (partition-is-flag-available? partition PARTITION-FLAG-BOOT))
           (flag-esp?
            (partition-is-flag-available? partition PARTITION-FLAG-ESP)))
      (when (and has-name? name)
        (partition-set-name partition name))
      (partition-set-system partition fs-type)
      (when flag-bootable?
        (partition-set-flag partition
                            PARTITION-FLAG-BOOT
                            (if bootable? 1 0)))
      (when flag-esp?
        (partition-set-flag partition
                            PARTITION-FLAG-ESP
                            (if esp? 1 0)))
      #t))

  (define (listbox-action listbox-item)
    (let* ((item (car listbox-item))
           (partition (user-partition-parted-object
                       target-user-partition))
           (disk (partition-disk partition))
           (device (disk-device disk)))
      (list
       item
       (case item
         ((name)
          (let* ((old-name (user-partition-name target-user-partition))
                 (name
                  (run-input-page (G_ "Please enter the partition gpt name.")
                                  (G_ "Partition name")
                                  #:default-text old-name)))
            (user-partition
             (inherit target-user-partition)
             (name name))))
         ((type)
          (let ((new-type (run-type-page partition)))
            (user-partition
             (inherit target-user-partition)
             (type new-type))))
         ((bootable)
          (user-partition
           (inherit target-user-partition)
           (bootable? (not (user-partition-bootable?
                            target-user-partition)))))
         ((esp?)
          (let ((new-esp? (not (user-partition-esp?
                                target-user-partition))))
            (user-partition
             (inherit target-user-partition)
             (esp? new-esp?)
             (mount-point (if new-esp?
                              (default-esp-mount-point)
                              "")))))
         ((crypt-label)
          (let* ((label (user-partition-crypt-label
                         target-user-partition))
                 (new-label
                  (and (not label)
                       (run-input-page
                        (G_ "Please enter the encrypted label")
                        (G_ "Encryption label")))))
            (user-partition
             (inherit target-user-partition)
             (need-formatting? #t)
             (crypt-label new-label))))
         ((need-formatting?)
          (user-partition
           (inherit target-user-partition)
           (need-formatting?
            (not (user-partition-need-formatting?
                  target-user-partition)))))
         ((size)
          (let* ((old-size (user-partition-size target-user-partition))
                 (max-size-value (partition-length partition))
                 (max-size (unit-format device max-size-value))
                 (start (partition-start partition))
                 (size (run-input-page
                        (format #f (G_ "Please enter the size of the partition.\
 The maximum size is ~a.") max-size)
                        (G_ "Partition size")
                        #:default-text (or old-size max-size)))
                 (size-percentage (read-percentage size))
                 (size-value (if size-percentage
                                 (nearest-exact-integer
                                  (/ (* max-size-value size-percentage)
                                     100))
                                 (numeric-size device size)))
                 (end (and size-value
                           (+ start size-value)))
                 (size-range (numeric-size-range device size))
                 (size-range-ok? (and size-range
                                      (< (+ start
                                            (geometry-start size-range))
                                         (partition-end partition)))))
            (cond
             ((and size-percentage (> size-percentage 100))
              (run-error-page
               (G_ "The percentage can not be superior to 100.")
               (G_ "Size error"))
              target-user-partition)
             ((not size-value)
              (run-error-page
               (G_ "The requested size is incorrectly formatted, or too large.")
               (G_ "Size error"))
              target-user-partition)
             ((not (or size-percentage size-range-ok?))
              (run-error-page
               (G_ "The request size is superior to the maximum size.")
               (G_ "Size error"))
              target-user-partition)
             (else
              (fill-user-partition-geom target-user-partition
                                        #:device device
                                        #:size size
                                        #:start start
                                        #:end end)))))
         ((fs-type)
          (let ((fs-type (run-fs-type-page)))
            (user-partition
             (inherit target-user-partition)
             (fs-type fs-type))))
         ((mount-point)
          (let* ((old-mount (or (user-partition-mount-point
                                 target-user-partition)
                                ""))
                 (mount
                  (run-input-page
                   (G_ "Please enter the desired mounting point for this \
partition. Leave this field empty if you don't want to set a mounting point.")
                   (G_ "Mounting point")
                   #:default-text old-mount
                   #:allow-empty-input? #t)))
            (user-partition
             (inherit target-user-partition)
             (mount-point (and (not (string=? mount ""))
                               mount)))))))))

  (define (button-action)
    (let* ((partition (user-partition-parted-object
                       target-user-partition))
           (prev-part (partition-prev partition))
           (disk (partition-disk partition))
           (device (disk-device disk))
           (creation? (freespace-partition? partition))
           (start (partition-start partition))
           (end (partition-end partition))
           (new-user-partition
            (if (user-partition-start target-user-partition)
                target-user-partition
                (fill-user-partition-geom target-user-partition
                                          #:device device
                                          #:start start
                                          #:end end))))
      ;; It the backend PARTITION has free-space type, it means we are
      ;; creating a new partition, otherwise, we are editing an already
      ;; existing PARTITION.
      (if creation?
          (let* ((ok-create-partition?
                  (inform-can-create-partition? new-user-partition))
                 (new-partition
                  (and ok-create-partition?
                       (mkpart disk
                               new-user-partition
                               #:previous-partition prev-part))))
            (and new-partition
                 (user-partition
                  (inherit new-user-partition)
                  (need-formatting? #t)
                  (file-name (partition-get-path new-partition))
                  (disk-file-name (device-path device))
                  (parted-object new-partition))))
          (and (apply-user-partition-changes new-user-partition)
               new-user-partition))))

  (let* ((items (user-partition-description target-user-partition))
         (partition (user-partition-parted-object
                     target-user-partition))
         (disk (partition-disk partition))
         (device (disk-device disk))
         (file-name (device-path device))
         (number-str (partition-print-number partition))
         (type (user-partition-type target-user-partition))
         (type-str (symbol->string type))
         (start (unit-format device (partition-start partition)))
         (creation? (freespace-partition? partition))
         (default-item (and default-item
                            (find (lambda (item)
                                    (eq? (car item) default-item))
                                  items)))
         (result
          (run-listbox-selection-page
           #:info-text
           (if creation?
               (format #f (G_ "Creating ~a partition starting at ~a of ~a.")
                       type-str start file-name)
               (format #f (G_ "You are currently editing partition ~a.")
                       number-str))
           #:title (if creation?
                       (G_ "Partition creation")
                       (G_ "Partition edit"))
           #:listbox-items items
           #:listbox-item->text cdr
           #:sort-listbox-items? #f
           #:listbox-default-item default-item
           #:button-text (G_ "OK")
           #:listbox-callback-procedure listbox-action
           #:button-callback-procedure button-action)))
    (match result
      ((item new-user-partition)
       (run-partition-page new-user-partition
                           #:default-item item))
      (else result))))

(define* (run-disk-page disks
                        #:optional (user-partitions '())
                        #:key (guided? #f))
  "Run a page allowing to edit the partition tables of the given DISKS. If
specified, USER-PARTITIONS is a list of <user-partition> records associated to
the partitions on DISKS."

  (define (other-logical-partitions? partitions)
    "Return #t if at least one of the partition in PARTITIONS list is a
logical partition, return #f otherwise."
    (any logical-partition? partitions))

  (define (other-non-logical-partitions? partitions)
    "Return #t is at least one of the partitions in PARTITIONS list is not a
logical partition, return #f otherwise."
    (let ((non-logical-partitions
           (remove logical-partition? partitions)))
      (or (any normal-partition? non-logical-partitions)
          (any freespace-partition? non-logical-partitions))))

  (define (add-tree-symbols partitions descriptions)
    "Concatenate tree symbols to the given DESCRIPTIONS list and return
it. The PARTITIONS list is the list of partitions described in
DESCRIPTIONS. The tree symbols are used to indicate the partition's disk and
for logical partitions, the extended partition which includes them."
    (match descriptions
      (() '())
      ((description . rest-descriptions)
       (match partitions
         ((partition . rest-partitions)
          (if (null? rest-descriptions)
              (list (if (logical-partition? partition)
                        (string-append " ┗━ " description)
                        (string-append "┗━  " description)))
              (cons (cond
                     ((extended-partition? partition)
                      (if (other-non-logical-partitions? rest-partitions)
                          (string-append "┣┳  " description)
                          (string-append "┗┳  " description)))
                     ((logical-partition? partition)
                      (if (other-logical-partitions? rest-partitions)
                          (if (other-non-logical-partitions? rest-partitions)
                              (string-append "┃┣━ " description)
                              (string-append " ┣━ " description))
                          (if (other-non-logical-partitions? rest-partitions)
                              (string-append "┃┗━ " description)
                              (string-append " ┗━ " description))))
                     (else
                      (string-append "┣━  " description)))
                    (add-tree-symbols rest-partitions
                                      rest-descriptions))))))))

  (define (skip-item? item)
    (eq? (car item) 'skip))

  (define (disk-items)
    "Return the list of strings describing DISKS."
    (let loop ((disks disks))
      (match disks
        (() '())
        ((disk . rest)
         (let* ((device (disk-device disk))
                (partitions (disk-partitions disk))
                (partitions*
                 (filter-map
                  (lambda (partition)
                    (and (not (metadata-partition? partition))
                         (not (small-freespace-partition? device
                                                          partition))
                         partition))
                  partitions))
                (descriptions (add-tree-symbols
                               partitions*
                               (partitions-descriptions partitions*
                                                        user-partitions)))
                (partition-items (map cons partitions* descriptions)))
           (append
            `((,disk . ,(device-description device disk))
              ,@partition-items
              ,@(if (null? rest)
                    '()
                    '((skip . ""))))
            (loop rest)))))))

  (define (remove-user-partition-by-partition user-partitions partition)
    "Return the USER-PARTITIONS list with the record with the given PARTITION
object removed. If PARTITION is an extended partition, also remove all logical
partitions from USER-PARTITIONS."
    (remove (lambda (p)
              (let ((cur-partition (user-partition-parted-object p)))
                (or (equal? cur-partition partition)
                    (and (extended-partition? partition)
                         (logical-partition? cur-partition)))))
            user-partitions))

  (define (remove-user-partition-by-disk user-partitions disk)
    "Return the USER-PARTITIONS list with the <user-partition> records located
on given DISK removed."
    (remove (lambda (p)
              (let* ((partition (user-partition-parted-object p))
                     (cur-disk (partition-disk partition)))
                (equal? cur-disk disk)))
            user-partitions))

  (define (update-user-partitions user-partitions new-user-partition)
    "Update or insert NEW-USER-PARTITION record in USER-PARTITIONS list
depending if one of the <user-partition> record in USER-PARTITIONS has the
same PARTITION object as NEW-USER-PARTITION."
    (let* ((partition (user-partition-parted-object new-user-partition))
           (user-partitions*
            (remove-user-partition-by-partition user-partitions
                                                partition)))
      (cons new-user-partition user-partitions*)))

  (define (button-ok-action)
    "Commit the modifications to all DISKS and return #t."
    (for-each (lambda (disk)
                (disk-commit disk))
              disks)
    #t)

  (define (listbox-action listbox-item)
    "A disk or a partition has been selected. If it's a disk, ask for a label
to create a new partition table. If it is a partition, propose the user to
edit it."
    (let ((item (car listbox-item)))
      (cond
       ((disk? item)
        (let ((label (run-label-page (G_ "Back") (const #f))))
          (if label
              (let* ((device (disk-device item))
                     (new-disk (mklabel device label))
                     (commit-new-disk (disk-commit new-disk))
                     (other-disks (remove (lambda (disk)
                                            (equal? disk item))
                                          disks))
                     (new-user-partitions
                      (remove-user-partition-by-disk user-partitions item)))
                `((disks . ,(cons new-disk other-disks))
                  (user-partitions . ,new-user-partitions)))
              `((disks . ,disks)
                (user-partitions . ,user-partitions)))))
       ((partition? item)
        (let* ((partition item)
               (disk (partition-disk partition))
               (device (disk-device disk))
               (existing-user-partition
                (find-user-partition-by-parted-object user-partitions
                                                      partition))
               (edit-user-partition
                (or existing-user-partition
                    (partition->user-partition partition))))
          `((disks . ,disks)
            (user-partitions . ,user-partitions)
            (edit-user-partition . ,edit-user-partition)))))))

  (define (hotkey-action key listbox-item)
    "The DELETE key has been pressed on a disk or a partition item."
    (let ((item (car listbox-item))
          (default-result
            `((disks . ,disks)
              (user-partitions . ,user-partitions))))
      (cond
       ((disk? item)
        (let* ((device (disk-device item))
               (file-name (device-path device))
               (info-text
                (format #f (G_ "Are you sure you want to delete everything on disk ~a?")
                        file-name))
               (result (choice-window (G_ "Delete disk")
                                      (G_ "OK")
                                      (G_ "Exit")
                                      info-text)))
          (case result
            ((1)
             (disk-remove-all-partitions item)
             `((disks . ,disks)
               (user-partitions
                . ,(remove-user-partition-by-disk user-partitions item))))
            (else
             default-result))))
       ((partition? item)
        (if (freespace-partition? item)
            (run-error-page (G_ "You cannot delete a free space area.")
                            (G_ "Delete partition"))
            (let* ((disk (partition-disk item))
                   (number-str (partition-print-number item))
                   (info-text
                    (format #f (G_ "Are you sure you want to delete partition ~a?")
                            number-str))
                   (result (choice-window (G_ "Delete partition")
                                          (G_ "OK")
                                          (G_ "Exit")
                                          info-text)))
              (case result
                ((1)
                 (let ((new-user-partitions
                        (remove-user-partition-by-partition user-partitions
                                                            item)))
                   (disk-remove-partition* disk item)
                   `((disks . ,disks)
                     (user-partitions . ,new-user-partitions))))
                (else
                 default-result))))))))

  (let* ((info-text (G_ "You can change a disk's partition table by \
selecting it and pressing ENTER. You can also edit a partition by selecting it \
and pressing ENTER, or remove it by pressing DELETE. To create a new \
partition, select a free space area and press ENTER.

At least one partition must have its mounting point set to '/'."))
         (guided-info-text (format #f (G_ "This is the proposed \
partitioning. It is still possible to edit it or to go back to install menu \
by pressing the Exit button.~%~%")))
         (result
          (run-listbox-selection-page
           #:info-text (if guided?
                           (string-append guided-info-text info-text)
                           info-text)

          #:title (if guided?
                      (G_ "Guided partitioning")
                      (G_ "Manual partitioning"))
          #:info-textbox-width 76         ;we need a lot of room for INFO-TEXT
          #:listbox-height 12
          #:listbox-items (disk-items)
          #:listbox-item->text cdr
          #:sort-listbox-items? #f
          #:skip-item-procedure? skip-item?
          #:allow-delete? #t
          #:button-text (G_ "OK")
          #:button-callback-procedure button-ok-action

          ;; Consider client replies equivalent to hitting the "OK" button.
          ;; XXX: In practice this means that clients cannot do anything but
          ;; approve the predefined list of partitions.
          #:client-callback-procedure (lambda (_) (button-ok-action))

          #:button2-text (G_ "Exit")
          #:button2-callback-procedure button-exit-action
          #:listbox-callback-procedure listbox-action
          #:hotkey-callback-procedure hotkey-action)))
    (if (eq? result #t)
        (let ((user-partitions-ok?
               (guard
                   (c ((no-root-mount-point? c)
                       (run-error-page
                        (G_ "No root mount point found.")
                        (G_ "Missing mount point"))
                       #f))
                 (check-user-partitions user-partitions))))
          (if user-partitions-ok?
              user-partitions
              (run-disk-page disks user-partitions
                             #:guided? guided?)))
        (let* ((result-disks (assoc-ref result 'disks))
               (result-user-partitions (assoc-ref result
                                                  'user-partitions))
               (edit-user-partition (assoc-ref result
                                               'edit-user-partition))
               (can-create-partition?
                (and edit-user-partition
                     (inform-can-create-partition? edit-user-partition)))
               (new-user-partition (and edit-user-partition
                                        can-create-partition?
                                        (run-partition-page
                                         edit-user-partition)))
               (new-user-partitions
                (if new-user-partition
                    (update-user-partitions result-user-partitions
                                            new-user-partition)
                    result-user-partitions)))
          (run-disk-page result-disks new-user-partitions
                         #:guided? guided?)))))

(define (run-partioning-page)
  "Run a page asking the user for a partitioning method."
  (define (run-page devices)
    (let* ((items
            `((entire . ,(G_ "Guided - using the entire disk"))
              (entire-encrypted . ,(G_ "Guided - using the entire disk with encryption"))
              (manual . ,(G_ "Manual"))))
           (result (run-listbox-selection-page
                    #:info-text (G_ "Please select a partitioning method.")
                    #:title (G_ "Partitioning method")
                    #:listbox-height (+ (length items) 2)
                    #:listbox-items items
                    #:listbox-item->text cdr
                    #:sort-listbox-items? #f
                    #:button-text (G_ "Exit")
                    #:button-callback-procedure button-exit-action))
           (method (car result)))
      (cond
       ((or (eq? method 'entire)
            (eq? method 'entire-encrypted))
         (let* ((device (run-device-page devices))
                (disk-type (disk-probe device))
                (disk (if disk-type
                          (disk-new device)
                          (let* ((label (run-label-page
                                         (G_ "Exit")
                                         button-exit-action))
                                 (disk (mklabel device label)))
                            (disk-commit disk)
                            disk)))
                (scheme (symbol-append method '- (run-scheme-page)))
                (user-partitions (auto-partition! disk #:scheme scheme)))
           (run-disk-page (list disk) user-partitions
                          #:guided? #t)))
       ((eq? method 'manual)
         (let* ((disks (filter-map disk-new devices))
                (user-partitions (append-map
                                  create-special-user-partitions
                                  (map disk-partitions disks)))
                (result-user-partitions (run-disk-page disks
                                                       user-partitions)))
           result-user-partitions)))))

  (init-parted)
  (let* ((non-install-devices (non-install-devices))
         (user-partitions (run-page non-install-devices))
         (user-partitions-with-pass (prompt-luks-passwords
                                     user-partitions))
         (form (draw-formatting-page)))
    ;; Make sure the disks are not in use before proceeding to formatting.
    (free-parted non-install-devices)
    (format-user-partitions user-partitions-with-pass)
    (destroy-form-and-pop form)
    user-partitions))


code:
;;; GNU Guix --- Functional package management for GNU
;;; Copyright © 2018 Mathieu Othacehe <m.othacehe@gmail.com>
;;; Copyright © 2019 Ludovic Courtès <ludo@gnu.org>
;;;
;;; 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 installer newt services)
  #:use-module (gnu installer services)
  #:use-module (gnu installer steps)
  #:use-module (gnu installer newt page)
  #:use-module (gnu installer newt utils)
  #:use-module (guix i18n)
  #:use-module (srfi srfi-34)
  #:use-module (srfi srfi-35)
  #:use-module (newt)
  #:export (run-services-page))

(define (run-desktop-environments-cbt-page)
  "Run a page allowing the user to choose between various desktop
environments."
  (let ((items (filter desktop-system-service? %system-services)))
    (run-checkbox-tree-page
     #:info-text (G_ "Please select the desktop(s) environment(s) you wish to \
install. If you select multiple desktops environments, you will be able to \
choose the one to use on the log-in screen.")
     #:title (G_ "Desktop environment")
     #:items items
     #:selection (map system-service-recommended? items)
     #:item->text system-service-name             ;no i18n for DE names
     #:checkbox-tree-height 8
     #:exit-button-callback-procedure
     (lambda ()
       (raise
        (condition
         (&installer-step-abort)))))))

(define (run-networking-cbt-page)
  "Run a page allowing the user to select networking services."
  (let ((items (filter (lambda (service)
                         (eq? 'networking (system-service-type service)))
                       %system-services)))
    (run-checkbox-tree-page
     #:info-text (G_ "You can now select networking services to run on your \
system.")
     #:title (G_ "Network service")
     #:items items
     #:selection (map system-service-recommended? items)
     #:item->text (compose G_ system-service-name)
     #:checkbox-tree-height 5
     #:exit-button-callback-procedure
     (lambda ()
       (raise
        (condition
         (&installer-step-abort)))))))

(define (run-network-management-page)
  "Run a page to select among several network management methods."
  (let ((title (G_ "Network management")))
    (run-listbox-selection-page
     #:title title
     #:info-text (G_ "Choose the method to manage network connections.

We recommend NetworkManager or Connman for a WiFi-capable laptop; the DHCP \
client may be enough for a server.")
     #:info-textbox-width 70
     #:listbox-items (filter (lambda (service)
                               (eq? 'network-management
                                    (system-service-type service)))
                             %system-services)
     #:listbox-item->text (compose G_ system-service-name)
     #:sort-listbox-items? #f
     #:button-text (G_ "Exit")
     #:button-callback-procedure
     (lambda _
       (raise
        (condition
         (&installer-step-abort)))))))

(define (run-services-page)
  (let ((desktop (run-desktop-environments-cbt-page)))
    ;; When the user did not select any desktop services, and thus didn't get
    ;; '%desktop-services', offer network management services.
    (append desktop
            (run-networking-cbt-page)
            (if (null? desktop)
                (list (run-network-management-page))
                '()))))

license: mit


code:
;;; GNU Guix --- Functional package management for GNU
;;; Copyright © 2018 Mathieu Othacehe <m.othacehe@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 installer newt timezone)
  #:use-module (gnu installer steps)
  #:use-module (gnu installer timezone)
  #:use-module (gnu installer newt page)
  #:use-module (guix i18n)
  #:use-module (srfi srfi-1)
  #:use-module (srfi srfi-26)
  #:use-module (srfi srfi-34)
  #:use-module (srfi srfi-35)
  #:use-module (ice-9 match)
  #:use-module (ice-9 receive)
  #:use-module (newt)
  #:export (run-timezone-page))

;; Information textbox width.
(define info-textbox-width (make-parameter 40))

(define (fill-timezones listbox timezones)
  "Fill the given LISTBOX with TIMEZONES. Return an association list
correlating listbox keys with timezones."
  (map (lambda (timezone)
         (let ((key (append-entry-to-listbox listbox timezone)))
           (cons key timezone)))
       timezones))

(define (run-timezone-page zonetab)
  "Run a page displaying available timezones, grouped by regions. The user is
invited to select a timezone. The selected timezone, under Posix format is
returned."
  (define (all-but-last list)
    (reverse (cdr (reverse list))))

  (define (run-page timezone-tree)
    (define (loop path)
      ;; XXX: Translation of time zones isn't perfect here because the
      ;; "iso_3166-1" domain contains translation for "territories" (like
      ;; "Antarctic") but not for continents (like "Africa").
      (let ((timezones (locate-children timezone-tree path)))
        (run-listbox-selection-page
         #:title (G_ "Timezone")
         #:info-text (G_ "Please select a timezone.")
         #:listbox-items timezones
         #:listbox-item->text (cut gettext <> "iso_3166-1")
         #:button-text (if (null? path)
                           (G_ "Exit")
                           (G_ "Back"))
         #:button-callback-procedure
         (if (null? path)
             (lambda _
               (raise
                (condition
                 (&installer-step-abort))))
             (lambda _
               (loop (all-but-last path))))
         #:listbox-callback-procedure
         (lambda (timezone)
           (let* ((timezone* (append path (list timezone)))
                  (tz (timezone->posix-tz timezone*)))
             (if (timezone-has-child? timezone-tree timezone*)
                 (loop timezone*)
                 tz))))))
    (loop '()))

  (let ((timezone-tree (zonetab->timezone-tree zonetab)))
    (run-page timezone-tree)))


code:
;;; GNU Guix --- Functional package management for GNU
;;; Copyright © 2018 Mathieu Othacehe <m.othacehe@gmail.com>
;;; Copyright © 2019, 2020 Ludovic Courtès <ludo@gnu.org>
;;; Copyright © 2019 Tobias Geerinckx-Rice <me@tobias.gr>
;;;
;;; 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 installer newt user)
  #:use-module (gnu installer user)
  #:use-module ((gnu installer steps) #:select (&installer-step-abort))
  #:use-module (gnu installer newt page)
  #:use-module (gnu installer newt utils)
  #:use-module (gnu installer utils)
  #:use-module (guix i18n)
  #:use-module (newt)
  #:use-module (ice-9 match)
  #:use-module (ice-9 receive)
  #:use-module (srfi srfi-1)
  #:use-module (srfi srfi-26)
  #:use-module (srfi srfi-34)
  #:use-module (srfi srfi-35)
  #:export (run-user-page))

(define* (run-user-add-page #:key (name "") (real-name "")
                            (home-directory ""))
  "Run a form to enter the user name, home directory, and password.  Use NAME,
REAL-NAME, and HOME-DIRECTORY as the initial values in the form."
  (define (pad-label label)
    (string-pad-right label 25))

  (let* ((label-name
          (make-label -1 -1 (pad-label (G_ "Name"))))
         (label-real-name
          (make-label -1 -1 (pad-label (G_ "Real name"))))
         (label-home-directory
          (make-label -1 -1 (pad-label (G_ "Home directory"))))
         (label-password
          (make-label -1 -1 (pad-label (G_ "Password"))))
         (entry-width 35)
         (entry-name (make-entry -1 -1 entry-width
                                 #:initial-value name))
         (entry-real-name (make-entry -1 -1 entry-width
                                      #:initial-value real-name))
         (entry-home-directory (make-entry -1 -1 entry-width
                                           #:initial-value home-directory))
         (password-visible-cb
          (make-checkbox -1 -1 (G_ "Show") #\space "x "))
         (entry-password (make-entry -1 -1 entry-width
                                     #:flags (logior FLAG-PASSWORD
                                                     FLAG-SCROLL)))
         (entry-grid (make-grid 3 5))
         (button-grid (make-grid 1 1))
         (ok-button (make-button -1 -1 (G_ "OK")))
         (grid (make-grid 1 2))
         (title (G_ "User creation"))
         (set-entry-grid-field
          (cut set-grid-field entry-grid <> <> GRID-ELEMENT-COMPONENT <>))
         (form (make-form)))

    (set-entry-grid-field 0 0 label-name)
    (set-entry-grid-field 1 0 entry-name)
    (set-entry-grid-field 0 1 label-real-name)
    (set-entry-grid-field 1 1 entry-real-name)
    (set-entry-grid-field 0 2 label-home-directory)
    (set-entry-grid-field 1 2 entry-home-directory)
    (set-entry-grid-field 0 3 label-password)
    (set-entry-grid-field 1 3 entry-password)

    (set-grid-field entry-grid
                    2 3
                    GRID-ELEMENT-COMPONENT
                    password-visible-cb
                    #:pad-left 1)

    (set-grid-field button-grid 0 0 GRID-ELEMENT-COMPONENT ok-button)

    (add-component-callback
     entry-name
     (lambda ()
       (set-entry-text entry-home-directory
                       (string-append "/home/" (entry-value entry-name)))

       (when (string-null? (entry-value entry-real-name))
         (set-entry-text entry-real-name
                         (string-titlecase (entry-value entry-name))))))

    (add-component-callback
     password-visible-cb
     (lambda ()
       (set-entry-flags entry-password
                        FLAG-PASSWORD
                        FLAG-ROLE-TOGGLE)))

    (add-components-to-form form
                            label-name label-real-name
                            label-home-directory label-password
                            entry-name entry-real-name
                            entry-home-directory entry-password
                            password-visible-cb
                            ok-button)

    (make-wrapped-grid-window (vertically-stacked-grid
                               GRID-ELEMENT-SUBGRID entry-grid
                               GRID-ELEMENT-SUBGRID button-grid)
                              title)

    (let ((error-page
           (lambda ()
             (run-error-page (G_ "Empty inputs are not allowed.")
                             (G_ "Empty input")))))
      (receive (exit-reason argument)
          (run-form form)
        (dynamic-wind
          (const #t)
          (lambda ()
            (when (eq? exit-reason 'exit-component)
              (cond
               ((components=? argument ok-button)
                (let ((name           (entry-value entry-name))
                      (real-name      (entry-value entry-real-name))
                      (home-directory (entry-value entry-home-directory))
                      (password       (entry-value entry-password)))
                  (if (or (string=? name "")
                          (string=? home-directory ""))
                      (begin
                        (error-page)
                        (run-user-add-page))
                      (let ((password (confirm-password password)))
                        (if password
                            (user
                             (name name)
                             (real-name real-name)
                             (home-directory home-directory)
                             (password password))
                            (run-user-add-page #:name name
                                               #:real-name real-name
                                               #:home-directory
                                               home-directory)))))))))
          (lambda ()
            (destroy-form-and-pop form)))))))

(define* (confirm-password password #:optional (try-again (const #f)))
  "Ask the user to confirm PASSWORD, a possibly empty string.  Call TRY-AGAIN,
a thunk, if the confirmation doesn't match PASSWORD, and return its result."
  (define confirmation
    (run-input-page (G_ "Please confirm the password.")
                    (G_ "Password confirmation required")
                    #:allow-empty-input? #t
                    #:input-visibility-checkbox? #t))

  (if (string=? password confirmation)
      password
      (begin
        (run-error-page
         (G_ "Password mismatch, please try again.")
         (G_ "Password error"))
        (try-again))))

(define (run-root-password-page)
  (define password
    ;; TRANSLATORS: Leave "root" untranslated: it refers to the name of the
    ;; system administrator account.
    (run-input-page (G_ "Please choose a password for the system \
administrator (\"root\").")
                    (G_ "System administrator password")
                    #:input-visibility-checkbox? #t))

  (confirm-password password run-root-password-page))

(define (run-user-page)
  (define (run users)
    (let* ((listbox (make-listbox
                     -1 -1 10
                     (logior FLAG-SCROLL FLAG-BORDER)))
           (info-textbox
            (make-reflowed-textbox
             -1 -1
             (G_ "Please add at least one user to system\
 using the 'Add' button.")
             40 #:flags FLAG-BORDER))
           (add-button (make-compact-button -1 -1 (G_ "Add")))
           (del-button (make-compact-button -1 -1 (G_ "Delete")))
           (listbox-button-grid
            (apply
             vertically-stacked-grid
             GRID-ELEMENT-COMPONENT add-button
             `(,@(if (null? users)
                     '()
                     (list GRID-ELEMENT-COMPONENT del-button)))))
           (ok-button (make-button -1 -1 (G_ "OK")))
           (exit-button (make-button -1 -1 (G_ "Exit")))
           (title (G_ "User creation"))
           (grid
            (vertically-stacked-grid
             GRID-ELEMENT-COMPONENT info-textbox
             GRID-ELEMENT-SUBGRID (horizontal-stacked-grid
                                   GRID-ELEMENT-COMPONENT listbox
                                   GRID-ELEMENT-SUBGRID listbox-button-grid)
             GRID-ELEMENT-SUBGRID (horizontal-stacked-grid
                                   GRID-ELEMENT-COMPONENT ok-button
                                   GRID-ELEMENT-COMPONENT exit-button)))
           (sorted-users (sort users (lambda (a b)
                                       (string<= (user-name a)
                                                 (user-name b)))))
           (listbox-elements
            (map
             (lambda (user)
               `((key . ,(append-entry-to-listbox listbox
                                                  (user-name user)))
                 (user . ,user)))
             sorted-users))
           (form (make-form)))

      (add-form-to-grid grid form #t)
      (make-wrapped-grid-window grid title)
      (if (null? users)
          (set-current-component form add-button)
          (set-current-component form ok-button))

      (receive (exit-reason argument)
          (run-form-with-clients form '(add-users))
        (dynamic-wind
          (const #t)
          (lambda ()
            (match exit-reason
              ('exit-component
               (cond
                ((components=? argument add-button)
                 (run (cons (run-user-add-page) users)))
                ((components=? argument del-button)
                 (let* ((current-user-key (current-listbox-entry listbox))
                        (users
                         (map (cut assoc-ref <> 'user)
                              (remove (lambda (element)
                                        (equal? (assoc-ref element 'key)
                                                current-user-key))
                                      listbox-elements))))
                   (run users)))
                ((components=? argument ok-button)
                 (when (null? users)
                   (run-error-page (G_ "Please create at least one user.")
                                   (G_ "No user"))
                   (run users))
                 (reverse users))
                ((components=? argument exit-button)
                 (raise
                  (condition
                   (&installer-step-abort))))))
              ('exit-fd-ready
               ;; Read the complete user list at once.
               (match argument
                 ((('user ('name names) ('real-name real-names)
                          ('home-directory homes) ('password passwords))
                   ..1)
                  (map (lambda (name real-name home password)
                         (user (name name) (real-name real-name)
                               (home-directory home)
                               (password password)))
                       names real-names homes passwords))))))
          (lambda ()
            (destroy-form-and-pop form))))))

  ;; Add a "root" user simply to convey the root password.
  (cons (user (name "root")
              (home-directory "/root")
              (password (run-root-password-page)))
        (run '())))


code:
;;; GNU Guix --- Functional package management for GNU
;;; Copyright © 2018 Mathieu Othacehe <m.othacehe@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 installer newt utils)
  #:use-module (ice-9 receive)
  #:use-module (newt)
  #:export (screen-columns
            screen-rows

            destroy-form-and-pop
            set-screen-size!))

;; Number of columns and rows of the terminal.
(define screen-columns (make-parameter 0))
(define screen-rows    (make-parameter 0))

(define (destroy-form-and-pop form)
  "Destroy the given FORM and pop the current window."
  (destroy-form form)
  (pop-window))

(define (set-screen-size!)
  "Set the parameters 'screen-columns' and 'screen-rows' to the number of
columns and rows respectively of the current terminal."
  (receive (columns rows)
      (screen-size)
    (screen-columns columns)
    (screen-rows rows)))


code:
;;; GNU Guix --- Functional package management for GNU
;;; Copyright © 2018 Mathieu Othacehe <m.othacehe@gmail.com>
;;; Copyright © 2020 Ludovic Courtès <ludo@gnu.org>
;;;
;;; 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
;;;
;;; 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 installer newt welcome)
  #:use-module (gnu installer steps)
  #:use-module (gnu installer utils)
  #:use-module (gnu installer newt page)
  #:use-module (gnu installer newt utils)
  #:use-module (guix build syscalls)
  #:use-module (guix i18n)
  #:use-module (srfi srfi-1)
  #:use-module (srfi srfi-34)
  #:use-module (srfi srfi-35)
  #:use-module (ice-9 match)
  #:use-module (ice-9 receive)
  #:use-module (newt)
  #:export (run-welcome-page))

;; Expected width and height for the logo.
(define logo-width (make-parameter 43))
(define logo-height (make-parameter 19))

(define info-textbox-width (make-parameter 70))
(define options-listbox-height (make-parameter 5))

(define* (run-menu-page title info-text logo
                        #:key
                        listbox-items
                        listbox-item->text)
  "Run a page with the given TITLE, to ask the user to choose between
LISTBOX-ITEMS displayed in a listbox. The listbox items are converted to text
using LISTBOX-ITEM->TEXT procedure. Display the textual LOGO in the center of
the page. Contrary to other pages, we cannot resort to grid layouts, because
we want this page to occupy all the screen space available."
  (define (fill-listbox listbox items)
    (map (lambda (item)
           (let* ((text (listbox-item->text item))
                  (key (append-entry-to-listbox listbox text)))
             (cons key item)))
         items))

  (let* ((logo-textbox
          (make-textbox -1 -1 (logo-width) (logo-height) 0))
         (info-textbox
          (make-reflowed-textbox -1 -1
                                 info-text
                                 (info-textbox-width)))
         (options-listbox
          (make-listbox -1 -1
                        (options-listbox-height)
                        (logior FLAG-BORDER FLAG-RETURNEXIT)))
         (keys (fill-listbox options-listbox listbox-items))
         (grid (vertically-stacked-grid
                GRID-ELEMENT-COMPONENT logo-textbox
                GRID-ELEMENT-COMPONENT info-textbox
                GRID-ELEMENT-COMPONENT options-listbox))
         (form (make-form)))

    (define (choice->item str)
      ;; Return the item that corresponds to STR.
      (match (find (match-lambda
                     ((key . item)
                      (string=? str (listbox-item->text item))))
                   keys)
        ((key . item) item)
        (#f (raise (condition (&installer-step-abort))))))

    (set-textbox-text logo-textbox (read-all logo))

    (add-form-to-grid grid form #t)
    (make-wrapped-grid-window grid title)

    (receive (exit-reason argument)
        (run-form-with-clients form
                               `(menu (title ,title)
                                      (text ,info-text)
                                      (items
                                       ,(map listbox-item->text
                                             listbox-items))))
      (dynamic-wind
        (const #t)
        (lambda ()
          (match exit-reason
            ('exit-component
             (let* ((entry (current-listbox-entry options-listbox))
                    (item (assoc-ref keys entry)))
               (match item
                 ((text . proc)
                  (proc)))))
            ('exit-fd-ready
             (let* ((choice argument)
                    (item   (choice->item choice)))
               (match item
                 ((text . proc)
                  (proc)))))))
        (lambda ()
          (destroy-form-and-pop form))))))

(define (run-welcome-page logo)
  "Run a welcome page with the given textual LOGO displayed at the center of
the page. Ask the user to choose between manual installation, graphical
installation and reboot."
  (run-menu-page
   (G_ "GNU Guix install")
   (G_ "Welcome to GNU Guix system installer!

You will be guided through a graphical installation program.

If you are familiar with GNU/Linux and you want tight control over \
the installation process, you can instead choose manual installation.  \
Documentation is accessible at any time by pressing Ctrl-Alt-F2.")
   logo
   #:listbox-items
   `((,(G_ "Graphical install using a terminal based interface")
      .
      ,(const #t))
     (,(G_ "Install using the shell based process")
      .
      ,(lambda ()
         ;; Switch to TTY3, where a root shell is available for shell based
         ;; install. The other root TTY's would have been ok too.
         (system* "chvt" "3")
         (run-welcome-page logo)))
     (,(G_ "Reboot")
      .
      ,(lambda ()
         (newt-finish)
         (reboot))))
   #:listbox-item->text car))


code:
;;; GNU Guix --- Functional package management for GNU
;;; Copyright © 2018 Mathieu Othacehe <m.othacehe@gmail.com>
;;; Copyright © 2019 Meiyo Peng <meiyo@riseup.net>
;;; Copyright © 2019 Tobias Geerinckx-Rice <me@tobias.gr>
;;;
;;; 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 installer newt wifi)
  #:use-module (gnu installer connman)
  #:use-module (gnu installer steps)
  #:use-module (gnu installer newt utils)
  #:use-module (gnu installer newt page)
  #:use-module (guix i18n)
  #:use-module (guix records)
  #:use-module (ice-9 format)
  #:use-module (ice-9 popen)
  #:use-module (ice-9 receive)
  #:use-module (ice-9 regex)
  #:use-module (ice-9 rdelim)
  #:use-module (srfi srfi-1)
  #:use-module (srfi srfi-34)
  #:use-module (srfi srfi-35)
  #:use-module (newt)
  #:export (run-wifi-page))

;; This record associates a connman service to its key the listbox.
(define-record-type* <service-item>
  service-item make-service-item
  service-item?
  (service   service-item-service) ; connman <service>
  (key       service-item-key)) ; newt listbox-key

(define (strength->string strength)
  "Convert STRENGTH as an integer percentage into a text printable strength
bar using unicode characters. Taken from NetworkManager's
nmc_wifi_strength_bars."
  (let ((quarter #\x2582)
        (half #\x2584)
        (three-quarter #\x2586)
        (full #\x2588))
    (cond
     ((> strength 80)
      ;; ▂▄▆█
      (string quarter half three-quarter full))
     ((> strength 55)
      ;; ▂▄▆_
      (string quarter half three-quarter #\_))
     ((> strength 30)
      ;; ▂▄__
      (string quarter half #\_ #\_))
     ((> strength 5)
      ;; ▂___
      (string quarter #\_ #\_ #\_))
     (else
      ;; ____
      (string quarter #\_ #\_ #\_ #\_)))))

(define (force-wifi-scan)
  "Force a wifi scan. Raise a condition if no wifi technology is available."
  (let* ((technologies (connman-technologies))
         (wifi-technology
          (find (lambda (technology)
                  (string=? (technology-type technology) "wifi"))
                technologies)))
    (if wifi-technology
        (connman-scan-technology wifi-technology)
        (raise (condition
                (&message
                 (message (G_ "Unable to find a wifi technology"))))))))

(define (draw-scanning-page)
  "Draw a page to indicate a wifi scan in progress."
  (draw-info-page (G_ "Scanning wifi for available networks, please wait.")
                  (G_ "Scan in progress")))

(define (run-wifi-password-page)
  "Run a page prompting user for a password and return it."
  (run-input-page (G_ "Please enter the wifi password.")
                  (G_ "Password required")
                  #:input-visibility-checkbox? #t))

(define (run-wrong-password-page service-name)
  "Run a page to inform user of a wrong password input."
  (run-error-page
   (format #f (G_ "The password you entered for ~a is incorrect.")
           service-name)
   (G_ "Wrong password")))

(define (run-unknown-error-page service-name)
  "Run a page to inform user that a connection error happened."
  (run-error-page
   (format #f
           (G_ "An error occurred while trying to connect to ~a, please retry.")
           service-name)
   (G_ "Connection error")))

(define (password-callback)
  (run-wifi-password-page))

(define (connect-wifi-service listbox service-items)
  "Connect to the wifi service selected in LISTBOX. SERVICE-ITEMS is the list
of <service-item> records present in LISTBOX."
  (let* ((listbox-key (current-listbox-entry listbox))
         (item (find (lambda (item)
                       (eq? (service-item-key item) listbox-key))
                     service-items))
         (service (service-item-service item))
         (service-name (service-name service))
         (form (draw-connecting-page service-name)))
    (dynamic-wind
      (const #t)
      (lambda ()
        (guard (c ((connman-password-error? c)
                   (run-wrong-password-page service-name)
                   #f)
                  ((connman-already-connected-error? c)
                   #t)
                  ((connman-connection-error? c)
                   (run-unknown-error-page service-name)
                   #f))
          (connman-connect-with-auth service password-callback)))
      (lambda ()
        (destroy-form-and-pop form)))))

(define (run-wifi-scan-page)
  "Force a wifi scan and draw a page during the operation."
  (let ((form (draw-scanning-page)))
    (force-wifi-scan)
    (destroy-form-and-pop form)))

(define (wifi-services)
  "Return all the connman services of wifi type."
  (let ((services (connman-services)))
    (filter (lambda (service)
              (and (string=? (service-type service) "wifi")
                   (service-name service)
                   (not (string-null? (service-name service)))))
            services)))

(define* (fill-wifi-services listbox wifi-services)
  "Append all the services in WIFI-SERVICES to the given LISTBOX."
  (clear-listbox listbox)
  (map (lambda (service)
         (let* ((text (service->text service))
                (key (append-entry-to-listbox listbox text)))
           (service-item
            (service service)
            (key key))))
       wifi-services))

;; Maximum length of a wifi service name.
(define service-name-max-length (make-parameter 20))

;; Height of the listbox displaying wifi services.
(define wifi-listbox-height (make-parameter 20))

;; Information textbox width.
(define info-textbox-width (make-parameter 40))

(define (service->text service)
  "Return a string composed of the name and the strength of the given
SERVICE. A '*' preceding the service name indicates that it is connected."
  (let* ((name (service-name service))
         (padded-name (string-pad-right name
                                        (service-name-max-length)))
         (strength (service-strength service))
         (strength-string (strength->string strength))
         (state (service-state service))
         (connected? (or (string=? state "online")
                         (string=? state "ready"))))
    (format #f "~c ~a ~a~%"
            (if connected? #\* #\ )
            padded-name
            strength-string)))

(define (run-wifi-page)
  "Run a page displaying available wifi networks in a listbox. Connect to the
network when the corresponding listbox entry is selected. A button allow to
force a wifi scan."
  (let* ((listbox (make-listbox
                   -1 -1
                   (wifi-listbox-height)
                   (logior FLAG-SCROLL FLAG-BORDER FLAG-RETURNEXIT)))
         (form (make-form))
         (buttons-grid (make-grid 1 1))
         (middle-grid (make-grid 2 1))
         (info-text (G_ "Please select a wifi network."))
         (info-textbox
          (make-reflowed-textbox -1 -1 info-text
                                 (info-textbox-width)
                                 #:flags FLAG-BORDER))
         (exit-button (make-button -1 -1 (G_ "Exit")))
         (scan-button (make-button -1 -1 (G_ "Scan")))
         (services (wifi-services))
         (service-items '()))

    (if (null? services)
        (append-entry-to-listbox listbox (G_ "No wifi detected"))
        (set! service-items (fill-wifi-services listbox services)))

    (set-grid-field middle-grid 0 0 GRID-ELEMENT-COMPONENT listbox)
    (set-grid-field middle-grid 1 0 GRID-ELEMENT-COMPONENT scan-button
                    #:anchor ANCHOR-TOP
                    #:pad-left 2)
    (set-grid-field buttons-grid 0 0 GRID-ELEMENT-COMPONENT exit-button)

    (add-components-to-form form
                            info-textbox
                            listbox scan-button
                            exit-button)
    (make-wrapped-grid-window
     (basic-window-grid info-textbox middle-grid buttons-grid)
     (G_ "Wifi"))

    (receive (exit-reason argument)
        (run-form form)
      (dynamic-wind
        (const #t)
        (lambda ()
          (when (eq? exit-reason 'exit-component)
            (cond
             ((components=? argument scan-button)
              (run-wifi-scan-page)
              (run-wifi-page))
             ((components=? argument exit-button)
              (raise
               (condition
                (&installer-step-abort))))
             ((components=? argument listbox)
              (let ((result (connect-wifi-service listbox service-items)))
                (unless result
                  (run-wifi-page)))))))
        (lambda ()
          (destroy-form-and-pop form))))))