summaryrefslogtreecommitdiff
path: root/src/twopane.bash
blob: 0284e4b2c36960184597f85b8def573fb47d48e6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
#!/bin/bash
BASH_ARGV0=twopane.bash
echo -n "$0" >/proc/$BASHPID/comm
set -e
set -f
set -o pipefail
shopt -s lastpipe

PS4='+ \t$LINENO\t '

. read_chars.bash
. finally.bash

kill_tty_forward()
{
        read pid < "$TWOPANE"/tty_forward.pid
        /bin/kill "${1:-'-INT'}" -- -$pid 2>/dev/null
}

BOT_SIZE=8
BOT_TITLE=input

DO_RESTART=
DO_START=
DO_START=y
DO_RESTART=y

if [ $# = 0 ]
then
        TOP_CMD="$SHELL -i"
        if [ "$DO_RESTART" ]
        then
                SIG=INT
                BOT_CMD=PROMPT_COMMAND=prompt_command
                TOP_EXIT=restart
        elif [ "$DO_START" ]
        then
                BOT_CMD=start
                TOP_EXIT=quit
        else
                BOT_CMD=PROMPT_COMMAND=prompt_command
                TOP_EXIT=prompt
        fi
elif [ "$TWOPANE" -a "$*" = detach ]
then
        kill_tty_forward -TSTP
        exit
elif [ "$TWOPANE" -a "$*" = focus ]
then
        screen -X focus
        exit
elif [ "$TWOPANE" -a "$*" = quit ]
then
        screen -X quit
        exit
else
        TOP_CMD=$*
        BOT_CMD=start
        TOP_EXIT=quit
fi
TOP_TITLE="Command: $TOP_CMD"

TWOPANE=$(mktemp -d)
export TWOPANE TOP_CMD BOT_CMD TOP_TITLE BOT_TITLE BOT_SIZE
trap 'rm -r "$TWOPANE"' EXIT
# STY=$(systemd-escape -p "$TWOPANE")
systemd_escape_path()
{
        declare -n path="$1" result="$2"
        if [ "$TERMUX_VERSION" ]
        then
                result=$(basename "$path")
        else
                result=$(realpath "$path")
        fi
        result=${result//-/--}
        result=${result//\//-}
}
systemd_escape_path TWOPANE STY
STY=$0.$$.$STY

save_file()
{
        cat > "$TWOPANE"/"${1:?$0: Error: filename cannot be empty string}"
}

save_screenrc()
{
        save_file screenrc"${1:+.$1}"
}

save_screenrc <<'.'
# Disable keybindings.
unbindall
escape \0\0
# Disable messages.  This is needed for screen -X/-Q to work reasonably.
msgwait 0
msgminwait 0

bellmsg ^G
vbell off

# Try to disable blocking the terminal on ^S.
# Doesn't seem to work here.
# More is needed.  Xterm?
nonblock on

# Enable mouse focus
defmousetrack on
mousetrack on

caption string '%t'
layout new
split
focus bottom
resize $BOT_SIZE
screen -ln -t "$BOT_TITLE" 0 bash --noprofile --rcfile "$TWOPANE"/bashrc -i
layout save 0
.

with_screen_pane()
{
        (( $# >= 2 )) || return
        declare -i PANE="$1" LOCK
        (( PANE > 0 )) || return
        (
                flock $LOCK
                "${@:2}"
        ) {LOCK}>"$TWOPANE"/pane$PANE
}

check_screen_pane()
{
        (( PANE > 0 )) || return
        screen -p "$PANE" -Q info >/dev/null
}

kill_screen_pane()
{
        (( PANE > 0 )) || return
        while check_screen_pane "$PANE"
        do
                screen -p "$PANE" -X kill
        done
}

start_screen_pane()
{
        (( PANE > 0 )) || return
        if check_screen_pane "$PANE"
        then
                i "pane already running: $PANE"
                return
        else
                i "starting pane: $PANE"
        fi
        shift
        if [ $# = 0 ]
        then
                set -f
                set -- ${TOP_CMD:-bash -i}
        fi
        TOP_TITLE="Command: ${*@Q}"
        screen -X focus top
        screen -X screen -ln -t "$TOP_TITLE" "$PANE" "$@"
        start_screen_pane_subprocess
}

start_screen_pane_subprocess()
{
        (( PANE > 0 )) || return
        subproc_command=(
                exec -a gnuscreen-input-filter
                        socat
                                UNIX-LISTEN:"$TWOPANE"/socket
                                STDIN,cfmakeraw,opost=1,onlcr=1!!STDOUT
        )
        screen -p "$PANE" -X exec .!. bash -c "${subproc_command[*]}"
}

restart_pane()
{
        (( PANE > 0 )) || return
        kill_screen_pane
        start_screen_pane "$@"
}

restart_top_pane()
{
        with_screen_pane 1 restart_pane "$@"
}

# connect_coproc() -- start a coprocess and connect it to copied file
# descriptors named {NAME}_IN and {NAME}_OUT where {NAME} is the
# supplied first argument or default "COPROC".  {NAME} is the name of
# the created bash coprocess.

# The copied file descriptors (unlike the original coprocess
# file descriptors, in ${NAME[0]} and ${NAME[1]}) can be
# passed to external processes (e.g.: socat(1) instances) and
# used in subshells.

# The created coprocess is silently disowned from job control before
# bash can make noise about it.
connect_coproc()
{
        [ $# -gt 0 ] || set -- COPROC
        declare -n coproc="$1"
        shift
        [ $# -gt 0 ] || set -- "${!coproc}"
        declare -n std0="${!coproc}_IN"
        declare -n std1="${!coproc}_OUT"
        declare -n std2="${!coproc}_ERR"
        declare -n pid="${!coproc}_PID"
        if ! [ "$pid" ]
        then
                i "coproc starting: ${!coproc}"
                {
                        coproc "${!coproc}" \
                        {
                                "$@"
                        } 2>&$std2 {std2}>&-
                        unset std2
                        disown "%coproc ${!coproc} "
                } {std2}>&2 2>/dev/null
        else
                i "coproc already running: ${!coproc}"
        fi
        {
                exec {std0}<&0 {std1}>&1
        } <&${coproc[0]} >&${coproc[1]}
}

disconnect_coproc()
{
        [ $# -gt 0 ] || set -- COPROC
        declare -n coproc="$1"
        declare -n std0="${!coproc}_IN"
        declare -n std1="${!coproc}_OUT"
        declare -n  pid="${!coproc}_PID"
        if [ "$std0" -o "$std1" ]
        then
                exec {std0}<&- {std1}>&-
        fi
        if [ "$pid" ]
        then
                kill "$pid" 2>/dev/null
                wait -f "$pid" 2>/dev/null
        fi
        unset coproc std0 std1 pid
}

connect()
{
        if ! [ "$TOP_PANE_PID" ]
        then
                disconnect_sink ECHOSEND
                connect_coproc TOP_PANE
        fi
        connect_sink TTY_WRITER write-tty
        connect_sink ECHOSEND echo_sender
}

disconnect()
{
        : "${TOP_PANE_IN@A} ${TOP_PANE_OUT@A} ${TOP_PANE_PID@A} ${TOP_PANE[@]@A}"
        disconnect_coproc TOP_PANE
        : "${ECHOSEND@A} ${ECHOSEND_PID@A}"
        disconnect_sink ECHOSEND
}

sendc()
{
        [ "${TOP_PANE[0]}" ] || connect
        printf '%s' "$*" >&${TOP_PANE_OUT?Internal error}
}

send()
{
        [ "${TOP_PANE[0]}" ] || connect
        printf '%s\n' "$*" >&${TOP_PANE_OUT?Internal error}
}

tty_forward()
{
        printf '%d\n' "$BASHPID" > "$TWOPANE"/tty_forward.pid
        trap 'kill -INT $$' INT
        read-tty
}

TOP_PANE()
{
        (exec -a bottom-pane-tty-forward socat - UNIX-CONNECT:"$TWOPANE"/socket,forever)
        case "$TOP_EXIT" in
                restart )
                        x kill_tty_forward -TSTP
                        x kill -INT $$
                ;;
                quit )
                        quit
                ;;
                prompt | * )
                        x kill_tty_forward -TSTP
                        focus bottom
                ;;
        esac
}

magic_fifo_sink()
{
        # Some bash magic from superuser.com.
        # Use two PIDs instead of one inode to make fifo.  (Not just
        # less expensive but more robust, except! uses Linux procfs.)
        # https://superuser.com/questions/184307/bash-create-anonymous-fifo
        declare -n fd_out="$1"
        local fd_in reader writer
        {
                sleep 1 | sleep 1 &
                reader=$!
                writer=$(jobs -p %+)
                disown
        } &>/dev/null
        exec {fd_out}>/proc/$writer/fd/1 {fd_in}</proc/$reader/fd/0
        quiet_bg "${@:2}" <&"$fd_in"
}

# This function serves to replace bash's builtin >() syntax.  That
# syntax does not allow the asynchronous command to be subject to
# interactive job control.  The actual bash implementation of >() uses a
# /proc/fd/ trick on Linux to avoid mkfifo.
fifo_sink()
{
        (( $# > 0 )) || set -- SINK
        (( $# > 1 )) || set -- "$1" "$1"
        declare -n fd_out="$1"
        local fifo fd_in
        fifo=${TWOPANE:-$TMP}/sink_${!fd_out}.$$.fifo
        mkfifo "$fifo" || return

        exec {fd_out}<>"$fifo"
        fd_in=$fd_out
        rm "$fifo"
        quiet_bg "${@:2}" <&"$fd_in" {fd_in}<&-
        return
}

connect_sink()
{
        (( $# > 0 )) || set -- SINK
        declare -n sinkfd="$1"
        declare -n pid="${!sinkfd}_PID"
        declare -n sinkstartcmd="${!sinkfd}_start_command"
        if (( $# >= 2 ))
        then
                sinkstartcmd=$(printf '%q\n' "${@:2}")
        elif [ ! "$sinkstartcmd" ]
        then
                sinkstartcmd="${!sinkfd}"
        fi
        if kill -0 "$pid" &>/dev/null
        then
                i "sink already running: ${!sinkfd}"
        else
                i "sink starting: ${!sinkfd}"
                local cmd
                cmd=($sinkstartcmd)
                (( ${#cmd} > 0 )) || return
                fifo_sink "${!sinkfd}" "${cmd[@]}"
                pid=$!
        fi
}

check_restart_sink()
{
        connect_sink "$1"
}

disconnect_sink()
{
        (( $# > 0 )) || set -- SINK
        declare -n sinkfd="$1"
        [ "$sinkfd" ] || return
        declare -n pid="${!sinkfd}_PID"
        i "sink stopping: ${!sinkfd}"
        exec {sinkfd}>&-
        kill $pid 2>/dev/null
        kill -CONT $pid 2>/dev/null
        disown $pid &>/dev/null
        unset fd pid
}

quiet_bg()
{
        local STDERR
        {
                eval "$(printf '%q ' "$@") & 2>&\$STDERR {STDERR}>&-"
        } {STDERR}>&2 2>/dev/null
}

# echo_sender() reads from two inputs and writes to two outputs.
#
# Read from both:
#       read from stdin
#       read from $TOP_PANE_IN
# Write to both:
#       write to stdout
#       write to $TOP_PANE_OUT
# I.e.:
#       read from /dev/tty on stdin
#       read from the socat-coproc forwarding the top pane's tty input.
#       write to /dev/tty on stdout
#       write to the socat-coproc forwarding tty input into the top pane.
#
#       For the network it is just an echo,
#       here we could place an input filter,
#       but we have none.
echo_sender()
{
        trap 'exit' TTOU
        (exec -a echo_sender socat - fd:"${TOP_PANE_IN?${LINENO@Q}}"!!-) |
        tee /dev/fd/"${TTY_WRITER?${LINENO@Q}}" |
        socat - fd:"${TOP_PANE_OUT?${LINENO@Q}}"
}

restart_tty_forward()
{
        detach
        with_screen_pane 1 start_screen_pane "$@"
        focus bottom
        connect
        i 'starting tty_forward'
        quiet_bg tty_forward >&$ECHOSEND
        echo $! > "$TWOPANE"/tty_forward.pid
}

attach()
{
        if ! jobs %tty_forward &>/dev/null
        then
                restart_tty_forward "$@"
        fi
        focus top
        { %tty_forward; } &>/dev/null
        focus bottom
}

detach()
{
        {
                kill -INT %tty_forward
                disown %tty_forward
        } &>/dev/null
}

restart() { attach "$@"; }
start() { attach "$@"; }
foreground() { attach "$@"; }
twopane() { attach "$@"; }
forward() { attach "$@"; }

quit()
{
        screen -X quit
}

focus()
{
        screen -X focus "$@"
}

resize()
{
        screen -X resize "$@"
}

SIGUSR1()
{
        i "SIGUSR1: ${BASH_COMMAND@A}"
}

SIGCHLD()
{
        i "SIGCHILD: ${BASH_COMMAND@A}"
}

killpgrp()
{
        (( $# == 2 )) && /bin/kill "$1" -- -"$2"
}

prompt_command()
{
        [ "$TOP_EXIT" = 'restart' ] || return 0

        if [ "$SIG" = INT ]
        then
                finally 'unset SIG; start' detach
                return
        fi

        check_restart_sink ECHOSEND

        local job
        if      ! { job=$(jobs %tty_forward 2>/dev/null) && [ "$job" ]; }
        then
                finally 'start' :
                return
        fi

        read _ jobstatus _ <<< "${job?${LINENO@A}}"
        case "${jobstatus?${LINENO@A}}" in
                Running )
                        jobs -x finally 'attach' killpgrp -CONT %tty_forward
                ;;
                Interrupt )
                        finally 'start' :
                ;;
                Stopped )
                ;;
        esac
}

SIGINT()
{
        i INT "${BASH_COMMAND@A}"
        disown $TOP_PANE_PID $ECHOSEND_PID 2>/dev/null
        kill $TOP_PANE_PID $ECHOSEND_PID 2>/dev/null
        SIG=INT
        PROMPT_COMMAND=prompt_command
}

our_bashrc_main()
{
        BASH_ARGV0=twopane
        echo -n "$0" >/proc/$BASHPID/comm
        set -m
        set -f
        set -o pipefail
        trap 'SIGUSR1' USR1
        # trap 'SIGCHLD' CHLD
        trap 'SIGINT' INT
        trap '! [ "$DEBUG" ] || read -p "Exit> "; quit' EXIT
        export PS1="$BOT_TITLE\\\$ "
        export PS4='+ \t$LINENO\t '
}

save_file bashrc <<.
${TOP_CMD@A}
${BOT_CMD@A}
${TOP_TITLE@A}
${BOT_TITLE@A}
${TOP_EXIT@A}
$(declare -f)
our_bashrc_main
$BOT_CMD
.

main()
{
        screen -c "$TWOPANE"/screenrc -m -S "$STY" -ln
}

main "$@"