| 1 | package Lab::Measurement::KeyboardHandling; | ||
| 2 | #ABSTRACT: Minimal keyboard input handling | ||
| 3 | $Lab::Measurement::KeyboardHandling::VERSION = '3.899'; | ||
| 4 | use v5.20; | ||
| 5 | |||
| 6 | use Term::ReadKey; | ||
| 7 | |||
| 8 | my $labkey_initialized = 0; | ||
| 9 | |||
| 10 | sub labkey_safe_exit { | ||
| 11 | ReadMode('normal'); | ||
| 12 | exit(@_); | ||
| 13 | } | ||
| 14 | |||
| 15 | sub labkey_safe_int { | ||
| 16 | ReadMode('normal'); | ||
| 17 | exit(1); | ||
| 18 | } | ||
| 19 | |||
| 20 | sub labkey_safe_die { | ||
| 21 | ReadMode('normal'); | ||
| 22 | |||
| 23 | # In order to print stack trace do not call exit(@_) here. | ||
| 24 | } | ||
| 25 | |||
| 26 | sub labkey_init { | ||
| 27 | $SIG{'INT'} = \&labkey_safe_int; | ||
| 28 | $SIG{'QUIT'} = \&labkey_safe_exit; | ||
| 29 | $SIG{__DIE__} = \&labkey_safe_die; | ||
| 30 | END { labkey_safe_exit(); } | ||
| 31 | ReadMode('raw'); | ||
| 32 | $labkey_initialized = 1; | ||
| 33 | } | ||
| 34 | |||
| 35 | sub labkey_check { | ||
| 36 | |||
| 37 | # handle as much as we can here directly | ||
| 38 | # q - exit: if parameter soft=1 is passed, just return "DIE", otherwise exit | ||
| 39 | # p - pause, i.e. output "Measurement paused, press any key to continue" | ||
| 40 | # t - output script timing info | ||
| 41 | my $soft = shift; | ||
| 42 | |||
| 43 | if ( ( $labkey_initialized == 1 ) | ||
| 44 | && ( defined( my $key = ReadKey(-1) ) ) ) { | ||
| 45 | |||
| 46 | # input waiting; it's in $key | ||
| 47 | if ( $key eq 'q' ) { | ||
| 48 | print "Terminating on keyboard request\n"; | ||
| 49 | if ( $soft == 1 ) { return "DIE"; } | ||
| 50 | else { exit; } | ||
| 51 | } | ||
| 52 | if ( $key eq 'p' ) { | ||
| 53 | print "Measurement paused, press any key to continue\n"; | ||
| 54 | while ( !defined( my $key = ReadKey(-1) ) ) { | ||
| 55 | sleep 1; | ||
| 56 | } | ||
| 57 | print "Measurement continuing\n"; | ||
| 58 | } | ||
| 59 | if ( $key eq 't' ) { | ||
| 60 | print "Timing info following (maybe, sometime)\n"; | ||
| 61 | } | ||
| 62 | } | ||
| 63 | return ""; | ||
| 64 | } | ||
| 65 | |||
| 66 | sub labkey_soft_check { | ||
| 67 | return labkey_check(1); | ||
| 68 | } | ||
| 69 | |||
| 70 | 1; | ||
| 71 | |||
| 72 | __END__ |