# The questions, as the setup of the kit asked them (libexec/setup-frontend.sh there): dialog for a person at a terminal, plain lines
# for a script; Back and Quit in both. Here a form shows all the questions at once. Sourced by the commands, not run.
#
# Environment: OPENSIM_SETUP_UI=plain|dialog (default: dialog at a terminal), FE_TTY (where the person types, default /dev/tty),
# FE_INPUT_FD (a descriptor to read the answers from instead: the tests), FE_SCREEN (where dialog draws, default /dev/tty).
#
# Every question returns 0 when answered, 1 for Back (:back in plain mode), 2 for Quit (:quit, the end of the input).
#
# A form is the fields by the name of the variable that holds the answer (the proposal on the way in, the answer on the way out),
# with LABEL[name] and, for what is not shown when typed, SECRET[name]=1 (and READONLY[name]=1 for what is only shown). A field with
# choices has OPTIONS[name], the lines key, unit separator, label; HELP[name] is a line that tells about a field:
#
#   declare -A LABEL=([name]="Grid name" [password]="Password") SECRET=([password]=1)
#   ui_form "Title" "Text above the form" name password

FE_TTY=${FE_TTY:-/dev/tty}
FE_INPUT_FD=${FE_INPUT_FD:-}
FE_SCREEN=${FE_SCREEN:-/dev/tty}
FE_UI=
FE_ANSWER=

fe_dialog_fits_terminal() {
	[[ $1 =~ ^[0-9]+$ ]] && (( $1 >= 78 ))
}

# The way to ask: dialog for a person at a terminal when it is installed (recommended, not required), plain lines otherwise: no
# dialog, nobody there (a script, the tests: the answers come from FE_INPUT_FD or the standard input), a terminal too narrow
fe_choose_ui() {
	FE_UI=${OPENSIM_SETUP_UI:-}
	[[ -n $FE_UI ]] && return
	FE_UI=plain
	if [[ -z $FE_INPUT_FD && $FE_TTY == /dev/tty && $FE_SCREEN == /dev/tty && -t 0 && -t 1 ]]; then
		command -v dialog >/dev/null 2>&1 || return 0
		local terminal_size terminal_columns
		terminal_size=$(stty size <"$FE_TTY" 2>/dev/null) || terminal_size=
		terminal_columns=${terminal_size#* }
		if fe_dialog_fits_terminal "$terminal_columns"; then
			FE_UI=dialog
		fi
	fi
}

# Read from the person: the options of read and the name of the variable
fe_in() {
	if [[ -n $FE_INPUT_FD ]]; then
		IFS= read -r -u "$FE_INPUT_FD" "$@"
	else
		IFS= read -r "$@" <"$FE_TTY"
	fi
}

# Read a line from the person: 0 when read, 2 at the end of the input (nobody is there to answer)
fe_read() { # prompt default [secret]
	local value
	if [[ -n ${3:-} ]]; then
		fe_in -s -p "$1" value || return 2
		printf '\n' >&2
	elif [[ $FE_TTY == /dev/tty && -z $FE_INPUT_FD ]]; then
		fe_in -e -p "$1" -i "$2" value || return 2
	else
		# Nobody types at a terminal (a script, the tests): the question is shown, read does not show it for what is not one
		printf '%s' "$1" >&2
		fe_in value || return 2
		[[ -z $value ]] && value=$2
	fi
	FE_ANSWER=$value
}

# Answers that are not an answer: :back and :quit
fe_special() {
	case $FE_ANSWER in
	:back | :b) return 1 ;;
	:quit | :q) return 2 ;;
	esac
	return 0
}

# The configuration of dialog: the one of the person, and Enter moves to the next field of a form (the last one leads to OK), which
# submits only when it is pressed on the button
fe_dialogrc() {
	FE_DIALOGRC=${FE_DIALOGRC:-${TMP:-$(mktemp)}.dialogrc}
	{
		cat "${DIALOGRC:-${HOME:-}/.dialogrc}" 2>/dev/null || true
		printf '%s\n' 'bindkey formfield ENTER form_NEXT' 'bindkey formfield ^M form_NEXT' 'bindkey formfield ^J form_NEXT'
	} >"$FE_DIALOGRC"
}

# Whether the terminal is told UTF-8 (its locale): else what dialog draws is said in ASCII
fe_utf8() {
	[[ "$(locale charmap 2>/dev/null)" == UTF-8 ]]
}

