Debian Codegraph @

eg/rl-callbacktest

raw
1 #!/usr/bin/env perl
2 #
3 # rl-callbacktest: 2.4.14 Alternate Interface Example
4 #
5 # Copyright (C) 2024 Hiroo Hayashi
6 #
7 # Derived from: examples/rl-callbacktest.c in the GNU Readline Library
8
9 use strict;
10 use warnings;
11 use Term::ReadLine;
12
13 my $t = new Term::ReadLine 'rl-callbacktest';
14 my $a = $t->Attribs;
15
16 my $sigwinch_received = 0;
17 my $running = 0;
18 my $prompt = 'rltest$ ';
19
20 # Handle window size changes when readline is not active and reading
21 # characters.
22 sub sigwinch_handler {
23 my $sig = shift;
24 $sigwinch_received = 1;
25 }
26
27 # Callback function called for each line when accept-line executed, EOF
28 # seen, or EOF character read. This sets a flag and returns; it could
29 # also call exit(3).
30 sub cb_linehandler {
31 my $line = shift;
32
33 # Can use ^D (stty eof) or `exit' to exit.
34 if (!$line || $line eq "exit") {
35 print "\n" unless $line;
36 print "exit\n";
37
38 # This function needs to be called to reset the terminal settings,
39 # and calling it from the line handler keeps one extra prompt from
40 # being displayed.
41 $t->callback_handler_remove();
42
43 $running = 0;
44 } else {
45 $t->add_history($line) if $line;
46 print "input line: $line\n";
47 }
48 }
49
50 # Handle SIGWINCH
51 $SIG{WINCH} = \&sigwinch_handler;
52
53 # Install the line handler.
54 $t->callback_handler_install($prompt, \&cb_linehandler);
55
56 # Enter a simple event loop. This waits until something is available
57 # to read on readline's input stream (defaults to standard input) and
58 # calls the builtin character read callback to read it. It does not
59 # have to modify the user's terminal settings.
60 $running = 1;
61 while ($running) {
62 my $fds = '';
63 vec($fds, fileno($a->{instream}), 1) = 1;
64
65 my $r = select($fds, undef, undef, undef);
66 if ($r < 0 && $! && !$!{EINTR}) { # EINTR is not an error
67 warn "$0: select: $!\n";
68 $t->callback_handler_remove();
69 last;
70 }
71 if ($sigwinch_received) {
72 warn "$0: SIGWINCH received\n";
73 $t->resize_terminal();
74 $sigwinch_received = 0;
75 }
76 next if $r < 0; # select returns EINTR (interrupted system call)
77
78 if (vec($fds, fileno($a->{instream}), 1)) {
79 $t->callback_read_char();
80 }
81 }
82
83 print "$0: Event loop has exited\n";
84 exit 0;