Term-TermKey-0.17000755001750001750 013433351022 12443 5ustar00leoleo000000000000Term-TermKey-0.17/Build.PL000444001750001750 110413433351022 14070 0ustar00leoleo000000000000use strict; use warnings; use Module::Build::Using::PkgConfig; my $build = Module::Build::Using::PkgConfig->new( module_name => 'Term::TermKey', configure_requires => { 'Module::Build' => '0.4004', # test_requires }, test_requires => { 'Test::More' => '0.88', # done_testing 'Test::Refcount' => 0, }, license => 'perl', create_license => 1, create_readme => 1, ); $build->use_pkgconfig( "termkey", atleast_version => '0.16', alien => "Alien::libtermkey", alien_version => '0.13', ); $build->create_build_script; Term-TermKey-0.17/Changes000444001750001750 602113433351022 14072 0ustar00leoleo000000000000Revision history for Term-TermKey 0.17 2019-02-20 22:13:39 [CHANGES] * Switch build system to Module::Build::Using::PkgConfig * Generally updated module docs, etc... 0.16 CHANGES: * Meta-merge a configure-time dependency on Alien::libtermkey, as it may be helpful on smoke-test machines. 0.15 CHANGES: * Updated for libtermkey 0.16: + Support TERMKEY_TYPE_MODEREPORT and TERMKEY_TYPE_UNKNOWN_CSI 0.14 CHANGES: * Updated for libtermkey 0.15: + Support TERMKEY_TYPE_POSITION * Provide accessors on key event objects for mouse and position report details 0.13 CHANGES: * Updated for libtermkey 0.14: + Wrap termkey_{start,stop}, termkey_is_started 0.12 CHANGES: * Updated for libtermkey 0.13: + Wrap termkey_new_abstract, termkey_{get,set}_buffer_size * Optionally use Alien::libtermkey if it is available 0.11 CHANGES: * Updated for libtermkey 0.12: + Wrap termkey_push_bytes function + Support filehandle-less (abstract) instances 0.10 CHANGES: * Updated for libtermkey 0.10: + Wrap TERMKEY_CANON_* flags and termkey_{get,set} functions BUGFIXES: * Ensure that EINTR flag shadowing doesn't break ability to read the RAW or UTF8 flags back out of the underlying object 0.09 CHANGES: * Updated for libtermkey 0.9: + Wrap TERMKEY_RES_ERROR, TERMKEY_FLAG_EINTR * Implement EINTR retry logic in XS wrappings so that PERL_ASYNC_CHECK() can dispatch safe signal handlers 0.08 CHANGES: * Updated for libtermkey 0.7: + Added ->parse_key, ->parse_key_at_pos, ->keycmp * Added $key->modifier_shift, modifier_alt, modifier_ctrl 0.07 CHANGES: * Updated for libtermkey 0.6 - two new flag constants BUGFIXES: * Keep a reference to the underlying terminal filehandle globref to ensure it doesn't get destroyed too early 0.06 CHANGES: * Store underlying Term::TermKey object in Term::TermKey::Key event objects; allows $key->format() shortcut * More tests - test simple keypresses, use Test::Refcount 0.05 CHANGES: * Updated for libtermkey 0.5; addsmouse support * Added 'use warnings' also to example scripts 0.04 CHANGES: * Use binmode :encoding(UTF-8) rather than :utf8 * Updated for libtermkey 0.3 * Added 'use warnings' * Various small updates to keep CPANTS happy 0.03 CHANGES: * Added wrapping of termkey_keyname2sym(). 0.02 CHANGES: * Quote async example inline, rather than refering to filename. BUGFIXES: * Detect Ctrl-C in either upper or lowercase, to account for libtermkey version 0.2. * eval{}-wrap the initial call to ExtUtils::PkgConfig in case of failure. 0.01 First version, released on an unsuspecting world. Term-TermKey-0.17/LICENSE000444001750001750 4376213433351022 13641 0ustar00leoleo000000000000This software is copyright (c) 2019 by Paul Evans . This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. Terms of the Perl programming language system itself a) the GNU General Public License as published by the Free Software Foundation; either version 1, or (at your option) any later version, or b) the "Artistic License" --- The GNU General Public License, Version 1, February 1989 --- This software is Copyright (c) 2019 by Paul Evans . This is free software, licensed under: The GNU General Public License, Version 1, February 1989 GNU GENERAL PUBLIC LICENSE Version 1, February 1989 Copyright (C) 1989 Free Software Foundation, Inc. 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The license agreements of most software companies try to keep users at the mercy of those companies. By contrast, our General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. The General Public License applies to the Free Software Foundation's software and to any other program whose authors commit to using it. You can use it for your programs, too. When we speak of free software, we are referring to freedom, not price. Specifically, the General Public License is designed to make sure that you have the freedom to give away or sell copies of free software, that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of a such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must tell them their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any work containing the Program or a portion of it, either verbatim or with modifications. Each licensee is addressed as "you". 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this General Public License and to the absence of any warranty; and give any other recipients of the Program a copy of this General Public License along with the Program. You may charge a fee for the physical act of transferring a copy. 2. You may modify your copy or copies of the Program or any portion of it, and copy and distribute such modifications under the terms of Paragraph 1 above, provided that you also do the following: a) cause the modified files to carry prominent notices stating that you changed the files and the date of any change; and b) cause the whole of any work that you distribute or publish, that in whole or in part contains the Program or any part thereof, either with or without modifications, to be licensed at no charge to all third parties under the terms of this General Public License (except that you may choose to grant warranty protection to some or all third parties, at your option). c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the simplest and most usual way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this General Public License. d) You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. Mere aggregation of another independent work with the Program (or its derivative) on a volume of a storage or distribution medium does not bring the other work under the scope of these terms. 3. You may copy and distribute the Program (or a portion or derivative of it, under Paragraph 2) in object code or executable form under the terms of Paragraphs 1 and 2 above provided that you also do one of the following: a) accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Paragraphs 1 and 2 above; or, b) accompany it with a written offer, valid for at least three years, to give any third party free (except for a nominal charge for the cost of distribution) a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Paragraphs 1 and 2 above; or, c) accompany it with the information you received as to where the corresponding source code may be obtained. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form alone.) Source code for a work means the preferred form of the work for making modifications to it. For an executable file, complete source code means all the source code for all modules it contains; but, as a special exception, it need not include source code for modules which are standard libraries that accompany the operating system on which the executable file runs, or for standard header files or definitions files that accompany that operating system. 4. You may not copy, modify, sublicense, distribute or transfer the Program except as expressly provided under this General Public License. Any attempt otherwise to copy, modify, sublicense, distribute or transfer the Program is void, and will automatically terminate your rights to use the Program under this License. However, parties who have received copies, or rights to use copies, from you under this General Public License will not have their licenses terminated so long as such parties remain in full compliance. 5. By copying, distributing or modifying the Program (or any work based on the Program) you indicate your acceptance of this license to do so, and all its terms and conditions. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. 7. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of the license which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the license, you may choose any version ever published by the Free Software Foundation. 8. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 9. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 10. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS Appendix: How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to humanity, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) 19yy This program 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 1, or (at your option) any later version. This program 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 this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301 USA Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) 19xx name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (a program to direct compilers to make passes at assemblers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice That's all there is to it! --- The Artistic License 1.0 --- This software is Copyright (c) 2019 by Paul Evans . This is free software, licensed under: The Artistic License 1.0 The Artistic License Preamble The intent of this document is to state the conditions under which a Package may be copied, such that the Copyright Holder maintains some semblance of artistic control over the development of the package, while giving the users of the package the right to use and distribute the Package in a more-or-less customary fashion, plus the right to make reasonable modifications. Definitions: - "Package" refers to the collection of files distributed by the Copyright Holder, and derivatives of that collection of files created through textual modification. - "Standard Version" refers to such a Package if it has not been modified, or has been modified in accordance with the wishes of the Copyright Holder. - "Copyright Holder" is whoever is named in the copyright or copyrights for the package. - "You" is you, if you're thinking about copying or distributing this Package. - "Reasonable copying fee" is whatever you can justify on the basis of media cost, duplication charges, time of people involved, and so on. (You will not be required to justify it to the Copyright Holder, but only to the computing community at large as a market that must bear the fee.) - "Freely Available" means that no fee is charged for the item itself, though there may be fees involved in handling the item. It also means that recipients of the item may redistribute it under the same conditions they received it. 1. You may make and give away verbatim copies of the source form of the Standard Version of this Package without restriction, provided that you duplicate all of the original copyright notices and associated disclaimers. 2. You may apply bug fixes, portability fixes and other modifications derived from the Public Domain or from the Copyright Holder. A Package modified in such a way shall still be considered the Standard Version. 3. You may otherwise modify your copy of this Package in any way, provided that you insert a prominent notice in each changed file stating how and when you changed that file, and provided that you do at least ONE of the following: a) place your modifications in the Public Domain or otherwise make them Freely Available, such as by posting said modifications to Usenet or an equivalent medium, or placing the modifications on a major archive site such as ftp.uu.net, or by allowing the Copyright Holder to include your modifications in the Standard Version of the Package. b) use the modified Package only within your corporation or organization. c) rename any non-standard executables so the names do not conflict with standard executables, which must also be provided, and provide a separate manual page for each non-standard executable that clearly documents how it differs from the Standard Version. d) make other distribution arrangements with the Copyright Holder. 4. You may distribute the programs of this Package in object code or executable form, provided that you do at least ONE of the following: a) distribute a Standard Version of the executables and library files, together with instructions (in the manual page or equivalent) on where to get the Standard Version. b) accompany the distribution with the machine-readable source of the Package with your modifications. c) accompany any non-standard executables with their corresponding Standard Version executables, giving the non-standard executables non-standard names, and clearly documenting the differences in manual pages (or equivalent), together with instructions on where to get the Standard Version. d) make other distribution arrangements with the Copyright Holder. 5. You may charge a reasonable copying fee for any distribution of this Package. You may charge any fee you choose for support of this Package. You may not charge a fee for this Package itself. However, you may distribute this Package in aggregate with other (possibly commercial) programs as part of a larger (possibly commercial) software distribution provided that you do not advertise this Package as a product of your own. 6. The scripts and library files supplied as input to or produced as output from the programs of this Package do not automatically fall under the copyright of this Package, but belong to whomever generated them, and may be sold commercially, and may be aggregated with this Package. 7. C or perl subroutines supplied by you and linked into this Package shall not be considered part of this Package. 8. The name of the Copyright Holder may not be used to endorse or promote products derived from this software without specific prior written permission. 9. THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. The End Term-TermKey-0.17/MANIFEST000444001750001750 55613433351022 13717 0ustar00leoleo000000000000Build.PL Changes examples/async.pl examples/lineeditor.pl examples/parse-inputrc.pl examples/simple.pl lib/Term/TermKey.pm lib/Term/TermKey.xs LICENSE MANIFEST This list of files META.json META.yml README t/00use.t t/01symname.t t/02getkey.t t/03read.t t/04parse_format.t t/05flags.t t/06mouse.t t/07position.t t/08modereport.t t/09unknown_csi.t t/99pod.t typemap Term-TermKey-0.17/META.json000444001750001750 213713433351022 14224 0ustar00leoleo000000000000{ "abstract" : "perl wrapper around C", "author" : [ "Paul Evans " ], "dynamic_config" : 1, "generated_by" : "Module::Build version 0.4224", "license" : [ "perl_5" ], "meta-spec" : { "url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec", "version" : 2 }, "name" : "Term-TermKey", "prereqs" : { "build" : { "requires" : { "ExtUtils::CBuilder" : "0" } }, "configure" : { "requires" : { "Module::Build" : "0.4004", "Module::Build::Using::PkgConfig" : "0" } }, "test" : { "requires" : { "Test::More" : "0.88", "Test::Refcount" : "0" } } }, "provides" : { "Term::TermKey" : { "file" : "lib/Term/TermKey.pm", "version" : "0.17" } }, "release_status" : "stable", "resources" : { "license" : [ "http://dev.perl.org/licenses/" ] }, "version" : "0.17", "x_serialization_backend" : "JSON::PP version 4.00" } Term-TermKey-0.17/META.yml000444001750001750 127413433351022 14055 0ustar00leoleo000000000000--- abstract: 'perl wrapper around C' author: - 'Paul Evans ' build_requires: ExtUtils::CBuilder: '0' Test::More: '0.88' Test::Refcount: '0' configure_requires: Module::Build: '0.4004' Module::Build::Using::PkgConfig: '0' dynamic_config: 1 generated_by: 'Module::Build version 0.4224, CPAN::Meta::Converter version 2.150010' license: perl meta-spec: url: http://module-build.sourceforge.net/META-spec-v1.4.html version: '1.4' name: Term-TermKey provides: Term::TermKey: file: lib/Term/TermKey.pm version: '0.17' resources: license: http://dev.perl.org/licenses/ version: '0.17' x_serialization_backend: 'CPAN::Meta::YAML version 0.018' Term-TermKey-0.17/README000444001750001750 5213213433351022 13503 0ustar00leoleo000000000000NAME Term::TermKey - perl wrapper around libtermkey SYNOPSIS use Term::TermKey; my $tk = Term::TermKey->new( \*STDIN ); print "Press any key\n"; $tk->waitkey( my $key ); print "You pressed: " . $tk->format_key( $key, 0 ); DESCRIPTION Note that libtermkey itself is deprecated in favour of its eventual merge into libtickit. As a result, uses of this module should also be considered deprecated. Consider rewriting code to use Tickit instead; either by creating a Tickit::Term to receive key input events, or perform a more wholescale rewrite into using Tickit generally for all screen interaction purposes. This module provides a light perl wrapper around the libtermkey library. This library attempts to provide an abstract way to read keypress events in terminal-based programs by providing structures that describe keys, rather than simply returning raw bytes as read from the TTY device. This version of Term::TermKey requires libtermkey version at least 0.16. Multi-byte keys, ambiguous keys, and waittime Some keypresses generate multiple bytes from the terminal. There is also the ambiguity between multi-byte CSI or SS3 sequences, and the Escape key itself. The waittime timer is used to distinguish them. When some bytes arrive that could be the start of possibly multiple different keypress events, the library will attempt to wait for more bytes to arrive that would finish it. If no more bytes arrive after this time, then the bytes will be reported as events as they stand, even if this results in interpreting a partially-complete Escape sequence as a literal Escape key followed by some normal letters or other symbols. Similarly, if the start of an incomplete UTF-8 sequence arrives when the library is in UTF-8 mode, this will be reported as the UTF-8 replacement character (U+FFFD) if it is incomplete after this time. CONSTRUCTOR new $tk = Term::TermKey->new( $fh, $flags ) Construct a new Term::TermKey object that wraps the given term handle. $fh should be either an IO handle reference, an integer referring to a plain POSIX file descriptor, of undef. $flags is optional, but if given should contain the flags to pass to libtermkey's constructor. Assumes a default of 0 if not supplied. See the FLAG_* constants. new_abstract $tk = Term::TermKey->new_abstract( $termtype, $flags ) Construct a new abstract Term::TermKey object not associated with a filehandle. Input may be fed to it using the push_bytes() method rather than waitkey() or advisereadable(). The name of the termtype should be given in the $termtype string. METHODS start stop $success = $tk->start $success = $tk->stop Start or stop IO interactions from the instance. Starting will send the terminal initialisation sequence and set up termios(5) settings, stopping will send the terminal shutdown sequence and restore termios(5) back to the initial values. After construction, a Term::TermKey instance is already started, but these methods may be used to suspend and resume, for example, on receipt of a SIGTSTP signal requesting that the application background itself. Returns false if it fails; $! will contain an error code. is_started $started = $tk->is_started Returns true if the instance has been started, or false if it is stopped. get_flags set_flags $flags = $tk->get_flags $tk->set_flags( $newflags ) Accessor and mutator for the flags. One of the FLAG_UTF8 or FLAG_RAW flags will be set, even if neither was present in the constructor, as in this case the library will attempt to detect if the current locale is UTF-8 aware or not. get_canonflags set_canonflags $canonflags = $tk->get_canonflags $tk->set_canonflags( $newcanonflags ) Accessor and mutator for the canonicalisation flags. get_waittime set_waittime $msec = $tk->get_waittime $tk->set_waittime( $msec ) Accessor and mutator for the maximum wait time in miliseconds. The underlying libtermkey library will have specified a default value when the object was constructed. get_buffer_remaining $bytes = $tk->get_buffer_remaining Accessor returning the number of bytes of buffer space remaining in the buffer; the space in which push_bytes can write. get_buffer_size set_buffer_size $bytes = $tk->get_buffer_size $tk->set_buffer_size( $size ) Accessor and mutator to for the total buffer size to store pending bytes. If the underlying termkey_set_buffer_size(3) call fails, the set_buffer_size method will throw an exception. getkey $res = $tk->getkey( $key ) Attempt to retrieve a single keypress event from the buffer, and put it in $key. If successful, will return RES_KEY to indicate that the $key structure now contains a new keypress event. If $key is an undefined lvalue (such as a new scalar variable) it will be initialised to contain a new key structure. If nothing is in the buffer it will return RES_NONE. If the buffer contains a partial keypress event which does not yet contain all the bytes required, it will return RES_AGAIN (see above section about multibyte events). If no events are ready and the input stream is now closed, will return RES_EOF. This method will not block, nor will it perform any IO on the underlying file descriptor. For a normal blocking read, see waitkey(). getkey_force $res = $tk->getkey_force( $key ) Similar to getkey(), but will not return RES_AGAIN if a partial match was found. Instead, it will force an interpretation of the bytes, even if this means interpreting the start of an -prefixed multibyte sequence as a literal Escape key followed by normal letters. If $key is an undefined lvalue (such as a new scalar variable) it will be initialised to contain a new key structure. This method will not block, nor will it perform any IO on the underlying file descriptor. For a normal blocking read, see waitkey(). waitkey $res = $tk->waitkey( $key ) Attempt to retrieve a single keypress event from the buffer, or block until one is available. If successful, will return RES_KEY to indicate that the $key structure now contains a new keypress event. If an IO error occurs it will return RES_ERROR, and if the input stream is now closed it will return RES_EOF. If $key is an undefined lvalue (such as a new scalar variable) it will be initialised to contain a new key structure. advisereadable $res = $tk->advisereadable Inform the underlying library that new input may be available on the underlying file descriptor and so it should call read() to obtain it. Will return RES_AGAIN if it read at least one more byte, RES_NONE if no more input was found, or RES_ERROR if an IO error occurs. Normally this method would only be used in programs that want to use Term::TermKey asynchronously; see the EXAMPLES section. This method gracefully handles an EAGAIN error from the underlying read() syscall. push_bytes $len = $tk->push_bytes( $bytes ) Feed more bytes into the input buffer. This is primarily useful for feeding input into filehandle-less instances, constructed by passing undef or -1 as the filehandle to the constructor. After calling this method, these bytes will be available to read as keypresses by the getkey method. get_keyname $str = $tk->get_keyname( $sym ) Returns the name of a key sym, such as returned by Term::TermKey::Key->sym(). keyname2sym $sym = $tk->keyname2sym( $keyname ) Look up the sym for a named key. The result of this method call can be compared directly against the value returned by Term::TermKey::Key->sym(). Because this method has to perform a linear search of key names, it is best called rarely, perhaps during program initialisation, and the result stored for easier comparisons during runtime. interpret_unknown_csi ( $cmd, @args ) = $tk->interpret_unknown_csi( $key ) If $key contains an unknown CSI event then its command and arguments are returned in a list. $cmd will be a string of 1 to 3 characters long, containing the initial and intermediate characters if present, followed by the main command character. @args will contain the numerical arguments, where missing arguments are replaced by -1. If $key does not contain an unknown CSI event then an empty list is returned. Note that this method needs to be called immediately after getkey or waitkey, or at least, before calling either of those methods again. The actual CSI sequence is retained in the libtermkey buffer, and only retrieved by this method call. Calling getkey or waitkey again may overwrite that buffer. format_key $str = $tk->format_key( $key, $format ) Return a string representation of the keypress event in $key, following the flags given. See the descriptions of the flags, below, for more detail. This may be useful for matching keypress events against keybindings stored in a hash. See EXAMPLES section for more detail. parse_key $key = $tk->parse_key( $str, $format ) Return a keypress event by parsing the string representation in $str, following the flags given. This method is an inverse of format_key. This may be useful for parsing entries from a configuration file or similar. parse_key_at_pos $key = $tk->parse_key_at_pos( $str, $format ) Return a keypress event by parsing the string representation in a region of $str, following the flags given. Where parse_key will start at the beginning of the string and requires the entire input to be consumed, this method will start at the current pos() position in $str (or at the beginning of the string if none is yet set), and after a successful parse, will update it to the end of the matched section. This position does not have to be at the end of the string. $str must therefore be a real scalar variable, and not a string literal. This may be useful for incremental parsing of configuration or other data, out of a larger string. keycmp $cmp = $tk->keycmp( $key1, $key2 ) Compares the two given keypress events, returning a number less than, equal to, or greater than zero, depending on the ordering. Keys are ordered first by type (unicode, keysym, function, mouse), then by value within that type, then finally by modifier bits. This may be useful in sort expressions: my @sorted_keys = sort { $tk->keycmp( $a, $b ) } @keys; KEY OBJECTS The Term::TermKey::Key subclass is used to store a single keypress event. Objects in this class cannot be changed by perl code. getkey(), getkey_force() or waitkey() will overwrite the contents of the structure with a new value. Keys cannot be constructed, but getkey(), getkey_force() or waitkey() will place a new key structure in the $key variable if it is undefined when they are called. parse_key() and parse_key_at_pos() will return new keys. type $key->type The type of event. One of TYPE_UNICODE, TYPE_FUNCTION, TYPE_KEYSYM, TYPE_MOUSE, TYPE_POSITION, TYPE_MODEREPORT, TYPE_UNKNOWN_CSI. type_is_... $key->type_is_unicode $key->type_is_function $key->type_is_keysym $key->type_is_mouse $key->type_is_position $key->type_is_modereport $key->type_is_unknown_csi Shortcuts which return a boolean. codepoint $key->codepoint The Unicode codepoint number for TYPE_UNICODE, or 0 otherwise. number $key->number The function key number for TYPE_FUNCTION, or 0 otherwise. sym $key->sym The key symbol number for TYPE_KEYSYM, or 0 otherwise. This can be passed to Term::TermKey->get_keyname(), or compared to a result earlier obtained from Term::TermKey->keyname2sym(). modifiers $key->modifiers The modifier bitmask. Can be compared against the KEYMOD_* constants. modifier_... $key->modifier_shift $key->modifier_alt $key->modifier_ctrl Shortcuts which return a boolean if the appropriate modifier is present. utf8 $key->utf8 A string representation of the given Unicode codepoint. If the underlying termkey library is in UTF-8 mode then this will be a UTF-8 string. If it is in raw mode, then this will be a single raw byte. mouseev button $key->mouseev $key->button The details of a mouse event for TYPE_MOUSE, or undef for other types of event. line col $key->line $key->col The details of a mouse or position event, or undef for other types of event. termkey $key->termkey Return the underlying Term::TermKey object this key was retrieved from. format $str = $key->format( $format ) Returns a string representation of the keypress event, identically to calling format_key on the underlying Term::TermKey object. EXPORTED CONSTANTS The following constant names are all derived from the underlying libtermkey library. For more detail see the documentation on the library. These constants are possible values of $key->type TYPE_UNICODE a Unicode codepoint TYPE_FUNCTION a numbered function key TYPE_KEYSYM a symbolic key TYPE_MOUSE a mouse movement or button press or release TYPE_POSITION a cursor position report TYPE_MODEREPORT an ANSI or DEC mode report TYPE_UNKNOWN_CSI an unrecognised CSI sequence These constants are result values from getkey(), getkey_force(), waitkey() or advisereadable() RES_NONE No key event is ready. RES_KEY A key event has been provided. RES_EOF No key events are ready and the terminal has been closed, so no more will arrive. RES_AGAIN No key event is ready yet, but a partial one has been found. This is only returned by getkey(). To obtain the partial result even if it never completes, call getkey_force(). RES_ERROR Returned by waitkey or advisereadable if an IO error occurs while trying to read another key event. These constants are key modifier masks for $key->modifiers KEYMOD_SHIFT KEYMOD_ALT KEYMOD_CTRL Should be obvious ;) These constants are types of mouse event which may be returned by $key->mouseev or interpret_mouse: MOUSE_UNKNOWN The type of mouse event was not recognised MOUSE_PRESS The event reports a mouse button being pressed MOUSE_DRAG The event reports the mouse being moved while a button is held down MOUSE_RELEASE The event reports the mouse buttons being released, or the mouse moved without a button held. These constants are flags for the constructor, Term::TermKey->new FLAG_NOINTERPRET Do not attempt to interpret C0 codes into keysyms (ie. Backspace, Tab, Enter, Escape). Instead report them as plain Ctrl-letter events. FLAG_CONVERTKP Convert xterm's alternate keypad symbols into the plain ASCII codes they would represent. FLAG_RAW Ignore locale settings; do not attempt to recombine UTF-8 sequences. Instead report only raw values. FLAG_UTF8 Ignore locale settings; force UTF-8 recombining on. FLAG_NOTERMIOS Even if the terminal file descriptor represents a TTY device, do not call the tcsetattr() termios function on it to set in canonical input mode. FLAG_SPACESYMBOL Sets the CANON_SPACESYMBOL canonicalisation flag. See below. FLAG_CTRLC Disable the SIGINT behaviour of the Ctrl-C key, allowing it to be read as a modified Unicode keypress. FLAG_EINTR Disable retry on signal interrupt; instead report it as an error with RES_ERROR and $! set to EINTR. Without this flag, IO operations will be retried if interrupted. These constants are canonicalisation flags for set_canonflags and get_canonflags CANON_SPACESYMBOL With this flag set, the Space key will appear as a TYPE_KEYSYM key event whose symname is "Space". Without this flag, it appears as a normal TYPE_UNICODE character. CANON_DELBS With this flag set, the ASCII DEL byte is interpreted as the "Backspace" keysym, rather than "DEL". This flag does not affect the interpretation of ASCII BS, which is always represented as "Backspace". These constants are flags to format_key FORMAT_LONGMOD Print full modifier names e.g. Shift- instead of abbreviating to S-. FORMAT_CARETCTRL If the only modifier is Ctrl on a plain character, render it as ^X. FORMAT_ALTISMETA Use the name Meta or the letter M instead of Alt or A. FORMAT_WRAPBRACKET If the key event is a special key instead of unmodified Unicode, wrap it in . FORMAT_MOUSE_POS If the event is a mouse event, also include the cursor position; rendered as @ ($col,$line) FORMAT_VIM Shortcut to FORMAT_ALTISMETA|FORMAT_WRAPBRACKET; which gives an output close to the format the vim editor uses. EXAMPLES A simple print-until-Ctrl-C loop This program just prints every keypress until the user presses Ctrl-C. use Term::TermKey qw( FLAG_UTF8 RES_EOF FORMAT_VIM ); my $tk = Term::TermKey->new(\*STDIN); # ensure perl and libtermkey agree on Unicode handling binmode( STDOUT, ":encoding(UTF-8)" ) if $tk->get_flags & FLAG_UTF8; while( ( my $ret = $tk->waitkey( my $key ) ) != RES_EOF ) { print "Got key: ".$tk->format_key( $key, FORMAT_VIM )."\n"; } Configuration of custom keypresses Because format_key() yields a plain string representation of a keypress it can be used as a hash key to look up a "handler" routine for the key. The following implements a simple line input program, though obviously lacking many features in a true line editor like readline. use Term::TermKey qw( FLAG_UTF8 RES_EOF FORMAT_LONGMOD ); my $tk = Term::TermKey->new(\*STDIN); # ensure perl and libtermkey agree on Unicode handling binmode( STDOUT, ":encoding(UTF-8)" ) if $tk->get_flags & FLAG_UTF8; my $line = ""; $| = 1; my %key_handlers = ( "Enter" => sub { print "\nThe line is: $line\n"; $line = ""; }, "Backspace" => sub { return unless length $line; substr( $line, -1, 1 ) = ""; print "\cH \cH"; # erase it }, # other handlers ... ); while( ( my $ret = $tk->waitkey( my $key ) ) != RES_EOF ) { my $handler = $key_handlers{ $tk->format_key( $key, FORMAT_LONGMOD ) }; if( $handler ) { $handler->( $key ); } elsif( $key->type_is_unicode and !$key->modifiers ) { my $char = $key->utf8; $line .= $char; print $char; } } Asynchronous operation Because the getkey() method performs no IO itself, it can be combined with the advisereadable() method in an asynchronous program. use IO::Select; use Term::TermKey qw( FLAG_UTF8 RES_KEY RES_AGAIN RES_EOF FORMAT_VIM ); my $select = IO::Select->new(); my $tk = Term::TermKey->new(\*STDIN); $select->add(\*STDIN); # ensure perl and libtermkey agree on Unicode handling binmode( STDOUT, ":encoding(UTF-8)" ) if $tk->get_flags & FLAG_UTF8; sub on_key { my ( $tk, $key ) = @_; print "You pressed " . $tk->format_key( $key, FORMAT_VIM ) . "\n"; } my $again = 0; while(1) { my $timeout = $again ? $tk->get_waittime/1000 : undef; my @ready = $select->can_read($timeout); if( !@ready ) { my $ret; while( ( $ret = $tk->getkey_force( my $key ) ) == RES_KEY ) { on_key( $tk, $key ); } } while( my $fh = shift @ready ) { if( $fh == \*STDIN ) { $tk->advisereadable; my $ret; while( ( $ret = $tk->getkey( my $key ) ) == RES_KEY ) { on_key( $tk, $key ); } $again = ( $ret == RES_AGAIN ); exit if $ret == RES_EOF; } # Deal with other filehandles here } } There may also be more appropriate modules on CPAN for particular event frameworks; see the SEE ALSO section below. SEE ALSO * http://www.leonerd.org.uk/code/libtermkey/ - libtermkey home page * Term::TermKey::Async - terminal key input using libtermkey with IO::Async * POE::Wheel::TermKey - terminal key input using libtermkey with POE * AnyEvent::TermKey - terminal key input using libtermkey with AnyEvent AUTHOR Paul Evans Term-TermKey-0.17/typemap000444001750001750 6313433351022 14141 0ustar00leoleo000000000000Term::TermKey T_PTROBJ Term::TermKey::Key T_PTROBJ Term-TermKey-0.17/examples000755001750001750 013433351022 14261 5ustar00leoleo000000000000Term-TermKey-0.17/examples/async.pl000444001750001750 211613433351022 16070 0ustar00leoleo000000000000#!/usr/bin/perl -w use strict; use warnings; use IO::Select; use Term::TermKey qw( FLAG_UTF8 RES_KEY RES_AGAIN RES_EOF FORMAT_VIM ); my $select = IO::Select->new(); my $tk = Term::TermKey->new(\*STDIN); $select->add(\*STDIN); # ensure perl and libtermkey agree on Unicode handling binmode( STDOUT, ":encoding(UTF-8)" ) if $tk->get_flags & FLAG_UTF8; sub on_key { my ( $tk, $key ) = @_; print "You pressed " . $tk->format_key( $key, FORMAT_VIM ) . "\n"; } my $again = 0; while(1) { my $timeout = $again ? $tk->get_waittime/1000 : undef; my @ready = $select->can_read($timeout); if( !@ready ) { my $ret; while( ( $ret = $tk->getkey_force( my $key ) ) == RES_KEY ) { on_key( $tk, $key ); } } while( my $fh = shift @ready ) { if( $fh == \*STDIN ) { $tk->advisereadable; my $ret; while( ( $ret = $tk->getkey( my $key ) ) == RES_KEY ) { on_key( $tk, $key ); } $again = ( $ret == RES_AGAIN ); exit if $ret == RES_EOF; } # Deal with other filehandles here } } Term-TermKey-0.17/examples/lineeditor.pl000444001750001750 156113433351022 17114 0ustar00leoleo000000000000#!/usr/bin/perl -w use strict; use warnings; use Term::TermKey qw( FLAG_UTF8 RES_EOF FORMAT_LONGMOD ); my $tk = Term::TermKey->new(\*STDIN); # ensure perl and libtermkey agree on Unicode handling binmode( STDOUT, ":encoding(UTF-8)" ) if $tk->get_flags & FLAG_UTF8; my $line = ""; $| = 1; my %key_handlers = ( "Enter" => sub { print "\nThe line is: $line\n"; $line = ""; }, "Backspace" => sub { return unless length $line; substr( $line, -1, 1 ) = ""; print "\cH \cH"; # erase it }, # other handlers ... ); while( ( my $ret = $tk->waitkey( my $key ) ) != RES_EOF ) { my $handler = $key_handlers{ $tk->format_key( $key, FORMAT_LONGMOD ) }; if( $handler ) { $handler->( $key ); } elsif( $key->type_is_unicode and !$key->modifiers ) { my $char = $key->utf8; $line .= $char; print $char; } } Term-TermKey-0.17/examples/parse-inputrc.pl000444001750001750 232313433351022 17547 0ustar00leoleo000000000000#!/usr/bin/perl use strict; use warnings; use feature qw( say switch ); use Term::TermKey; my $tk = Term::TermKey->new( undef ); my $path = shift @ARGV || "/etc/inputrc"; open my $rc, "<", $path or die "Cannot read $path - $!"; my @ifs; while( <$rc> ) { chomp; given($_) { when( m/^#/ or m/^\s*$/ ) { # comment or blank say $_ } when( m/^\$if ([^=]+)=(.*)$/ ) { print " " x @ifs; say "\$if $1=$2"; push @ifs, "$1=$2"; } when( m/^\$endif$/ ) { pop @ifs; print " " x @ifs; say "\$endif"; } when( m/^set (\S+)\s+(.*)$/ ) { print " " x @ifs; say "set $1 $2"; } when( m/"(.*)": (.*)$/ ) { my ( $bytes, $binding ) = ( $1, $2 ); # TODO: This probably needs a lot more work $bytes =~ s/\\e/\e/g; $bytes =~ s{\\C-(.)}{chr( 0x1f & ord $1)}eg; print " " x @ifs; $tk->push_bytes( $bytes ); while( $tk->getkey( my $key ) ) { print $tk->format_key( $key, Term::TermKey::FORMAT_VIM ); } say ": $binding"; } default { die "Not sure how to parse line $_\n"; } } } Term-TermKey-0.17/examples/simple.pl000444001750001750 203413433351022 16243 0ustar00leoleo000000000000#!/usr/bin/perl -w use strict; use warnings; use Getopt::Long; use Term::TermKey qw( FLAG_UTF8 RES_EOF FORMAT_VIM FORMAT_MOUSE_POS ); my $mouse; GetOptions( 'm|mouse=i' => \$mouse ) or exit(1); $|++; if( $mouse ) { print "\e[?${mouse}h"; } $SIG{WINCH} = sub { print "Window resize\n" }; my $tk = Term::TermKey->new(\*STDIN); # ensure perl and libtermkey agree on Unicode handling binmode( STDOUT, ":encoding(UTF-8)" ) if $tk->get_flags & FLAG_UTF8; while( ( my $ret = $tk->waitkey( my $key ) ) != RES_EOF ) { if( $key->type_is_mouse ) { printf "Got mouse: %s(%d) at (%d,%d)\n", [qw( * press drag release )]->[$key->mouseev], $key->button, $key->line, $key->col; } elsif( $key->type_is_position ) { printf "Got position report: at (%d,%d)\n", $key->line, $key->col; } else { print "Got key: ".$tk->format_key( $key, FORMAT_VIM )."\n"; if( $key->type_is_unicode && !$key->modifiers && $key->utf8 eq "?" ) { print "\e[6n"; } } } if( $mouse ) { print "\e[?${mouse}l"; } Term-TermKey-0.17/lib000755001750001750 013433351022 13211 5ustar00leoleo000000000000Term-TermKey-0.17/lib/Term000755001750001750 013433351022 14120 5ustar00leoleo000000000000Term-TermKey-0.17/lib/Term/TermKey.pm000444001750001750 5235213433351022 16222 0ustar00leoleo000000000000# You may distribute under the terms of either the GNU General Public License # or the Artistic License (the same terms as Perl itself) # # (C) Paul Evans, 2009-2019 -- leonerd@leonerd.org.uk package Term::TermKey; use strict; use warnings; our $VERSION = '0.17'; use Exporter 'import'; require XSLoader; XSLoader::load( __PACKAGE__, $VERSION ); =head1 NAME C - perl wrapper around C =head1 SYNOPSIS use Term::TermKey; my $tk = Term::TermKey->new( \*STDIN ); print "Press any key\n"; $tk->waitkey( my $key ); print "You pressed: " . $tk->format_key( $key, 0 ); =head1 DESCRIPTION =over 4 B that C itself is deprecated in favour of its eventual merge into C. As a result, uses of this module should also be considered deprecated. Consider rewriting code to use L instead; either by creating a L to receive key input events, or perform a more wholescale rewrite into using C generally for all screen interaction purposes. =back This module provides a light perl wrapper around the C library. This library attempts to provide an abstract way to read keypress events in terminal-based programs by providing structures that describe keys, rather than simply returning raw bytes as read from the TTY device. This version of C requires C version at least 0.16. =head2 Multi-byte keys, ambiguous keys, and waittime Some keypresses generate multiple bytes from the terminal. There is also the ambiguity between multi-byte CSI or SS3 sequences, and the Escape key itself. The waittime timer is used to distinguish them. When some bytes arrive that could be the start of possibly multiple different keypress events, the library will attempt to wait for more bytes to arrive that would finish it. If no more bytes arrive after this time, then the bytes will be reported as events as they stand, even if this results in interpreting a partially-complete Escape sequence as a literal Escape key followed by some normal letters or other symbols. Similarly, if the start of an incomplete UTF-8 sequence arrives when the library is in UTF-8 mode, this will be reported as the UTF-8 replacement character (U+FFFD) if it is incomplete after this time. =cut =head1 CONSTRUCTOR =cut =head2 new $tk = Term::TermKey->new( $fh, $flags ) Construct a new C object that wraps the given term handle. C<$fh> should be either an IO handle reference, an integer referring to a plain POSIX file descriptor, of C. C<$flags> is optional, but if given should contain the flags to pass to C's constructor. Assumes a default of 0 if not supplied. See the C constants. =head2 new_abstract $tk = Term::TermKey->new_abstract( $termtype, $flags ) Construct a new abstract C object not associated with a filehandle. Input may be fed to it using the C method rather than C or C. The name of the termtype should be given in the C<$termtype> string. =cut =head1 METHODS =cut # The following documents the various XS-implemented methods in TermKey.xs in # the same order =head2 start =head2 stop $success = $tk->start $success = $tk->stop Start or stop IO interactions from the instance. Starting will send the terminal initialisation sequence and set up C settings, stopping will send the terminal shutdown sequence and restore C back to the initial values. After construction, a C instance is already started, but these methods may be used to suspend and resume, for example, on receipt of a C signal requesting that the application background itself. Returns false if it fails; C<$!> will contain an error code. =head2 is_started $started = $tk->is_started Returns true if the instance has been started, or false if it is stopped. =head2 get_flags =head2 set_flags $flags = $tk->get_flags $tk->set_flags( $newflags ) Accessor and mutator for the flags. One of the C or C flags will be set, even if neither was present in the constructor, as in this case the library will attempt to detect if the current locale is UTF-8 aware or not. =cut =head2 get_canonflags =head2 set_canonflags $canonflags = $tk->get_canonflags $tk->set_canonflags( $newcanonflags ) Accessor and mutator for the canonicalisation flags. =cut =head2 get_waittime =head2 set_waittime $msec = $tk->get_waittime $tk->set_waittime( $msec ) Accessor and mutator for the maximum wait time in miliseconds. The underlying C library will have specified a default value when the object was constructed. =cut =head2 get_buffer_remaining $bytes = $tk->get_buffer_remaining Accessor returning the number of bytes of buffer space remaining in the buffer; the space in which C can write. =head2 get_buffer_size =head2 set_buffer_size $bytes = $tk->get_buffer_size $tk->set_buffer_size( $size ) Accessor and mutator to for the total buffer size to store pending bytes. If the underlying C call fails, the C method will throw an exception. =cut =head2 getkey $res = $tk->getkey( $key ) Attempt to retrieve a single keypress event from the buffer, and put it in C<$key>. If successful, will return C to indicate that the C<$key> structure now contains a new keypress event. If C<$key> is an undefined lvalue (such as a new scalar variable) it will be initialised to contain a new key structure. If nothing is in the buffer it will return C. If the buffer contains a partial keypress event which does not yet contain all the bytes required, it will return C (see above section about multibyte events). If no events are ready and the input stream is now closed, will return C. This method will not block, nor will it perform any IO on the underlying file descriptor. For a normal blocking read, see C. =cut =head2 getkey_force $res = $tk->getkey_force( $key ) Similar to C, but will not return C if a partial match was found. Instead, it will force an interpretation of the bytes, even if this means interpreting the start of an C<< >>-prefixed multibyte sequence as a literal C key followed by normal letters. If C<$key> is an undefined lvalue (such as a new scalar variable) it will be initialised to contain a new key structure. This method will not block, nor will it perform any IO on the underlying file descriptor. For a normal blocking read, see C. =cut =head2 waitkey $res = $tk->waitkey( $key ) Attempt to retrieve a single keypress event from the buffer, or block until one is available. If successful, will return C to indicate that the C<$key> structure now contains a new keypress event. If an IO error occurs it will return C, and if the input stream is now closed it will return C. If C<$key> is an undefined lvalue (such as a new scalar variable) it will be initialised to contain a new key structure. =cut =head2 advisereadable $res = $tk->advisereadable Inform the underlying library that new input may be available on the underlying file descriptor and so it should call C to obtain it. Will return C if it read at least one more byte, C if no more input was found, or C if an IO error occurs. Normally this method would only be used in programs that want to use C asynchronously; see the EXAMPLES section. This method gracefully handles an C error from the underlying C syscall. =cut =head2 push_bytes $len = $tk->push_bytes( $bytes ) Feed more bytes into the input buffer. This is primarily useful for feeding input into filehandle-less instances, constructed by passing C or C<-1> as the filehandle to the constructor. After calling this method, these bytes will be available to read as keypresses by the C method. =cut =head2 get_keyname $str = $tk->get_keyname( $sym ) Returns the name of a key sym, such as returned by C<< Term::TermKey::Key->sym() >>. =cut =head2 keyname2sym $sym = $tk->keyname2sym( $keyname ) Look up the sym for a named key. The result of this method call can be compared directly against the value returned by C<< Term::TermKey::Key->sym() >>. Because this method has to perform a linear search of key names, it is best called rarely, perhaps during program initialisation, and the result stored for easier comparisons during runtime. =cut =head2 interpret_unknown_csi ( $cmd, @args ) = $tk->interpret_unknown_csi( $key ) If C<$key> contains an unknown CSI event then its command and arguments are returned in a list. C<$cmd> will be a string of 1 to 3 characters long, containing the initial and intermediate characters if present, followed by the main command character. C<@args> will contain the numerical arguments, where missing arguments are replaced by -1. If C<$key> does not contain an unknown CSI event then an empty list is returned. Note that this method needs to be called immediately after C or C, or at least, before calling either of those methods again. The actual CSI sequence is retained in the F buffer, and only retrieved by this method call. Calling C or C again may overwrite that buffer. =cut =head2 format_key $str = $tk->format_key( $key, $format ) Return a string representation of the keypress event in C<$key>, following the flags given. See the descriptions of the flags, below, for more detail. This may be useful for matching keypress events against keybindings stored in a hash. See EXAMPLES section for more detail. =cut =head2 parse_key $key = $tk->parse_key( $str, $format ) Return a keypress event by parsing the string representation in C<$str>, following the flags given. This method is an inverse of C. This may be useful for parsing entries from a configuration file or similar. =cut =head2 parse_key_at_pos $key = $tk->parse_key_at_pos( $str, $format ) Return a keypress event by parsing the string representation in a region of C<$str>, following the flags given. Where C will start at the beginning of the string and requires the entire input to be consumed, this method will start at the current C position in C<$str> (or at the beginning of the string if none is yet set), and after a successful parse, will update it to the end of the matched section. This position does not have to be at the end of the string. C<$str> must therefore be a real scalar variable, and not a string literal. This may be useful for incremental parsing of configuration or other data, out of a larger string. =cut =head2 keycmp $cmp = $tk->keycmp( $key1, $key2 ) Compares the two given keypress events, returning a number less than, equal to, or greater than zero, depending on the ordering. Keys are ordered first by type (unicode, keysym, function, mouse), then by value within that type, then finally by modifier bits. This may be useful in C expressions: my @sorted_keys = sort { $tk->keycmp( $a, $b ) } @keys; =cut =head1 KEY OBJECTS The C subclass is used to store a single keypress event. Objects in this class cannot be changed by perl code. C, C or C will overwrite the contents of the structure with a new value. Keys cannot be constructed, but C, C or C will place a new key structure in the C<$key> variable if it is undefined when they are called. C and C will return new keys. =head2 type $key->type The type of event. One of C, C, C, C, C, C, C. =head2 type_is_... $key->type_is_unicode $key->type_is_function $key->type_is_keysym $key->type_is_mouse $key->type_is_position $key->type_is_modereport $key->type_is_unknown_csi Shortcuts which return a boolean. =head2 codepoint $key->codepoint The Unicode codepoint number for C, or 0 otherwise. =head2 number $key->number The function key number for C, or 0 otherwise. =head2 sym $key->sym The key symbol number for C, or 0 otherwise. This can be passed to C<< Term::TermKey->get_keyname() >>, or compared to a result earlier obtained from C<< Term::TermKey->keyname2sym() >>. =head2 modifiers $key->modifiers The modifier bitmask. Can be compared against the C constants. =head2 modifier_... $key->modifier_shift $key->modifier_alt $key->modifier_ctrl Shortcuts which return a boolean if the appropriate modifier is present. =head2 utf8 $key->utf8 A string representation of the given Unicode codepoint. If the underlying C library is in UTF-8 mode then this will be a UTF-8 string. If it is in raw mode, then this will be a single raw byte. =head2 mouseev =head2 button $key->mouseev $key->button The details of a mouse event for C, or C for other types of event. =head2 line =head2 col $key->line $key->col The details of a mouse or position event, or C for other types of event. =head2 termkey $key->termkey Return the underlying C object this key was retrieved from. =head2 format $str = $key->format( $format ) Returns a string representation of the keypress event, identically to calling C on the underlying C object. =cut sub Term::TermKey::Key::format { my $self = shift; return $self->termkey->format_key( $self, @_ ); } =head1 EXPORTED CONSTANTS The following constant names are all derived from the underlying C library. For more detail see the documentation on the library. These constants are possible values of C<< $key->type >> =over 4 =item C a Unicode codepoint =item C a numbered function key =item C a symbolic key =item C a mouse movement or button press or release =item C a cursor position report =item C an ANSI or DEC mode report =item C an unrecognised CSI sequence =back These constants are result values from C, C, C or C =over 4 =item C No key event is ready. =item C A key event has been provided. =item C No key events are ready and the terminal has been closed, so no more will arrive. =item C No key event is ready yet, but a partial one has been found. This is only returned by C. To obtain the partial result even if it never completes, call C. =item C Returned by C or C if an IO error occurs while trying to read another key event. =back These constants are key modifier masks for C<< $key->modifiers >> =over 4 =item C =item C =item C Should be obvious ;) =back These constants are types of mouse event which may be returned by C<< $key->mouseev >> or C: =over 4 =item C The type of mouse event was not recognised =item C The event reports a mouse button being pressed =item C The event reports the mouse being moved while a button is held down =item C The event reports the mouse buttons being released, or the mouse moved without a button held. =back These constants are flags for the constructor, C<< Term::TermKey->new >> =over 4 =item C Do not attempt to interpret C0 codes into keysyms (ie. C, C, C, C). Instead report them as plain C events. =item C Convert xterm's alternate keypad symbols into the plain ASCII codes they would represent. =item C Ignore locale settings; do not attempt to recombine UTF-8 sequences. Instead report only raw values. =item C Ignore locale settings; force UTF-8 recombining on. =item C Even if the terminal file descriptor represents a TTY device, do not call the C C function on it to set in canonical input mode. =item C Sets the C canonicalisation flag. See below. =item C Disable the C behaviour of the C key, allowing it to be read as a modified Unicode keypress. =item C Disable retry on signal interrupt; instead report it as an error with C and C<$!> set to C. Without this flag, IO operations will be retried if interrupted. =back These constants are canonicalisation flags for C and C =over 4 =item C With this flag set, the Space key will appear as a C key event whose symname is C<"Space">. Without this flag, it appears as a normal C character. =item C With this flag set, the ASCII C byte is interpreted as the C<"Backspace"> keysym, rather than C<"DEL">. This flag does not affect the interpretation of ASCII C, which is always represented as C<"Backspace">. =back These constants are flags to C =over 4 =item C Print full modifier names e.g. C instead of abbreviating to C. =item C If the only modifier is C on a plain character, render it as C<^X>. =item C Use the name C or the letter C instead of C or C. =item C If the key event is a special key instead of unmodified Unicode, wrap it in C<< >>. =item C If the event is a mouse event, also include the cursor position; rendered as C<@ ($col,$line)> =item C Shortcut to C; which gives an output close to the format the F editor uses. =back =cut =head1 EXAMPLES =head2 A simple print-until-C loop This program just prints every keypress until the user presses C. use Term::TermKey qw( FLAG_UTF8 RES_EOF FORMAT_VIM ); my $tk = Term::TermKey->new(\*STDIN); # ensure perl and libtermkey agree on Unicode handling binmode( STDOUT, ":encoding(UTF-8)" ) if $tk->get_flags & FLAG_UTF8; while( ( my $ret = $tk->waitkey( my $key ) ) != RES_EOF ) { print "Got key: ".$tk->format_key( $key, FORMAT_VIM )."\n"; } =head2 Configuration of custom keypresses Because C yields a plain string representation of a keypress it can be used as a hash key to look up a "handler" routine for the key. The following implements a simple line input program, though obviously lacking many features in a true line editor like F. use Term::TermKey qw( FLAG_UTF8 RES_EOF FORMAT_LONGMOD ); my $tk = Term::TermKey->new(\*STDIN); # ensure perl and libtermkey agree on Unicode handling binmode( STDOUT, ":encoding(UTF-8)" ) if $tk->get_flags & FLAG_UTF8; my $line = ""; $| = 1; my %key_handlers = ( "Enter" => sub { print "\nThe line is: $line\n"; $line = ""; }, "Backspace" => sub { return unless length $line; substr( $line, -1, 1 ) = ""; print "\cH \cH"; # erase it }, # other handlers ... ); while( ( my $ret = $tk->waitkey( my $key ) ) != RES_EOF ) { my $handler = $key_handlers{ $tk->format_key( $key, FORMAT_LONGMOD ) }; if( $handler ) { $handler->( $key ); } elsif( $key->type_is_unicode and !$key->modifiers ) { my $char = $key->utf8; $line .= $char; print $char; } } =head2 Asynchronous operation Because the C method performs no IO itself, it can be combined with the C method in an asynchronous program. use IO::Select; use Term::TermKey qw( FLAG_UTF8 RES_KEY RES_AGAIN RES_EOF FORMAT_VIM ); my $select = IO::Select->new(); my $tk = Term::TermKey->new(\*STDIN); $select->add(\*STDIN); # ensure perl and libtermkey agree on Unicode handling binmode( STDOUT, ":encoding(UTF-8)" ) if $tk->get_flags & FLAG_UTF8; sub on_key { my ( $tk, $key ) = @_; print "You pressed " . $tk->format_key( $key, FORMAT_VIM ) . "\n"; } my $again = 0; while(1) { my $timeout = $again ? $tk->get_waittime/1000 : undef; my @ready = $select->can_read($timeout); if( !@ready ) { my $ret; while( ( $ret = $tk->getkey_force( my $key ) ) == RES_KEY ) { on_key( $tk, $key ); } } while( my $fh = shift @ready ) { if( $fh == \*STDIN ) { $tk->advisereadable; my $ret; while( ( $ret = $tk->getkey( my $key ) ) == RES_KEY ) { on_key( $tk, $key ); } $again = ( $ret == RES_AGAIN ); exit if $ret == RES_EOF; } # Deal with other filehandles here } } There may also be more appropriate modules on CPAN for particular event frameworks; see the C section below. =cut =head1 SEE ALSO =over 4 =item * L - C home page =item * L - terminal key input using C with L =item * L - terminal key input using C with L =item * L - terminal key input using C with L =back =head1 AUTHOR Paul Evans =cut 0x55AA; Term-TermKey-0.17/lib/Term/TermKey.xs000444001750001750 3721513433351022 16241 0ustar00leoleo000000000000/* You may distribute under the terms of either the GNU General Public License * or the Artistic License (the same terms as Perl itself) * * (C) Paul Evans, 2009-2012 -- leonerd@leonerd.org.uk */ #include "EXTERN.h" #include "perl.h" #include "XSUB.h" #include /* Because of Perl's safe signal handling, we have to always enable the * TERMKEY_FLAG_EINTR flag, and implement retry logic ourselves in the * wrappings of termkey_waitkey and termkey_advisereadable */ /* We can reuse the preinterpret fields in this structure, knowing that * they'll never be used for more than one type at once */ #define FIELD_BUTTON 0 #define FIELD_INITIAL 0 #define FIELD_LINE 1 #define FIELD_MODE 1 #define FIELD_COL 2 #define FIELD_VALUE 2 typedef struct key_extended { TermKeyKey k; SV *termkey; TermKeyMouseEvent mouseev; int fields[3]; } *Term__TermKey__Key; typedef struct termkey_with_fh { TermKey *tk; SV *fh; int flag_eintr; } *Term__TermKey; static void setup_constants(void) { HV *stash; AV *export; stash = gv_stashpvn("Term::TermKey", 13, TRUE); export = get_av("Term::TermKey::EXPORT", TRUE); #define DO_CONSTANT(c) \ newCONSTSUB(stash, #c+8, newSViv(c)); \ av_push(export, newSVpv(#c+8, 0)); DO_CONSTANT(TERMKEY_TYPE_UNICODE) DO_CONSTANT(TERMKEY_TYPE_FUNCTION) DO_CONSTANT(TERMKEY_TYPE_KEYSYM) DO_CONSTANT(TERMKEY_TYPE_MOUSE) DO_CONSTANT(TERMKEY_TYPE_POSITION) DO_CONSTANT(TERMKEY_TYPE_MODEREPORT) DO_CONSTANT(TERMKEY_TYPE_UNKNOWN_CSI) DO_CONSTANT(TERMKEY_RES_NONE) DO_CONSTANT(TERMKEY_RES_KEY) DO_CONSTANT(TERMKEY_RES_EOF) DO_CONSTANT(TERMKEY_RES_AGAIN) DO_CONSTANT(TERMKEY_RES_ERROR) DO_CONSTANT(TERMKEY_KEYMOD_SHIFT) DO_CONSTANT(TERMKEY_KEYMOD_ALT) DO_CONSTANT(TERMKEY_KEYMOD_CTRL) DO_CONSTANT(TERMKEY_MOUSE_UNKNOWN) DO_CONSTANT(TERMKEY_MOUSE_PRESS) DO_CONSTANT(TERMKEY_MOUSE_DRAG) DO_CONSTANT(TERMKEY_MOUSE_RELEASE) DO_CONSTANT(TERMKEY_FLAG_NOINTERPRET) DO_CONSTANT(TERMKEY_FLAG_CONVERTKP) DO_CONSTANT(TERMKEY_FLAG_RAW) DO_CONSTANT(TERMKEY_FLAG_UTF8) DO_CONSTANT(TERMKEY_FLAG_NOTERMIOS) DO_CONSTANT(TERMKEY_FLAG_SPACESYMBOL) DO_CONSTANT(TERMKEY_FLAG_CTRLC) DO_CONSTANT(TERMKEY_FLAG_EINTR) DO_CONSTANT(TERMKEY_CANON_SPACESYMBOL) DO_CONSTANT(TERMKEY_CANON_DELBS) DO_CONSTANT(TERMKEY_FORMAT_LONGMOD) DO_CONSTANT(TERMKEY_FORMAT_CARETCTRL) DO_CONSTANT(TERMKEY_FORMAT_ALTISMETA) DO_CONSTANT(TERMKEY_FORMAT_WRAPBRACKET) DO_CONSTANT(TERMKEY_FORMAT_MOUSE_POS) DO_CONSTANT(TERMKEY_FORMAT_VIM) } static struct key_extended *get_keystruct_or_new(SV *sv, const char *funcname, SV *termkey) { struct key_extended *key; if(sv && !SvOK(sv)) { Newx(key, 1, struct key_extended); sv_setref_pv(sv, "Term::TermKey::Key", (void*)key); key->termkey = NULL; } else if(sv_derived_from(sv, "Term::TermKey::Key")) { IV tmp = SvIV((SV*)SvRV(sv)); key = INT2PTR(struct key_extended *, tmp); } else Perl_croak(aTHX_ "%s: %s is not of type %s", funcname, "key", "Term::TermKey::Key"); if(!key->termkey || SvRV(key->termkey) != SvRV(termkey)) { if(key->termkey) SvREFCNT_dec(key->termkey); key->termkey = newRV_inc(SvRV(termkey)); } return key; } static void preinterpret_key(Term__TermKey__Key key, TermKey *tk) { if(key->k.type == TERMKEY_TYPE_MOUSE) termkey_interpret_mouse(tk, &key->k, &key->mouseev, &key->fields[FIELD_BUTTON], &key->fields[FIELD_LINE], &key->fields[FIELD_COL]); else if(key->k.type == TERMKEY_TYPE_POSITION) termkey_interpret_position(tk, &key->k, &key->fields[FIELD_LINE], &key->fields[FIELD_COL]); else if(key->k.type == TERMKEY_TYPE_MODEREPORT) termkey_interpret_modereport(tk, &key->k, &key->fields[FIELD_INITIAL], &key->fields[FIELD_MODE], &key->fields[FIELD_VALUE]); } MODULE = Term::TermKey::Key PACKAGE = Term::TermKey::Key PREFIX = key_ void DESTROY(self) Term::TermKey::Key self CODE: SvREFCNT_dec(self->termkey); Safefree(self); int type(self) Term::TermKey::Key self CODE: RETVAL = self->k.type; OUTPUT: RETVAL bool type_is_unicode(self) Term::TermKey::Key self CODE: RETVAL = self->k.type == TERMKEY_TYPE_UNICODE; OUTPUT: RETVAL bool type_is_function(self) Term::TermKey::Key self CODE: RETVAL = self->k.type == TERMKEY_TYPE_FUNCTION; OUTPUT: RETVAL bool type_is_keysym(self) Term::TermKey::Key self CODE: RETVAL = self->k.type == TERMKEY_TYPE_KEYSYM; OUTPUT: RETVAL bool type_is_mouse(self) Term::TermKey::Key self CODE: RETVAL = self->k.type == TERMKEY_TYPE_MOUSE; OUTPUT: RETVAL bool type_is_position(self) Term::TermKey::Key self CODE: RETVAL = self->k.type == TERMKEY_TYPE_POSITION; OUTPUT: RETVAL bool type_is_modereport(self) Term::TermKey::Key self CODE: RETVAL = self->k.type == TERMKEY_TYPE_MODEREPORT; OUTPUT: RETVAL bool type_is_unknown_csi(self) Term::TermKey::Key self CODE: RETVAL = self->k.type == TERMKEY_TYPE_UNKNOWN_CSI; OUTPUT: RETVAL int codepoint(self) Term::TermKey::Key self CODE: RETVAL = self->k.type == TERMKEY_TYPE_UNICODE ? self->k.code.codepoint : 0; OUTPUT: RETVAL int number(self) Term::TermKey::Key self CODE: RETVAL = self->k.type == TERMKEY_TYPE_FUNCTION ? self->k.code.number : 0; OUTPUT: RETVAL int sym(self) Term::TermKey::Key self CODE: RETVAL = self->k.type == TERMKEY_TYPE_KEYSYM ? self->k.code.sym : TERMKEY_SYM_NONE; OUTPUT: RETVAL int modifiers(self) Term::TermKey::Key self CODE: RETVAL = self->k.modifiers; OUTPUT: RETVAL bool modifier_shift(self) Term::TermKey::Key self CODE: RETVAL = self->k.modifiers & TERMKEY_KEYMOD_SHIFT; OUTPUT: RETVAL bool modifier_alt(self) Term::TermKey::Key self CODE: RETVAL = self->k.modifiers & TERMKEY_KEYMOD_ALT; OUTPUT: RETVAL bool modifier_ctrl(self) Term::TermKey::Key self CODE: RETVAL = self->k.modifiers & TERMKEY_KEYMOD_CTRL; OUTPUT: RETVAL SV * termkey(self) Term::TermKey::Key self CODE: RETVAL = newRV_inc(SvRV(self->termkey)); OUTPUT: RETVAL SV * utf8(self) Term::TermKey::Key self CODE: if(self->k.type == TERMKEY_TYPE_UNICODE) { IV tmp; TermKey *termkey; RETVAL = newSVpv(self->k.utf8, 0); tmp = SvIV((SV*)SvRV(self->termkey)); termkey = (INT2PTR(Term__TermKey, tmp))->tk; if(termkey_get_flags(termkey) & TERMKEY_FLAG_UTF8) SvUTF8_on(RETVAL); } else RETVAL = &PL_sv_undef; OUTPUT: RETVAL SV * mouseev(self) Term::TermKey::Key self CODE: if(self->k.type == TERMKEY_TYPE_MOUSE) RETVAL = newSViv(self->mouseev); else RETVAL = &PL_sv_undef; OUTPUT: RETVAL SV * button(self) Term::TermKey::Key self CODE: if(self->k.type == TERMKEY_TYPE_MOUSE) RETVAL = newSViv(self->fields[FIELD_BUTTON]); else RETVAL = &PL_sv_undef; OUTPUT: RETVAL SV * line(self) Term::TermKey::Key self CODE: if(self->k.type == TERMKEY_TYPE_MOUSE || self->k.type == TERMKEY_TYPE_POSITION) RETVAL = newSViv(self->fields[FIELD_LINE]); else RETVAL = &PL_sv_undef; OUTPUT: RETVAL SV * col(self) Term::TermKey::Key self CODE: if(self->k.type == TERMKEY_TYPE_MOUSE || self->k.type == TERMKEY_TYPE_POSITION) RETVAL = newSViv(self->fields[FIELD_COL]); else RETVAL = &PL_sv_undef; OUTPUT: RETVAL SV * initial(self) Term::TermKey::Key self CODE: if(self->k.type == TERMKEY_TYPE_MODEREPORT) { char str[2] = { self->fields[FIELD_INITIAL], 0 }; RETVAL = newSVpv(str, 0); } else RETVAL = &PL_sv_undef; OUTPUT: RETVAL SV * mode(self) Term::TermKey::Key self CODE: if(self->k.type == TERMKEY_TYPE_MODEREPORT) RETVAL = newSViv(self->fields[FIELD_MODE]); else RETVAL = &PL_sv_undef; OUTPUT: RETVAL SV * value(self) Term::TermKey::Key self CODE: if(self->k.type == TERMKEY_TYPE_MODEREPORT) RETVAL = newSViv(self->fields[FIELD_VALUE]); else RETVAL = &PL_sv_undef; OUTPUT: RETVAL MODULE = Term::TermKey PACKAGE = Term::TermKey PREFIX = termkey_ BOOT: TERMKEY_CHECK_VERSION; setup_constants(); Term::TermKey new(package, fh, flags=0) SV *fh int flags INIT: int fd; CODE: Newx(RETVAL, 1, struct termkey_with_fh); if(!SvOK(fh)) { fd = -1; RETVAL->fh = NULL; } else if(SvROK(fh)) { fd = PerlIO_fileno(IoIFP(sv_2io(fh))); RETVAL->fh = SvREFCNT_inc(SvRV(fh)); } else { fd = SvIV(fh); RETVAL->fh = NULL; } RETVAL->tk = termkey_new(fd, flags | TERMKEY_FLAG_EINTR); RETVAL->flag_eintr = flags & TERMKEY_FLAG_EINTR; OUTPUT: RETVAL Term::TermKey new_abstract(package, termtype, flags=0) char *termtype int flags CODE: Newx(RETVAL, 1, struct termkey_with_fh); RETVAL->tk = termkey_new_abstract(termtype, flags | TERMKEY_FLAG_EINTR); RETVAL->flag_eintr = flags & TERMKEY_FLAG_EINTR; RETVAL->fh = NULL; OUTPUT: RETVAL void DESTROY(self) Term::TermKey self CODE: termkey_destroy(self->tk); if(self->fh) SvREFCNT_dec(self->fh); Safefree(self); OUTPUT: int start(self) Term::TermKey self CODE: RETVAL = termkey_start(self->tk); OUTPUT: RETVAL int stop(self) Term::TermKey self CODE: RETVAL = termkey_stop(self->tk); OUTPUT: RETVAL int is_started(self) Term::TermKey self CODE: RETVAL = termkey_is_started(self->tk); OUTPUT: RETVAL int get_flags(self) Term::TermKey self CODE: /* Still need to read flags out of underlying termkey instance to get * flags it might modify - UTF-8 or RAW */ RETVAL = self->flag_eintr | (termkey_get_flags(self->tk) & ~TERMKEY_FLAG_EINTR); OUTPUT: RETVAL void set_flags(self, newflags) Term::TermKey self int newflags CODE: self->flag_eintr = newflags & TERMKEY_FLAG_EINTR; termkey_set_flags(self->tk, newflags | TERMKEY_FLAG_EINTR); OUTPUT: int get_canonflags(self) Term::TermKey self CODE: RETVAL = termkey_get_canonflags(self->tk); OUTPUT: RETVAL void set_canonflags(self, newcanonflags) Term::TermKey self int newcanonflags CODE: termkey_set_canonflags(self->tk, newcanonflags); OUTPUT: int get_waittime(self) Term::TermKey self CODE: RETVAL = termkey_get_waittime(self->tk); OUTPUT: RETVAL void set_waittime(self, msec) Term::TermKey self int msec CODE: termkey_set_waittime(self->tk, msec); OUTPUT: size_t get_buffer_remaining(self) Term::TermKey self CODE: RETVAL = termkey_get_buffer_remaining(self->tk); OUTPUT: RETVAL size_t get_buffer_size(self) Term::TermKey self CODE: RETVAL = termkey_get_buffer_size(self->tk); OUTPUT: RETVAL void set_buffer_size(self, size) Term::TermKey self size_t size CODE: if(!termkey_set_buffer_size(self->tk, size)) croak("termkey_set_buffer_size(): ", strerror(errno)); int getkey(self, key) Term::TermKey self Term::TermKey::Key key = NO_INIT PREINIT: TermKeyResult res; PPCODE: key = get_keystruct_or_new(ST(1), "Term::TermKey::getkey", ST(0)); res = termkey_getkey(self->tk, &key->k); if(res == TERMKEY_RES_KEY) preinterpret_key(key, self->tk); mPUSHi(res); XSRETURN(1); int getkey_force(self, key) Term::TermKey self Term::TermKey::Key key = NO_INIT PREINIT: TermKeyResult res; PPCODE: key = get_keystruct_or_new(ST(1), "Termk::TermKey::getkey_force", ST(0)); res = termkey_getkey_force(self->tk, &key->k); if(res == TERMKEY_RES_KEY) preinterpret_key(key, self->tk); mPUSHi(res); XSRETURN(1); void waitkey(self, key) Term::TermKey self Term::TermKey::Key key = NO_INIT PREINIT: TermKeyResult res; PPCODE: key = get_keystruct_or_new(ST(1), "Term::TermKey::waitkey", ST(0)); while(1) { res = termkey_waitkey(self->tk, &key->k); if(res != TERMKEY_RES_ERROR) break; if(errno != EINTR || self->flag_eintr) break; PERL_ASYNC_CHECK(); } if(res == TERMKEY_RES_KEY) preinterpret_key(key, self->tk); mPUSHi(res); XSRETURN(1); int advisereadable(self) Term::TermKey self CODE: while(1) { RETVAL = termkey_advisereadable(self->tk); if(RETVAL != TERMKEY_RES_ERROR) break; if(errno != EINTR || self->flag_eintr) break; PERL_ASYNC_CHECK(); } OUTPUT: RETVAL size_t push_bytes(self, bytes) Term::TermKey self SV *bytes CODE: RETVAL = termkey_push_bytes(self->tk, SvPV_nolen(bytes), SvCUR(bytes)); OUTPUT: RETVAL const char * get_keyname(self, sym) Term::TermKey self int sym CODE: RETVAL = termkey_get_keyname(self->tk, sym); OUTPUT: RETVAL int keyname2sym(self, keyname) Term::TermKey self const char *keyname CODE: RETVAL = termkey_keyname2sym(self->tk, keyname); OUTPUT: RETVAL void interpret_mouse(self, key) Term::TermKey self Term::TermKey::Key key PREINIT: TermKeyMouseEvent ev; int button; int line, col; PPCODE: if(termkey_interpret_mouse(self->tk, &key->k, &ev, &button, &line, &col) != TERMKEY_RES_KEY) XSRETURN(0); mPUSHi(ev); mPUSHi(button); mPUSHi(line); mPUSHi(col); XSRETURN(4); void interpret_unknown_csi(self, key) Term::TermKey self Term::TermKey::Key key PREINIT: size_t nargs = 16; long args[16]; unsigned long cmd; char str[4]; int i; PPCODE: if(termkey_interpret_csi(self->tk, &key->k, args, &nargs, &cmd) != TERMKEY_RES_KEY) XSRETURN(0); i = 0; // Initial byte first if((cmd >> 8) & 0xff) str[i++] = (cmd >> 8) & 0xff; // Intermediate byte second if((cmd >> 16) & 0xff) str[i++] = (cmd >> 16) & 0xff; // Command byte last str[i++] = cmd & 0xff; str[i] = 0; mPUSHp(str, i); for(i = 0; i < nargs; i++) mPUSHi(args[i]); XSRETURN(nargs + 1); SV * format_key(self, key, format) Term::TermKey self Term::TermKey::Key key int format CODE: RETVAL = newSVpvn("", 50); SvCUR_set(RETVAL, termkey_strfkey(self->tk, SvPV_nolen(RETVAL), SvLEN(RETVAL), &key->k, format)); if(termkey_get_flags(self->tk) & TERMKEY_FLAG_UTF8) SvUTF8_on(RETVAL); OUTPUT: RETVAL SV * parse_key(self, str, format) Term::TermKey self char *str int format PREINIT: const char *ret; Term__TermKey__Key key; CODE: RETVAL = newSV(0); key = get_keystruct_or_new(RETVAL, "Term::TermKey::parse_key", ST(0)); ret = termkey_strpkey(self->tk, str, &key->k, format); if(!ret || ret[0]) { SvREFCNT_dec(RETVAL); XSRETURN_UNDEF; } OUTPUT: RETVAL SV * parse_key_at_pos(self, str, format) Term::TermKey self SV *str int format PREINIT: const char *str_base, *str_start, *str_end; MAGIC *posmg = NULL; Term__TermKey__Key key; CODE: if(SvREADONLY(str)) croak("str must not be a string literal"); str_start = str_base = SvPV_nolen(str); if(SvTYPE(str) >= SVt_PVMG && SvMAGIC(str)) posmg = mg_find(str, PERL_MAGIC_regex_global); if(posmg) str_start += posmg->mg_len; /* already in bytes */ RETVAL = newSV(0); key = get_keystruct_or_new(RETVAL, "Term::TermKey::parse_key_at_pos", ST(0)); str_end = termkey_strpkey(self->tk, str_start, &key->k, format); if(!str_end) { SvREFCNT_dec(RETVAL); XSRETURN_UNDEF; } if(!posmg) posmg = sv_magicext(str, NULL, PERL_MAGIC_regex_global, &PL_vtbl_mglob, NULL, 0); posmg->mg_len = str_end - str_base; /* already in bytes */ OUTPUT: RETVAL int keycmp(self, key1, key2) Term::TermKey self Term::TermKey::Key key1 Term::TermKey::Key key2 CODE: RETVAL = termkey_keycmp(self->tk, &key1->k, &key2->k); OUTPUT: RETVAL Term-TermKey-0.17/t000755001750001750 013433351022 12706 5ustar00leoleo000000000000Term-TermKey-0.17/t/00use.t000444001750001750 14713433351022 14146 0ustar00leoleo000000000000#!/usr/bin/perl use strict; use warnings; use Test::More; use_ok( "Term::TermKey" ); done_testing; Term-TermKey-0.17/t/01symname.t000444001750001750 61213433351022 15021 0ustar00leoleo000000000000#!/usr/bin/perl use strict; use warnings; use Test::More; use Term::TermKey; my $tk = Term::TermKey->new_abstract( "vt100", 0 ); defined $tk or die "Cannot create termkey instance"; # We know 'Space' ought to exist my $sym = $tk->keyname2sym( 'Space' ); ok( defined $sym, "defined keyname2sym('Space')" ); is( $tk->get_keyname( $sym ), 'Space', "get_keyname eq Space" ); done_testing; Term-TermKey-0.17/t/02getkey.t000444001750001750 434113433351022 14664 0ustar00leoleo000000000000#!/usr/bin/perl use strict; use warnings; use Test::More; use Test::Refcount; use Term::TermKey; my $tk = Term::TermKey->new_abstract( "vt100", 0 ); is_oneref( $tk, '$tk has refcount 1 initially' ); my $buffsize = $tk->get_buffer_size; cmp_ok( $buffsize, '>', 0, 'get_buffer_size > 0' ); is( $tk->get_buffer_remaining, $buffsize, "get_buffer_remaining initially $buffsize" ); my $key; is( $tk->getkey( $key ), RES_NONE, 'getkey yields RES_NONE when empty' ); ok( defined $key, '$key is defined' ); is_oneref( $key, '$key has refcount 1 after getkey()' ); is_refcount( $tk, 2, '$tk has refcount 2 after getkey()' ); is( $tk->push_bytes( "h" ), 1, 'push_bytes consumes 1 byte' ); is( $tk->get_buffer_remaining, $buffsize - 1, 'get_buffer_remaining after push_bytes' ); is( $tk->getkey( $key ), RES_KEY, 'getkey yields RES_KEY after h' ); is( $key->termkey, $tk, '$key->termkey after h' ); ok( $key->type_is_unicode, '$key->type_is_unicode after h' ); is( $key->codepoint, ord("h"), '$key->codepoint after h' ); is( $key->modifiers, 0, '$key->modifiers after h' ); is( $key->utf8, "h", '$key->utf8 after h' ); is( $key->format( 0 ), "h", '$key->format after h' ); is( $tk->get_buffer_remaining, $buffsize, 'get_buffer_remaining getkey' ); is( $tk->getkey( $key ), RES_NONE, 'getkey yields RES_NONE a second time' ); $tk->push_bytes( "\cA" ); is( $tk->getkey( $key ), RES_KEY, 'getkey yields RES_KEY after C-a' ); ok( $key->type_is_unicode, '$key->type_is_unicode after C-a' ); is( $key->codepoint, ord("a"), '$key->codepoint after C-a' ); is( $key->modifiers, KEYMOD_CTRL, '$key->modifiers after C-a' ); is( $key->format( 0 ), "C-a", '$key->format after C-a' ); $tk->push_bytes( "\eOA" ); is( $tk->getkey( $key ), RES_KEY, 'getkey yields RES_KEY after Up' ); ok( $key->type_is_keysym, '$key->type_is_keysym after Up' ); is( $key->sym, $tk->keyname2sym("Up"), '$key->keysym after Up' ); is( $key->modifiers, 0, '$key->modifiers after Up' ); is( $key->format( 0 ), "Up", '$key->format after Up' ); is_oneref( $key, '$key has refcount 1 before dropping' ); is_refcount( $tk, 2, '$tk has refcount 2 before dropping key' ); undef $key; is_oneref( $tk, '$k has refcount 1 before EOF' ); done_testing; Term-TermKey-0.17/t/03read.t000444001750001750 274213433351022 14313 0ustar00leoleo000000000000#!/usr/bin/perl use strict; use warnings; use Test::More; use Test::Refcount; use IO::Handle; use Term::TermKey; pipe( my ( $rd, $wr ) ) or die "Cannot pipe() - $!"; # Sanitise this just in case $ENV{TERM} = "vt100"; is_oneref( $rd, '$rd has refcount 1 initially' ); my $tk = Term::TermKey->new( $rd, 0 ); is_oneref( $tk, '$tk has refcount 1 initially' ); is_refcount( $rd, 2, '$rd has refcount 2 after Term::TermKey->new' ); my $key; is( $tk->getkey( $key ), RES_NONE, 'getkey yields RES_NONE when empty' ); ok( defined $key, '$key is defined' ); is_oneref( $key, '$key has refcount 1 after getkey()' ); is_refcount( $tk, 2, '$tk has refcount 2 after getkey()' ); $wr->syswrite( "h" ); is( $tk->getkey( $key ), RES_NONE, 'getkey yields RES_NONE before advisereadable' ); $tk->advisereadable; is( $tk->getkey( $key ), RES_KEY, 'getkey yields RES_KEY after h' ); is( $key->termkey, $tk, '$key->termkey after h' ); ok( $key->type_is_unicode, '$key->type_is_unicode after h' ); is( $key->codepoint, ord("h"), '$key->codepoint after h' ); is( $key->modifiers, 0, '$key->modifiers after h' ); is( $key->utf8, "h", '$key->utf8 after h' ); is( $key->format( 0 ), "h", '$key->format after h' ); is( $tk->getkey( $key ), RES_NONE, 'getkey yields RES_NONE a second time' ); undef $key; is_oneref( $tk, '$k has refcount 1 before EOF' ); is_refcount( $rd, 2, '$rd has refcount 2 before dropping $tk' ); undef $tk; is_oneref( $rd, '$rd has refcount 1 before EOF' ); done_testing; Term-TermKey-0.17/t/04parse_format.t000444001750001750 304013433351022 16053 0ustar00leoleo000000000000#!/usr/bin/perl use strict; use warnings; use Test::More; use Term::TermKey; my $tk = Term::TermKey->new_abstract( "vt100", FLAG_NOTERMIOS ); my $key; ok( defined( $key = $tk->parse_key( "A", 0 ) ), '->parse_key "A" defined' ); ok( $key->type_is_unicode, '$key->type_is_unicode' ); is( $key->codepoint, ord("A"), '$key->codepoint' ); is( $key->modifiers, 0, '$key->modifiers' ); is( $tk->format_key( $key, 0 ), "A", '->format_key yields "A"' ); ok( defined( $key = $tk->parse_key( "Ctrl-b", FORMAT_LONGMOD ) ), '->parse_key "Ctrl-b" defined' ); ok( $key->type_is_unicode, '$key->type_is_unicode' ); is( $key->codepoint, ord("b"), '$key->codepoint' ); is( $key->modifiers, KEYMOD_CTRL, '$key->modifiers' ); is( $tk->format_key( $key, FORMAT_LONGMOD ), "Ctrl-b", '->format_key yields "Ctrl-b"' ); ok( !defined( $key = $tk->parse_key( "NoSuchKey", 0 ) ), '->parse_key "NoSuchKey" not defined' ); { my $str = "bind Alt-V = verbose"; pos($str) = 5; ok( defined( $key = $tk->parse_key_at_pos( $str, FORMAT_LONGMOD ) ), '->parse_key_at_pos defined' ); ok( $key->type_is_unicode, '$key->type_is_unicode' ); is( $key->codepoint, ord("V"), '$key->codepoint' ); is( $key->modifiers, KEYMOD_ALT, '$key->modifiers' ); is( pos($str), 10, 'pos($str) after ->parse_key_at_pos' ); } { my $str = "Ctrl-Up = up-page"; ok( defined( $key = $tk->parse_key_at_pos( $str, FORMAT_LONGMOD ) ), '->parse_key_at_pos defined upgrade' ); is( pos($str), 7, 'pos($str) after ->parse_key_at_pos upgrade' ); } done_testing; Term-TermKey-0.17/t/05flags.t000444001750001750 156313433351022 14476 0ustar00leoleo000000000000#!/usr/bin/perl use strict; use warnings; use Test::More; use Term::TermKey qw( FLAG_UTF8 FLAG_RAW ); { my $tk = Term::TermKey->new_abstract( "vt100", FLAG_UTF8 ); is( $tk->get_flags & (FLAG_UTF8|FLAG_RAW), FLAG_UTF8, 'Explicit UTF-8 flag preserved' ); } { my $tk = Term::TermKey->new_abstract( "vt100", FLAG_RAW ); is( $tk->get_flags & (FLAG_UTF8|FLAG_RAW), FLAG_RAW, 'Explicit RAW flag preserved' ); } # Force UTF-8 on { local @ENV{qw( LANG LC_MESSAGES LC_ALL )} = ( "en_GB.UTF-8" ) x 3; my $tk = Term::TermKey->new( \*STDIN, 0 ); is( $tk->get_flags & (FLAG_UTF8|FLAG_RAW), FLAG_UTF8, 'Autodetected UTF-8' ); } # Force UTF-8 off { local @ENV{qw( LANG LC_MESSAGES LC_ALL )} = ( "en_GB.ISO-8859-1" ) x 3; my $tk = Term::TermKey->new( \*STDIN, 0 ); is( $tk->get_flags & (FLAG_UTF8|FLAG_RAW), FLAG_RAW, 'Autodetected RAW' ); } done_testing; Term-TermKey-0.17/t/06mouse.t000444001750001750 114013433351022 14522 0ustar00leoleo000000000000#!/usr/bin/perl use strict; use warnings; use Test::More; use Term::TermKey; my $tk = Term::TermKey->new_abstract( "vt100", 0 ); $tk->push_bytes( "\e[M \"#" ); my $key; is( $tk->getkey( $key ), RES_KEY, 'getkey yields RES_KEY after mouse press' ); ok( $key->type_is_mouse, '$key->type_is_mouse after mouse press' ); is( $key->mouseev, MOUSE_PRESS, '$key->mouseev after mouse press' ); is( $key->button, 1, '$key->button after mouse press' ); is( $key->line, 3, '$key->line after mouse press' ); is( $key->col, 2, '$key->col after mouse press' ); done_testing; Term-TermKey-0.17/t/07position.t000444001750001750 75713433351022 15234 0ustar00leoleo000000000000#!/usr/bin/perl use strict; use warnings; use Test::More; use Term::TermKey; my $tk = Term::TermKey->new_abstract( "vt100", 0 ); $tk->push_bytes( "\e[?3;5R" ); my $key; is( $tk->getkey( $key ), RES_KEY, 'getkey yields RES_KEY after cursor position report' ); ok( $key->type_is_position, '$key->type_is_position after cursor position report' ); is( $key->line, 3, '$key->line after cursor position report' ); is( $key->col, 5, '$key->col after cursor position report' ); done_testing; Term-TermKey-0.17/t/08modereport.t000444001750001750 166113433351022 15564 0ustar00leoleo000000000000#!/usr/bin/perl use strict; use warnings; use Test::More; use Term::TermKey; my $tk = Term::TermKey->new_abstract( "vt100", 0 ); $tk->push_bytes( "\e[15;1\$y" ); my $key; is( $tk->getkey( $key ), RES_KEY, 'getkey yields RES_KEY after ANSI mode report' ); ok( $key->type_is_modereport, '$key->type_is_modereport after ANSI mode report' ); is( $key->initial, "", '$key->initial after ANSI mode report' ); is( $key->mode, 15, '$key->mode after ANSI mode report' ); is( $key->value, 1, '$key->value after ANSI mode report' ); $tk->push_bytes( "\e[?4;2\$y" ); is( $tk->getkey( $key ), RES_KEY, 'getkey yields RES_KEY after DEC mode report' ); ok( $key->type_is_modereport, '$key->type_is_modereport after DEC mode report' ); is( $key->initial, "?", '$key->initial after DEC mode report' ); is( $key->mode, 4, '$key->mode after DEC mode report' ); is( $key->value, 2, '$key->value after DEC mode report' ); done_testing; Term-TermKey-0.17/t/09unknown_csi.t000444001750001750 151313433351022 15736 0ustar00leoleo000000000000#!/usr/bin/perl use strict; use warnings; use Test::More; use Term::TermKey; my $tk = Term::TermKey->new_abstract( "vt100", 0 ); $tk->push_bytes( "\e[>1;2v" ); my $key; is( $tk->getkey( $key ), RES_KEY, 'getkey yields RES_KEY after unrecognised CSI > v' ); ok( $key->type_is_unknown_csi, '$key->type_is_unknown_csi after unrecognised CSI > v' ); my ( $cmd, @args ) = $tk->interpret_unknown_csi( $key ); is( $cmd, ">v", '$cmd for unrecognised CSI > v' ); is_deeply( \@args, [ 1, 2 ], '@args for unrecognised CSI > v' ); $tk->push_bytes( "\e[?4; w" ); is( $tk->getkey( $key ), RES_KEY, 'getkey yields RES_KEY after unrecognised CSI ? Sp w' ); ( $cmd, @args ) = $tk->interpret_unknown_csi( $key ); is( $cmd, "? w", '$cmd for unrecognised CSI ? Sp w' ); is_deeply( \@args, [ 4 ], '@args for unrecognised CSI ? Sp w' ); done_testing; Term-TermKey-0.17/t/99pod.t000444001750001750 25713433351022 14160 0ustar00leoleo000000000000#!/usr/bin/perl use strict; use warnings; use Test::More; eval "use Test::Pod 1.00"; plan skip_all => "Test::Pod 1.00 required for testing POD" if $@; all_pod_files_ok();