# A text in ASCII when the locale is not UTF-8 (an arrow ->, an ellipsis ...), as it is else
fe_ascii() { # text
	if fe_utf8; then
		printf '%s' "$1"
	else
		local text=${1//→/->} out
		text=${text//…/...}
		out=$(iconv -f UTF-8 -t ASCII//TRANSLIT <<<"$text" 2>/dev/null) && printf '%s' "$out" || printf '%s' "$text"
	fi
}

# A line of a panel within its width: shortened in the middle when longer (its start and its end kept), never cut silently
fe_fit() { # text, width
	local text=$1 width=$2 mark='…' half
	fe_utf8 || mark='...'
	((${#text} <= width)) && { printf '%s' "$text"; return; }
	half=$(((width - ${#mark}) / 2))
	printf '%s%s%s' "${text:0:half}" "$mark" "${text: -$((width - ${#mark} - half))}"
}

# dialog, its answer in FE_ANSWER; the cancel button is Back unless FE_CANCEL says another. The text above a menu, a form or a checklist
# is never empty: dialog refuses an empty one at once (status 255), the screen could not be answered. Its texts in ASCII when the
# locale is not UTF-8 (what it draws would be garbled else)
fe_dialog() { # title, arguments of dialog
	local title=$1 out status=0 argument
	shift
	if ! fe_utf8; then
		local _u_ascii=()
		for argument in "$@"; do _u_ascii+=("$(fe_ascii "$argument")"); done
		set -- "${_u_ascii[@]}"
		title=$(fe_ascii "$title")
	fi
	[[ -f "${FE_DIALOGRC:-}" ]] || fe_dialogrc
	out=$(DIALOGRC="$FE_DIALOGRC" dialog --output-fd 9 --title "$title" ${FE_OK:+--ok-label "$FE_OK"} --cancel-label "${FE_CANCEL:-Back}" ${FE_EXTRA:+--extra-button --extra-label "$FE_EXTRA"} ${FE_HELP:+--help-button --help-label "$FE_HELP"} "$@" 9>&1 >"$FE_SCREEN" <"$FE_SCREEN") || status=$?
	FE_ANSWER=$out
	case $status in
	0) return 0 ;;
	1) return 1 ;;
	# The button of its own a screen may have (FE_EXTRA: the passwords of the review shown)
	3) [[ -n "${FE_EXTRA:-}" ]] && return 3 || return 2 ;;
	# A fourth button (FE_HELP), when a screen needs one more
	2) [[ -n "${FE_HELP:-}" ]] && return 5 || return 2 ;;
	*) return 2 ;;
	esac
}

# ui_menu VARIABLE "Title" "Text" DEFAULT KEY "Label" [KEY "Label"...]: the key of the line chosen, the default proposed
ui_menu() {
	local variable=$1 title=$2 text=$3 default=$4 keys=() labels=() items=() i status=0 height
	shift 4
	while (($# >= 2)); do
		keys+=("$1")
		labels+=("$2")
		items+=("$1" "$2")
		shift 2
	done
	fe_choose_ui
	if [[ $FE_UI == dialog ]]; then
		# The size is given: a menu height of 0 shows one line on some builds, and the tags repeat the labels
		height=$((${#keys[@]} + 7 + $(fe_lines "$text")))
		fe_dialog "$title" ${default:+--default-item "$default"} --no-tags --menu "${text:- }" "$height" 60 "${#keys[@]}" "${items[@]}" || return $?
	else
		[[ -n "$text" ]] && printf '\n%s\n' "$text" >&2
		for i in "${!keys[@]}"; do
			printf '  %d) %s\n' "$((i + 1))" "${labels[$i]}" >&2
		done
		local line=1
		for i in "${!keys[@]}"; do
			[[ "${keys[$i]}" == "$default" ]] && line=$((i + 1))
		done
		while :; do
			fe_read "$title [$line]: " "$line" || return 2
			fe_special || return $?
			if [[ $FE_ANSWER =~ ^[0-9]+$ ]] && ((FE_ANSWER >= 1 && FE_ANSWER <= ${#keys[@]})); then
				FE_ANSWER=${keys[FE_ANSWER - 1]}
				break
			fi
			for i in "${!keys[@]}"; do
				[[ "${keys[$i]}" == "$FE_ANSWER" ]] && break 2
			done
		done
	fi
	printf -v "$variable" '%s' "$FE_ANSWER"
	return $status
}

# The number of lines of a text, 0 for none
fe_lines() {
	[[ -z "$1" ]] && echo 0 || grep -c '' <<<"$1"
}

# ui_form "Title" "Text" NAME...: all the questions at once. (The locals are named so that they cannot hide a variable of a form.)
ui_form() {
	local _u_title=$1 _u_text=$2 _u_n _u_i _u_w=0 _u_items=() _u_values=()
	shift 2
	local _u_names=("$@")
	fe_choose_ui
	# Choices cannot be typed in a form of dialog: the fields as a list, each one changed on its own
	if [[ $FE_UI == dialog ]] && fe_has_choices "${_u_names[@]}"; then
		ui_form_list "$_u_title" "$_u_text" "${_u_names[@]}"
	elif [[ $FE_UI == dialog ]]; then
		for _u_n in "${_u_names[@]}"; do ((${#LABEL[$_u_n]} > _u_w)) && _u_w=${#LABEL[$_u_n]}; done
		for _u_i in "${!_u_names[@]}"; do
			_u_n=${_u_names[$_u_i]}
			_u_items+=("${LABEL[$_u_n]}" "$((_u_i + 1))" 1 "${!_u_n}" "$((_u_i + 1))" "$((_u_w + 2))" 40 200 "$([[ -n "${READONLY[$_u_n]:-}" ]] && echo 2 || echo "${SECRET[$_u_n]:-0}")")
		done
		# Enter goes to the next field (fe_dialogrc): the buttons are reached with Tab, said at the bottom of the box
		fe_dialog "$_u_title" --hline "Enter: next field, Tab: buttons" --insecure --mixedform "${_u_text:- }" "$((${#_u_names[@]} + 8 + $(grep -c '' <<<"$_u_text")))" 72 "${#_u_names[@]}" "${_u_items[@]}" || return $?
		mapfile -t _u_values <<<"$FE_ANSWER"
		for _u_i in "${!_u_names[@]}"; do
			printf -v "${_u_names[$_u_i]}" '%s' "${_u_values[$_u_i]:-}"
		done
	else
		ui_form_plain "$_u_title" "$_u_text" "${_u_names[@]}"
	fi
}

# The form as text: every question with its answer, a number to change one, Enter when it is right
ui_form_plain() {
	local _u_title=$1 _u_text=$2 _u_n _u_i _u_shown _u_status
	shift 2
	local _u_names=("$@")
	[[ -n "$_u_text" ]] && printf '\n%s\n' "$_u_text" >&2
	# One question alone is asked as one, its proposal ready to be kept with Enter or changed
	_u_n=${_u_names[0]}
	if ((${#_u_names[@]} == 1)) && [[ -z "${OPTIONS[$_u_n]:-}" && -z "${SECRET[$_u_n]:-}" && -z "${READONLY[$_u_n]:-}" ]]; then
		fe_read "? ${LABEL[$_u_n]}: " "${!_u_n}" || return 2
		fe_special || return $?
		printf -v "$_u_n" '%s' "$FE_ANSWER"
		return 0
	fi
	while :; do
		printf '\n%s\n' "$_u_title" >&2
		for _u_i in "${!_u_names[@]}"; do
			_u_n=${_u_names[$_u_i]}
			_u_shown=$(fe_shown "$_u_n")
			printf '  %d) %-26s %s\n' "$((_u_i + 1))" "${LABEL[$_u_n]}" "$_u_shown" >&2
			[[ -n "${HELP[$_u_n]:-}" ]] && printf '     %s\n' "${HELP[$_u_n]}" >&2
		done
		fe_read "Edit [1-${#_u_names[@]}, Enter to continue]: " '' || return 2
		fe_special || return $?
		[[ -z "$FE_ANSWER" ]] && return 0
		if [[ "$FE_ANSWER" =~ ^[0-9]+$ ]] && ((FE_ANSWER >= 1 && FE_ANSWER <= ${#_u_names[@]})); then
			_u_n=${_u_names[$((FE_ANSWER - 1))]}
			_u_status=0
			[[ -n "${READONLY[$_u_n]:-}" ]] && continue
			if [[ -n "${OPTIONS[$_u_n]:-}" ]]; then
				fe_choice "$_u_n" || (($? == 1)) || return 2
				continue
			elif [[ -n "${SECRET[$_u_n]:-}" ]]; then
				fe_read "${LABEL[$_u_n]}: " '' secret || return 2
			else
				fe_read "${LABEL[$_u_n]}: " "${!_u_n}" || return 2
			fi
			printf -v "$_u_n" '%s' "$FE_ANSWER"
		fi
	done
}

# fe_has_choices NAME...: whether one of the fields has choices
fe_has_choices() {
	local _u_n
	for _u_n in "$@"; do
		[[ -n "${OPTIONS[$_u_n]:-}" ]] && return 0
	done
	return 1
}

# fe_shown NAME: the answer of a field as it is shown, the label of its choice when it has choices, stars for a secret
fe_shown() {
	local _u_n=$1 _u_key _u_label
	if [[ -n "${SECRET[$_u_n]:-}" && -n "${!_u_n}" ]]; then
		printf '********'
		return
	fi
	if [[ -n "${OPTIONS[$_u_n]:-}" ]]; then
		while IFS=$'\x1f' read -r _u_key _u_label; do
			[[ "$_u_key" == "${!_u_n}" ]] && printf '%s' "$_u_label" && return
		done <<<"${OPTIONS[$_u_n]}"
	fi
	printf '%s' "${!_u_n}"
}

# fe_choice NAME: one of the choices of a field, the one it has proposed; 1 for Back (the answer kept)
fe_choice() {
	local _u_n=$1 _u_key _u_label _u_items=() _u_choice
	while IFS=$'\x1f' read -r _u_key _u_label; do
		_u_items+=("$_u_key" "$_u_label")
	done <<<"${OPTIONS[$_u_n]}"
	FE_OK= FE_CANCEL=Back FE_EXTRA= ui_menu _u_choice "${LABEL[$_u_n]}" "${HELP[$_u_n]:-${LABEL[$_u_n]}}" "${!_u_n}" "${_u_items[@]}" || return $?
	printf -v "$_u_n" '%s' "$_u_choice"
}

# The form as a list in dialog: Enter changes the field chosen (a menu for its choices, a line to type for the others), its help at the
# bottom; the button of the screen goes on
ui_form_list() {
	local _u_title=$1 _u_text=$2 _u_n _u_i _u_w=0 _u_items=() _u_status _u_current= _u_next=${FE_OK:-OK} _u_back=${FE_CANCEL:-Back}
	shift 2
	local _u_names=("$@")
	for _u_n in "${_u_names[@]}"; do ((${#LABEL[$_u_n]} > _u_w)) && _u_w=${#LABEL[$_u_n]}; done
	# The labels in a column of 34 at most, the values readable beside them (68 the width of a line of the panel); the whole label is
	# the title of the panel its Change opens
	((_u_w > 34)) && _u_w=34
	while :; do
		_u_items=()
		for _u_i in "${!_u_names[@]}"; do
			_u_n=${_u_names[$_u_i]}
			_u_items+=("$((_u_i + 1))" "$(printf '%-*s  %s' "$_u_w" "$(fe_fit "${LABEL[$_u_n]}" "$_u_w")" "$(fe_fit "$(fe_shown "$_u_n")" $((68 - _u_w - 2)))")" "${HELP[$_u_n]:-${LABEL[$_u_n]}}")
		done
		_u_status=0
		FE_OK=Change FE_CANCEL=$_u_back FE_EXTRA=$_u_next fe_dialog "$_u_title" --hline "Enter: change, Tab: buttons" --item-help --no-tags \
			${_u_current:+--default-item "$_u_current"} --menu "${_u_text:- }" "$((${#_u_names[@]} + 8 + $(fe_lines "$_u_text")))" 78 "${#_u_names[@]}" "${_u_items[@]}" || _u_status=$?
		case $_u_status in
		0) ;;
		3) return 0 ;;
		*) return "$_u_status" ;;
		esac
		_u_current=$FE_ANSWER
		_u_n=${_u_names[$((FE_ANSWER - 1))]}
		[[ -n "${READONLY[$_u_n]:-}" ]] && continue
		if [[ -n "${OPTIONS[$_u_n]:-}" ]]; then
			fe_choice "$_u_n" || (($? == 1)) || return 2
		else
			_u_status=0
			FE_OK= FE_CANCEL=Back FE_EXTRA= fe_dialog "${LABEL[$_u_n]}" $([[ -n "${SECRET[$_u_n]:-}" ]] && echo --insecure --passwordbox || echo --inputbox) \
				"${HELP[$_u_n]:-${LABEL[$_u_n]}}" 10 72 "${!_u_n}" || _u_status=$?
			case $_u_status in
			0) printf -v "$_u_n" '%s' "$FE_ANSWER" ;;
			1) ;;
			*) return 2 ;;
			esac
		fi
	done
}

# ui_message "Text": something to read before going on
ui_message() {
	fe_choose_ui
	if [[ $FE_UI == dialog ]]; then
		FE_CANCEL=OK fe_dialog "OpenSim" --msgbox "$1" 6 50 || true
	else
		printf '%s\n' "$1" >&2
	fi
}

# ui_checks "Title" "Text" NAME...: yes or no for each, in the variable of that name (LABEL[name] says it); check boxes in dialog
ui_checks() {
	local _u_title=$1 _u_text=$2 _u_n _u_i _u_items=() _u_picked
	shift 2
	local _u_names=("$@")
	fe_choose_ui
	if [[ $FE_UI == dialog ]]; then
		for _u_n in "${_u_names[@]}"; do
			_u_items+=("$_u_n" "${LABEL[$_u_n]}" "$([[ ${!_u_n} == yes ]] && echo on || echo off)")
		done
		fe_dialog "$_u_title" --no-tags --separate-output --checklist "${_u_text:- }" "$((${#_u_names[@]} + 8 + $(fe_lines "$_u_text")))" 50 "${#_u_names[@]}" "${_u_items[@]}" || return $?
		_u_picked=$'\n'$FE_ANSWER$'\n'
		for _u_n in "${_u_names[@]}"; do
			[[ $_u_picked == *$'\n'"$_u_n"$'\n'* ]] && printf -v "$_u_n" yes || printf -v "$_u_n" no
		done
	else
		[[ -n "$_u_text" ]] && printf '\n%s\n' "$_u_text" >&2
		# The choices proposed on one line, kept with Enter; each asked only when the person chooses them
		_u_picked=
		for _u_n in "${_u_names[@]}"; do
			_u_picked+="${_u_picked:+ }$([[ ${!_u_n} == yes ]] && echo '[x]' || echo '[ ]') ${LABEL[$_u_n]}"
		done
		while :; do
			fe_read "? $_u_title (Enter keeps them, c to choose): $_u_picked " '' || return 2
			fe_special || return $?
			case ${FE_ANSWER,,} in
			'' | y | yes) return 0 ;;
			c | choose) break ;;
			esac
		done
		for _u_n in "${_u_names[@]}"; do
			while :; do
				fe_read "${LABEL[$_u_n]} [${!_u_n}]: " "${!_u_n}" || return 2
				fe_special || return $?
				case ${FE_ANSWER,,} in
				y | yes) printf -v "$_u_n" yes ;;
				n | no) printf -v "$_u_n" no ;;
				*) continue ;;
				esac
				break
			done
		done
	fi
}

# ui_review "Title" "Text" "ROWS": what the setup stands for, to confirm and to change. ROWS is the lines section, label, value, name,
# current value, options (JSON) separated by the unit separator; a line with a name is changed as in a form: REVIEW_EDITS then holds
# the change (JSON) and the status is 4, for the engine to check it and show the review again. Enter asks Start; no goes back to the
# list. In dialog a panel like the others: a line chosen and changed (Change), then Start.
ui_review() {
	local _u_title=$1 _u_text_above=$2 _u_rows=$3 _u_section _u_label _u_value _u_name _u_current _u_options _u_previous= _u_items=() _u_n=0
	local _u_height _u_lines _u_above _u_text= _u_i _u_names=() _u_currents=() _u_labels=() _u_choices=() _u_wholes=() _u_key _u_choice
	REVIEW_EDITS='{}'
	fe_choose_ui
	while IFS=$'\x1f' read -r _u_section _u_label _u_value _u_name _u_current _u_options; do
		[[ -z "$_u_section" ]] && continue
		if [[ "$_u_section" != "$_u_previous" ]]; then
			_u_items+=("h$((++_u_n))" "-- ${_u_section^} --")
			_u_previous=$_u_section
			_u_text+="  ${_u_section^}"$'\n'
		fi
		_u_names+=("$_u_name")
		_u_currents+=("$_u_current")
		_u_labels+=("$_u_label")
		_u_choices+=("$_u_options")
		_u_items+=("r${#_u_names[@]}" "$(fe_fit "$_u_label: $_u_value" 66)")
		_u_wholes+=("$_u_label: $_u_value")
		_u_text+=$(printf '  %3d) %-20s %s' "${#_u_names[@]}" "$_u_label" "$_u_value")$'\n'
	done <<<"$_u_rows"
	if [[ $FE_UI == dialog ]]; then
		# A panel like the others: a line chosen (arrows, Tab to the buttons) and changed with Change, then Start; the list scrolls
		# when it does not fit (a terminal of 24 lines has 15 for it)
		local _u_status _u_start=${FE_OK:-Start} _u_show=${FE_EXTRA:-} _u_tag _u_value
		# As tall as the terminal lets it be (two lines kept), then the list scrolls
		local _u_rows_max
		_u_rows_max=$(stty size <"$FE_TTY" 2>/dev/null | cut -d' ' -f1)
		[[ "$_u_rows_max" =~ ^[0-9]+$ ]] && ((_u_rows_max >= 15)) || _u_rows_max=24
		_u_lines=$((${#_u_items[@]} / 2))
		_u_above=$(fe_lines "$_u_text_above")
		_u_height=$((_u_lines + 7 + _u_above > _u_rows_max - 2 ? _u_rows_max - 2 : _u_lines + 7 + _u_above))
		while :; do
			_u_status=0
			FE_OK=Change FE_EXTRA=$_u_start FE_HELP=$_u_show fe_dialog "$_u_title" --scrollbar --no-tags --menu "${_u_text_above:- }" "$_u_height" 78 "$((_u_height - 7 - _u_above))" "${_u_items[@]}" || _u_status=$?
			_u_tag=$FE_ANSWER
			case $_u_status in
			3)
				if [[ -n "${FE_BEFORE_START:-}" ]]; then "$FE_BEFORE_START" "$_u_rows" || return 2; fi
				return 0
				;;
			5) return 3 ;;
			0) ;;
			*) return "$_u_status" ;;
			esac
			[[ "$_u_tag" == r* ]] || continue
			_u_i=$((${_u_tag#r} - 1))
			# A line that names nothing is only shown: whole, when the panel had to shorten it
			if [[ -z "${_u_names[$_u_i]}" ]]; then
				((${#_u_wholes[$_u_i]} > 66)) && FE_CANCEL=OK FE_OK= FE_EXTRA= FE_HELP= fe_dialog "${_u_labels[$_u_i]}" --msgbox "${_u_wholes[$_u_i]}" 10 76 || true
				continue
			fi
			if [[ -n "${_u_choices[$_u_i]}" && "${_u_choices[$_u_i]}" != null ]]; then
				local _u_menu=()
				while IFS=$'\x1f' read -r _u_key _u_choice; do _u_menu+=("$_u_key" "$_u_choice"); done < <(jq -r 'to_entries[] | "\(.key)\u001f\(.value)"' <<<"${_u_choices[$_u_i]}")
				FE_OK= FE_CANCEL=Back FE_EXTRA= FE_HELP= ui_menu _u_value "${_u_labels[$_u_i]}" '' "${_u_currents[$_u_i]}" "${_u_menu[@]}" || continue
			else
				# Its name once, as the title of the panel (dialog wants a text: a space)
				FE_OK= FE_CANCEL=Back FE_EXTRA= FE_HELP= fe_dialog "${_u_labels[$_u_i]}" --inputbox " " 7 70 "${_u_currents[$_u_i]}" || continue
				_u_value=$FE_ANSWER
			fi
			REVIEW_EDITS=$(jq -cn --arg name "${_u_names[$_u_i]}" --arg value "$_u_value" '{($name): $value}')
			return 4
		done
	fi
	[[ -n "$_u_text_above" ]] && printf '\n%s\n' "$_u_text_above" >&2
	printf '%s\n%s' "$_u_title" "$_u_text" >&2
	while :; do
		fe_read "Edit [1-${#_u_names[@]}, Enter to continue]${FE_EXTRA:+, s: $FE_EXTRA}: " '' || return 2
		# The button of its own the engine gives (the passwords of the reviews that show them)
		[[ -z "${FE_EXTRA:-}" || ! "$FE_ANSWER" =~ ^(s|:show)$ ]] || return 3
		fe_special || return $?
		if [[ -z "$FE_ANSWER" ]]; then
			# What its caller still asks before the start, from the values of the review (the line of the website in Apache)
			if [[ -n "${FE_BEFORE_START:-}" ]]; then
				"$FE_BEFORE_START" "$_u_rows" || return 2
			fi
			fe_read "? ${FE_OK:-Start}? [Y/n] " y || return 2
			[[ -z "$FE_ANSWER" || "$FE_ANSWER" == [yY]* ]] && return 0
			continue
		fi
		[[ "$FE_ANSWER" =~ ^[0-9]+$ ]] && ((FE_ANSWER >= 1 && FE_ANSWER <= ${#_u_names[@]})) || continue
		_u_i=$((FE_ANSWER - 1))
		# A line that names nothing is only shown
		[[ -n "${_u_names[$_u_i]}" ]] || continue
		if [[ -n "${_u_choices[$_u_i]}" && "${_u_choices[$_u_i]}" != null ]]; then
			local _u_menu=()
			while IFS=$'\x1f' read -r _u_key _u_choice; do _u_menu+=("$_u_key" "$_u_choice"); done < <(jq -r 'to_entries[] | "\(.key)\u001f\(.value)"' <<<"${_u_choices[$_u_i]}")
			FE_OK= FE_CANCEL=Back FE_EXTRA= ui_menu _u_choice "${_u_labels[$_u_i]}" '' "${_u_currents[$_u_i]}" "${_u_menu[@]}" || continue
			FE_ANSWER=$_u_choice
		else
			fe_read "${_u_labels[$_u_i]}: " "${_u_currents[$_u_i]}" || return 2
		fi
		REVIEW_EDITS=$(jq -cn --arg name "${_u_names[$_u_i]}" --arg value "$FE_ANSWER" '{($name): $value}')
		return 4
	done
}

# _ui_var NAME: NAME as a name of variable, whatever the engine called it (a hyphen in the name of an option...): every character that
# is not a letter or a digit becomes _ and its code in hexadecimal
_ui_var() {
	local _u_in=$1 _u_out= _u_c _u_i
	for ((_u_i = 0; _u_i < ${#_u_in}; _u_i++)); do
		_u_c=${_u_in:_u_i:1}
		[[ $_u_c == [A-Za-z0-9] ]] && _u_out+=$_u_c || _u_out+=$(printf '_%02x' "'$_u_c")
	done
	printf '%s' "$_u_out"
}

# ui_screen "SCREEN": draws a screen of the engine (menu, form, checks or review) and sets what goes back to it: $answers (the screen,
# filled, as JSON), $button (next, back or quit) and $state (as the engine gave it)
ui_screen() {
	local _u_screen=$1 _u_kind _u_title _u_text _u_status=0 _u_name _u_label _u_value _u_secret _u_note _u_key _u_items=() _u_names=() _u_default _u_var
	_u_kind=$(jq -r .kind <<<"$_u_screen")
	_u_title=$(jq -r .title <<<"$_u_screen")
	_u_text=$(jq -r '[.text, .notice] | map(select(. != "")) | join("\n\n")' <<<"$_u_screen")
	# The label of OK is the default of dialog: said only when it is another
	FE_OK=$(jq -r 'if (.buttons.next // "OK") == "OK" then empty else .buttons.next end' <<<"$_u_screen")
	FE_CANCEL=$(jq -r '.buttons.back // "Back"' <<<"$_u_screen")
	FE_EXTRA=$(jq -r '.buttons.show // empty' <<<"$_u_screen")
	state=$(jq -r .state <<<"$_u_screen")
	answers='{}'
	case $_u_kind in
	menu)
		_u_name=$(jq -r .name <<<"$_u_screen")
		_u_default=$(jq -r .value <<<"$_u_screen")
		while IFS=$'\x1f' read -r _u_key _u_label _u_note; do
			_u_items+=("$_u_key" "$_u_label${_u_note:+ ($_u_note)}")
		done < <(jq -r '.items[] | [.key, .label, .note] | join("\u001f")' <<<"$_u_screen")
		ui_menu _u_value "$_u_title" "$_u_text" "$_u_default" "${_u_items[@]}" || _u_status=$?
		answers=$(jq -cn --arg name "$_u_name" --arg value "$_u_value" '{($name): $value}')
		;;
	form)
		declare -gA LABEL=() SECRET=() READONLY=() ENGINE_NAME=() OPTIONS=() HELP=()
		while IFS=$'\x1f' read -r _u_name _u_label _u_value _u_secret _u_readonly _u_note _u_options; do
			if [[ -z $_u_value ]]; then
				case $_u_name in
				admin_user) _u_value=${OPENSIM_DB_ADMIN_USER:-} ;;
				admin_password) _u_value=${OPENSIM_DB_ADMIN_PASS:-} ;;
				esac
			fi
			_u_var=f_$(_ui_var "$_u_name")
			ENGINE_NAME[$_u_var]=$_u_name
			LABEL[$_u_var]=$_u_label
			[[ $_u_secret == true ]] && SECRET[$_u_var]=1
			[[ $_u_readonly == true ]] && READONLY[$_u_var]=1
			[[ -n $_u_note ]] && HELP[$_u_var]=$_u_note
			[[ -n $_u_options ]] && OPTIONS[$_u_var]=$(jq -r 'to_entries[] | "\(.key)\u001f\(.value)"' <<<"$_u_options")
			printf -v "$_u_var" '%s' "$_u_value"
			_u_names+=("$_u_var")
		done < <(jq -r '.fields[] | [.name, .label, .value, .secret, (.readonly // false), (.help // ""), (.options // "" | if . == "" then . else tojson end)] | map(tostring) | join("\u001f")' <<<"$_u_screen")
		ui_form "$_u_title" "$_u_text" "${_u_names[@]}" || _u_status=$?
		for _u_name in "${_u_names[@]}"; do
			[[ -n "${READONLY[$_u_name]:-}" ]] && continue
			answers=$(jq -c --arg name "${ENGINE_NAME[$_u_name]}" --arg value "${!_u_name}" '. + {($name): $value}' <<<"$answers")
		done
		;;
	checks)
		declare -gA LABEL=() ENGINE_NAME=()
		while IFS=$'\x1f' read -r _u_name _u_label _u_value _u_note; do
			_u_var=c_$(_ui_var "$_u_name")
			ENGINE_NAME[$_u_var]=$_u_name
			LABEL[$_u_var]="$_u_label${_u_note:+ ($_u_note)}"
			printf -v "$_u_var" '%s' "$([[ $_u_value == true ]] && echo yes || echo no)"
			_u_names+=("$_u_var")
		done < <(jq -r '.items[] | [.name, .label, .checked, .note] | map(tostring) | join("\u001f")' <<<"$_u_screen")
		ui_checks "$_u_title" "$_u_text" "${_u_names[@]}" || _u_status=$?
		for _u_name in "${_u_names[@]}"; do
			answers=$(jq -c --arg name "${ENGINE_NAME[$_u_name]}" --argjson value "$([[ ${!_u_name} == yes ]] && echo true || echo false)" '. + {($name): $value}' <<<"$answers")
		done
		;;
	review)
		ui_review "$_u_title" "$_u_text" "$(jq -r '.rows[] | [.section, .label, .value, (.name // ""), (.current // .value | tostring), (if .options then (.options | tojson) else "" end)] | join("\u001f")' <<<"$_u_screen")" || _u_status=$?
		# A line changed: the engine checks it, and shows the review again
		((_u_status != 4)) || answers=$REVIEW_EDITS
		if ((_u_status == 0)); then
			answers=$(jq -cn \
				--arg host "${OPENSIM_DB_HOST:-}" \
				--arg user "${OPENSIM_DB_USER:-}" \
				--arg password "${OPENSIM_DB_PASS:-}" \
				--arg admin_user "${OPENSIM_DB_ADMIN_USER:-}" \
				--arg admin_password "${OPENSIM_DB_ADMIN_PASS:-}" \
				'{database_host:$host,database_user:$user,database_password:$password,admin_user:$admin_user,admin_password:$admin_password} | with_entries(select(.value != ""))')
		fi
		;;
	*) die "The engine shows a screen this command does not know: $_u_kind" ;;
	esac
	case $_u_status in
	0) button=next ;;
	1) button=back ;;
	3) button=show ;;
	4) button=edit ;;
	*) button=quit ;;
	esac
	# What the engine is about to do takes time: said before it is asked
	_u_text=$(jq -r '.wait // empty' <<<"$_u_screen")
	if [[ $button == next && -n "$_u_text" ]]; then
		# The error output as it is: /dev/stderr cannot be reopened by a user who is not the one who owns the terminal (sudo -u)
		if [[ $FE_UI == dialog ]]; then printf '%s\n' "$_u_text" >"$FE_SCREEN"; else printf '%s\n' "$_u_text" >&2; fi
	fi
	return 0
}
