pyte-0.8.0/0000755f2us0000000000013261757021014123 5ustar s.lebedev00000000000000pyte-0.8.0/PKG-INFO0000644f2us0000000623413261757021015225 0ustar s.lebedev00000000000000Metadata-Version: 1.1 Name: pyte Version: 0.8.0 Summary: Simple VTXXX-compatible terminal emulator. Home-page: https://github.com/selectel/pyte Author: Sergei Lebedev Author-email: superbobry@gmail.com License: UNKNOWN Description: .. -*- mode: rst -*- :: _ | | _ __ _ _ | |_ ___ | '_ \ | | | || __|/ _ \ | |_) || |_| || |_| __/ | .__/ \__, | \__|\___| | | __/ | |_| |___/ 0.8.0 What is ``pyte``? ----------------- It's an in memory VTXXX-compatible terminal emulator. *XXX* stands for a series of video terminals, developed by `DEC `_ between 1970 and 1995. The first, and probably the most famous one, was VT100 terminal, which is now a de-facto standard for all virtual terminal emulators. ``pyte`` follows the suit. So, why would one need a terminal emulator library? * To screen scrape terminal apps, for example ``htop`` or ``aptitude``. * To write cross platform terminal emulators; either with a graphical (`xterm `_, `rxvt `_) or a web interface, like `AjaxTerm `_. * To have fun, hacking on the ancient, poorly documented technologies. **Note**: ``pyte`` started as a fork of `vt102 `_, which is an incomplete pure Python implementation of VT100 terminal. Installation ------------ If you have `pip `_ you can do the usual:: pip install pyte Otherwise, download the source from `GitHub `_ and run:: python setup.py install Similar projects ---------------- ``pyte`` is not alone in the weird world of terminal emulator libraries, here's a few other options worth checking out: `Termemulator `_, `pyqonsole `_, `webtty `_, `AjaxTerm `_ and of course `vt102 `_. Keywords: vt102,vte,terminal emulator Platform: any Classifier: Development Status :: 5 - Production/Stable Classifier: Environment :: Console Classifier: Intended Audience :: Developers Classifier: Operating System :: OS Independent Classifier: License :: OSI Approved :: GNU Lesser General Public License v3 (LGPLv3) Classifier: Programming Language :: Python :: 2.6 Classifier: Programming Language :: Python :: 2.7 Classifier: Programming Language :: Python :: 3.5 Classifier: Programming Language :: Python :: 3.6 Classifier: Topic :: Terminals :: Terminal Emulators/X Terminals pyte-0.8.0/LICENSE0000644f2us0000001674313062755665015156 0ustar s.lebedev00000000000000 GNU LESSER GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. This version of the GNU Lesser General Public License incorporates the terms and conditions of version 3 of the GNU General Public License, supplemented by the additional permissions listed below. 0. Additional Definitions. As used herein, "this License" refers to version 3 of the GNU Lesser General Public License, and the "GNU GPL" refers to version 3 of the GNU General Public License. "The Library" refers to a covered work governed by this License, other than an Application or a Combined Work as defined below. An "Application" is any work that makes use of an interface provided by the Library, but which is not otherwise based on the Library. Defining a subclass of a class defined by the Library is deemed a mode of using an interface provided by the Library. A "Combined Work" is a work produced by combining or linking an Application with the Library. The particular version of the Library with which the Combined Work was made is also called the "Linked Version". The "Minimal Corresponding Source" for a Combined Work means the Corresponding Source for the Combined Work, excluding any source code for portions of the Combined Work that, considered in isolation, are based on the Application, and not on the Linked Version. The "Corresponding Application Code" for a Combined Work means the object code and/or source code for the Application, including any data and utility programs needed for reproducing the Combined Work from the Application, but excluding the System Libraries of the Combined Work. 1. Exception to Section 3 of the GNU GPL. You may convey a covered work under sections 3 and 4 of this License without being bound by section 3 of the GNU GPL. 2. Conveying Modified Versions. If you modify a copy of the Library, and, in your modifications, a facility refers to a function or data to be supplied by an Application that uses the facility (other than as an argument passed when the facility is invoked), then you may convey a copy of the modified version: a) under this License, provided that you make a good faith effort to ensure that, in the event an Application does not supply the function or data, the facility still operates, and performs whatever part of its purpose remains meaningful, or b) under the GNU GPL, with none of the additional permissions of this License applicable to that copy. 3. Object Code Incorporating Material from Library Header Files. The object code form of an Application may incorporate material from a header file that is part of the Library. You may convey such object code under terms of your choice, provided that, if the incorporated material is not limited to numerical parameters, data structure layouts and accessors, or small macros, inline functions and templates (ten or fewer lines in length), you do both of the following: a) Give prominent notice with each copy of the object code that the Library is used in it and that the Library and its use are covered by this License. b) Accompany the object code with a copy of the GNU GPL and this license document. 4. Combined Works. You may convey a Combined Work under terms of your choice that, taken together, effectively do not restrict modification of the portions of the Library contained in the Combined Work and reverse engineering for debugging such modifications, if you also do each of the following: a) Give prominent notice with each copy of the Combined Work that the Library is used in it and that the Library and its use are covered by this License. b) Accompany the Combined Work with a copy of the GNU GPL and this license document. c) For a Combined Work that displays copyright notices during execution, include the copyright notice for the Library among these notices, as well as a reference directing the user to the copies of the GNU GPL and this license document. d) Do one of the following: 0) Convey the Minimal Corresponding Source under the terms of this License, and the Corresponding Application Code in a form suitable for, and under terms that permit, the user to recombine or relink the Application with a modified version of the Linked Version to produce a modified Combined Work, in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source. 1) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (a) uses at run time a copy of the Library already present on the user's computer system, and (b) will operate properly with a modified version of the Library that is interface-compatible with the Linked Version. e) Provide Installation Information, but only if you would otherwise be required to provide such information under section 6 of the GNU GPL, and only to the extent that such information is necessary to install and execute a modified version of the Combined Work produced by recombining or relinking the Application with a modified version of the Linked Version. (If you use option 4d0, the Installation Information must accompany the Minimal Corresponding Source and Corresponding Application Code. If you use option 4d1, you must provide the Installation Information in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.) 5. Combined Libraries. You may place library facilities that are a work based on the Library side by side in a single library together with other library facilities that are not Applications and are not covered by this License, and convey such a combined library under terms of your choice, if you do both of the following: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities, conveyed under the terms of this License. b) Give prominent notice with the combined library that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 6. Revised Versions of the GNU Lesser General Public License. The Free Software Foundation may publish revised and/or new versions of the GNU Lesser 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 Library as you received it specifies that a certain numbered version of the GNU Lesser General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that published version or of any later version published by the Free Software Foundation. If the Library as you received it does not specify a version number of the GNU Lesser General Public License, you may choose any version of the GNU Lesser General Public License ever published by the Free Software Foundation. If the Library as you received it specifies that a proxy can decide whether future versions of the GNU Lesser General Public License shall apply, that proxy's public statement of acceptance of any version is permanent authorization for you to choose that version for the Library. pyte-0.8.0/AUTHORS0000644f2us0000000035413261754104015174 0ustar s.lebedev00000000000000Authors ======= - George Shuklin - Sergei Lebedev Contributors ------------ - Alexey Shamrin - Steve Cohen - Jonathan Slenders - David O'Shea - Andreas Stührk - Dmitriy Novozhilov - Sergey Zavgorodniy - Byron Roosa - Andrew Crozier pyte-0.8.0/CHANGES0000644f2us0000002556013261756126015133 0ustar s.lebedev00000000000000pyte Changelog ============== Here you can see the full list of changes between each pyte release. Version 0.8.0 ------------- Released on April 6th, 2018. This release is NOT backward compatible with 0.7.X branch! - Modified the logic around tracking position in the ``HistoryScreen``, allowing the full history to be accessed. See PR #96 on GitHub. - Send C0 encoded CSI instead of C1, avoiding compatibility issues with unicode. See issue #99 on GitHub. - Changed ``Stream`` to really ignore ``SI`` in UTF-8 mode. See PR #106 on GitHub. Thanks to @jwodder! - Fixed `DECSCNM` handling bug. The attributes of ``Screen.default_char`` were not reversed leaving all blank characters as-is. See PR #102 on GitHub. Thanks to @zblz! - Correctly terminate OSC mode in ``Stream`` on receipt of a C0 encoded ``ST`` character. - Allowed resetting cursor attributes in the middle of the SGR sequence. See PR#109 on GiHub. Thanks @andreivasiliu! - On exit from `DECCOLM` mode, restore the terminal width from before entering `DECCOLM` mode. - Changed ``Screen.select_graphic_rendition`` to ignore malformed 256/24bit colours. See issue #115 on GitHub. Version 0.7.0 ------------- Released on October 7th 2017. This release is NOT backward compatible with 0.6.X branch! - Removed deprecated ``only`` parameter of ``Stream.attach``. - Removed deprecated ``encoding`` parameter of ``ByteStream``. - Fixed ``how == 3`` handling in ``DiffScreen.erase_in_display``. - Deprecated ``DiffScreen``. Its functionality has been backported to the base ``Screen`` class. - Fixed a bug in ``DiffScreen.draw`` which incorrectly handled the case when the input of ``draw`` required several lines. - Fixed a bug in ``Screen`` which did not ignore ``ESC (`` argument in UTF8 mode. See issue #88 on GitHub. - Changed ``Screen.resize`` to do nothing if the requested size matches the current one. - Disallowed private mode for ``Screen.report_device_attributes``. This was causing an infinite loop in Emacs and Vim. See issue #81 on GitHub. - Fixed a bug in `OSC` parsing, which caused ``Stream`` to hang upon receiving a palette reset request ``ESC ] R``. - Changed ``Screen.reset`` not to reset `DECOM`. See discussion in issue #95 on Github. - Changed the first tabstop to be at the 9-th column. See PR #98 on GitHub. Thanks to @gordon-quad! Version 0.6.0 ------------- Released on May 28th 2017 This release is NOT backward compatible with 0.5.X branch! - Optimized ``Stream.feed`` for plain-text input. The code was backported from ``pymux`` project by Jonathan Slenders. - Optimized ``Screen`` by changing ``Screen.buffer`` to dict-of-dicts. The idea was borrowed from ``pymux`` project by Jonathan Slenders. The implementation was done by @istarion. - Further optimized ``Stream._parser_fsm`` by forcing static binding between ``Stream`` events and ``Screen`` methods. The code was backported from ``pmux`` project by Jonathan Slenders. - Restricted ``Stream`` to a single listener and deprecated ``attach`` and ``detach``. The old logic can be emulated by a fanout proxy, forwarding events to a list of its listeners. - Replaced ``DebugStream`` with ``DebugScreen`` to workaround the single listener limitation (previsouly ``DebugStream`` implicitly added a listener when instantiated). Unlike other screens ``DebugScreen`` does not maintain any state. - Changed ``DebugScreen`` to emit JSON instead of custom text format. - Removed overly generic ``Screen.__before__`` and ``Screen.__after__``. - Renamed ``Screen.set_charset`` to a more appropriate ``Screen.define_charset``. - Added support for ECMA-035 `DOCS` command to ``ByteStream`` which no longer accepts ``encoding`` as an argument and instead sets it as instructed by `DOCS`. The default encoding is assumed to be UTF-8. - Added support for OSC sequences allowing to set terminal title and icon name. - Allowed 256 and 24bit colours in ``Screen.select_graphic_rendition``. - Added support for ``aixterm`` colours in ``Screen.select_graphic_rendition``, see issue #57 on GitHub. - Changed ``Screen.select_graphic_rendition`` to ignore 0 if it is given along with other attributes, ie ``"0;1;2"`` is now equivalent to ``"1;2"``. - Fixed rendering of multicolumn characters at ``Screen` boundaries. Thanks to @shaform! See PR #55 on GitHub. - Fixed ``Screen.display`` in the case of multicolumn characters. See issue #52 on GitHub. - Fixed `DECSTBM` handling in case of missing arguments. See issue #61 on GitHub. - Fixed the way ``Screen.cursor_up`` and ``Screen.cursor_down`` interact with the scrolling region. See #63 on GitHub. - Added a minimal web terminal example by @demiurg906. For a faster and more fully-featured version, see `demiurg906/pyte_gui `_. - Fixed ``Screen.cursor_back`` when called after the draw in the last column. - Fixed ``Screen.inser_characters`` when called with an argument larger than the number of columns. Thanks to @istarion! See PR #74 on GitHub. - Fixed ``Screen.erase_in_display`` which did not handle all values supported by ``TERM=linux``. See #80 on GitHub. Version 0.5.2 ------------- Pi Day bugfix release, released on March 14th, 2016 - Fixed a bug in handling DA request. See issue #46 on GitHub. Version 0.5.1 ------------- Bugfix release, released on January 10th 2015 - Fixed dependencies in setup.py. Version 0.5.0 ------------- Released on January 10th 2015 - Deprecated ``Stream.consume`` in favour of ``Stream.feed``. The latter allows for a more efficient implementation because it operates on the whole input string. - Improved ``Stream`` performance by converting FSM to a coroutine as suggested by Jonathan Slenders in issue #41 on GitHub. - Added support for `DA` (device attributes) and `DSR` (device status report). The implementation is based on the code by Jonathan Slenders. See issue #41 on GitHub. - ``Screen.draw`` now properly handles full/ambiguous-width characters. Thanks to the excellent `wcwidth `_ library by Jeff Quast. - Removed re-exports of abbreviated modules (e.g. ``mo`` as a synonym for ``modes``) from ``pyte``. - Removed ``Screen.size`` which misleadingly returned constructor arguments in reverse order. Please use ``Screen.columns`` and ``Screen.lines`` instead. - Fixed a bug in ``ByteStream`` which suppressed the exception if all of the decoders failed to process the input. Version 0.4.10 -------------- Bugfix release, released on August 4th 2015 - Fixed a bug in ``DiffScreen.draw`` which marked the wrong line as changed when `DECAWM` was enabled. - ``Stream`` now recognizes ESC % sequences for selecting control character set. However, these operations are no-op in the current version in a sense that ``ByteStream`` does not handle them to change encoding. Version 0.4.9 ------------- Bugfix release, released on December 3rd 2014 - Fixed a bug in ``Char`` initialization, see issue #24 on GitHub for details. - Updated error message in ``Stream``, referencing ``str`` is relevant for Python 3, but not Python 2. Version 0.4.8 ------------- Released on January 13th 2014 - ``Screen`` does NOT inherit from builtin ``list``, use ``Screen.buffer`` to access individual characters directly. This is a backward INCOMPATIBLE change. - ``Char._asdict`` was broken on Python 3.3 because of the changes in ``namedtuple`` implementation. - ``LAT1_MAP`` was an iterator because of the change in map semantics in Python 3. - Changed ``Screen`` to issues a CR in addition to LF when `DECAWM` mode is set and the cursor is at the right border of the screen. See http://www.vt100.net/docs/vt510-rm/DECAWM and issue #20 on GitHub for details. Version 0.4.7 ------------- Bugfix release, released on March 28th 2013 - Updated ``pyte`` and tests suite to work under Python 3.3. - Changed ``Screen`` so that `LNM` mode is reset by default, see http://www.vt100.net/docs/vt510-rm/LNM and issue #11 on GitHub for details. Version 0.4.6 ------------- Bugfix release, released on February 29th 2012 Version 0.4.5 ------------- Technical release, released on September 1st 2011 - Added MANIFEST.in and CenOS spec file Version 0.4.4 ------------- Bugfix release, released on July 17th 2011 - Removed ``pdb`` calls, left from ``HistoryScreen`` debugging -- silly, I know :) Version 0.4.3 ------------- Bugfix release, released on July 12th 2011 - Fixed encoding issues in ``DebugStream`` -- Unicode was not converted to bytes properly. - Fixed G0-1 charset handling and added VAX42 charset for the ancient stuff to work correctly. Version 0.4.2 ------------- Bugfix release, released on June 27th 2011 - Added a tiny debugging helper: ``python -m pyte your escape codes`` - Added ``Screen.__{before,after}__()`` hooks to ``Screen`` -- now subclasses can extend more than one command easily. - Fixed ``HistoryScreen`` -- now not as buggy as it used to be: and allows for custom ratio aspect when browsing history, see ``HistoryScreen`` documentation for details. - Fixed `DECTCEM` private mode handling -- when the mode is reset ``Screen.cursor.hidden`` is ``True`` otherwise it's ``False``. Version 0.4.1 ------------- Bugfix release, released on June 21st 2011 - Minor examples and documentation update before the first public release. Version 0.4.0 ------------- Released on June 21st 2011 - Improved cursor movement -- ``Screen`` passes all but one tests in `vttest`. - Changed the way ``Stream`` interacts with ``Screen`` -- event handlers are now implicitly looked up in screen's ``__dict__``, not connected manually. - Changed cursor API -- cursor position and attributes are encapsulated in a separate ``Cursor`` class. - Added support for `DECSCNM` -- toggle screen-wide reverse-video mode. - Added a couple of useful ``Screen`` subclasses: ``HistoryScreen`` which allows screen pagination and ``DiffScreen`` which tracks the changed lines. Version 0.3.9 ------------- Released on May 31st 2011 - Added initial support for G0-1 charsets (mappings taken from ``tty`` kernel driver) and SI, SO escape sequences. - Changed ``ByteStream`` to support fallback encodings -- it now takes a list of ``(encoding, errors)`` pairs and traverses it left to right on ``feed()``. - Switched to ``unicode_literals`` -- one step closer to Python3. Version 0.3.8 ------------- Released on May 23rd 2011 - Major rewrite of ``Screen`` internals -- highlights: inherits from ``list``; each character is represented by ``namedtuple`` which also holds SGR data. - Numerous bugfixes, especially in methods, dealing with manipulating character attributes. Version 0.3.7 ------------- First release after the adoption -- skipped a few version to reflect that. Released on May 16th 2011 - Added support for ANSI color codes, as listed in ``man console_codes``. Not implemented yet: setting alternate font, setting and resetting mappings, blinking text. - Added a couple of trivial usage examples in the `examples/` dir. pyte-0.8.0/tests/0000755f2us0000000000013261757021015265 5ustar s.lebedev00000000000000pyte-0.8.0/tests/test_input_output.py0000644f2us0000000115513117620156021455 0ustar s.lebedev00000000000000# -*- coding: utf-8 -*- import json import os.path import pytest import pyte captured_dir = os.path.join(os.path.dirname(__file__), "captured") @pytest.mark.parametrize("name", [ "cat-gpl3", "find-etc", "htop", "ls", "mc", "top", "vi" ]) def test_input_output(name): with open(os.path.join(captured_dir, name + ".input"), "rb") as handle: input = handle.read() with open(os.path.join(captured_dir, name + ".output")) as handle: output = json.load(handle) screen = pyte.Screen(80, 24) stream = pyte.ByteStream(screen) stream.feed(input) assert screen.display == output pyte-0.8.0/tests/test_screen.py0000644f2us0000013055513261755027020172 0ustar s.lebedev00000000000000# -*- coding: utf-8 -*- from __future__ import unicode_literals import copy import pytest import pyte from pyte import modes as mo, control as ctrl, graphics as g from pyte.screens import Char # Test helpers. def update(screen, lines, colored=[]): """Updates a given screen object with given lines, colors each line from ``colored`` in "red" and returns the modified screen. """ for y, line in enumerate(lines): for x, char in enumerate(line): if y in colored: attrs = {"fg": "red"} else: attrs = {} screen.buffer[y][x] = Char(data=char, **attrs) return screen def tolist(screen): return [[screen.buffer[y][x] for x in range(screen.columns)] for y in range(screen.lines)] # Tests. def test_initialize_char(): # Make sure that char can be correctly initialized with keyword # arguments. See #24 on GitHub for details. for field in Char._fields[1:]: char = Char(field[0], **{field: True}) assert getattr(char, field) def test_remove_non_existant_attribute(): screen = pyte.Screen(2, 2) assert tolist(screen) == [[screen.default_char, screen.default_char]] * 2 screen.select_graphic_rendition(24) # underline-off. assert tolist(screen) == [[screen.default_char, screen.default_char]] * 2 assert not screen.cursor.attrs.underscore def test_attributes(): screen = pyte.Screen(2, 2) assert tolist(screen) == [[screen.default_char, screen.default_char]] * 2 screen.select_graphic_rendition(1) # bold. # Still default, since we haven't written anything. assert tolist(screen) == [[screen.default_char, screen.default_char]] * 2 assert screen.cursor.attrs.bold screen.draw("f") assert tolist(screen) == [ [Char("f", "default", "default", bold=True), screen.default_char], [screen.default_char, screen.default_char] ] def test_colors(): screen = pyte.Screen(2, 2) screen.select_graphic_rendition(30) screen.select_graphic_rendition(40) assert screen.cursor.attrs.fg == "black" assert screen.cursor.attrs.bg == "black" screen.select_graphic_rendition(31) assert screen.cursor.attrs.fg == "red" assert screen.cursor.attrs.bg == "black" def test_colors256(): screen = pyte.Screen(2, 2) # a) OK-case. screen.select_graphic_rendition(g.FG_256, 5, 0) screen.select_graphic_rendition(g.BG_256, 5, 15) assert screen.cursor.attrs.fg == "000000" assert screen.cursor.attrs.bg == "ffffff" # b) invalid color. screen.select_graphic_rendition(48, 5, 100500) def test_colors256_missing_attrs(): # Test from https://github.com/selectel/pyte/issues/115 screen = pyte.Screen(2, 2) screen.select_graphic_rendition(g.FG_256) screen.select_graphic_rendition(g.BG_256) assert screen.cursor.attrs == screen.default_char def test_colors24bit(): screen = pyte.Screen(2, 2) # a) OK-case screen.select_graphic_rendition(38, 2, 0, 0, 0) screen.select_graphic_rendition(48, 2, 255, 255, 255) assert screen.cursor.attrs.fg == "000000" assert screen.cursor.attrs.bg == "ffffff" # b) invalid color. screen.select_graphic_rendition(48, 2, 255) def test_colors_aixterm(): # See issue #57 on GitHub. screen = pyte.Screen(2, 2) # a) foreground color. screen.select_graphic_rendition(94) assert screen.cursor.attrs.fg == "blue" assert screen.cursor.attrs.bold # b) background color. screen.select_graphic_rendition(104) assert screen.cursor.attrs.bg == "blue" assert screen.cursor.attrs.bold def test_colors_ignore_invalid(): screen = pyte.Screen(2, 2) default_attrs = screen.cursor.attrs screen.select_graphic_rendition(100500) assert screen.cursor.attrs == default_attrs screen.select_graphic_rendition(38, 100500) assert screen.cursor.attrs == default_attrs screen.select_graphic_rendition(48, 100500) assert screen.cursor.attrs == default_attrs def test_reset_resets_colors(): screen = pyte.Screen(2, 2) assert tolist(screen) == [[screen.default_char, screen.default_char]] * 2 screen.select_graphic_rendition(30) screen.select_graphic_rendition(40) assert screen.cursor.attrs.fg == "black" assert screen.cursor.attrs.bg == "black" screen.select_graphic_rendition(0) assert screen.cursor.attrs == screen.default_char def test_reset_works_between_attributes(): screen = pyte.Screen(2, 2) assert tolist(screen) == [[screen.default_char, screen.default_char]] * 2 # Red fg, reset, red bg screen.select_graphic_rendition(31, 0, 41) assert screen.cursor.attrs.fg == "default" assert screen.cursor.attrs.bg == "red" def test_multi_attribs(): screen = pyte.Screen(2, 2) assert tolist(screen) == [[screen.default_char, screen.default_char]] * 2 screen.select_graphic_rendition(1) screen.select_graphic_rendition(3) assert screen.cursor.attrs.bold assert screen.cursor.attrs.italics def test_attributes_reset(): screen = pyte.Screen(2, 2) screen.set_mode(mo.LNM) assert tolist(screen) == [[screen.default_char, screen.default_char]] * 2 screen.select_graphic_rendition(1) screen.draw("f") screen.draw("o") screen.draw("o") assert tolist(screen) == [ [Char("f", bold=True), Char("o", bold=True)], [Char("o", bold=True), screen.default_char], ] screen.cursor_position() screen.select_graphic_rendition(0) # Reset screen.draw("f") assert tolist(screen) == [ [Char("f"), Char("o", bold=True)], [Char("o", bold=True), screen.default_char], ] def test_resize(): screen = pyte.Screen(2, 2) screen.set_mode(mo.DECOM) screen.set_margins(0, 1) assert screen.columns == screen.lines == 2 assert tolist(screen) == [[screen.default_char, screen.default_char]] * 2 screen.resize(3, 3) assert screen.columns == screen.lines == 3 assert tolist(screen) == [ [screen.default_char, screen.default_char, screen.default_char] ] * 3 assert mo.DECOM in screen.mode assert screen.margins is None screen.resize(2, 2) assert screen.columns == screen.lines == 2 assert tolist(screen) == [[screen.default_char, screen.default_char]] * 2 # Quirks: # a) if the current display is narrower than the requested size, # new columns should be added to the right. screen = update(pyte.Screen(2, 2), ["bo", "sh"], [None, None]) screen.resize(2, 3) assert screen.display == ["bo ", "sh "] # b) if the current display is wider than the requested size, # columns should be removed from the right... screen = update(pyte.Screen(2, 2), ["bo", "sh"], [None, None]) screen.resize(2, 1) assert screen.display == ["b", "s"] # c) if the current display is shorter than the requested # size, new rows should be added on the bottom. screen = update(pyte.Screen(2, 2), ["bo", "sh"], [None, None]) screen.resize(3, 2) assert screen.display == ["bo", "sh", " "] # d) if the current display is taller than the requested # size, rows should be removed from the top. screen = update(pyte.Screen(2, 2), ["bo", "sh"], [None, None]) screen.resize(1, 2) assert screen.display == ["sh"] def test_resize_same(): screen = pyte.Screen(2, 2) screen.dirty.clear() screen.resize(2, 2) assert not screen.dirty def test_set_mode(): # Test mo.DECCOLM mode screen = update(pyte.Screen(3, 3), ["sam", "is ", "foo"]) screen.cursor_position(1, 1) screen.set_mode(mo.DECCOLM) for line in range(3): for char in tolist(screen)[line]: assert char == screen.default_char assert screen.columns == 132 assert screen.cursor.x == 0 assert screen.cursor.y == 0 screen.reset_mode(mo.DECCOLM) assert screen.columns == 3 # Test mo.DECOM mode screen = update(pyte.Screen(3, 3), ["sam", "is ", "foo"]) screen.cursor_position(1, 1) screen.set_mode(mo.DECOM) assert screen.cursor.x == 0 assert screen.cursor.y == 0 # Test mo.DECSCNM mode screen = update(pyte.Screen(3, 3), ["sam", "is ", "foo"]) screen.set_mode(mo.DECSCNM) for line in range(3): for char in tolist(screen)[line]: assert char.reverse assert screen.default_char.reverse screen.reset_mode(mo.DECSCNM) for line in range(3): for char in tolist(screen)[line]: assert not char.reverse assert not screen.default_char.reverse # Test mo.DECTCEM mode screen = update(pyte.Screen(3, 3), ["sam", "is ", "foo"]) screen.cursor.hidden = True screen.set_mode(mo.DECTCEM) assert not screen.cursor.hidden screen.reset_mode(mo.DECTCEM) assert screen.cursor.hidden def test_draw(): # ``DECAWM`` on (default). screen = pyte.Screen(3, 3) screen.set_mode(mo.LNM) assert mo.DECAWM in screen.mode for ch in "abc": screen.draw(ch) assert screen.display == ["abc", " ", " "] assert (screen.cursor.y, screen.cursor.x) == (0, 3) # ... one` more character -- now we got a linefeed! screen.draw("a") assert (screen.cursor.y, screen.cursor.x) == (1, 1) # ``DECAWM`` is off. screen = pyte.Screen(3, 3) screen.reset_mode(mo.DECAWM) for ch in "abc": screen.draw(ch) assert screen.display == ["abc", " ", " "] assert (screen.cursor.y, screen.cursor.x) == (0, 3) # No linefeed is issued on the end of the line ... screen.draw("a") assert screen.display == ["aba", " ", " "] assert (screen.cursor.y, screen.cursor.x) == (0, 3) # ``IRM`` mode is on, expecting new characters to move the old ones # instead of replacing them. screen.set_mode(mo.IRM) screen.cursor_position() screen.draw("x") assert screen.display == ["xab", " ", " "] screen.cursor_position() screen.draw("y") assert screen.display == ["yxa", " ", " "] def test_draw_russian(): # Test from https://github.com/selectel/pyte/issues/65 screen = pyte.Screen(20, 1) stream = pyte.Stream(screen) stream.feed("Нерусский текст") assert screen.display == ["Нерусский текст "] def test_draw_multiple_chars(): screen = pyte.Screen(10, 1) screen.draw("foobar") assert screen.cursor.x == 6 assert screen.display == ["foobar "] def test_draw_utf8(): # See https://github.com/selectel/pyte/issues/62 screen = pyte.Screen(1, 1) stream = pyte.ByteStream(screen) stream.feed(b"\xE2\x80\x9D") assert screen.display == ["”"] def test_draw_width2(): # Example from https://github.com/selectel/pyte/issues/9 screen = pyte.Screen(10, 1) screen.draw("コンニチハ") assert screen.cursor.x == screen.columns def test_draw_width2_line_end(): # Test from https://github.com/selectel/pyte/issues/55 screen = pyte.Screen(10, 1) screen.draw(" コンニチハ") assert screen.cursor.x == screen.columns @pytest.mark.xfail def test_draw_width2_irm(): screen = pyte.Screen(2, 1) screen.draw("コ") assert screen.display == ["コ"] assert tolist(screen) == [[Char("コ"), Char(" ")]] # Overwrite the stub part of a width 2 character. screen.set_mode(mo.IRM) screen.cursor_to_column(screen.columns) screen.draw("x") assert screen.display == [" x"] def test_draw_width0_combining(): screen = pyte.Screen(4, 2) # a) no prev. character screen.draw("\N{COMBINING DIAERESIS}") assert screen.display == [" ", " "] screen.draw("bad") # b) prev. character is on the same line screen.draw("\N{COMBINING DIAERESIS}") assert screen.display == ["bad̈ ", " "] # c) prev. character is on the prev. line screen.draw("!") screen.draw("\N{COMBINING DIAERESIS}") assert screen.display == ["bad̈!̈", " "] def test_draw_width0_irm(): screen = pyte.Screen(10, 1) screen.set_mode(mo.IRM) # The following should not insert any blanks. screen.draw("\N{ZERO WIDTH SPACE}") screen.draw("\u0007") # DELETE. assert screen.display == [" " * screen.columns] def test_draw_width0_decawm_off(): screen = pyte.Screen(10, 1) screen.reset_mode(mo.DECAWM) screen.draw(" コンニチハ") assert screen.cursor.x == screen.columns # The following should not advance the cursor. screen.draw("\N{ZERO WIDTH SPACE}") screen.draw("\u0007") # DELETE. assert screen.cursor.x == screen.columns def test_draw_cp437(): screen = pyte.Screen(5, 1) stream = pyte.ByteStream(screen) assert screen.charset == 0 screen.define_charset("U", "(") stream.select_other_charset("@") stream.feed("α ± ε".encode("cp437")) assert screen.display == ["α ± ε"] def test_draw_with_carriage_return(): # See https://github.com/selectel/pyte/issues/66 line = """\ ipcs -s | grep nobody |awk '{print$2}'|xargs -n1 i\ pcrm sem ;ps aux|grep -P 'httpd|fcgi'|grep -v grep\ |awk '{print$2 \x0D}'|xargs kill -9;/etc/init.d/ht\ tpd startssl""" screen = pyte.Screen(50, 3) stream = pyte.Stream(screen) stream.feed(line) assert screen.display == [ "ipcs -s | grep nobody |awk '{print$2}'|xargs -n1 i", "pcrm sem ;ps aux|grep -P 'httpd|fcgi'|grep -v grep", "}'|xargs kill -9;/etc/init.d/httpd startssl " ] def test_display_wcwidth(): screen = pyte.Screen(10, 1) screen.draw("コンニチハ") assert screen.display == ["コンニチハ"] def test_carriage_return(): screen = pyte.Screen(3, 3) screen.cursor.x = 2 screen.carriage_return() assert screen.cursor.x == 0 def test_index(): screen = update(pyte.Screen(2, 2), ["wo", "ot"], colored=[1]) # a) indexing on a row that isn't the last should just move # the cursor down. screen.index() assert (screen.cursor.y, screen.cursor.x) == (1, 0) assert tolist(screen) == [ [Char("w"), Char("o")], [Char("o", fg="red"), Char("t", fg="red")] ] # b) indexing on the last row should push everything up and # create a new row at the bottom. screen.index() assert screen.cursor.y == 1 assert tolist(screen) == [ [Char("o", fg="red"), Char("t", fg="red")], [screen.default_char, screen.default_char] ] # c) same with margins screen = update(pyte.Screen(2, 5), ["bo", "sh", "th", "er", "oh"], colored=[1, 2]) screen.set_margins(2, 4) screen.cursor.y = 3 # ... go! screen.index() assert (screen.cursor.y, screen.cursor.x) == (3, 0) assert screen.display == ["bo", "th", "er", " ", "oh"] assert tolist(screen) == [ [Char("b"), Char("o", "default")], [Char("t", "red"), Char("h", "red")], [Char("e"), Char("r")], [screen.default_char, screen.default_char], [Char("o"), Char("h")], ] # ... and again ... screen.index() assert (screen.cursor.y, screen.cursor.x) == (3, 0) assert screen.display == ["bo", "er", " ", " ", "oh"] assert tolist(screen) == [ [Char("b"), Char("o")], [Char("e"), Char("r")], [screen.default_char, screen.default_char], [screen.default_char, screen.default_char], [Char("o"), Char("h")], ] # ... and again ... screen.index() assert (screen.cursor.y, screen.cursor.x) == (3, 0) assert screen.display == ["bo", " ", " ", " ", "oh"] assert tolist(screen) == [ [Char("b"), Char("o")], [screen.default_char, screen.default_char], [screen.default_char, screen.default_char], [screen.default_char, screen.default_char], [Char("o"), Char("h")], ] # look, nothing changes! screen.index() assert (screen.cursor.y, screen.cursor.x) == (3, 0) assert screen.display == ["bo", " ", " ", " ", "oh"] assert tolist(screen) == [ [Char("b"), Char("o")], [screen.default_char, screen.default_char], [screen.default_char, screen.default_char], [screen.default_char, screen.default_char], [Char("o"), Char("h")], ] def test_reverse_index(): screen = update(pyte.Screen(2, 2), ["wo", "ot"], colored=[0]) # a) reverse indexing on the first row should push rows down # and create a new row at the top. screen.reverse_index() assert (screen.cursor.y, screen.cursor.x) == (0, 0) assert tolist(screen) == [ [screen.default_char, screen.default_char], [Char("w", fg="red"), Char("o", fg="red")] ] # b) once again ... screen.reverse_index() assert (screen.cursor.y, screen.cursor.x) == (0, 0) assert tolist(screen) == [ [screen.default_char, screen.default_char], [screen.default_char, screen.default_char], ] # c) same with margins screen = update(pyte.Screen(2, 5), ["bo", "sh", "th", "er", "oh"], colored=[2, 3]) screen.set_margins(2, 4) screen.cursor.y = 1 # ... go! screen.reverse_index() assert (screen.cursor.y, screen.cursor.x) == (1, 0) assert screen.display == ["bo", " ", "sh", "th", "oh"] assert tolist(screen) == [ [Char("b"), Char("o")], [screen.default_char, screen.default_char], [Char("s"), Char("h")], [Char("t", fg="red"), Char("h", fg="red")], [Char("o"), Char("h")], ] # ... and again ... screen.reverse_index() assert (screen.cursor.y, screen.cursor.x) == (1, 0) assert screen.display == ["bo", " ", " ", "sh", "oh"] assert tolist(screen) == [ [Char("b"), Char("o")], [screen.default_char, screen.default_char], [screen.default_char, screen.default_char], [Char("s"), Char("h")], [Char("o"), Char("h")], ] # ... and again ... screen.reverse_index() assert (screen.cursor.y, screen.cursor.x) == (1, 0) assert screen.display == ["bo", " ", " ", " ", "oh"] assert tolist(screen) == [ [Char("b"), Char("o")], [screen.default_char, screen.default_char], [screen.default_char, screen.default_char], [screen.default_char, screen.default_char], [Char("o"), Char("h")], ] # look, nothing changes! screen.reverse_index() assert (screen.cursor.y, screen.cursor.x) == (1, 0) assert screen.display == ["bo", " ", " ", " ", "oh"] assert tolist(screen) == [ [Char("b"), Char("o")], [screen.default_char, screen.default_char], [screen.default_char, screen.default_char], [screen.default_char, screen.default_char], [Char("o"), Char("h")], ] def test_linefeed(): screen = update(pyte.Screen(2, 2), ["bo", "sh"], [None, None]) screen.set_mode(mo.LNM) # a) LNM on by default (that's what `vttest` forces us to do). assert mo.LNM in screen.mode screen.cursor.x, screen.cursor.y = 1, 0 screen.linefeed() assert (screen.cursor.y, screen.cursor.x) == (1, 0) # b) LNM off. screen.reset_mode(mo.LNM) screen.cursor.x, screen.cursor.y = 1, 0 screen.linefeed() assert (screen.cursor.y, screen.cursor.x) == (1, 1) def test_linefeed_margins(): # See issue #63 on GitHub. screen = pyte.Screen(80, 24) screen.set_margins(3, 27) screen.cursor_position() assert (screen.cursor.y, screen.cursor.x) == (0, 0) screen.linefeed() assert (screen.cursor.y, screen.cursor.x) == (1, 0) def test_tabstops(): screen = pyte.Screen(10, 10) # Making sure initial tabstops are in place ... assert screen.tabstops == set([8]) # ... and clearing them. screen.clear_tab_stop(3) assert not screen.tabstops screen.cursor.x = 1 screen.set_tab_stop() screen.cursor.x = 8 screen.set_tab_stop() screen.cursor.x = 0 screen.tab() assert screen.cursor.x == 1 screen.tab() assert screen.cursor.x == 8 screen.tab() assert screen.cursor.x == 9 screen.tab() assert screen.cursor.x == 9 def test_clear_tabstops(): screen = pyte.Screen(10, 10) screen.clear_tab_stop(3) # a) clear a tabstop at current cusor location screen.cursor.x = 1 screen.set_tab_stop() screen.cursor.x = 5 screen.set_tab_stop() screen.clear_tab_stop() assert screen.tabstops == set([1]) screen.set_tab_stop() screen.clear_tab_stop(0) assert screen.tabstops == set([1]) # b) all tabstops screen.set_tab_stop() screen.cursor.x = 9 screen.set_tab_stop() screen.clear_tab_stop(3) assert not screen.tabstops def test_backspace(): screen = pyte.Screen(2, 2) assert screen.cursor.x == 0 screen.backspace() assert screen.cursor.x == 0 screen.cursor.x = 1 screen.backspace() assert screen.cursor.x == 0 def test_save_cursor(): # a) cursor position screen = pyte.Screen(10, 10) screen.save_cursor() screen.cursor.x, screen.cursor.y = 3, 5 screen.save_cursor() screen.cursor.x, screen.cursor.y = 4, 4 screen.restore_cursor() assert screen.cursor.x == 3 assert screen.cursor.y == 5 screen.restore_cursor() assert screen.cursor.x == 0 assert screen.cursor.y == 0 # b) modes screen = pyte.Screen(10, 10) screen.set_mode(mo.DECAWM, mo.DECOM) screen.save_cursor() screen.reset_mode(mo.DECAWM) screen.restore_cursor() assert mo.DECAWM in screen.mode assert mo.DECOM in screen.mode # c) attributes screen = pyte.Screen(10, 10) screen.select_graphic_rendition(4) screen.save_cursor() screen.select_graphic_rendition(24) assert screen.cursor.attrs == screen.default_char screen.restore_cursor() assert screen.cursor.attrs != screen.default_char assert screen.cursor.attrs == Char(" ", underscore=True) def test_restore_cursor_with_none_saved(): screen = pyte.Screen(10, 10) screen.set_mode(mo.DECOM) screen.cursor.x, screen.cursor.y = 5, 5 screen.restore_cursor() assert (screen.cursor.y, screen.cursor.x) == (0, 0) assert mo.DECOM not in screen.mode def test_restore_cursor_out_of_bounds(): screen = pyte.Screen(10, 10) # a) origin mode off. screen.cursor_position(5, 5) screen.save_cursor() screen.resize(3, 3) screen.reset() screen.restore_cursor() assert (screen.cursor.y, screen.cursor.x) == (2, 2) # b) origin mode is on. screen.resize(10, 10) screen.cursor_position(8, 8) screen.save_cursor() screen.resize(5, 5) screen.reset() screen.set_mode(mo.DECOM) screen.set_margins(2, 3) screen.restore_cursor() assert (screen.cursor.y, screen.cursor.x) == (2, 4) def test_insert_lines(): # a) without margins screen = update(pyte.Screen(3, 3), ["sam", "is ", "foo"], colored=[1]) screen.insert_lines() assert (screen.cursor.y, screen.cursor.x) == (0, 0) assert screen.display == [" ", "sam", "is "] assert tolist(screen) == [ [screen.default_char] * 3, [Char("s"), Char("a"), Char("m")], [Char("i", fg="red"), Char("s", fg="red"), Char(" ", fg="red")], ] screen = update(pyte.Screen(3, 3), ["sam", "is ", "foo"], colored=[1]) screen.insert_lines(2) assert (screen.cursor.y, screen.cursor.x) == (0, 0) assert screen.display == [" ", " ", "sam"] assert tolist(screen) == [ [screen.default_char] * 3, [screen.default_char] * 3, [Char("s"), Char("a"), Char("m")] ] # b) with margins screen = update(pyte.Screen(3, 5), ["sam", "is ", "foo", "bar", "baz"], colored=[2, 3]) screen.set_margins(1, 4) screen.cursor.y = 1 screen.insert_lines(1) assert (screen.cursor.y, screen.cursor.x) == (1, 0) assert screen.display == ["sam", " ", "is ", "foo", "baz"] assert tolist(screen) == [ [Char("s"), Char("a"), Char("m")], [screen.default_char] * 3, [Char("i"), Char("s"), Char(" ")], [Char("f", fg="red"), Char("o", fg="red"), Char("o", fg="red")], [Char("b"), Char("a"), Char("z")], ] screen = update(pyte.Screen(3, 5), ["sam", "is ", "foo", "bar", "baz"], colored=[2, 3]) screen.set_margins(1, 3) screen.cursor.y = 1 screen.insert_lines(1) assert (screen.cursor.y, screen.cursor.x) == (1, 0) assert screen.display == ["sam", " ", "is ", "bar", "baz"] assert tolist(screen) == [ [Char("s"), Char("a"), Char("m")], [screen.default_char] * 3, [Char("i"), Char("s"), Char(" ")], [Char("b", fg="red"), Char("a", fg="red"), Char("r", fg="red")], [Char("b"), Char("a"), Char("z")], ] screen.insert_lines(2) assert (screen.cursor.y, screen.cursor.x) == (1, 0) assert screen.display == ["sam", " ", " ", "bar", "baz"] assert tolist(screen) == [ [Char("s"), Char("a"), Char("m")], [screen.default_char] * 3, [screen.default_char] * 3, [Char("b", fg="red"), Char("a", fg="red"), Char("r", fg="red")], [Char("b"), Char("a"), Char("z")], ] # c) with margins -- trying to insert more than we have available screen = update(pyte.Screen(3, 5), ["sam", "is ", "foo", "bar", "baz"], colored=[2, 3]) screen.set_margins(2, 4) screen.cursor.y = 1 screen.insert_lines(20) assert (screen.cursor.y, screen.cursor.x) == (1, 0) assert screen.display == ["sam", " ", " ", " ", "baz"] assert tolist(screen) == [ [Char("s"), Char("a"), Char("m")], [screen.default_char] * 3, [screen.default_char] * 3, [screen.default_char] * 3, [Char("b"), Char("a"), Char("z")], ] # d) with margins -- trying to insert outside scroll boundaries; # expecting nothing to change screen = update(pyte.Screen(3, 5), ["sam", "is ", "foo", "bar", "baz"], colored=[2, 3]) screen.set_margins(2, 4) screen.insert_lines(5) assert (screen.cursor.y, screen.cursor.x) == (0, 0) assert screen.display == ["sam", "is ", "foo", "bar", "baz"] assert tolist(screen) == [ [Char("s"), Char("a"), Char("m")], [Char("i"), Char("s"), Char(" ")], [Char("f", fg="red"), Char("o", fg="red"), Char("o", fg="red")], [Char("b", fg="red"), Char("a", fg="red"), Char("r", fg="red")], [Char("b"), Char("a"), Char("z")], ] def test_delete_lines(): # a) without margins screen = update(pyte.Screen(3, 3), ["sam", "is ", "foo"], colored=[1]) screen.delete_lines() assert (screen.cursor.y, screen.cursor.x) == (0, 0) assert screen.display == ["is ", "foo", " "] assert tolist(screen) == [ [Char("i", fg="red"), Char("s", fg="red"), Char(" ", fg="red")], [Char("f"), Char("o"), Char("o")], [screen.default_char] * 3, ] screen.delete_lines(0) assert (screen.cursor.y, screen.cursor.x) == (0, 0) assert screen.display == ["foo", " ", " "] assert tolist(screen) == [ [Char("f"), Char("o"), Char("o")], [screen.default_char] * 3, [screen.default_char] * 3, ] # b) with margins screen = update(pyte.Screen(3, 5), ["sam", "is ", "foo", "bar", "baz"], colored=[2, 3]) screen.set_margins(1, 4) screen.cursor.y = 1 screen.delete_lines(1) assert (screen.cursor.y, screen.cursor.x) == (1, 0) assert screen.display == ["sam", "foo", "bar", " ", "baz"] assert tolist(screen) == [ [Char("s"), Char("a"), Char("m")], [Char("f", fg="red"), Char("o", fg="red"), Char("o", fg="red")], [Char("b", fg="red"), Char("a", fg="red"), Char("r", fg="red")], [screen.default_char] * 3, [Char("b"), Char("a"), Char("z")], ] screen = update(pyte.Screen(3, 5), ["sam", "is ", "foo", "bar", "baz"], colored=[2, 3]) screen.set_margins(1, 4) screen.cursor.y = 1 screen.delete_lines(2) assert (screen.cursor.y, screen.cursor.x) == (1, 0) assert screen.display == ["sam", "bar", " ", " ", "baz"] assert tolist(screen) == [ [Char("s"), Char("a"), Char("m")], [Char("b", fg="red"), Char("a", fg="red"), Char("r", fg="red")], [screen.default_char] * 3, [screen.default_char] * 3, [Char("b"), Char("a"), Char("z")], ] # c) with margins -- trying to delete more than we have available screen = update(pyte.Screen(3, 5), ["sam", "is ", "foo", "bar", "baz"], [None, None, [("red", "default")] * 3, [("red", "default")] * 3, None]) screen.set_margins(1, 4) screen.cursor.y = 1 screen.delete_lines(5) assert (screen.cursor.y, screen.cursor.x) == (1, 0) assert screen.display == ["sam", " ", " ", " ", "baz"] assert tolist(screen) == [ [Char("s"), Char("a"), Char("m")], [screen.default_char] * 3, [screen.default_char] * 3, [screen.default_char] * 3, [Char("b"), Char("a"), Char("z")], ] # d) with margins -- trying to delete outside scroll boundaries; # expecting nothing to change screen = update(pyte.Screen(3, 5), ["sam", "is ", "foo", "bar", "baz"], colored=[2, 3]) screen.set_margins(2, 4) screen.cursor.y = 0 screen.delete_lines(5) assert (screen.cursor.y, screen.cursor.x) == (0, 0) assert screen.display == ["sam", "is ", "foo", "bar", "baz"] assert tolist(screen) == [ [Char("s"), Char("a"), Char("m")], [Char("i"), Char("s"), Char(" ")], [Char("f", fg="red"), Char("o", fg="red"), Char("o", fg="red")], [Char("b", fg="red"), Char("a", fg="red"), Char("r", fg="red")], [Char("b"), Char("a"), Char("z")], ] def test_insert_characters(): screen = update(pyte.Screen(3, 4), ["sam", "is ", "foo", "bar"], colored=[0]) # a) normal case cursor = copy.copy(screen.cursor) screen.insert_characters(2) assert (screen.cursor.y, screen.cursor.x) == (cursor.y, cursor.x) assert tolist(screen)[0] == [ screen.default_char, screen.default_char, Char("s", fg="red") ] # b) now inserting from the middle of the line screen.cursor.y, screen.cursor.x = 2, 1 screen.insert_characters(1) assert tolist(screen)[2] == [Char("f"), screen.default_char, Char("o")] # c) inserting more than we have screen.cursor.y, screen.cursor.x = 3, 1 screen.insert_characters(10) assert tolist(screen)[3] == [ Char("b"), screen.default_char, screen.default_char ] # d) 0 is 1 screen = update(pyte.Screen(3, 3), ["sam", "is ", "foo"], colored=[0]) screen.cursor_position() screen.insert_characters() assert tolist(screen)[0] == [ screen.default_char, Char("s", fg="red"), Char("a", fg="red") ] screen = update(pyte.Screen(3, 3), ["sam", "is ", "foo"], colored=[0]) screen.cursor_position() screen.insert_characters(1) assert tolist(screen)[0] == [ screen.default_char, Char("s", fg="red"), Char("a", fg="red") ] def test_delete_characters(): screen = update(pyte.Screen(3, 3), ["sam", "is ", "foo"], colored=[0]) screen.delete_characters(2) assert (screen.cursor.y, screen.cursor.x) == (0, 0) assert screen.display == ["m ", "is ", "foo"] assert tolist(screen)[0] == [ Char("m", fg="red"), screen.default_char, screen.default_char ] screen.cursor.y, screen.cursor.x = 2, 2 screen.delete_characters() assert (screen.cursor.y, screen.cursor.x) == (2, 2) assert screen.display == ["m ", "is ", "fo "] screen.cursor.y, screen.cursor.x = 1, 1 screen.delete_characters(0) assert (screen.cursor.y, screen.cursor.x) == (1, 1) assert screen.display == ["m ", "i ", "fo "] # ! extreme cases. screen = update(pyte.Screen(5, 1), ["12345"], colored=[0]) screen.cursor.x = 1 screen.delete_characters(3) assert (screen.cursor.y, screen.cursor.x) == (0, 1) assert screen.display == ["15 "] assert tolist(screen)[0] == [ Char("1", fg="red"), Char("5", fg="red"), screen.default_char, screen.default_char, screen.default_char ] screen = update(pyte.Screen(5, 1), ["12345"], colored=[0]) screen.cursor.x = 2 screen.delete_characters(10) assert (screen.cursor.y, screen.cursor.x) == (0, 2) assert screen.display == ["12 "] assert tolist(screen)[0] == [ Char("1", fg="red"), Char("2", fg="red"), screen.default_char, screen.default_char, screen.default_char ] screen = update(pyte.Screen(5, 1), ["12345"], colored=[0]) screen.delete_characters(4) assert (screen.cursor.y, screen.cursor.x) == (0, 0) assert screen.display == ["5 "] assert tolist(screen)[0] == [ Char("5", fg="red"), screen.default_char, screen.default_char, screen.default_char, screen.default_char ] def test_erase_character(): screen = update(pyte.Screen(3, 3), ["sam", "is ", "foo"], colored=[0]) screen.erase_characters(2) assert (screen.cursor.y, screen.cursor.x) == (0, 0) assert screen.display == [" m", "is ", "foo"] assert tolist(screen)[0] == [ screen.default_char, screen.default_char, Char("m", fg="red") ] screen.cursor.y, screen.cursor.x = 2, 2 screen.erase_characters() assert (screen.cursor.y, screen.cursor.x) == (2, 2) assert screen.display == [" m", "is ", "fo "] screen.cursor.y, screen.cursor.x = 1, 1 screen.erase_characters(0) assert (screen.cursor.y, screen.cursor.x) == (1, 1) assert screen.display == [" m", "i ", "fo "] # ! extreme cases. screen = update(pyte.Screen(5, 1), ["12345"], colored=[0]) screen.cursor.x = 1 screen.erase_characters(3) assert (screen.cursor.y, screen.cursor.x) == (0, 1) assert screen.display == ["1 5"] assert tolist(screen)[0] == [ Char("1", fg="red"), screen.default_char, screen.default_char, screen.default_char, Char("5", "red") ] screen = update(pyte.Screen(5, 1), ["12345"], colored=[0]) screen.cursor.x = 2 screen.erase_characters(10) assert (screen.cursor.y, screen.cursor.x) == (0, 2) assert screen.display == ["12 "] assert tolist(screen)[0] == [ Char("1", fg="red"), Char("2", fg="red"), screen.default_char, screen.default_char, screen.default_char ] screen = update(pyte.Screen(5, 1), ["12345"], colored=[0]) screen.erase_characters(4) assert (screen.cursor.y, screen.cursor.x) == (0, 0) assert screen.display == [" 5"] assert tolist(screen)[0] == [ screen.default_char, screen.default_char, screen.default_char, screen.default_char, Char("5", fg="red") ] def test_erase_in_line(): screen = update(pyte.Screen(5, 5), ["sam i", "s foo", "but a", "re yo", "u? "], colored=[0]) screen.cursor_position(1, 3) # a) erase from cursor to the end of line screen.erase_in_line(0) assert (screen.cursor.y, screen.cursor.x) == (0, 2) assert screen.display == ["sa ", "s foo", "but a", "re yo", "u? "] assert tolist(screen)[0] == [ Char("s", fg="red"), Char("a", fg="red"), screen.default_char, screen.default_char, screen.default_char ] # b) erase from the beginning of the line to the cursor screen = update(screen, ["sam i", "s foo", "but a", "re yo", "u? "], colored=[0]) screen.erase_in_line(1) assert (screen.cursor.y, screen.cursor.x) == (0, 2) assert screen.display == [" i", "s foo", "but a", "re yo", "u? "] assert tolist(screen)[0] == [ screen.default_char, screen.default_char, screen.default_char, Char(" ", fg="red"), Char("i", fg="red") ] # c) erase the entire line screen = update(screen, ["sam i", "s foo", "but a", "re yo", "u? "], colored=[0]) screen.erase_in_line(2) assert (screen.cursor.y, screen.cursor.x) == (0, 2) assert screen.display == [" ", "s foo", "but a", "re yo", "u? "] assert tolist(screen)[0] == [screen.default_char] * 5 def test_erase_in_display(): screen = update(pyte.Screen(5, 5), ["sam i", "s foo", "but a", "re yo", "u? "], colored=[2, 3]) screen.cursor_position(3, 3) # a) erase from cursor to the end of the display, including # the cursor screen.erase_in_display(0) assert (screen.cursor.y, screen.cursor.x) == (2, 2) assert screen.display == ["sam i", "s foo", "bu ", " ", " "] assert tolist(screen)[2:] == [ [Char("b", fg="red"), Char("u", fg="red"), screen.default_char, screen.default_char, screen.default_char], [screen.default_char] * 5, [screen.default_char] * 5 ] # b) erase from the beginning of the display to the cursor, # including it screen = update(screen, ["sam i", "s foo", "but a", "re yo", "u? "], colored=[2, 3]) screen.erase_in_display(1) assert (screen.cursor.y, screen.cursor.x) == (2, 2) assert screen.display == [" ", " ", " a", "re yo", "u? "] assert tolist(screen)[:3] == [ [screen.default_char] * 5, [screen.default_char] * 5, [screen.default_char, screen.default_char, screen.default_char, Char(" ", fg="red"), Char("a", fg="red")], ] # c) erase the while display screen.erase_in_display(2) assert (screen.cursor.y, screen.cursor.x) == (2, 2) assert screen.display == [" ", " ", " ", " ", " "] assert tolist(screen) == [[screen.default_char] * 5] * 5 def test_cursor_up(): screen = pyte.Screen(10, 10) # Moving the cursor up at the top doesn't do anything screen.cursor_up(1) assert screen.cursor.y == 0 screen.cursor.y = 1 # Moving the cursor past the top moves it to the top screen.cursor_up(10) assert screen.cursor.y == 0 screen.cursor.y = 5 # Can move the cursor more than one up. screen.cursor_up(3) assert screen.cursor.y == 2 def test_cursor_down(): screen = pyte.Screen(10, 10) # Moving the cursor down at the bottom doesn't do anything screen.cursor.y = 9 screen.cursor_down(1) assert screen.cursor.y == 9 screen.cursor.y = 8 # Moving the cursor past the bottom moves it to the bottom screen.cursor_down(10) assert screen.cursor.y == 9 screen.cursor.y = 5 # Can move the cursor more than one down. screen.cursor_down(3) assert screen.cursor.y == 8 def test_cursor_back(): screen = pyte.Screen(10, 10) # Moving the cursor left at the margin doesn't do anything screen.cursor.x = 0 screen.cursor_back(1) assert screen.cursor.x == 0 screen.cursor.x = 3 # Moving the cursor past the left margin moves it to the left margin screen.cursor_back(10) assert screen.cursor.x == 0 screen.cursor.x = 5 # Can move the cursor more than one back. screen.cursor_back(3) assert screen.cursor.x == 2 def test_cursor_back_last_column(): screen = pyte.Screen(13, 1) screen.draw("Hello, world!") assert screen.cursor.x == screen.columns screen.cursor_back(5) assert screen.cursor.x == (screen.columns - 1) - 5 def test_cursor_forward(): screen = pyte.Screen(10, 10) # Moving the cursor right at the margin doesn't do anything screen.cursor.x = 9 screen.cursor_forward(1) assert screen.cursor.x == 9 # Moving the cursor past the right margin moves it to the right margin screen.cursor.x = 8 screen.cursor_forward(10) assert screen.cursor.x == 9 # Can move the cursor more than one forward. screen.cursor.x = 5 screen.cursor_forward(3) assert screen.cursor.x == 8 def test_cursor_position(): screen = pyte.Screen(10, 10) # a) testing that we expect 1-indexed values screen.cursor_position(5, 10) assert (screen.cursor.y, screen.cursor.x) == (4, 9) # b) but (0, 0) is also accepted and should be the same as (1, 1) screen.cursor_position(0, 10) assert (screen.cursor.y, screen.cursor.x) == (0, 9) # c) moving outside the margins constrains to within the screen # bounds screen.cursor_position(100, 5) assert (screen.cursor.y, screen.cursor.x) == (9, 4) screen.cursor_position(5, 100) assert (screen.cursor.y, screen.cursor.x) == (4, 9) # d) DECOM on screen.set_margins(5, 9) screen.set_mode(mo.DECOM) screen.cursor_position() assert (screen.cursor.y, screen.cursor.x) == (4, 0) screen.cursor_position(2, 0) assert (screen.cursor.y, screen.cursor.x) == (5, 0) # Note that cursor position doesn't change. screen.cursor_position(10, 0) assert (screen.cursor.y, screen.cursor.x) == (5, 0) def test_unicode(): screen = pyte.Screen(4, 2) stream = pyte.ByteStream(screen) stream.feed("тест".encode("utf-8")) assert screen.display == ["тест", " "] def test_alignment_display(): screen = pyte.Screen(5, 5) screen.set_mode(mo.LNM) screen.draw("a") screen.linefeed() screen.linefeed() screen.draw("b") assert screen.display == ["a ", " ", "b ", " ", " "] screen.alignment_display() assert screen.display == ["EEEEE", "EEEEE", "EEEEE", "EEEEE", "EEEEE"] def test_set_margins(): screen = pyte.Screen(10, 10) assert screen.margins is None # a) ok-case screen.set_margins(1, 5) assert screen.margins == (0, 4) # b) one of the margins is out of bounds screen.set_margins(100, 10) assert screen.margins != (99, 9) assert screen.margins == (0, 4) # c) no margins provided -- reset to full screen. screen.set_margins() assert screen.margins is None def test_hide_cursor(): screen = pyte.Screen(10, 10) # DECTCEM is set by default. assert mo.DECTCEM in screen.mode assert not screen.cursor.hidden # a) resetting DECTCEM hides the cursor. screen.reset_mode(mo.DECTCEM) assert screen.cursor.hidden # b) ... and it's back! screen.set_mode(mo.DECTCEM) assert not screen.cursor.hidden def test_report_device_attributes(): screen = pyte.Screen(10, 10) acc = [] screen.write_process_input = acc.append # a) noop screen.report_device_attributes(42) assert not acc # b) OK case screen.report_device_attributes() assert acc.pop() == ctrl.CSI + "?6c" def test_report_device_status(): screen = pyte.Screen(10, 10) acc = [] screen.write_process_input = acc.append # a) noop screen.report_device_status(42) assert not acc # b) terminal status screen.report_device_status(5) assert acc.pop() == ctrl.CSI + "0n" # c) cursor position, DECOM off screen.cursor_to_column(5) screen.report_device_status(6) assert acc.pop() == ctrl.CSI + "{0};{1}R".format(1, 5) # d) cursor position, DECOM on screen.cursor_position() screen.set_margins(5, 9) screen.set_mode(mo.DECOM) screen.cursor_to_line(5) screen.report_device_status(6) assert acc.pop() == ctrl.CSI + "{0};{1}R".format(5, 1) def test_screen_set_icon_name_title(): screen = pyte.Screen(10, 1) text = "±" screen.set_icon_name(text) assert screen.icon_name == text screen.set_title(text) assert screen.title == text pyte-0.8.0/tests/test_diff.py0000644f2us0000001005013121234606017574 0ustar s.lebedev00000000000000# -*- coding: utf-8 -*- from __future__ import unicode_literals import pyte from pyte import modes as mo def test_mark_whole_screen(): # .. this is straightforward -- make sure we have a dirty attribute # and whole screen is marked as dirty on initialization, reset, # resize etc. screen = pyte.DiffScreen(80, 24) # a) init. assert hasattr(screen, "dirty") assert isinstance(screen.dirty, set) assert screen.dirty == set(range(screen.lines)) # b) reset(). screen.dirty.clear() screen.reset() assert screen.dirty == set(range(screen.lines)) # c) resize(). screen.dirty.clear() screen.resize(130, 24) assert screen.dirty == set(range(screen.lines)) # d) alignment_display(). screen.dirty.clear() screen.alignment_display() assert screen.dirty == set(range(screen.lines)) def test_mark_single_line(): screen = pyte.DiffScreen(80, 24) # a) draw(). screen.dirty.clear() screen.draw("f") assert len(screen.dirty) == 1 assert screen.cursor.y in screen.dirty # b) rest ... for method in ["insert_characters", "delete_characters", "erase_characters", "erase_in_line"]: screen.dirty.clear() getattr(screen, method)() assert len(screen.dirty) == 1 assert screen.cursor.y in screen.dirty def test_modes(): # Making sure `DECSCNM` triggers a screen to be fully re-drawn. screen = pyte.DiffScreen(80, 24) screen.dirty.clear() screen.set_mode(mo.DECSCNM >> 5, private=True) assert screen.dirty == set(range(screen.lines)) screen.dirty.clear() screen.reset_mode(mo.DECSCNM >> 5, private=True) assert screen.dirty == set(range(screen.lines)) def test_index(): screen = pyte.DiffScreen(80, 24) screen.dirty.clear() # a) not at the bottom margin -- nothing is marked dirty. screen.index() assert not screen.dirty # b) whole screen is dirty. screen.cursor_to_line(24) screen.index() assert screen.dirty == set(range(screen.lines)) def test_reverse_index(): screen = pyte.DiffScreen(80, 24) screen.dirty.clear() # a) not at the top margin -- whole screen is dirty. screen.reverse_index() assert screen.dirty == set(range(screen.lines)) # b) nothing is marked dirty. screen.dirty.clear() screen.cursor_to_line(screen.lines // 2) screen.reverse_index() assert not screen.dirty def test_insert_delete_lines(): screen = pyte.DiffScreen(80, 24) screen.cursor_to_line(screen.lines // 2) for method in ["insert_lines", "delete_lines"]: screen.dirty.clear() getattr(screen, method)() assert screen.dirty == set(range(screen.cursor.y, screen.lines)) def test_erase_in_display(): screen = pyte.DiffScreen(80, 24) screen.cursor_to_line(screen.lines // 2) # a) from cursor to the end of the screen. screen.dirty.clear() screen.erase_in_display() assert screen.dirty == set(range(screen.cursor.y, screen.lines)) # b) from the begining of the screen to cursor. screen.dirty.clear() screen.erase_in_display(1) assert screen.dirty == set(range(0, screen.cursor.y + 1)) # c) whole screen. screen.dirty.clear() screen.erase_in_display(2) assert screen.dirty == set(range(0, screen.lines)) screen.dirty.clear() screen.erase_in_display(3) assert screen.dirty == set(range(0, screen.lines)) def test_draw_wrap(): screen = pyte.DiffScreen(80, 24) screen.set_mode(mo.DECAWM) # fill every character cell on the first row for _ in range(80): screen.draw("g") assert screen.cursor.y == 0 screen.dirty.clear() # now write one more character which should cause wrapping screen.draw("h") assert screen.cursor.y == 1 # regression test issue #36 where the wrong line was marked as # dirty assert screen.dirty == set([0, 1]) def test_draw_multiple_chars_wrap(): screen = pyte.Screen(5, 2) screen.dirty.clear() screen.draw("1234567890") assert screen.cursor.y == 1 assert screen.dirty == set([0, 1]) pyte-0.8.0/tests/test_history.py0000644f2us0000003076313261754104020407 0ustar s.lebedev00000000000000# -*- coding: utf-8 -*- from __future__ import unicode_literals import os import pyte from pyte import control as ctrl, modes as mo from pyte.compat import str def chars(history_lines, columns): return ["".join(history_lines[y][x].data for x in range(columns)) for y in range(len(history_lines))] def test_index(): screen = pyte.HistoryScreen(5, 5, history=50) # Filling the screen with line numbers, so it's easier to # track history contents. for idx in range(screen.lines): screen.draw(str(idx)) if idx != screen.lines - 1: screen.linefeed() assert not screen.history.top assert not screen.history.bottom # a) first index, expecting top history to be updated. line = screen.buffer[0] screen.index() assert screen.history.top assert screen.history.top[-1] == line # b) second index. line = screen.buffer[0] screen.index() assert len(screen.history.top) == 2 assert screen.history.top[-1] == line # c) rotation. for _ in range(screen.history.size * 2): screen.index() assert len(screen.history.top) == 50 def test_reverse_index(): screen = pyte.HistoryScreen(5, 5, history=50) # Filling the screen with line numbers, so it's easier to # track history contents. for idx in range(len(screen.buffer)): screen.draw(str(idx)) if idx != len(screen.buffer) - 1: screen.linefeed() assert not screen.history.top assert not screen.history.bottom screen.cursor_position() # a) first index, expecting top history to be updated. line = screen.buffer[-1] screen.reverse_index() assert screen.history.bottom assert screen.history.bottom[0] == line # b) second index. line = screen.buffer[-1] screen.reverse_index() assert len(screen.history.bottom) == 2 assert screen.history.bottom[1] == line # c) rotation. for _ in range(len(screen.buffer) ** screen.lines): screen.reverse_index() assert len(screen.history.bottom) == 50 def test_prev_page(): screen = pyte.HistoryScreen(4, 4, history=40) screen.set_mode(mo.LNM) assert screen.history.position == 40 # Once again filling the screen with line numbers, but this time, # we need them to span on multiple lines. for idx in range(screen.lines * 10): screen.draw(str(idx)) screen.linefeed() assert screen.history.top assert not screen.history.bottom assert screen.history.position == 40 assert screen.display == [ "37 ", "38 ", "39 ", " " ] assert chars(screen.history.top, screen.columns)[-4:] == [ "33 ", "34 ", "35 ", "36 " ] # a) first page up. screen.prev_page() assert screen.history.position == 38 assert len(screen.buffer) == screen.lines assert screen.display == [ "35 ", "36 ", "37 ", "38 " ] assert chars(screen.history.top, screen.columns)[-4:] == [ "31 ", "32 ", "33 ", "34 " ] assert len(screen.history.bottom) == 2 assert chars(screen.history.bottom, screen.columns) == [ "39 ", " ", ] # b) second page up. screen.prev_page() assert screen.history.position == 36 assert len(screen.buffer) == screen.lines assert screen.display == [ "33 ", "34 ", "35 ", "36 ", ] assert len(screen.history.bottom) == 4 assert chars(screen.history.bottom, screen.columns) == [ "37 ", "38 ", "39 ", " ", ] # c) same with odd number of lines. screen = pyte.HistoryScreen(5, 5, history=50) screen.set_mode(mo.LNM) for idx in range(screen.lines * 10): screen.draw(str(idx)) screen.linefeed() assert screen.history.top assert not screen.history.bottom assert screen.history.position == 50 assert screen.display == [ "46 ", "47 ", "48 ", "49 ", " " ] screen.prev_page() assert screen.history.position == 47 assert screen.display == [ "43 ", "44 ", "45 ", "46 ", "47 " ] assert len(screen.history.bottom) == 3 assert chars(screen.history.bottom, screen.columns) == [ "48 ", "49 ", " ", ] # d) with a ratio other than 0.5 screen = pyte.HistoryScreen(4, 4, history=40, ratio=0.75) screen.set_mode(mo.LNM) for idx in range(screen.lines * 10): screen.draw(str(idx)) screen.linefeed() assert screen.history.top assert not screen.history.bottom assert screen.history.position == 40 assert screen.display == [ "37 ", "38 ", "39 ", " " ] screen.prev_page() assert screen.history.position == 37 assert screen.display == [ "34 ", "35 ", "36 ", "37 " ] assert len(screen.history.bottom) == 3 assert chars(screen.history.bottom, screen.columns) == [ "38 ", "39 ", " " ] # e) same with cursor in the middle of the screen. screen = pyte.HistoryScreen(5, 5, history=50) screen.set_mode(mo.LNM) for idx in range(screen.lines * 10): screen.draw(str(idx)) screen.linefeed() assert screen.history.top assert not screen.history.bottom assert screen.history.position == 50 assert screen.display == [ "46 ", "47 ", "48 ", "49 ", " " ] screen.cursor_to_line(screen.lines // 2) while screen.history.position > screen.lines: screen.prev_page() assert screen.history.position == screen.lines assert len(screen.buffer) == screen.lines assert screen.display == [ "1 ", "2 ", "3 ", "4 ", "5 " ] while screen.history.position < screen.history.size: screen.next_page() assert screen.history.position == screen.history.size assert screen.display == [ "46 ", "47 ", "48 ", "49 ", " " ] # e) same with cursor near the middle of the screen. screen = pyte.HistoryScreen(5, 5, history=50) screen.set_mode(mo.LNM) for idx in range(screen.lines * 10): screen.draw(str(idx)) screen.linefeed() assert screen.history.top assert not screen.history.bottom assert screen.history.position == 50 assert screen.display == [ "46 ", "47 ", "48 ", "49 ", " " ] screen.cursor_to_line(screen.lines // 2 - 2) while screen.history.position > screen.lines: screen.prev_page() assert screen.history.position == screen.lines assert len(screen.buffer) == screen.lines assert screen.display == [ "1 ", "2 ", "3 ", "4 ", "5 " ] while screen.history.position < screen.history.size: screen.next_page() assert screen.history.position == screen.history.size assert len(screen.buffer) == screen.lines assert screen.display == [ "46 ", "47 ", "48 ", "49 ", " " ] def test_next_page(): screen = pyte.HistoryScreen(5, 5, history=50) screen.set_mode(mo.LNM) # Once again filling the screen with line numbers, but this time, # we need them to span on multiple lines. for idx in range(screen.lines * 5): screen.draw(str(idx)) screen.linefeed() assert screen.history.top assert not screen.history.bottom assert screen.history.position == 50 assert screen.display == [ "21 ", "22 ", "23 ", "24 ", " " ] # a) page up -- page down. screen.prev_page() screen.next_page() assert screen.history.top assert not screen.history.bottom assert screen.history.position == 50 assert screen.display == [ "21 ", "22 ", "23 ", "24 ", " " ] # b) double page up -- page down. screen.prev_page() screen.prev_page() screen.next_page() assert screen.history.position == 47 assert screen.history.top assert chars(screen.history.bottom, screen.columns) == [ "23 ", "24 ", " " ] assert screen.display == [ "18 ", "19 ", "20 ", "21 ", "22 " ] # c) double page up -- double page down screen.prev_page() screen.prev_page() screen.next_page() screen.next_page() assert screen.history.position == 47 assert len(screen.buffer) == screen.lines assert screen.display == [ "18 ", "19 ", "20 ", "21 ", "22 " ] def test_ensure_width(monkeypatch): screen = pyte.HistoryScreen(5, 5, history=50) screen.set_mode(mo.LNM) escape = dict(pyte.Stream.escape) escape.update({"N": "next_page", "P": "prev_page"}) monkeypatch.setattr(pyte.Stream, "escape", escape) stream = pyte.Stream(screen) for idx in range(screen.lines * 5): stream.feed("{0:04d}".format(idx) + os.linesep) assert screen.display == [ "0021 ", "0022 ", "0023 ", "0024 ", " " ] # Shrinking the screen should truncate the displayed lines following lines. screen.resize(5, 3) stream.feed(ctrl.ESC + "P") # Inequality because we have an all-empty last line. assert all(len(l) <= 3 for l in screen.history.bottom) assert screen.display == [ "001", # 18 "001", # 19 "002", # 20 "002", # 21 "002" # 22 ] def test_not_enough_lines(): screen = pyte.HistoryScreen(5, 5, history=6) screen.set_mode(mo.LNM) for idx in range(screen.lines): screen.draw(str(idx)) screen.linefeed() assert screen.history.top assert not screen.history.bottom assert screen.history.position == 6 assert screen.display == [ "1 ", "2 ", "3 ", "4 ", " " ] screen.prev_page() assert not screen.history.top assert len(screen.history.bottom) is 1 assert chars(screen.history.bottom, screen.columns) == [" "] assert screen.display == [ "0 ", "1 ", "2 ", "3 ", "4 ", ] screen.next_page() assert screen.history.top assert not screen.history.bottom assert screen.display == [ "1 ", "2 ", "3 ", "4 ", " " ] def test_draw(monkeypatch): screen = pyte.HistoryScreen(5, 5, history=50) screen.set_mode(mo.LNM) escape = dict(pyte.Stream.escape) escape.update({"N": "next_page", "P": "prev_page"}) monkeypatch.setattr(pyte.Stream, "escape", escape) stream = pyte.Stream(screen) for idx in range(screen.lines * 5): stream.feed(str(idx) + os.linesep) assert screen.display == [ "21 ", "22 ", "23 ", "24 ", " " ] # a) doing a pageup and then a draw -- expecting the screen # to scroll to the bottom before drawing anything. stream.feed(ctrl.ESC + "P") stream.feed(ctrl.ESC + "P") stream.feed(ctrl.ESC + "N") stream.feed("x") assert screen.display == [ "21 ", "22 ", "23 ", "24 ", "x " ] def test_cursor_is_hidden(monkeypatch): screen = pyte.HistoryScreen(5, 5, history=50) escape = dict(pyte.Stream.escape) escape.update({"N": "next_page", "P": "prev_page"}) monkeypatch.setattr(pyte.Stream, "escape", escape) stream = pyte.Stream(screen) for idx in range(screen.lines * 5): stream.feed(str(idx) + os.linesep) assert not screen.cursor.hidden stream.feed(ctrl.ESC + "P") assert screen.cursor.hidden stream.feed(ctrl.ESC + "P") assert screen.cursor.hidden stream.feed(ctrl.ESC + "N") assert screen.cursor.hidden stream.feed(ctrl.ESC + "N") assert not screen.cursor.hidden def test_erase_in_display(): screen = pyte.HistoryScreen(5, 5, history=6) screen.set_mode(mo.LNM) for idx in range(screen.lines): screen.draw(str(idx)) screen.linefeed() screen.prev_page() # See #80 on GitHub for details. screen.erase_in_display(3) assert not screen.history.top assert not screen.history.bottom pyte-0.8.0/tests/test_stream.py0000644f2us0000001737213261754104020202 0ustar s.lebedev00000000000000# -*- coding: utf-8 -*- from __future__ import unicode_literals import sys if sys.version_info[0] == 2: from cStringIO import StringIO else: from io import StringIO import pytest import pyte from pyte import charsets as cs, control as ctrl, escape as esc class counter(object): def __init__(self): self.count = 0 def __call__(self, *args, **kwargs): self.count += 1 class argcheck(counter): def __call__(self, *args, **kwargs): self.args = args self.kwargs = kwargs super(argcheck, self).__call__() class argstore(object): def __init__(self): self.seen = [] def __call__(self, *args): self.seen.extend(args) def test_basic_sequences(): for cmd, event in pyte.Stream.escape.items(): screen = pyte.Screen(80, 24) handler = counter() setattr(screen, event, handler) stream = pyte.Stream(screen) stream.feed(ctrl.ESC) assert not handler.count stream.feed(cmd) assert handler.count == 1, event def test_linefeed(): # ``linefeed`` is somewhat an exception, there's three ways to # trigger it. handler = counter() screen = pyte.Screen(80, 24) screen.linefeed = handler stream = pyte.Stream(screen) stream.feed(ctrl.LF + ctrl.VT + ctrl.FF) assert handler.count == 3 def test_unknown_sequences(): handler = argcheck() screen = pyte.Screen(80, 24) screen.debug = handler stream = pyte.Stream(screen) stream.feed(ctrl.CSI + "6;Z") assert handler.count == 1 assert handler.args == (6, 0) assert handler.kwargs == {} def test_non_csi_sequences(): for cmd, event in pyte.Stream.csi.items(): # a) single param handler = argcheck() screen = pyte.Screen(80, 24) setattr(screen, event, handler) stream = pyte.Stream(screen) stream.feed(ctrl.ESC + "[5" + cmd) assert handler.count == 1 assert handler.args == (5, ) # b) multiple params, and starts with CSI, not ESC [ handler = argcheck() screen = pyte.Screen(80, 24) setattr(screen, event, handler) stream = pyte.Stream(screen) stream.feed(ctrl.CSI + "5;12" + cmd) assert handler.count == 1 assert handler.args == (5, 12) def test_set_mode(): bugger = counter() screen = pyte.Screen(80, 24) handler = argcheck() screen.debug = bugger screen.set_mode = handler stream = pyte.Stream(screen) stream.feed(ctrl.CSI + "?9;2h") assert not bugger.count assert handler.count == 1 assert handler.args == (9, 2) assert handler.kwargs == {"private": True} def test_reset_mode(): bugger = counter() screen = pyte.Screen(80, 24) handler = argcheck() screen.debug = bugger screen.reset_mode = handler stream = pyte.Stream(screen) stream.feed(ctrl.CSI + "?9;2l") assert not bugger.count assert handler.count == 1 assert handler.args == (9, 2) def test_missing_params(): handler = argcheck() screen = pyte.Screen(80, 24) screen.cursor_position = handler stream = pyte.Stream(screen) stream.feed(ctrl.CSI + ";" + esc.HVP) assert handler.count == 1 assert handler.args == (0, 0) def test_overflow(): handler = argcheck() screen = pyte.Screen(80, 24) screen.cursor_position = handler stream = pyte.Stream(screen) stream.feed(ctrl.CSI + "999999999999999;99999999999999" + esc.HVP) assert handler.count == 1 assert handler.args == (9999, 9999) def test_interrupt(): bugger = argstore() handler = argcheck() screen = pyte.Screen(80, 24) screen.draw = bugger screen.cursor_position = handler stream = pyte.Stream(screen) stream.feed(ctrl.CSI + "10;" + ctrl.SUB + "10" + esc.HVP) assert not handler.count assert bugger.seen == [ ctrl.SUB, "10" + esc.HVP ] def test_control_characters(): handler = argcheck() screen = pyte.Screen(80, 24) screen.cursor_position = handler stream = pyte.Stream(screen) stream.feed(ctrl.CSI + "10;\t\t\n\r\n10" + esc.HVP) assert handler.count == 1 assert handler.args == (10, 10) @pytest.mark.parametrize('osc,st', [ (ctrl.OSC_C0, ctrl.ST_C0), (ctrl.OSC_C0, ctrl.ST_C1), (ctrl.OSC_C1, ctrl.ST_C0), (ctrl.OSC_C1, ctrl.ST_C1) ]) def test_set_title_icon_name(osc, st): screen = pyte.Screen(80, 24) stream = pyte.Stream(screen) # a) set only icon name stream.feed(osc + "1;foo" + st) assert screen.icon_name == "foo" # b) set only title stream.feed(osc + "2;foo" + st) assert screen.title == "foo" # c) set both icon name and title stream.feed(osc + "0;bar" + st) assert screen.title == screen.icon_name == "bar" # d) set both icon name and title then terminate with BEL stream.feed(osc + "0;bar" + st) assert screen.title == screen.icon_name == "bar" # e) test ➜ ('\xe2\x9e\x9c') symbol, that contains string terminator \x9c stream.feed("➜") assert screen.buffer[0][0].data == "➜" def test_compatibility_api(): screen = pyte.Screen(80, 24) stream = pyte.Stream() stream.attach(screen) # All of the following shouldn't raise errors. # a) adding more than one listener stream.attach(pyte.Screen(80, 24)) # b) feeding text stream.feed("привет") # c) detaching an attached screen. stream.detach(screen) def test_define_charset(): # Should be a noop. All input is UTF8. screen = pyte.Screen(3, 3) stream = pyte.Stream(screen) stream.feed(ctrl.ESC + "(B") assert screen.display[0] == " " * 3 def test_non_utf8_shifts(): screen = pyte.Screen(3, 3) handler = screen.shift_in = screen.shift_out = argcheck() stream = pyte.Stream(screen) stream.use_utf8 = False stream.feed(ctrl.SI) stream.feed(ctrl.SO) assert handler.count == 2 @pytest.mark.parametrize("input,expected", [ (b"foo", [["draw", ["foo"], {}]]), (b"\x1b[1;24r\x1b[4l\x1b[24;1H", [ ["set_margins", [1, 24], {}], ["reset_mode", [4], {}], ["cursor_position", [24, 1], {}]]) ]) def test_debug_stream(input, expected): output = StringIO() stream = pyte.ByteStream(pyte.DebugScreen(to=output)) stream.feed(input) output.seek(0) assert [eval(line) for line in output] == expected def test_byte_stream_feed(): screen = pyte.Screen(20, 1) screen.draw = handler = argcheck() stream = pyte.ByteStream(screen) stream.feed("Нерусский текст".encode("utf-8")) assert handler.count == 1 assert handler.args == ("Нерусский текст", ) def test_byte_stream_define_charset_unknown(): screen = pyte.Screen(3, 3) stream = pyte.ByteStream(screen) stream.select_other_charset("@") default_g0_charset = screen.g0_charset # ``"Z"`` is not supported by Linux terminal, so expect a noop. assert "Z" not in cs.MAPS stream.feed((ctrl.ESC + "(Z").encode()) assert screen.display[0] == " " * 3 assert screen.g0_charset == default_g0_charset @pytest.mark.parametrize("charset,mapping", cs.MAPS.items()) def test_byte_stream_define_charset(charset, mapping): screen = pyte.Screen(3, 3) stream = pyte.ByteStream(screen) stream.select_other_charset("@") stream.feed((ctrl.ESC + "(" + charset).encode()) assert screen.display[0] == " " * 3 assert screen.g0_charset == mapping def test_byte_stream_select_other_charset(): stream = pyte.ByteStream(pyte.Screen(3, 3)) assert stream.use_utf8 # on by default. # a) disable utf-8 stream.select_other_charset("@") assert not stream.use_utf8 # b) unknown code -- noop stream.select_other_charset("X") assert not stream.use_utf8 # c) enable utf-8 stream.select_other_charset("G") assert stream.use_utf8 pyte-0.8.0/MANIFEST.in0000644f2us0000000034513261755565015676 0ustar s.lebedev00000000000000include MANIFEST.in include AUTHORS include CHANGES include LICENSE include README recursive-include docs *.rst include docs/conf.py recursive-include examples *.py recursive-include tests *.py recursive-include tests/captured pyte-0.8.0/docs/0000755f2us0000000000013261757021015053 5ustar s.lebedev00000000000000pyte-0.8.0/docs/index.rst0000644f2us0000000220313120451262016701 0ustar s.lebedev00000000000000.. include:: ../README ``pyte`` users -------------- Believe it or not, there're projects which actually need a terminal emulator library. Not many of them use ``pyte``, though. Here's a shortlist the ones that do: * `Ajenti `_ -- a webadmin panel for Linux and BSD, which uses ``pyte`` for its terminal plugin. * `Pymux `_ -- a terminal multiplexor. * `BastionSSH `_ -- a tool for protecting, monitoring and accessing multiple SSH resources. * `Jumpserver `_ -- an open source springboard machine(fortress machine): authentication, authorization, audit, automated operation and maintenance. .. note:: Using ``pyte``? Add yourself to this list and submit a pull request. Show me the code! ----------------- Head over to our brief :ref:`tutorial` or, if you're feeling brave, dive right into the :ref:`api`; ``pyte`` also has a couple of examples in the `examples `_ directory. .. toctree:: tutorial api changelog pyte-0.8.0/docs/conf.py0000644f2us0000001613713261756156016372 0ustar s.lebedev00000000000000# -*- coding: utf-8 -*- # # pyte documentation build configuration file, created by # sphinx-quickstart on Fri Apr 8 12:49:51 2011. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys, os # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. sys.path.insert(0, os.path.abspath('..')) # -- General configuration ----------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = ['sphinx.ext.autodoc', 'sphinx.ext.todo', 'sphinx.ext.intersphinx', 'sphinx.ext.doctest', 'sphinx.ext.linkcode'] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'pyte' copyright = u'2011-2012 Selectel, 2012-2017 pyte authors and contributors' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = '0.8.0' # The full version, including alpha/beta/rc tags. release = '0.8.0' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # The reST default role (used for this markup: `text`) to use for all documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] linkcode_base_url = "https://github.com/selectel/pyte/tree/" def resolve_tag(): from urllib.request import urlopen from urllib.error import HTTPError try: urlopen(linkcode_base_url + release) except HTTPError: return "master" else: return release tag = resolve_tag() # Resolve function for the linkcode extension. def linkcode_resolve(domain, info): def find_source(): # try to find the file and line number, based on code from numpy: # https://github.com/numpy/numpy/blob/master/doc/source/conf.py#L286 obj = sys.modules[info['module']] for part in info['fullname'].split('.'): obj = getattr(obj, part) import inspect import os import pyte fn = inspect.getsourcefile(obj) fn = os.path.relpath(fn, os.path.dirname(pyte.__file__)) source, lineno = inspect.getsourcelines(obj) return fn, lineno, lineno + len(source) - 1 try: filename = 'pyte/%s#L%d-L%d' % find_source() except Exception: return None # Failed to resolve source or line numbers. return linkcode_base_url + "%s/%s" % (tag, filename) # -- Options for HTML output --------------------------------------------------- ## Read the docs style: try: import sphinx_rtd_theme except ImportError: html_theme = 'classic' else: html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] html_theme = 'sphinx_rtd_theme' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # " v documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". #html_static_path = ['_static'] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'pytedoc' # Example configuration for intersphinx: refer to the Python standard library. intersphinx_mapping = {'http://docs.python.org/': None} autodoc_member_order = 'bysource' todo_include_todos = True pyte-0.8.0/docs/tutorial.rst0000644f2us0000000667713062755665017503 0ustar s.lebedev00000000000000.. _tutorial: Tutorial -------- There are two important classes in ``pyte``: :class:`~pyte.screens.Screen` and :class:`~pyte.streams.Stream`. The `Screen` is the terminal screen emulator. It maintains an in-memory buffer of text and text-attributes to display. The `Stream` is the stream processor. It processes the input and dispatches events. Events are things like ``LINEFEED``, ``DRAW "a"``, or ``CURSOR_POSITION 10 10``. See the :ref:`API reference ` for more details. In general, if you just want to know what's being displayed on screen you can do something like the following: >>> from __future__ import unicode_literals >>> import pyte >>> screen = pyte.Screen(80, 24) >>> stream = pyte.Stream(screen) >>> stream.feed(b"Hello World!") >>> screen.display ['Hello World! ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '] **Note**: ``Screen`` has no idea what is the source of bytes fed into ``Stream``, so, obviously, it **can't read** or **change** environment variables, which implies that: * it doesn't adjust `LINES` and `COLUMNS` on ``"resize"`` event; * it doesn't use locale settings (`LC_*` and `LANG`); * it doesn't use `TERM` value and expects it to be `"linux"` and only `"linux"`. And that's it for Hello World! Head over to the `examples `_ for more. pyte-0.8.0/docs/changelog.rst0000644f2us0000000003013062755665017540 0ustar s.lebedev00000000000000.. include:: ../CHANGES pyte-0.8.0/docs/api.rst0000644f2us0000000200213120451030016331 0ustar s.lebedev00000000000000.. _api: API reference ============= .. automodule:: pyte.streams pyte.Stream ^^^^^^^^^^^ .. autoclass:: pyte.Stream pyte.ByteStream ^^^^^^^^^^^^^^^ .. autoclass:: pyte.ByteStream .. automodule:: pyte.screens pyte.screens.Screen ^^^^^^^^^^^^^^^^^^^ .. autoclass:: pyte.screens.Cursor :members: .. autoclass:: pyte.screens.Char :members: .. autoclass:: pyte.screens.Screen :members: pyte.screens.DiffScreen ^^^^^^^^^^^^^^^^^^^^^^^ .. autoclass:: pyte.screens.DiffScreen pyte.screens.HistoryScreen ^^^^^^^^^^^^^^^^^^^^^^^^^^ .. autoclass:: pyte.screens.History .. autoclass:: pyte.screens.HistoryScreen :members: pyte.screens.DebugScreen ^^^^^^^^^^^^^^^^^^^^^^^^ .. autoclass:: pyte.screens.DebugScreen .. automodule:: pyte.modes :members: .. automodule:: pyte.control :members: .. automodule:: pyte.escape :members: .. automodule:: pyte.graphics :members: .. automodule:: pyte.charsets :members: pyte-0.8.0/pyte.egg-info/0000755f2us0000000000013261757021016576 5ustar s.lebedev00000000000000pyte-0.8.0/pyte.egg-info/PKG-INFO0000644f2us0000000623413261757020017677 0ustar s.lebedev00000000000000Metadata-Version: 1.1 Name: pyte Version: 0.8.0 Summary: Simple VTXXX-compatible terminal emulator. Home-page: https://github.com/selectel/pyte Author: Sergei Lebedev Author-email: superbobry@gmail.com License: UNKNOWN Description: .. -*- mode: rst -*- :: _ | | _ __ _ _ | |_ ___ | '_ \ | | | || __|/ _ \ | |_) || |_| || |_| __/ | .__/ \__, | \__|\___| | | __/ | |_| |___/ 0.8.0 What is ``pyte``? ----------------- It's an in memory VTXXX-compatible terminal emulator. *XXX* stands for a series of video terminals, developed by `DEC `_ between 1970 and 1995. The first, and probably the most famous one, was VT100 terminal, which is now a de-facto standard for all virtual terminal emulators. ``pyte`` follows the suit. So, why would one need a terminal emulator library? * To screen scrape terminal apps, for example ``htop`` or ``aptitude``. * To write cross platform terminal emulators; either with a graphical (`xterm `_, `rxvt `_) or a web interface, like `AjaxTerm `_. * To have fun, hacking on the ancient, poorly documented technologies. **Note**: ``pyte`` started as a fork of `vt102 `_, which is an incomplete pure Python implementation of VT100 terminal. Installation ------------ If you have `pip `_ you can do the usual:: pip install pyte Otherwise, download the source from `GitHub `_ and run:: python setup.py install Similar projects ---------------- ``pyte`` is not alone in the weird world of terminal emulator libraries, here's a few other options worth checking out: `Termemulator `_, `pyqonsole `_, `webtty `_, `AjaxTerm `_ and of course `vt102 `_. Keywords: vt102,vte,terminal emulator Platform: any Classifier: Development Status :: 5 - Production/Stable Classifier: Environment :: Console Classifier: Intended Audience :: Developers Classifier: Operating System :: OS Independent Classifier: License :: OSI Approved :: GNU Lesser General Public License v3 (LGPLv3) Classifier: Programming Language :: Python :: 2.6 Classifier: Programming Language :: Python :: 2.7 Classifier: Programming Language :: Python :: 3.5 Classifier: Programming Language :: Python :: 3.6 Classifier: Topic :: Terminals :: Terminal Emulators/X Terminals pyte-0.8.0/pyte.egg-info/SOURCES.txt0000644f2us0000000123613261757020020463 0ustar s.lebedev00000000000000AUTHORS CHANGES LICENSE MANIFEST.in README setup.cfg setup.py docs/api.rst docs/changelog.rst docs/conf.py docs/index.rst docs/tutorial.rst examples/capture.py examples/debug.py examples/helloworld.py examples/history.py examples/nanoterm.py examples/webterm.py pyte/__init__.py pyte/__main__.py pyte/charsets.py pyte/compat.py pyte/control.py pyte/escape.py pyte/graphics.py pyte/modes.py pyte/screens.py pyte/streams.py pyte.egg-info/PKG-INFO pyte.egg-info/SOURCES.txt pyte.egg-info/dependency_links.txt pyte.egg-info/requires.txt pyte.egg-info/top_level.txt tests/test_diff.py tests/test_history.py tests/test_input_output.py tests/test_screen.py tests/test_stream.pypyte-0.8.0/pyte.egg-info/requires.txt0000644f2us0000000001013261757020021164 0ustar s.lebedev00000000000000wcwidth pyte-0.8.0/pyte.egg-info/top_level.txt0000644f2us0000000000513261757020021322 0ustar s.lebedev00000000000000pyte pyte-0.8.0/pyte.egg-info/dependency_links.txt0000644f2us0000000000113261757020022643 0ustar s.lebedev00000000000000 pyte-0.8.0/README0000644f2us0000000362313261756144015014 0ustar s.lebedev00000000000000.. -*- mode: rst -*- :: _ | | _ __ _ _ | |_ ___ | '_ \ | | | || __|/ _ \ | |_) || |_| || |_| __/ | .__/ \__, | \__|\___| | | __/ | |_| |___/ 0.8.0 What is ``pyte``? ----------------- It's an in memory VTXXX-compatible terminal emulator. *XXX* stands for a series of video terminals, developed by `DEC `_ between 1970 and 1995. The first, and probably the most famous one, was VT100 terminal, which is now a de-facto standard for all virtual terminal emulators. ``pyte`` follows the suit. So, why would one need a terminal emulator library? * To screen scrape terminal apps, for example ``htop`` or ``aptitude``. * To write cross platform terminal emulators; either with a graphical (`xterm `_, `rxvt `_) or a web interface, like `AjaxTerm `_. * To have fun, hacking on the ancient, poorly documented technologies. **Note**: ``pyte`` started as a fork of `vt102 `_, which is an incomplete pure Python implementation of VT100 terminal. Installation ------------ If you have `pip `_ you can do the usual:: pip install pyte Otherwise, download the source from `GitHub `_ and run:: python setup.py install Similar projects ---------------- ``pyte`` is not alone in the weird world of terminal emulator libraries, here's a few other options worth checking out: `Termemulator `_, `pyqonsole `_, `webtty `_, `AjaxTerm `_ and of course `vt102 `_. pyte-0.8.0/setup.py0000755f2us0000000241713261756133015647 0ustar s.lebedev00000000000000#! /usr/bin/env python # -*- coding: utf-8 -*- import os from setuptools import setup here = os.path.abspath(os.path.dirname(__file__)) DESCRIPTION = "Simple VTXXX-compatible terminal emulator." try: LONG_DESCRIPTION = open(os.path.join(here, "README")).read() except IOError: LONG_DESCRIPTION = "" CLASSIFIERS = [ "Development Status :: 5 - Production/Stable", "Environment :: Console", "Intended Audience :: Developers", "Operating System :: OS Independent", "License :: OSI Approved :: GNU Lesser General Public License v3 (LGPLv3)", "Programming Language :: Python :: 2.6", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3.5", "Programming Language :: Python :: 3.6", "Topic :: Terminals :: Terminal Emulators/X Terminals", ] setup(name="pyte", version="0.8.0", packages=["pyte"], install_requires=["wcwidth"], setup_requires=["pytest-runner"], tests_require=["pytest"], platforms=["any"], author="Sergei Lebedev", author_email="superbobry@gmail.com", description=DESCRIPTION, long_description=LONG_DESCRIPTION, classifiers=CLASSIFIERS, keywords=["vt102", "vte", "terminal emulator"], url="https://github.com/selectel/pyte") pyte-0.8.0/examples/0000755f2us0000000000013261757021015741 5ustar s.lebedev00000000000000pyte-0.8.0/examples/nanoterm.py0000644f2us0000000235213062755665020153 0ustar s.lebedev00000000000000# -*- coding: utf-8 -*- """ nanoterm ~~~~~~~~ An example showing how to feed :class:`~pyte.streams.Stream` from a running terminal app. :copyright: (c) 2015 by pyte authors and contributors, see AUTHORS for details. :license: LGPL, see LICENSE for more details. """ from __future__ import print_function, unicode_literals import os import pty import select import signal import sys import pyte if __name__ == "__main__": if len(sys.argv) <= 1: sys.exit("usage: %prog% command [args]") screen = pyte.Screen(80, 24) stream = pyte.ByteStream(screen) p_pid, master_fd = pty.fork() if p_pid == 0: # Child. os.execvpe(sys.argv[1], sys.argv[1:], env=dict(TERM="linux", COLUMNS="80", LINES="24")) while True: try: [_master_fd], _wlist, _xlist = select.select( [master_fd], [], [], 1) except (KeyboardInterrupt, # Stop right now! ValueError): # Nothing to read. break else: data = os.read(master_fd, 1024) if not data: break stream.feed(data) os.kill(p_pid, signal.SIGTERM) print(*screen.display, sep="\n") pyte-0.8.0/examples/webterm.py0000644f2us0000001025013120451262017746 0ustar s.lebedev00000000000000""" webterm ~~~~~~~ An example showing how to use :mod:`pyte` to implement a basic single-user web terminal. Client-side ``webterm.js`` supports * incremental rendering via :data:`~pyte.screens.DiffScreen.dirty`, * most of the common keyboard events, * pagination on Meta + P/Meta + A. .. note:: This example requires at least Python 3.5 and a recent version of ``aiohttp`` library. .. seealso:: `The TTY demystified `_ for an introduction to the inner workings of the TTY subsystem. :copyright: (c) 2017 by pyte authors and contributors, see AUTHORS for details. :license: LGPL, see LICENSE for more details. """ import json import os import pty import shlex import signal import webbrowser from pathlib import Path import aiohttp import asyncio from aiohttp import web import pyte class Terminal: def __init__(self, columns, lines, p_in): self.screen = pyte.HistoryScreen(columns, lines) self.screen.set_mode(pyte.modes.LNM) self.screen.write_process_input = \ lambda data: p_in.write(data.encode()) self.stream = pyte.ByteStream() self.stream.attach(self.screen) def feed(self, data): self.stream.feed(data) def dumps(self): cursor = self.screen.cursor lines = [] for y in self.screen.dirty: line = self.screen.buffer[y] data = [(char.data, char.reverse, char.fg, char.bg) for char in (line[x] for x in range(self.screen.columns))] lines.append((y, data)) self.screen.dirty.clear() return json.dumps({"c": (cursor.x, cursor.y), "lines": lines}) def open_terminal(command="bash", columns=80, lines=24): p_pid, master_fd = pty.fork() if p_pid == 0: # Child. argv = shlex.split(command) env = dict(TERM="linux", LC_ALL="en_GB.UTF-8", COLUMNS=str(columns), LINES=str(lines)) os.execvpe(argv[0], argv, env) # File-like object for I/O with the child process aka command. p_out = os.fdopen(master_fd, "w+b", 0) return Terminal(columns, lines, p_out), p_pid, p_out async def websocket_handler(request): ws = web.WebSocketResponse() await ws.prepare(request) request.app["websockets"].add(asyncio.Task.current_task()) terminal, p_pid, p_out = open_terminal() ws.send_str(terminal.dumps()) def on_master_output(): terminal.feed(p_out.read(65536)) ws.send_str(terminal.dumps()) loop = asyncio.get_event_loop() loop.add_reader(p_out, on_master_output) try: async for msg in ws: if msg.type == aiohttp.WSMsgType.TEXT: if msg.data == pyte.control.ESC + "N": terminal.screen.next_page() ws.send_str(terminal.dumps()) elif msg.data == pyte.control.ESC + "P": terminal.screen.prev_page() ws.send_str(terminal.dumps()) else: p_out.write(msg.data.encode()) elif msg.type == aiohttp.WSMsgType.ERROR: raise ws.exception() except (asyncio.CancelledError, OSError): # Process died? pass finally: loop.remove_reader(p_out) os.kill(p_pid, signal.SIGTERM) p_out.close() if not is_shutting_down: request.app["websockets"].remove(asyncio.Task.current_task()) await ws.close() return ws is_shutting_down = False async def on_shutdown(app): """Closes all WS connections on shutdown.""" global is_shutting_down is_shutting_down = True for task in app["websockets"]: task.cancel() try: await task except asyncio.CancelledError: pass if __name__ == "__main__": app = web.Application() app["websockets"] = set() app.router.add_get("/ws", websocket_handler) app.router.add_static("/", Path(__file__).parent / "static", show_index=True) app.on_shutdown.append(on_shutdown) webbrowser.open_new_tab("http://localhost:8080/index.html") web.run_app(app) pyte-0.8.0/examples/capture.py0000644f2us0000000234113261755500017756 0ustar s.lebedev00000000000000# -*- coding: utf-8 -*- """ capture ~~~~~~~ An example showing how to capure output from a running terminal app. :copyright: (c) 2015 by pyte authors and contributors, see AUTHORS for details. :license: LGPL, see LICENSE for more details. """ from __future__ import print_function, unicode_literals import os import pty import signal import select import sys if __name__ == "__main__": try: output_path, *argv = sys.argv[1:] except ValueError: sys.exit("usage: %prog% output command [args]") p_pid, master_fd = pty.fork() if p_pid == 0: # Child. os.execvpe(argv[0], argv, env=dict(TERM="linux", COLUMNS="80", LINES="24")) with open(output_path, "wb") as handle: while True: try: [_master_fd], _wlist, _xlist = select.select( [master_fd], [], [], 1) except (KeyboardInterrupt, # Stop right now! ValueError): # Nothing to read. break else: data = os.read(master_fd, 1024) if not data: break handle.write(data) os.kill(p_pid, signal.SIGTERM) pyte-0.8.0/examples/debug.py0000644f2us0000001145313062755665017420 0ustar s.lebedev00000000000000# -*- coding: utf-8 -*- """ debug ~~~~~ ... what if I need to debug a bunch of escape sequences? Just use :class:`~pyte.streams.DebugStream` instead of the usual :class:`~pyte.streams.Stream`. Note though, that it requires :func:`bytes` as input. :copyright: (c) 2011-2013 by Selectel, see AUTHORS for details. :license: LGPL, see LICENSE for more details. """ from __future__ import print_function, unicode_literals import pyte # A blob of `ADOM` output we need to debug. Hey! I know this is ugly ... blob = b"""\x1b[25d\x1b[0;10m\x1b[39;49m\x1b[37m\x1b[40m\x1b[23;15H\x1b[37m\x1b[40mSt:28 Le: 1 Wi: 8 Dx:12 To:31 Ch: 3 Ap: 5 Ma: 9 Pe:11 C\x08\x1b[0;10m\x1b[39;49m\x1b[37m\x1b[40m\x1b[5d\x08\x08\x1b[?25h\x1b[?0c\x1b[?25l\x1b[?1c\x1b[H\x1b[K\x1b[2d\x1b[A\x1b[37m\x1b[40mA\x1b[5;75H\x1b[33m\x1b[40m.\x1b[6d\x08\x1b[0;10;1m\x1b[30m\x1b[40m@\x1b[7;73H^\x1b[8d\x1b[0;10m\x1b[33m\x1b[40m.\x1b[H\x1b[C\x1b[0;10m\x1b[39;49m\x1b[37m\x1b[40m\x1b[C\x1b[37m\x1b[40mroad.\x1b[0;10m\x1b[39;49m\x1b[37m\x1b[40m\x1b[24;78H\x1b[6;75H\x1b[?25h\x1b[?0c\x1b[?25l\x1b[?1c\x1b[H\x1b[K\x1b[2d\x1b[A\x1b[37m\x1b[40mA\x1b[5;72H\x1b[0;10;1m\x1b[37m\x1b[40m^\x1b[6d\x08^\x1b[30m\x1b[40m^@\x1b[0;10m\x1b[33m\x1b[40m.\x1b[7;72H\x1b[0;10;1m\x1b[30m\x1b[40m^\x1b[8d\x1b[0;10m\x1b[33m\x1b[40m..\x1b[0;10;1m\x1b[37m\x1b[40m^\x1b[H\x1b[C\x1b[0;10m\x1b[39;49m\x1b[37m\x1b[40m\x1b[C\x1b[37m\x1b[40mroad.\x1b[0;10m\x1b[39;49m\x1b[37m\x1b[40m\x1b[24;78H\x1b[6;74H\x1b[?25h\x1b[?0c\x1b[?25l\x1b[?1c\x1b[H\x1b[K\x1b[2d\x1b[A\x1b[37m\x1b[40mYou\x1b[0;10m\x1b[39;49m\x1b[37m\x1b[40m\x1b[C\x1b[37m\x1b[40mneed\x1b[0;10m\x1b[39;49m\x1b[37m\x1b[40m\x1b[C\x1b[37m\x1b[40mspecial\x1b[0;10m\x1b[39;49m\x1b[37m\x1b[40m\x1b[C\x1b[37m\x1b[40mequipment\x1b[0;10m\x1b[39;49m\x1b[37m\x1b[40m\x1b[C\x1b[37m\x1b[40mto\x1b[0;10m\x1b[39;49m\x1b[37m\x1b[40m\x1b[C\x1b[37m\x1b[40mscale\x1b[0;10m\x1b[39;49m\x1b[37m\x1b[40m\x1b[C\x1b[37m\x1b[40mthose\x1b[0;10m\x1b[39;49m\x1b[37m\x1b[40m\x1b[C\x1b[37m\x1b[40mmountains.\x1b[0;10m\x1b[39;49m\x1b[37m\x1b[40m\x1b[24;78H\x1b[6;74H\x1b[?25h\x1b[?0c\x1b[?25l\x1b[?1c\x1b[H\x1b[K\x1b[2d\x1b[A\x1b[37m\x1b[40mYou\x1b[0;10m\x1b[39;49m\x1b[37m\x1b[40m\x1b[C\x1b[37m\x1b[40mneed\x1b[0;10m\x1b[39;49m\x1b[37m\x1b[40m\x1b[C\x1b[37m\x1b[40mspecial\x1b[0;10m\x1b[39;49m\x1b[37m\x1b[40m\x1b[C\x1b[37m\x1b[40mequipment\x1b[0;10m\x1b[39;49m\x1b[37m\x1b[40m\x1b[C\x1b[37m\x1b[40mto\x1b[0;10m\x1b[39;49m\x1b[37m\x1b[40m\x1b[C\x1b[37m\x1b[40mscale\x1b[0;10m\x1b[39;49m\x1b[37m\x1b[40m\x1b[C\x1b[37m\x1b[40mthose\x1b[0;10m\x1b[39;49m\x1b[37m\x1b[40m\x1b[C\x1b[37m\x1b[40mmountains.\x1b[0;10m\x1b[39;49m\x1b[37m\x1b[40m\x1b[24;78H\x1b[6;74H\x1b[?25h\x1b[?0c\x1b[?25l\x1b[?1c\x1b[H\x1b[K\x1b[2d\x1b[A\x1b[37m\x1b[40mA\x1b[6;74H\x1b[33m\x1b[40m.\x1b[7d\x08\x1b[0;10;1m\x1b[30m\x1b[40m@\x1b[8;72H\x1b[0;10m\x1b[33m\x1b[40m.\x1b[9d\x1b[0;10;1m\x1b[30m\x1b[40m^\x1b[37m\x1b[40m^^\x1b[H\x1b[C\x1b[0;10m\x1b[39;49m\x1b[37m\x1b[40m\x1b[C\x1b[37m\x1b[40mroad.\x1b[0;10m\x1b[39;49m\x1b[37m\x1b[40m\x1b[24;78H\x1b[7;74H\x1b[?25h\x1b[?0c\x1b[?25l\x1b[?1c\x1b[H\x1b[K\x1b[2d\x1b[A\x1b[37m\x1b[40mYou\x1b[0;10m\x1b[39;49m\x1b[37m\x1b[40m\x1b[C\x1b[37m\x1b[40mneed\x1b[0;10m\x1b[39;49m\x1b[37m\x1b[40m\x1b[C\x1b[37m\x1b[40mspecial\x1b[0;10m\x1b[39;49m\x1b[37m\x1b[40m\x1b[C\x1b[37m\x1b[40mequipment\x1b[0;10m\x1b[39;49m\x1b[37m\x1b[40m\x1b[C\x1b[37m\x1b[40mto\x1b[0;10m\x1b[39;49m\x1b[37m\x1b[40m\x1b[C\x1b[37m\x1b[40mscale\x1b[0;10m\x1b[39;49m\x1b[37m\x1b[40m\x1b[C\x1b[37m\x1b[40mthose\x1b[0;10m\x1b[39;49m\x1b[37m\x1b[40m\x1b[C\x1b[37m\x1b[40mmountains.\x1b[0;10m\x1b[39;49m\x1b[37m\x1b[40m\x1b[24;78H\x1b[7;74H\x1b[?25h\x1b[?0c\x1b[?25l\x1b[?1c\x1b[H\x1b[K\x1b[2d\x1b[A\x1b[37m\x1b[40mA\x1b[7;74H\x1b[33m\x1b[40m.\x1b[8d\x08\x1b[0;10;1m\x1b[30m\x1b[40m@\x1b[9;72H\x1b[0;10m\x1b[33m\x1b[40m~\x1b[10d\x1b[0;10;1m\x1b[30m\x1b[40m^\x1b[H\x1b[C\x1b[0;10m\x1b[39;49m\x1b[37m\x1b[40m\x1b[C\x1b[37m\x1b[40mroad.\x1b[0;10m\x1b[39;49m\x1b[37m\x1b[40m\x1b[24;78H\x1b[8;74H\x1b[?25h\x1b[?0c\x1b[?25l\x1b[?1c\x1b[H\x1b[K\x1b[2d\x1b[A\x1b[37m\x1b[40mA\x1b[7;71H\x1b[0;10;1m\x1b[30m\x1b[40m^\x1b[8d\x08\x1b[0;10m\x1b[33m\x1b[40m..\x1b[0;10;1m\x1b[30m\x1b[40m@\x1b[0;10m\x1b[33m\x1b[40m.\x1b[9;71H.\x1b[10d\x1b[32m\x1b[40m&\x1b[0;10;1m\x1b[30m\x1b[40m^^\x1b[H\x1b[C\x1b[0;10m\x1b[39;49m\x1b[37m\x1b[40m\x1b[C\x1b[37m\x1b[40mroad.\x1b[0;10m\x1b[39;49m\x1b[37m\x1b[40m\x1b[24;78H\x1b[8;73H\x1b[?25h\x1b[?0c\x1b[?25l\x1b[?1c\x1b[H\x1b[K\x1b[2d\x1b[A\x1b[37m\x1b[40mA\x1b[6;71H\x1b[0;10;1m\x1b[37m\x1b[40m^\x1b[7d\x08\x08\x1b[30m\x1b[40m^\x1b[8d\x08^\x1b[0;10m\x1b[33m\x1b[40m.\x1b[0;10;1m\x1b[30m\x1b[40m@\x1b[0;10m\x1b[33m\x1b[40m.\x1b[9;70H.\x1b[10d\x1b[32m\x1b[40m&\x1b[H\x1b[C\x1b[0;10m\x1b[39;49m\x1b[37m\x1b[40m\x1b[C\x1b[37m\x1b[40mroad.\x1b[0;10m\x1b[39;49m\x1b[37m\x1b[40m\x1b[24;78H\x1b[8;72H\x1b[?25h\x1b[?0c""" if __name__ == "__main__": stream = pyte.ByteStream(pyte.DebugScreen()) stream.feed(blob) pyte-0.8.0/examples/helloworld.py0000644f2us0000000101713062755665020500 0ustar s.lebedev00000000000000# -*- coding: utf-8 -*- """ helloworld ~~~~~~~~~~ A minimal working example for :mod:`pyte`. :copyright: (c) 2011-2013 by Selectel, see AUTHORS for details. :license: LGPL, see LICENSE for more details. """ from __future__ import print_function, unicode_literals import pyte if __name__ == "__main__": screen = pyte.Screen(80, 24) stream = pyte.Stream(screen) stream.feed("Hello World!") for idx, line in enumerate(screen.display, 1): print("{0:2d} {1} ¶".format(idx, line)) pyte-0.8.0/examples/history.py0000644f2us0000000244613062755665020035 0ustar s.lebedev00000000000000# -*- coding: utf-8 -*- """ history ~~~~~~~ A tiny example to show how pagination works. :copyright: (c) 2011-2013 by Selectel, see AUTHORS for details. :license: LGPL, see LICENSE for more details. """ from __future__ import print_function, unicode_literals import os import random import string import sys if sys.version_info[0] == 2: input = raw_input import pyte from pyte import modes as mo def print_screen(screen, text): print(pyte.control.ESC + pyte.escape.RIS) for idx, line in enumerate(screen.display, 1): print("{0:2d} {1} ¶".format(idx, line)) input(os.linesep + os.linesep + text) def random_string(n, alphabet=string.ascii_letters + " "): return "".join(random.choice(alphabet) for _ in range(n)) if __name__ == "__main__": # ``ratio=1`` means scroll the whole screen. screen = pyte.HistoryScreen(80, 12, ratio=1) screen.set_mode(mo.LNM) stream = pyte.Stream(screen) pages = 3 stream.feed(os.linesep.join(random_string(screen.columns) for _ in range(screen.lines * pages))) screen.prev_page() print_screen(screen, "Hit ENTER to move up!") screen.prev_page() print_screen(screen, "Hit ENTER to move back down!") screen.next_page() print_screen(screen, "OK?") pyte-0.8.0/setup.cfg0000644f2us0000000007713261757021015750 0ustar s.lebedev00000000000000[aliases] test = pytest [egg_info] tag_build = tag_date = 0 pyte-0.8.0/pyte/0000755f2us0000000000013261757021015104 5ustar s.lebedev00000000000000pyte-0.8.0/pyte/graphics.py0000644f2us0000000656113261754104017265 0ustar s.lebedev00000000000000# -*- coding: utf-8 -*- """ pyte.graphics ~~~~~~~~~~~~~ This module defines graphic-related constants, mostly taken from :manpage:`console_codes(4)` and http://pueblo.sourceforge.net/doc/manual/ansi_color_codes.html. :copyright: (c) 2011-2012 by Selectel. :copyright: (c) 2012-2017 by pyte authors and contributors, see AUTHORS for details. :license: LGPL, see LICENSE for more details. """ from __future__ import unicode_literals #: A mapping of ANSI text style codes to style names, "+" means the: #: attribute is set, "-" -- reset; example: #: #: >>> text[1] #: '+bold' #: >>> text[9] #: '+strikethrough' TEXT = { 1: "+bold", 3: "+italics", 4: "+underscore", 7: "+reverse", 9: "+strikethrough", 22: "-bold", 23: "-italics", 24: "-underscore", 27: "-reverse", 29: "-strikethrough", } #: A mapping of ANSI foreground color codes to color names. #: #: >>> FG_ANSI[30] #: 'black' #: >>> FG_ANSI[38] #: 'default' FG_ANSI = { 30: "black", 31: "red", 32: "green", 33: "brown", 34: "blue", 35: "magenta", 36: "cyan", 37: "white", 39: "default" # white. } #: An alias to :data:`~pyte.graphics.FG_ANSI` for compatibility. FG = FG_ANSI #: A mapping of non-standard ``aixterm`` foreground color codes to #: color names. These are high intensity colors and thus should be #: complemented by ``+bold``. FG_AIXTERM = { 90: "black", 91: "red", 92: "green", 93: "brown", 94: "blue", 95: "magenta", 96: "cyan", 97: "white" } #: A mapping of ANSI background color codes to color names. #: #: >>> BG_ANSI[40] #: 'black' #: >>> BG_ANSI[48] #: 'default' BG_ANSI = { 40: "black", 41: "red", 42: "green", 43: "brown", 44: "blue", 45: "magenta", 46: "cyan", 47: "white", 49: "default" # black. } #: An alias to :data:`~pyte.graphics.BG_ANSI` for compatibility. BG = BG_ANSI #: A mapping of non-standard ``aixterm`` background color codes to #: color names. These are high intensity colors and thus should be #: complemented by ``+bold``. BG_AIXTERM = { 100: "black", 101: "red", 102: "green", 103: "brown", 104: "blue", 105: "magenta", 106: "cyan", 107: "white" } #: SGR code for foreground in 256 or True color mode. FG_256 = 38 #: SGR code for background in 256 or True color mode. BG_256 = 48 #: A table of 256 foreground or background colors. # The following code is part of the Pygments project (BSD licensed). FG_BG_256 = [ (0x00, 0x00, 0x00), # 0 (0xcd, 0x00, 0x00), # 1 (0x00, 0xcd, 0x00), # 2 (0xcd, 0xcd, 0x00), # 3 (0x00, 0x00, 0xee), # 4 (0xcd, 0x00, 0xcd), # 5 (0x00, 0xcd, 0xcd), # 6 (0xe5, 0xe5, 0xe5), # 7 (0x7f, 0x7f, 0x7f), # 8 (0xff, 0x00, 0x00), # 9 (0x00, 0xff, 0x00), # 10 (0xff, 0xff, 0x00), # 11 (0x5c, 0x5c, 0xff), # 12 (0xff, 0x00, 0xff), # 13 (0x00, 0xff, 0xff), # 14 (0xff, 0xff, 0xff), # 15 ] # colors 16..231: the 6x6x6 color cube valuerange = (0x00, 0x5f, 0x87, 0xaf, 0xd7, 0xff) for i in range(216): r = valuerange[(i // 36) % 6] g = valuerange[(i // 6) % 6] b = valuerange[i % 6] FG_BG_256.append((r, g, b)) # colors 232..255: grayscale for i in range(24): v = 8 + i * 10 FG_BG_256.append((v, v, v)) FG_BG_256 = ["{0:02x}{1:02x}{2:02x}".format(r, g, b) for r, g, b in FG_BG_256] pyte-0.8.0/pyte/escape.py0000644f2us0000001015213117620156016713 0ustar s.lebedev00000000000000# -*- coding: utf-8 -*- """ pyte.escape ~~~~~~~~~~~ This module defines both CSI and non-CSI escape sequences, recognized by :class:`~pyte.streams.Stream` and subclasses. :copyright: (c) 2011-2012 by Selectel. :copyright: (c) 2012-2017 by pyte authors and contributors, see AUTHORS for details. :license: LGPL, see LICENSE for more details. """ from __future__ import unicode_literals #: *Reset*. RIS = "c" #: *Index*: Move cursor down one line in same column. If the cursor is #: at the bottom margin, the screen performs a scroll-up. IND = "D" #: *Next line*: Same as :data:`pyte.control.LF`. NEL = "E" #: Tabulation set: Set a horizontal tab stop at cursor position. HTS = "H" #: *Reverse index*: Move cursor up one line in same column. If the #: cursor is at the top margin, the screen performs a scroll-down. RI = "M" #: Save cursor: Save cursor position, character attribute (graphic #: rendition), character set, and origin mode selection (see #: :data:`DECRC`). DECSC = "7" #: *Restore cursor*: Restore previously saved cursor position, character #: attribute (graphic rendition), character set, and origin mode #: selection. If none were saved, move cursor to home position. DECRC = "8" # "Sharp" escape sequences. # ------------------------- #: *Alignment display*: Fill screen with uppercase E's for testing #: screen focus and alignment. DECALN = "8" # ECMA-48 CSI sequences. # --------------------- #: *Insert character*: Insert the indicated # of blank characters. ICH = "@" #: *Cursor up*: Move cursor up the indicated # of lines in same column. #: Cursor stops at top margin. CUU = "A" #: *Cursor down*: Move cursor down the indicated # of lines in same #: column. Cursor stops at bottom margin. CUD = "B" #: *Cursor forward*: Move cursor right the indicated # of columns. #: Cursor stops at right margin. CUF = "C" #: *Cursor back*: Move cursor left the indicated # of columns. Cursor #: stops at left margin. CUB = "D" #: *Cursor next line*: Move cursor down the indicated # of lines to #: column 1. CNL = "E" #: *Cursor previous line*: Move cursor up the indicated # of lines to #: column 1. CPL = "F" #: *Cursor horizontal align*: Move cursor to the indicated column in #: current line. CHA = "G" #: *Cursor position*: Move cursor to the indicated line, column (origin #: at ``1, 1``). CUP = "H" #: *Erase data* (default: from cursor to end of line). ED = "J" #: *Erase in line* (default: from cursor to end of line). EL = "K" #: *Insert line*: Insert the indicated # of blank lines, starting from #: the current line. Lines displayed below cursor move down. Lines moved #: past the bottom margin are lost. IL = "L" #: *Delete line*: Delete the indicated # of lines, starting from the #: current line. As lines are deleted, lines displayed below cursor #: move up. Lines added to bottom of screen have spaces with same #: character attributes as last line move up. DL = "M" #: *Delete character*: Delete the indicated # of characters on the #: current line. When character is deleted, all characters to the right #: of cursor move left. DCH = "P" #: *Erase character*: Erase the indicated # of characters on the #: current line. ECH = "X" #: *Horizontal position relative*: Same as :data:`CUF`. HPR = "a" #: *Device Attributes*. DA = "c" #: *Vertical position adjust*: Move cursor to the indicated line, #: current column. VPA = "d" #: *Vertical position relative*: Same as :data:`CUD`. VPR = "e" #: *Horizontal / Vertical position*: Same as :data:`CUP`. HVP = "f" #: *Tabulation clear*: Clears a horizontal tab stop at cursor position. TBC = "g" #: *Set mode*. SM = "h" #: *Reset mode*. RM = "l" #: *Select graphics rendition*: The terminal can display the following #: character attributes that change the character display without #: changing the character (see :mod:`pyte.graphics`). SGR = "m" #: *Device status report*. DSR = "n" #: *Select top and bottom margins*: Selects margins, defining the #: scrolling region; parameters are top and bottom line. If called #: without any arguments, whole screen is used. DECSTBM = "r" #: *Horizontal position adjust*: Same as :data:`CHA`. HPA = "'" pyte-0.8.0/pyte/streams.py0000644f2us0000003363713261754104017147 0ustar s.lebedev00000000000000# -*- coding: utf-8 -*- """ pyte.streams ~~~~~~~~~~~~ This module provides three stream implementations with different features; for starters, here's a quick example of how streams are typically used: >>> import pyte >>> screen = pyte.Screen(80, 24) >>> stream = pyte.Stream(screen) >>> stream.feed("\x1b[5B") # Move the cursor down 5 rows. >>> screen.cursor.y 5 :copyright: (c) 2011-2012 by Selectel. :copyright: (c) 2012-2017 by pyte authors and contributors, see AUTHORS for details. :license: LGPL, see LICENSE for more details. """ from __future__ import absolute_import, unicode_literals import codecs import itertools import re import warnings from collections import defaultdict from . import control as ctrl, escape as esc from .compat import pass_through_str class Stream(object): """A stream is a state machine that parses a stream of bytes and dispatches events based on what it sees. :param pyte.screens.Screen screen: a screen to dispatch events to. :param bool strict: check if a given screen implements all required events. .. note:: Stream only accepts text as input, but if for some reason you need to feed it with bytes, consider using :class:`~pyte.streams.ByteStream` instead. .. versionchanged 0.6.0:: For performance reasons the binding between stream events and screen methods was made static. As a result, the stream **will not** dispatch events to methods added to screen **after** the stream was created. .. seealso:: `man console_codes `_ For details on console codes listed bellow in :attr:`basic`, :attr:`escape`, :attr:`csi`, :attr:`sharp`. """ #: Control sequences, which don't require any arguments. basic = { ctrl.BEL: "bell", ctrl.BS: "backspace", ctrl.HT: "tab", ctrl.LF: "linefeed", ctrl.VT: "linefeed", ctrl.FF: "linefeed", ctrl.CR: "carriage_return", ctrl.SO: "shift_out", ctrl.SI: "shift_in", } #: non-CSI escape sequences. escape = { esc.RIS: "reset", esc.IND: "index", esc.NEL: "linefeed", esc.RI: "reverse_index", esc.HTS: "set_tab_stop", esc.DECSC: "save_cursor", esc.DECRC: "restore_cursor", } #: "sharp" escape sequences -- ``ESC # ``. sharp = { esc.DECALN: "alignment_display", } #: CSI escape sequences -- ``CSI P1;P2;...;Pn ``. csi = { esc.ICH: "insert_characters", esc.CUU: "cursor_up", esc.CUD: "cursor_down", esc.CUF: "cursor_forward", esc.CUB: "cursor_back", esc.CNL: "cursor_down1", esc.CPL: "cursor_up1", esc.CHA: "cursor_to_column", esc.CUP: "cursor_position", esc.ED: "erase_in_display", esc.EL: "erase_in_line", esc.IL: "insert_lines", esc.DL: "delete_lines", esc.DCH: "delete_characters", esc.ECH: "erase_characters", esc.HPR: "cursor_forward", esc.DA: "report_device_attributes", esc.VPA: "cursor_to_line", esc.VPR: "cursor_down", esc.HVP: "cursor_position", esc.TBC: "clear_tab_stop", esc.SM: "set_mode", esc.RM: "reset_mode", esc.SGR: "select_graphic_rendition", esc.DSR: "report_device_status", esc.DECSTBM: "set_margins", esc.HPA: "cursor_to_column" } #: A set of all events dispatched by the stream. events = frozenset(itertools.chain( basic.values(), escape.values(), sharp.values(), csi.values(), ["define_charset"], ["set_icon_name", "set_title"], # OSC. ["draw", "debug"])) #: A regular expression pattern matching everything what can be #: considered plain text. _special = set([ctrl.ESC, ctrl.CSI_C1, ctrl.NUL, ctrl.DEL, ctrl.OSC_C1]) _special.update(basic) _text_pattern = re.compile( "[^" + "".join(map(re.escape, _special)) + "]+") del _special def __init__(self, screen=None, strict=True): self.listener = None self.strict = strict self.use_utf8 = True if screen is not None: self.attach(screen) def attach(self, screen): """Adds a given screen to the listener queue. :param pyte.screens.Screen screen: a screen to attach to. """ if self.listener is not None: warnings.warn("As of version 0.6.0 the listener queue is " "restricted to a single element. Existing " "listener {0} will be replaced." .format(self.listener), DeprecationWarning) if self.strict: for event in self.events: if not hasattr(screen, event): raise TypeError("{0} is missing {1}".format(screen, event)) self.listener = screen self._parser = self._parser_fsm() self._taking_plain_text = next(self._parser) def detach(self, screen): """Remove a given screen from the listener queue and fails silently if it's not attached. :param pyte.screens.Screen screen: a screen to detach. """ if screen is self.listener: self.listener = None def feed(self, data): """Consume some data and advances the state as necessary. :param str data: a blob of data to feed from. """ send = self._parser.send draw = self.listener.draw match_text = self._text_pattern.match taking_plain_text = self._taking_plain_text length = len(data) offset = 0 while offset < length: if taking_plain_text: match = match_text(data, offset) if match: start, offset = match.span() draw(data[start:offset]) else: taking_plain_text = False else: taking_plain_text = send(data[offset:offset + 1]) offset += 1 self._taking_plain_text = taking_plain_text def _parser_fsm(self): """An FSM implemented as a coroutine. This generator is not the most beautiful, but it is as performant as possible. When a process generates a lot of output, then this will be the bottleneck, because it processes just one character at a time. Don't change anything without profiling first. """ basic = self.basic listener = self.listener draw = listener.draw debug = listener.debug ESC, CSI_C1 = ctrl.ESC, ctrl.CSI_C1 OSC_C1 = ctrl.OSC_C1 SP_OR_GT = ctrl.SP + ">" NUL_OR_DEL = ctrl.NUL + ctrl.DEL CAN_OR_SUB = ctrl.CAN + ctrl.SUB ALLOWED_IN_CSI = "".join([ctrl.BEL, ctrl.BS, ctrl.HT, ctrl.LF, ctrl.VT, ctrl.FF, ctrl.CR]) OSC_TERMINATORS = set([ctrl.ST_C0, ctrl.ST_C1, ctrl.BEL]) def create_dispatcher(mapping): return defaultdict(lambda: debug, dict( (event, getattr(listener, attr)) for event, attr in mapping.items())) basic_dispatch = create_dispatcher(basic) sharp_dispatch = create_dispatcher(self.sharp) escape_dispatch = create_dispatcher(self.escape) csi_dispatch = create_dispatcher(self.csi) while True: # ``True`` tells ``Screen.feed`` that it is allowed to send # chunks of plain text directly to the listener, instead # of this generator. char = yield True if char == ESC: # Most non-VT52 commands start with a left-bracket after the # escape and then a stream of parameters and a command; with # a single notable exception -- :data:`escape.DECOM` sequence, # which starts with a sharp. # # .. versionchanged:: 0.4.10 # # For compatibility with Linux terminal stream also # recognizes ``ESC % C`` sequences for selecting control # character set. However, in the current version these # are noop. char = yield if char == "[": char = CSI_C1 # Go to CSI. elif char == "]": char = OSC_C1 # Go to OSC. else: if char == "#": sharp_dispatch[(yield)]() if char == "%": self.select_other_charset((yield)) elif char in "()": code = yield if self.use_utf8: continue # See http://www.cl.cam.ac.uk/~mgk25/unicode.html#term # for the why on the UTF-8 restriction. listener.define_charset(code, mode=char) else: escape_dispatch[char]() continue # Don't go to CSI. if char in basic: # Ignore shifts in UTF-8 mode. See # http://www.cl.cam.ac.uk/~mgk25/unicode.html#term for # the why on UTF-8 restriction. if (char == ctrl.SI or char == ctrl.SO) and self.use_utf8: continue basic_dispatch[char]() elif char == CSI_C1: # All parameters are unsigned, positive decimal integers, with # the most significant digit sent first. Any parameter greater # than 9999 is set to 9999. If you do not specify a value, a 0 # value is assumed. # # .. seealso:: # # `VT102 User Guide `_ # For details on the formatting of escape arguments. # # `VT220 Programmer Ref. `_ # For details on the characters valid for use as # arguments. params = [] current = "" private = False while True: char = yield if char == "?": private = True elif char in ALLOWED_IN_CSI: basic_dispatch[char]() elif char in SP_OR_GT: pass # Secondary DA is not supported atm. elif char in CAN_OR_SUB: # If CAN or SUB is received during a sequence, the # current sequence is aborted; terminal displays # the substitute character, followed by characters # in the sequence received after CAN or SUB. draw(char) break elif char.isdigit(): current += char else: params.append(min(int(current or 0), 9999)) if char == ";": current = "" else: if private: csi_dispatch[char](*params, private=True) else: csi_dispatch[char](*params) break # CSI is finished. elif char == OSC_C1: code = yield if code == "R": continue # Reset palette. Not implemented. elif code == "P": continue # Set palette. Not implemented. param = "" while True: char = yield if char == ESC: char += yield if char in OSC_TERMINATORS: break else: param += char param = param[1:] # Drop the ;. if code in "01": listener.set_icon_name(param) if code in "02": listener.set_title(param) elif char not in NUL_OR_DEL: draw(char) def select_other_charset(self, code): """Select other (non G0 or G1) charset. :param str code: character set code, should be a character from ``"@G8"``, otherwise ignored. .. note:: We currently follow ``"linux"`` and only use this command to switch from ISO-8859-1 to UTF-8 and back. .. versionadded:: 0.6.0 .. seealso:: `Standard ECMA-35, Section 15.4 \ `_ for a description of VTXXX character set machinery. """ # A noop since all input is Unicode-only. class ByteStream(Stream): """A stream which takes bytes as input. Bytes are decoded to text using either UTF-8 (default) or the encoding selected via :meth:`~pyte.Stream.select_other_charset`. .. attribute:: use_utf8 Assume the input to :meth:`~pyte.streams.ByteStream.feed` is encoded using UTF-8. Defaults to ``True``. """ def __init__(self, *args, **kwargs): super(ByteStream, self).__init__(*args, **kwargs) self.utf8_decoder = codecs.getincrementaldecoder("utf-8")("replace") def feed(self, data): if self.use_utf8: data = self.utf8_decoder.decode(data) else: data = pass_through_str(data) super(ByteStream, self).feed(data) def select_other_charset(self, code): if code == "@": self.use_utf8 = False self.utf8_decoder.reset() elif code in "G8": self.use_utf8 = True pyte-0.8.0/pyte/compat.py0000644f2us0000000140213117620156016734 0ustar s.lebedev00000000000000# -*- coding: utf-8 -*- """ pyte.compat ~~~~~~~~~~~ Python version specific compatibility fixes. :copyright: (c) 2015-2017 by pyte authors and contributors, see AUTHORS for details. :license: LGPL, see LICENSE for more details. """ import sys if sys.version_info[0] == 2: from future_builtins import map range = xrange str = unicode chr = unichr def pass_through_str(data): """Decode :func:`bytes` to :func:`str` using pass-through encoding.""" return "".join(chr(ord(ch)) for ch in data) else: from builtins import map, range, str, chr def pass_through_str(data): """Decode :func:`bytes` to :func:`str` using pass-through encoding.""" return "".join(map(chr, data)) pyte-0.8.0/pyte/control.py0000644f2us0000000337413261754104017144 0ustar s.lebedev00000000000000# -*- coding: utf-8 -*- """ pyte.control ~~~~~~~~~~~~ This module defines simple control sequences, recognized by :class:`~pyte.streams.Stream`, the set of codes here is for ``TERM=linux`` which is a superset of VT102. :copyright: (c) 2011-2012 by Selectel. :copyright: (c) 2012-2017 by pyte authors and contributors, see AUTHORS for details. :license: LGPL, see LICENSE for more details. """ from __future__ import unicode_literals #: *Space*: Not suprisingly -- ``" "``. SP = " " #: *Null*: Does nothing. NUL = "\x00" #: *Bell*: Beeps. BEL = "\x07" #: *Backspace*: Backspace one column, but not past the begining of the #: line. BS = "\x08" #: *Horizontal tab*: Move cursor to the next tab stop, or to the end #: of the line if there is no earlier tab stop. HT = "\x09" #: *Linefeed*: Give a line feed, and, if :data:`pyte.modes.LNM` (new #: line mode) is set also a carriage return. LF = "\n" #: *Vertical tab*: Same as :data:`LF`. VT = "\x0b" #: *Form feed*: Same as :data:`LF`. FF = "\x0c" #: *Carriage return*: Move cursor to left margin on current line. CR = "\r" #: *Shift out*: Activate G1 character set. SO = "\x0e" #: *Shift in*: Activate G0 character set. SI = "\x0f" #: *Cancel*: Interrupt escape sequence. If received during an escape or #: control sequence, cancels the sequence and displays substitution #: character. CAN = "\x18" #: *Substitute*: Same as :data:`CAN`. SUB = "\x1a" #: *Escape*: Starts an escape sequence. ESC = "\x1b" #: *Delete*: Is ignored. DEL = "\x7f" #: *Control sequence introducer*. CSI_C0 = ESC + "[" CSI_C1 = "\x9b" CSI = CSI_C0 #: *String terminator*. ST_C0 = ESC + "\\" ST_C1 = "\x9c" ST = ST_C0 #: *Operating system command*. OSC_C0 = ESC + "]" OSC_C1 = "\x9d" OSC = OSC_C0 pyte-0.8.0/pyte/charsets.py0000644f2us0000001663113062755665017314 0ustar s.lebedev00000000000000# -*- coding: utf-8 -*- """ pyte.charsets ~~~~~~~~~~~~~ This module defines ``G0`` and ``G1`` charset mappings the same way they are defined for linux terminal, see ``linux/drivers/tty/consolemap.c`` @ http://git.kernel.org .. note:: ``VT100_MAP`` and ``IBMPC_MAP`` were taken unchanged from linux kernel source and therefore are licensed under **GPL**. :copyright: (c) 2011-2012 by Selectel. :copyright: (c) 2012-2017 by pyte authors and contributors, see AUTHORS for details. :license: LGPL, see LICENSE for more details. """ from __future__ import absolute_import, unicode_literals from .compat import chr, map #: Latin1. LAT1_MAP = "".join(map(chr, range(256))) #: VT100 graphic character set. VT100_MAP = "".join(chr(c) for c in [ 0x0000, 0x0001, 0x0002, 0x0003, 0x0004, 0x0005, 0x0006, 0x0007, 0x0008, 0x0009, 0x000a, 0x000b, 0x000c, 0x000d, 0x000e, 0x000f, 0x0010, 0x0011, 0x0012, 0x0013, 0x0014, 0x0015, 0x0016, 0x0017, 0x0018, 0x0019, 0x001a, 0x001b, 0x001c, 0x001d, 0x001e, 0x001f, 0x0020, 0x0021, 0x0022, 0x0023, 0x0024, 0x0025, 0x0026, 0x0027, 0x0028, 0x0029, 0x002a, 0x2192, 0x2190, 0x2191, 0x2193, 0x002f, 0x2588, 0x0031, 0x0032, 0x0033, 0x0034, 0x0035, 0x0036, 0x0037, 0x0038, 0x0039, 0x003a, 0x003b, 0x003c, 0x003d, 0x003e, 0x003f, 0x0040, 0x0041, 0x0042, 0x0043, 0x0044, 0x0045, 0x0046, 0x0047, 0x0048, 0x0049, 0x004a, 0x004b, 0x004c, 0x004d, 0x004e, 0x004f, 0x0050, 0x0051, 0x0052, 0x0053, 0x0054, 0x0055, 0x0056, 0x0057, 0x0058, 0x0059, 0x005a, 0x005b, 0x005c, 0x005d, 0x005e, 0x00a0, 0x25c6, 0x2592, 0x2409, 0x240c, 0x240d, 0x240a, 0x00b0, 0x00b1, 0x2591, 0x240b, 0x2518, 0x2510, 0x250c, 0x2514, 0x253c, 0x23ba, 0x23bb, 0x2500, 0x23bc, 0x23bd, 0x251c, 0x2524, 0x2534, 0x252c, 0x2502, 0x2264, 0x2265, 0x03c0, 0x2260, 0x00a3, 0x00b7, 0x007f, 0x0080, 0x0081, 0x0082, 0x0083, 0x0084, 0x0085, 0x0086, 0x0087, 0x0088, 0x0089, 0x008a, 0x008b, 0x008c, 0x008d, 0x008e, 0x008f, 0x0090, 0x0091, 0x0092, 0x0093, 0x0094, 0x0095, 0x0096, 0x0097, 0x0098, 0x0099, 0x009a, 0x009b, 0x009c, 0x009d, 0x009e, 0x009f, 0x00a0, 0x00a1, 0x00a2, 0x00a3, 0x00a4, 0x00a5, 0x00a6, 0x00a7, 0x00a8, 0x00a9, 0x00aa, 0x00ab, 0x00ac, 0x00ad, 0x00ae, 0x00af, 0x00b0, 0x00b1, 0x00b2, 0x00b3, 0x00b4, 0x00b5, 0x00b6, 0x00b7, 0x00b8, 0x00b9, 0x00ba, 0x00bb, 0x00bc, 0x00bd, 0x00be, 0x00bf, 0x00c0, 0x00c1, 0x00c2, 0x00c3, 0x00c4, 0x00c5, 0x00c6, 0x00c7, 0x00c8, 0x00c9, 0x00ca, 0x00cb, 0x00cc, 0x00cd, 0x00ce, 0x00cf, 0x00d0, 0x00d1, 0x00d2, 0x00d3, 0x00d4, 0x00d5, 0x00d6, 0x00d7, 0x00d8, 0x00d9, 0x00da, 0x00db, 0x00dc, 0x00dd, 0x00de, 0x00df, 0x00e0, 0x00e1, 0x00e2, 0x00e3, 0x00e4, 0x00e5, 0x00e6, 0x00e7, 0x00e8, 0x00e9, 0x00ea, 0x00eb, 0x00ec, 0x00ed, 0x00ee, 0x00ef, 0x00f0, 0x00f1, 0x00f2, 0x00f3, 0x00f4, 0x00f5, 0x00f6, 0x00f7, 0x00f8, 0x00f9, 0x00fa, 0x00fb, 0x00fc, 0x00fd, 0x00fe, 0x00ff ]) #: IBM Codepage 437. IBMPC_MAP = "".join(chr(c) for c in [ 0x0000, 0x263a, 0x263b, 0x2665, 0x2666, 0x2663, 0x2660, 0x2022, 0x25d8, 0x25cb, 0x25d9, 0x2642, 0x2640, 0x266a, 0x266b, 0x263c, 0x25b6, 0x25c0, 0x2195, 0x203c, 0x00b6, 0x00a7, 0x25ac, 0x21a8, 0x2191, 0x2193, 0x2192, 0x2190, 0x221f, 0x2194, 0x25b2, 0x25bc, 0x0020, 0x0021, 0x0022, 0x0023, 0x0024, 0x0025, 0x0026, 0x0027, 0x0028, 0x0029, 0x002a, 0x002b, 0x002c, 0x002d, 0x002e, 0x002f, 0x0030, 0x0031, 0x0032, 0x0033, 0x0034, 0x0035, 0x0036, 0x0037, 0x0038, 0x0039, 0x003a, 0x003b, 0x003c, 0x003d, 0x003e, 0x003f, 0x0040, 0x0041, 0x0042, 0x0043, 0x0044, 0x0045, 0x0046, 0x0047, 0x0048, 0x0049, 0x004a, 0x004b, 0x004c, 0x004d, 0x004e, 0x004f, 0x0050, 0x0051, 0x0052, 0x0053, 0x0054, 0x0055, 0x0056, 0x0057, 0x0058, 0x0059, 0x005a, 0x005b, 0x005c, 0x005d, 0x005e, 0x005f, 0x0060, 0x0061, 0x0062, 0x0063, 0x0064, 0x0065, 0x0066, 0x0067, 0x0068, 0x0069, 0x006a, 0x006b, 0x006c, 0x006d, 0x006e, 0x006f, 0x0070, 0x0071, 0x0072, 0x0073, 0x0074, 0x0075, 0x0076, 0x0077, 0x0078, 0x0079, 0x007a, 0x007b, 0x007c, 0x007d, 0x007e, 0x2302, 0x00c7, 0x00fc, 0x00e9, 0x00e2, 0x00e4, 0x00e0, 0x00e5, 0x00e7, 0x00ea, 0x00eb, 0x00e8, 0x00ef, 0x00ee, 0x00ec, 0x00c4, 0x00c5, 0x00c9, 0x00e6, 0x00c6, 0x00f4, 0x00f6, 0x00f2, 0x00fb, 0x00f9, 0x00ff, 0x00d6, 0x00dc, 0x00a2, 0x00a3, 0x00a5, 0x20a7, 0x0192, 0x00e1, 0x00ed, 0x00f3, 0x00fa, 0x00f1, 0x00d1, 0x00aa, 0x00ba, 0x00bf, 0x2310, 0x00ac, 0x00bd, 0x00bc, 0x00a1, 0x00ab, 0x00bb, 0x2591, 0x2592, 0x2593, 0x2502, 0x2524, 0x2561, 0x2562, 0x2556, 0x2555, 0x2563, 0x2551, 0x2557, 0x255d, 0x255c, 0x255b, 0x2510, 0x2514, 0x2534, 0x252c, 0x251c, 0x2500, 0x253c, 0x255e, 0x255f, 0x255a, 0x2554, 0x2569, 0x2566, 0x2560, 0x2550, 0x256c, 0x2567, 0x2568, 0x2564, 0x2565, 0x2559, 0x2558, 0x2552, 0x2553, 0x256b, 0x256a, 0x2518, 0x250c, 0x2588, 0x2584, 0x258c, 0x2590, 0x2580, 0x03b1, 0x00df, 0x0393, 0x03c0, 0x03a3, 0x03c3, 0x00b5, 0x03c4, 0x03a6, 0x0398, 0x03a9, 0x03b4, 0x221e, 0x03c6, 0x03b5, 0x2229, 0x2261, 0x00b1, 0x2265, 0x2264, 0x2320, 0x2321, 0x00f7, 0x2248, 0x00b0, 0x2219, 0x00b7, 0x221a, 0x207f, 0x00b2, 0x25a0, 0x00a0 ]) #: VAX42 character set. VAX42_MAP = "".join(chr(c) for c in [ 0x0000, 0x263a, 0x263b, 0x2665, 0x2666, 0x2663, 0x2660, 0x2022, 0x25d8, 0x25cb, 0x25d9, 0x2642, 0x2640, 0x266a, 0x266b, 0x263c, 0x25b6, 0x25c0, 0x2195, 0x203c, 0x00b6, 0x00a7, 0x25ac, 0x21a8, 0x2191, 0x2193, 0x2192, 0x2190, 0x221f, 0x2194, 0x25b2, 0x25bc, 0x0020, 0x043b, 0x0022, 0x0023, 0x0024, 0x0025, 0x0026, 0x0027, 0x0028, 0x0029, 0x002a, 0x002b, 0x002c, 0x002d, 0x002e, 0x002f, 0x0030, 0x0031, 0x0032, 0x0033, 0x0034, 0x0035, 0x0036, 0x0037, 0x0038, 0x0039, 0x003a, 0x003b, 0x003c, 0x003d, 0x003e, 0x0435, 0x0040, 0x0041, 0x0042, 0x0043, 0x0044, 0x0045, 0x0046, 0x0047, 0x0048, 0x0049, 0x004a, 0x004b, 0x004c, 0x004d, 0x004e, 0x004f, 0x0050, 0x0051, 0x0052, 0x0053, 0x0054, 0x0055, 0x0056, 0x0057, 0x0058, 0x0059, 0x005a, 0x005b, 0x005c, 0x005d, 0x005e, 0x005f, 0x0060, 0x0441, 0x0062, 0x0063, 0x0064, 0x0065, 0x0066, 0x0067, 0x0435, 0x0069, 0x006a, 0x006b, 0x006c, 0x006d, 0x006e, 0x043a, 0x0070, 0x0071, 0x0442, 0x0073, 0x043b, 0x0435, 0x0076, 0x0077, 0x0078, 0x0079, 0x007a, 0x007b, 0x007c, 0x007d, 0x007e, 0x2302, 0x00c7, 0x00fc, 0x00e9, 0x00e2, 0x00e4, 0x00e0, 0x00e5, 0x00e7, 0x00ea, 0x00eb, 0x00e8, 0x00ef, 0x00ee, 0x00ec, 0x00c4, 0x00c5, 0x00c9, 0x00e6, 0x00c6, 0x00f4, 0x00f6, 0x00f2, 0x00fb, 0x00f9, 0x00ff, 0x00d6, 0x00dc, 0x00a2, 0x00a3, 0x00a5, 0x20a7, 0x0192, 0x00e1, 0x00ed, 0x00f3, 0x00fa, 0x00f1, 0x00d1, 0x00aa, 0x00ba, 0x00bf, 0x2310, 0x00ac, 0x00bd, 0x00bc, 0x00a1, 0x00ab, 0x00bb, 0x2591, 0x2592, 0x2593, 0x2502, 0x2524, 0x2561, 0x2562, 0x2556, 0x2555, 0x2563, 0x2551, 0x2557, 0x255d, 0x255c, 0x255b, 0x2510, 0x2514, 0x2534, 0x252c, 0x251c, 0x2500, 0x253c, 0x255e, 0x255f, 0x255a, 0x2554, 0x2569, 0x2566, 0x2560, 0x2550, 0x256c, 0x2567, 0x2568, 0x2564, 0x2565, 0x2559, 0x2558, 0x2552, 0x2553, 0x256b, 0x256a, 0x2518, 0x250c, 0x2588, 0x2584, 0x258c, 0x2590, 0x2580, 0x03b1, 0x00df, 0x0393, 0x03c0, 0x03a3, 0x03c3, 0x00b5, 0x03c4, 0x03a6, 0x0398, 0x03a9, 0x03b4, 0x221e, 0x03c6, 0x03b5, 0x2229, 0x2261, 0x00b1, 0x2265, 0x2264, 0x2320, 0x2321, 0x00f7, 0x2248, 0x00b0, 0x2219, 0x00b7, 0x221a, 0x207f, 0x00b2, 0x25a0, 0x00a0 ]) MAPS = { "B": LAT1_MAP, "0": VT100_MAP, "U": IBMPC_MAP, "V": VAX42_MAP } pyte-0.8.0/pyte/__init__.py0000644f2us0000000322513117620156017215 0ustar s.lebedev00000000000000# -*- coding: utf-8 -*- """ pyte ~~~~ `pyte` implements a mix of VT100, VT220 and VT520 specification, and aims to support most of the `TERM=linux` functionality. Two classes: :class:`~pyte.streams.Stream`, which parses the command stream and dispatches events for commands, and :class:`~pyte.screens.Screen` which, when used with a stream maintains a buffer of strings representing the screen of a terminal. .. warning:: From ``xterm/main.c`` "If you think you know what all of this code is doing, you are probably very mistaken. There be serious and nasty dragons here" -- nothing has changed. :copyright: (c) 2011-2012 by Selectel. :copyright: (c) 2012-2017 by pyte authors and contributors, see AUTHORS for details. :license: LGPL, see LICENSE for more details. """ from __future__ import absolute_import __all__ = ("Screen", "DiffScreen", "HistoryScreen", "DebugScreen", "Stream", "ByteStream") import io from .screens import Screen, DiffScreen, HistoryScreen, DebugScreen from .streams import Stream, ByteStream if __debug__: from .compat import str def dis(chars): """A :func:`dis.dis` for terminals. >>> dis(b"\x07") # doctest: +NORMALIZE_WHITESPACE ["bell", [], {}] >>> dis(b"\x1b[20m") # doctest: +NORMALIZE_WHITESPACE ["select_graphic_rendition", [20], {}] """ if isinstance(chars, str): chars = chars.encode("utf-8") with io.StringIO() as buf: ByteStream(DebugScreen(to=buf)).feed(chars) print(buf.getvalue()) pyte-0.8.0/pyte/modes.py0000644f2us0000000356613062755665016612 0ustar s.lebedev00000000000000# -*- coding: utf-8 -*- """ pyte.modes ~~~~~~~~~~ This module defines terminal mode switches, used by :class:`~pyte.screens.Screen`. There're two types of terminal modes: * `non-private` which should be set with ``ESC [ N h``, where ``N`` is an integer, representing mode being set; and * `private` which should be set with ``ESC [ ? N h``. The latter are shifted 5 times to the right, to be easily distinguishable from the former ones; for example `Origin Mode` -- :data:`DECOM` is ``192`` not ``6``. >>> DECOM 192 :copyright: (c) 2011-2012 by Selectel. :copyright: (c) 2012-2017 by pyte authors and contributors, see AUTHORS for details. :license: LGPL, see LICENSE for more details. """ #: *Line Feed/New Line Mode*: When enabled, causes a received #: :data:`~pyte.control.LF`, :data:`pyte.control.FF`, or #: :data:`~pyte.control.VT` to move the cursor to the first column of #: the next line. LNM = 20 #: *Insert/Replace Mode*: When enabled, new display characters move #: old display characters to the right. Characters moved past the #: right margin are lost. Otherwise, new display characters replace #: old display characters at the cursor position. IRM = 4 # Private modes. # .............. #: *Text Cursor Enable Mode*: determines if the text cursor is #: visible. DECTCEM = 25 << 5 #: *Screen Mode*: toggles screen-wide reverse-video mode. DECSCNM = 5 << 5 #: *Origin Mode*: allows cursor addressing relative to a user-defined #: origin. This mode resets when the terminal is powered up or reset. #: It does not affect the erase in display (ED) function. DECOM = 6 << 5 #: *Auto Wrap Mode*: selects where received graphic characters appear #: when the cursor is at the right margin. DECAWM = 7 << 5 #: *Column Mode*: selects the number of columns per line (80 or 132) #: on the screen. DECCOLM = 3 << 5 pyte-0.8.0/pyte/screens.py0000644f2us0000013326513261754536017142 0ustar s.lebedev00000000000000# -*- coding: utf-8 -*- """ pyte.screens ~~~~~~~~~~~~ This module provides classes for terminal screens, currently it contains three screens with different features: * :class:`~pyte.screens.Screen` -- base screen implementation, which handles all the core escape sequences, recognized by :class:`~pyte.streams.Stream`. * If you need a screen to keep track of the changed lines (which you probably do need) -- use :class:`~pyte.screens.DiffScreen`. * If you also want a screen to collect history and allow pagination -- :class:`pyte.screen.HistoryScreen` is here for ya ;) .. note:: It would be nice to split those features into mixin classes, rather than subclasses, but it's not obvious how to do -- feel free to submit a pull request. :copyright: (c) 2011-2012 by Selectel. :copyright: (c) 2012-2017 by pyte authors and contributors, see AUTHORS for details. :license: LGPL, see LICENSE for more details. """ from __future__ import absolute_import, unicode_literals, division import copy import json import math import os import sys import unicodedata import warnings from collections import deque, namedtuple, defaultdict from wcwidth import wcwidth # There is no standard 2.X backport for ``lru_cache``. if sys.version_info >= (3, 2): from functools import lru_cache wcwidth = lru_cache(maxsize=4096)(wcwidth) from . import ( charsets as cs, control as ctrl, graphics as g, modes as mo ) from .compat import map, range, str from .streams import Stream #: A container for screen's scroll margins. Margins = namedtuple("Margins", "top bottom") #: A container for savepoint, created on :data:`~pyte.escape.DECSC`. Savepoint = namedtuple("Savepoint", [ "cursor", "g0_charset", "g1_charset", "charset", "origin", "wrap" ]) class Char(namedtuple("Char", [ "data", "fg", "bg", "bold", "italics", "underscore", "strikethrough", "reverse", ])): """A single styled on-screen character. :param str data: unicode character. Invariant: ``len(data) == 1``. :param str fg: foreground colour. Defaults to ``"default"``. :param str bg: background colour. Defaults to ``"default"``. :param bool bold: flag for rendering the character using bold font. Defaults to ``False``. :param bool italics: flag for rendering the character using italic font. Defaults to ``False``. :param bool underscore: flag for rendering the character underlined. Defaults to ``False``. :param bool strikethrough: flag for rendering the character with a strike-through line. Defaults to ``False``. :param bool reverse: flag for swapping foreground and background colours during rendering. Defaults to ``False``. """ __slots__ = () def __new__(cls, data, fg="default", bg="default", bold=False, italics=False, underscore=False, strikethrough=False, reverse=False): return super(Char, cls).__new__(cls, data, fg, bg, bold, italics, underscore, strikethrough, reverse) class Cursor(object): """Screen cursor. :param int x: 0-based horizontal cursor position. :param int y: 0-based vertical cursor position. :param pyte.screens.Char attrs: cursor attributes (see :meth:`~pyte.screens.Screen.select_graphic_rendition` for details). """ __slots__ = ("x", "y", "attrs", "hidden") def __init__(self, x, y, attrs=Char(" ")): self.x = x self.y = y self.attrs = attrs self.hidden = False class StaticDefaultDict(dict): """A :func:`dict` with a static default value. Unlike :func:`collections.defaultdict` this implementation does not implicitly update the mapping when queried with a missing key. >>> d = StaticDefaultDict(42) >>> d["foo"] 42 >>> d {} """ def __init__(self, default): self.default = default def __missing__(self, key): return self.default class Screen(object): """ A screen is an in-memory matrix of characters that represents the screen display of the terminal. It can be instantiated on its own and given explicit commands, or it can be attached to a stream and will respond to events. .. attribute:: buffer A sparse ``lines x columns`` :class:`~pyte.screens.Char` matrix. .. attribute:: dirty A set of line numbers, which should be re-drawn. The user is responsible for clearing this set when changes have been applied. >>> screen = Screen(80, 24) >>> screen.dirty.clear() >>> screen.draw("!") >>> list(screen.dirty) [0] .. versionadded:: 0.7.0 .. attribute:: cursor Reference to the :class:`~pyte.screens.Cursor` object, holding cursor position and attributes. .. attribute:: margins Margins determine which screen lines move during scrolling (see :meth:`index` and :meth:`reverse_index`). Characters added outside the scrolling region do not make the screen to scroll. The value is ``None`` if margins are set to screen boundaries, otherwise -- a pair 0-based top and bottom line indices. .. attribute:: charset Current charset number; can be either ``0`` or ``1`` for `G0` and `G1` respectively, note that `G0` is activated by default. .. note:: According to ``ECMA-48`` standard, **lines and columns are 1-indexed**, so, for instance ``ESC [ 10;10 f`` really means -- move cursor to position (9, 9) in the display matrix. .. versionchanged:: 0.4.7 .. warning:: :data:`~pyte.modes.LNM` is reset by default, to match VT220 specification. Unfortunatelly this makes :mod:`pyte` fail ``vttest`` for cursor movement. .. versionchanged:: 0.4.8 .. warning:: If `DECAWM` mode is set than a cursor will be wrapped to the **beginning** of the next line, which is the behaviour described in ``man console_codes``. .. seealso:: `Standard ECMA-48, Section 6.1.1 \ `_ for a description of the presentational component, implemented by ``Screen``. """ @property def default_char(self): """An empty character with default foreground and background colors.""" reverse = mo.DECSCNM in self.mode return Char(data=" ", fg="default", bg="default", reverse=reverse) def __init__(self, columns, lines): self.savepoints = [] self.columns = columns self.lines = lines self.buffer = defaultdict(lambda: StaticDefaultDict(self.default_char)) self.dirty = set() self.reset() def __repr__(self): return ("{0}({1}, {2})".format(self.__class__.__name__, self.columns, self.lines)) @property def display(self): """A :func:`list` of screen lines as unicode strings.""" def render(line): is_wide_char = False for x in range(self.columns): if is_wide_char: # Skip stub is_wide_char = False continue char = line[x].data assert sum(map(wcwidth, char[1:])) == 0 is_wide_char = wcwidth(char[0]) == 2 yield char return ["".join(render(self.buffer[y])) for y in range(self.lines)] def reset(self): """Reset the terminal to its initial state. * Scrolling margins are reset to screen boundaries. * Cursor is moved to home location -- ``(0, 0)`` and its attributes are set to defaults (see :attr:`default_char`). * Screen is cleared -- each character is reset to :attr:`default_char`. * Tabstops are reset to "every eight columns". * All lines are marked as :attr:`dirty`. .. note:: Neither VT220 nor VT102 manuals mention that terminal modes and tabstops should be reset as well, thanks to :manpage:`xterm` -- we now know that. """ self.dirty.update(range(self.lines)) self.buffer.clear() self.margins = None self.mode = set([mo.DECAWM, mo.DECTCEM]) self.title = "" self.icon_name = "" self.charset = 0 self.g0_charset = cs.LAT1_MAP self.g1_charset = cs.VT100_MAP # From ``man terminfo`` -- "... hardware tabs are initially # set every `n` spaces when the terminal is powered up. Since # we aim to support VT102 / VT220 and linux -- we use n = 8. self.tabstops = set(range(8, self.columns, 8)) self.cursor = Cursor(0, 0) self.cursor_position() self.saved_columns = None def resize(self, lines=None, columns=None): """Resize the screen to the given size. If the requested screen size has more lines than the existing screen, lines will be added at the bottom. If the requested size has less lines than the existing screen lines will be clipped at the top of the screen. Similarly, if the existing screen has less columns than the requested screen, columns will be added at the right, and if it has more -- columns will be clipped at the right. :param int lines: number of lines in the new screen. :param int columns: number of columns in the new screen. .. versionchanged:: 0.7.0 If the requested screen size is identical to the current screen size, the method does nothing. """ lines = lines or self.lines columns = columns or self.columns if lines == self.lines and columns == self.columns: return # No changes. self.dirty.update(range(lines)) if lines < self.lines: self.save_cursor() self.cursor_position(0, 0) self.delete_lines(self.lines - lines) # Drop from the top. self.restore_cursor() if columns < self.columns: for line in self.buffer.values(): for x in range(columns, self.columns): line.pop(x, None) self.lines, self.columns = lines, columns self.set_margins() def set_margins(self, top=None, bottom=None): """Select top and bottom margins for the scrolling region. :param int top: the smallest line number that is scrolled. :param int bottom: the biggest line number that is scrolled. """ if top is None and bottom is None: self.margins = None return margins = self.margins or Margins(0, self.lines - 1) # Arguments are 1-based, while :attr:`margins` are zero # based -- so we have to decrement them by one. We also # make sure that both of them is bounded by [0, lines - 1]. if top is None: top = margins.top else: top = max(0, min(top - 1, self.lines - 1)) if bottom is None: bottom = margins.bottom else: bottom = max(0, min(bottom - 1, self.lines - 1)) # Even though VT102 and VT220 require DECSTBM to ignore # regions of width less than 2, some programs (like aptitude # for example) rely on it. Practicality beats purity. if bottom - top >= 1: self.margins = Margins(top, bottom) # The cursor moves to the home position when the top and # bottom margins of the scrolling region (DECSTBM) changes. self.cursor_position() def set_mode(self, *modes, **kwargs): """Set (enable) a given list of modes. :param list modes: modes to set, where each mode is a constant from :mod:`pyte.modes`. """ # Private mode codes are shifted, to be distingiushed from non # private ones. if kwargs.get("private"): modes = [mode << 5 for mode in modes] if mo.DECSCNM in modes: self.dirty.update(range(self.lines)) self.mode.update(modes) # When DECOLM mode is set, the screen is erased and the cursor # moves to the home position. if mo.DECCOLM in modes: self.saved_columns = self.columns self.resize(columns=132) self.erase_in_display(2) self.cursor_position() # According to VT520 manual, DECOM should also home the cursor. if mo.DECOM in modes: self.cursor_position() # Mark all displayed characters as reverse. if mo.DECSCNM in modes: for line in self.buffer.values(): line.default = self.default_char for x in line: line[x] = line[x]._replace(reverse=True) self.select_graphic_rendition(7) # +reverse. # Make the cursor visible. if mo.DECTCEM in modes: self.cursor.hidden = False def reset_mode(self, *modes, **kwargs): """Reset (disable) a given list of modes. :param list modes: modes to reset -- hopefully, each mode is a constant from :mod:`pyte.modes`. """ # Private mode codes are shifted, to be distinguished from non # private ones. if kwargs.get("private"): modes = [mode << 5 for mode in modes] if mo.DECSCNM in modes: self.dirty.update(range(self.lines)) self.mode.difference_update(modes) # Lines below follow the logic in :meth:`set_mode`. if mo.DECCOLM in modes: if self.columns == 132 and self.saved_columns is not None: self.resize(columns=self.saved_columns) self.saved_columns = None self.erase_in_display(2) self.cursor_position() if mo.DECOM in modes: self.cursor_position() if mo.DECSCNM in modes: for line in self.buffer.values(): line.default = self.default_char for x in line: line[x] = line[x]._replace(reverse=False) self.select_graphic_rendition(27) # -reverse. # Hide the cursor. if mo.DECTCEM in modes: self.cursor.hidden = True def define_charset(self, code, mode): """Define ``G0`` or ``G1`` charset. :param str code: character set code, should be a character from ``"B0UK"``, otherwise ignored. :param str mode: if ``"("`` ``G0`` charset is defined, if ``")"`` -- we operate on ``G1``. .. warning:: User-defined charsets are currently not supported. """ if code in cs.MAPS: if mode == "(": self.g0_charset = cs.MAPS[code] elif mode == ")": self.g1_charset = cs.MAPS[code] def shift_in(self): """Select ``G0`` character set.""" self.charset = 0 def shift_out(self): """Select ``G1`` character set.""" self.charset = 1 def draw(self, data): """Display decoded characters at the current cursor position and advances the cursor if :data:`~pyte.modes.DECAWM` is set. :param str data: text to display. .. versionchanged:: 0.5.0 Character width is taken into account. Specifically, zero-width and unprintable characters do not affect screen state. Full-width characters are rendered into two consecutive character containers. """ data = data.translate( self.g1_charset if self.charset else self.g0_charset) for char in data: char_width = wcwidth(char) # If this was the last column in a line and auto wrap mode is # enabled, move the cursor to the beginning of the next line, # otherwise replace characters already displayed with newly # entered. if self.cursor.x == self.columns: if mo.DECAWM in self.mode: self.dirty.add(self.cursor.y) self.carriage_return() self.linefeed() elif char_width > 0: self.cursor.x -= char_width # If Insert mode is set, new characters move old characters to # the right, otherwise terminal is in Replace mode and new # characters replace old characters at cursor position. if mo.IRM in self.mode and char_width > 0: self.insert_characters(char_width) line = self.buffer[self.cursor.y] if char_width == 1: line[self.cursor.x] = self.cursor.attrs._replace(data=char) elif char_width == 2: # A two-cell character has a stub slot after it. line[self.cursor.x] = self.cursor.attrs._replace(data=char) if self.cursor.x + 1 < self.columns: line[self.cursor.x + 1] = self.cursor.attrs \ ._replace(data="") elif char_width == 0 and unicodedata.combining(char): # A zero-cell character is combined with the previous # character either on this or preceeding line. if self.cursor.x: last = line[self.cursor.x - 1] normalized = unicodedata.normalize("NFC", last.data + char) line[self.cursor.x - 1] = last._replace(data=normalized) elif self.cursor.y: last = self.buffer[self.cursor.y - 1][self.columns - 1] normalized = unicodedata.normalize("NFC", last.data + char) self.buffer[self.cursor.y - 1][self.columns - 1] = \ last._replace(data=normalized) else: break # Unprintable character or doesn't advance the cursor. # .. note:: We can't use :meth:`cursor_forward()`, because that # way, we'll never know when to linefeed. if char_width > 0: self.cursor.x = min(self.cursor.x + char_width, self.columns) self.dirty.add(self.cursor.y) def set_title(self, param): """Set terminal title. .. note:: This is an XTerm extension supported by the Linux terminal. """ self.title = param def set_icon_name(self, param): """Set icon name. .. note:: This is an XTerm extension supported by the Linux terminal. """ self.icon_name = param def carriage_return(self): """Move the cursor to the beginning of the current line.""" self.cursor.x = 0 def index(self): """Move the cursor down one line in the same column. If the cursor is at the last line, create a new line at the bottom. """ top, bottom = self.margins or Margins(0, self.lines - 1) if self.cursor.y == bottom: # TODO: mark only the lines within margins? self.dirty.update(range(self.lines)) for y in range(top, bottom): self.buffer[y] = self.buffer[y + 1] self.buffer.pop(bottom, None) else: self.cursor_down() def reverse_index(self): """Move the cursor up one line in the same column. If the cursor is at the first line, create a new line at the top. """ top, bottom = self.margins or Margins(0, self.lines - 1) if self.cursor.y == top: # TODO: mark only the lines within margins? self.dirty.update(range(self.lines)) for y in range(bottom, top, -1): self.buffer[y] = self.buffer[y - 1] self.buffer.pop(top, None) else: self.cursor_up() def linefeed(self): """Perform an index and, if :data:`~pyte.modes.LNM` is set, a carriage return. """ self.index() if mo.LNM in self.mode: self.carriage_return() def tab(self): """Move to the next tab space, or the end of the screen if there aren't anymore left. """ for stop in sorted(self.tabstops): if self.cursor.x < stop: column = stop break else: column = self.columns - 1 self.cursor.x = column def backspace(self): """Move cursor to the left one or keep it in its position if it's at the beginning of the line already. """ self.cursor_back() def save_cursor(self): """Push the current cursor position onto the stack.""" self.savepoints.append(Savepoint(copy.copy(self.cursor), self.g0_charset, self.g1_charset, self.charset, mo.DECOM in self.mode, mo.DECAWM in self.mode)) def restore_cursor(self): """Set the current cursor position to whatever cursor is on top of the stack. """ if self.savepoints: savepoint = self.savepoints.pop() self.g0_charset = savepoint.g0_charset self.g1_charset = savepoint.g1_charset self.charset = savepoint.charset if savepoint.origin: self.set_mode(mo.DECOM) if savepoint.wrap: self.set_mode(mo.DECAWM) self.cursor = savepoint.cursor self.ensure_hbounds() self.ensure_vbounds(use_margins=True) else: # If nothing was saved, the cursor moves to home position; # origin mode is reset. :todo: DECAWM? self.reset_mode(mo.DECOM) self.cursor_position() def insert_lines(self, count=None): """Insert the indicated # of lines at line with cursor. Lines displayed **at** and below the cursor move down. Lines moved past the bottom margin are lost. :param count: number of lines to insert. """ count = count or 1 top, bottom = self.margins or Margins(0, self.lines - 1) # If cursor is outside scrolling margins it -- do nothin'. if top <= self.cursor.y <= bottom: self.dirty.update(range(self.cursor.y, self.lines)) for y in range(bottom, self.cursor.y - 1, -1): if y + count <= bottom and y in self.buffer: self.buffer[y + count] = self.buffer[y] self.buffer.pop(y, None) self.carriage_return() def delete_lines(self, count=None): """Delete the indicated # of lines, starting at line with cursor. As lines are deleted, lines displayed below cursor move up. Lines added to bottom of screen have spaces with same character attributes as last line moved up. :param int count: number of lines to delete. """ count = count or 1 top, bottom = self.margins or Margins(0, self.lines - 1) # If cursor is outside scrolling margins -- do nothin'. if top <= self.cursor.y <= bottom: self.dirty.update(range(self.cursor.y, self.lines)) for y in range(self.cursor.y, bottom + 1): if y + count <= bottom: if y + count in self.buffer: self.buffer[y] = self.buffer.pop(y + count) else: self.buffer.pop(y, None) self.carriage_return() def insert_characters(self, count=None): """Insert the indicated # of blank characters at the cursor position. The cursor does not move and remains at the beginning of the inserted blank characters. Data on the line is shifted forward. :param int count: number of characters to insert. """ self.dirty.add(self.cursor.y) count = count or 1 line = self.buffer[self.cursor.y] for x in range(self.columns, self.cursor.x - 1, -1): if x + count <= self.columns: line[x + count] = line[x] line.pop(x, None) def delete_characters(self, count=None): """Delete the indicated # of characters, starting with the character at cursor position. When a character is deleted, all characters to the right of cursor move left. Character attributes move with the characters. :param int count: number of characters to delete. """ self.dirty.add(self.cursor.y) count = count or 1 line = self.buffer[self.cursor.y] for x in range(self.cursor.x, self.columns): if x + count <= self.columns: line[x] = line.pop(x + count, self.default_char) else: line.pop(x, None) def erase_characters(self, count=None): """Erase the indicated # of characters, starting with the character at cursor position. Character attributes are set cursor attributes. The cursor remains in the same position. :param int count: number of characters to erase. .. note:: Using cursor attributes for character attributes may seem illogical, but if recall that a terminal emulator emulates a type writer, it starts to make sense. The only way a type writer could erase a character is by typing over it. """ self.dirty.add(self.cursor.y) count = count or 1 line = self.buffer[self.cursor.y] for x in range(self.cursor.x, min(self.cursor.x + count, self.columns)): line[x] = self.cursor.attrs def erase_in_line(self, how=0, private=False): """Erase a line in a specific way. Character attributes are set to cursor attributes. :param int how: defines the way the line should be erased in: * ``0`` -- Erases from cursor to end of line, including cursor position. * ``1`` -- Erases from beginning of line to cursor, including cursor position. * ``2`` -- Erases complete line. :param bool private: when ``True`` only characters marked as eraseable are affected **not implemented**. """ self.dirty.add(self.cursor.y) if how == 0: interval = range(self.cursor.x, self.columns) elif how == 1: interval = range(self.cursor.x + 1) elif how == 2: interval = range(self.columns) line = self.buffer[self.cursor.y] for x in interval: line[x] = self.cursor.attrs def erase_in_display(self, how=0, private=False): """Erases display in a specific way. Character attributes are set to cursor attributes. :param int how: defines the way the line should be erased in: * ``0`` -- Erases from cursor to end of screen, including cursor position. * ``1`` -- Erases from beginning of screen to cursor, including cursor position. * ``2`` and ``3`` -- Erases complete display. All lines are erased and changed to single-width. Cursor does not move. :param bool private: when ``True`` only characters marked as eraseable are affected **not implemented**. """ if how == 0: interval = range(self.cursor.y + 1, self.lines) elif how == 1: interval = range(self.cursor.y) elif how == 2 or how == 3: interval = range(self.lines) self.dirty.update(interval) for y in interval: line = self.buffer[y] for x in line: line[x] = self.cursor.attrs if how == 0 or how == 1: self.erase_in_line(how) def set_tab_stop(self): """Set a horizontal tab stop at cursor position.""" self.tabstops.add(self.cursor.x) def clear_tab_stop(self, how=0): """Clear a horizontal tab stop. :param int how: defines a way the tab stop should be cleared: * ``0`` or nothing -- Clears a horizontal tab stop at cursor position. * ``3`` -- Clears all horizontal tab stops. """ if how == 0: # Clears a horizontal tab stop at cursor position, if it's # present, or silently fails if otherwise. self.tabstops.discard(self.cursor.x) elif how == 3: self.tabstops = set() # Clears all horizontal tab stops. def ensure_hbounds(self): """Ensure the cursor is within horizontal screen bounds.""" self.cursor.x = min(max(0, self.cursor.x), self.columns - 1) def ensure_vbounds(self, use_margins=None): """Ensure the cursor is within vertical screen bounds. :param bool use_margins: when ``True`` or when :data:`~pyte.modes.DECOM` is set, cursor is bounded by top and and bottom margins, instead of ``[0; lines - 1]``. """ if (use_margins or mo.DECOM in self.mode) and self.margins is not None: top, bottom = self.margins else: top, bottom = 0, self.lines - 1 self.cursor.y = min(max(top, self.cursor.y), bottom) def cursor_up(self, count=None): """Move cursor up the indicated # of lines in same column. Cursor stops at top margin. :param int count: number of lines to skip. """ top, _bottom = self.margins or Margins(0, self.lines - 1) self.cursor.y = max(self.cursor.y - (count or 1), top) def cursor_up1(self, count=None): """Move cursor up the indicated # of lines to column 1. Cursor stops at bottom margin. :param int count: number of lines to skip. """ self.cursor_up(count) self.carriage_return() def cursor_down(self, count=None): """Move cursor down the indicated # of lines in same column. Cursor stops at bottom margin. :param int count: number of lines to skip. """ _top, bottom = self.margins or Margins(0, self.lines - 1) self.cursor.y = min(self.cursor.y + (count or 1), bottom) def cursor_down1(self, count=None): """Move cursor down the indicated # of lines to column 1. Cursor stops at bottom margin. :param int count: number of lines to skip. """ self.cursor_down(count) self.carriage_return() def cursor_back(self, count=None): """Move cursor left the indicated # of columns. Cursor stops at left margin. :param int count: number of columns to skip. """ # Handle the case when we've just drawn in the last column # and would wrap the line on the next :meth:`draw()` call. if self.cursor.x == self.columns: self.cursor.x -= 1 self.cursor.x -= count or 1 self.ensure_hbounds() def cursor_forward(self, count=None): """Move cursor right the indicated # of columns. Cursor stops at right margin. :param int count: number of columns to skip. """ self.cursor.x += count or 1 self.ensure_hbounds() def cursor_position(self, line=None, column=None): """Set the cursor to a specific `line` and `column`. Cursor is allowed to move out of the scrolling region only when :data:`~pyte.modes.DECOM` is reset, otherwise -- the position doesn't change. :param int line: line number to move the cursor to. :param int column: column number to move the cursor to. """ column = (column or 1) - 1 line = (line or 1) - 1 # If origin mode (DECOM) is set, line number are relative to # the top scrolling margin. if self.margins is not None and mo.DECOM in self.mode: line += self.margins.top # Cursor is not allowed to move out of the scrolling region. if not self.margins.top <= line <= self.margins.bottom: return self.cursor.x = column self.cursor.y = line self.ensure_hbounds() self.ensure_vbounds() def cursor_to_column(self, column=None): """Move cursor to a specific column in the current line. :param int column: column number to move the cursor to. """ self.cursor.x = (column or 1) - 1 self.ensure_hbounds() def cursor_to_line(self, line=None): """Move cursor to a specific line in the current column. :param int line: line number to move the cursor to. """ self.cursor.y = (line or 1) - 1 # If origin mode (DECOM) is set, line number are relative to # the top scrolling margin. if mo.DECOM in self.mode: self.cursor.y += self.margins.top # FIXME: should we also restrict the cursor to the scrolling # region? self.ensure_vbounds() def bell(self, *args): """Bell stub -- the actual implementation should probably be provided by the end-user. """ def alignment_display(self): """Fills screen with uppercase E's for screen focus and alignment.""" self.dirty.update(range(self.lines)) for y in range(self.lines): for x in range(self.columns): self.buffer[y][x] = self.buffer[y][x]._replace(data="E") def select_graphic_rendition(self, *attrs): """Set display attributes. :param list attrs: a list of display attributes to set. """ replace = {} # Fast path for resetting all attributes. if not attrs or attrs == (0, ): self.cursor.attrs = self.default_char return else: attrs = list(reversed(attrs)) while attrs: attr = attrs.pop() if attr == 0: # Reset all attributes. replace.update(self.default_char._asdict()) elif attr in g.FG_ANSI: replace["fg"] = g.FG_ANSI[attr] elif attr in g.BG: replace["bg"] = g.BG_ANSI[attr] elif attr in g.TEXT: attr = g.TEXT[attr] replace[attr[1:]] = attr.startswith("+") elif attr in g.FG_AIXTERM: replace.update(fg=g.FG_AIXTERM[attr], bold=True) elif attr in g.BG_AIXTERM: replace.update(bg=g.BG_AIXTERM[attr], bold=True) elif attr in (g.FG_256, g.BG_256): key = "fg" if attr == g.FG_256 else "bg" try: n = attrs.pop() if n == 5: # 256. m = attrs.pop() replace[key] = g.FG_BG_256[m] elif n == 2: # 24bit. # This is somewhat non-standard but is nonetheless # supported in quite a few terminals. See discussion # here https://gist.github.com/XVilka/8346728. replace[key] = "{0:02x}{1:02x}{2:02x}".format( attrs.pop(), attrs.pop(), attrs.pop()) except IndexError: pass self.cursor.attrs = self.cursor.attrs._replace(**replace) def report_device_attributes(self, mode=0, **kwargs): """Report terminal identity. .. versionadded:: 0.5.0 .. versionchanged:: 0.7.0 If ``private`` keyword argument is set, the method does nothing. This behaviour is consistent with VT220 manual. """ # We only implement "primary" DA which is the only DA request # VT102 understood, see ``VT102ID`` in ``linux/drivers/tty/vt.c``. if mode == 0 and not kwargs.get("private"): self.write_process_input(ctrl.CSI + "?6c") def report_device_status(self, mode): """Report terminal status or cursor position. :param int mode: if 5 -- terminal status, 6 -- cursor position, otherwise a noop. .. versionadded:: 0.5.0 """ if mode == 5: # Request for terminal status. self.write_process_input(ctrl.CSI + "0n") elif mode == 6: # Request for cursor position. x = self.cursor.x + 1 y = self.cursor.y + 1 # "Origin mode (DECOM) selects line numbering." if mo.DECOM in self.mode: y -= self.margins.top self.write_process_input(ctrl.CSI + "{0};{1}R".format(y, x)) def write_process_input(self, data): """Write data to the process running inside the terminal. By default is a noop. :param str data: text to write to the process ``stdin``. .. versionadded:: 0.5.0 """ def debug(self, *args, **kwargs): """Endpoint for unrecognized escape sequences. By default is a noop. """ class DiffScreen(Screen): """ A screen subclass, which maintains a set of dirty lines in its :attr:`dirty` attribute. The end user is responsible for emptying a set, when a diff is applied. .. deprecated:: 0.7.0 The functionality contained in this class has been merged into :class:`~pyte.screens.Screen` and will be removed in 0.8.0. Please update your code accordingly. """ def __init__(self, *args, **kwargs): warnings.warn( "The functionality of ``DiffScreen` has been merged into " "``Screen`` and will be removed in 0.8.0. Please update " "your code accordingly.", DeprecationWarning) super(DiffScreen, self).__init__(*args, **kwargs) History = namedtuple("History", "top bottom ratio size position") class HistoryScreen(Screen): """A :class:~`pyte.screens.Screen` subclass, which keeps track of screen history and allows pagination. This is not linux-specific, but still useful; see page 462 of VT520 User's Manual. :param int history: total number of history lines to keep; is split between top and bottom queues. :param int ratio: defines how much lines to scroll on :meth:`next_page` and :meth:`prev_page` calls. .. attribute:: history A pair of history queues for top and bottom margins accordingly; here's the overall screen structure:: [ 1: .......] [ 2: .......] <- top history [ 3: .......] ------------ [ 4: .......] s [ 5: .......] c [ 6: .......] r [ 7: .......] e [ 8: .......] e [ 9: .......] n ------------ [10: .......] [11: .......] <- bottom history [12: .......] .. note:: Don't forget to update :class:`~pyte.streams.Stream` class with appropriate escape sequences -- you can use any, since pagination protocol is not standardized, for example:: Stream.escape["N"] = "next_page" Stream.escape["P"] = "prev_page" """ _wrapped = set(Stream.events) _wrapped.update(["next_page", "prev_page"]) def __init__(self, columns, lines, history=100, ratio=.5): self.history = History(deque(maxlen=history), deque(maxlen=history), float(ratio), history, history) super(HistoryScreen, self).__init__(columns, lines) def _make_wrapper(self, event, handler): def inner(*args, **kwargs): self.before_event(event) result = handler(*args, **kwargs) self.after_event(event) return result return inner def __getattribute__(self, attr): value = super(HistoryScreen, self).__getattribute__(attr) if attr in HistoryScreen._wrapped: return HistoryScreen._make_wrapper(self, attr, value) else: return value def before_event(self, event): """Ensure a screen is at the bottom of the history buffer. :param str event: event name, for example ``"linefeed"``. """ if event not in ["prev_page", "next_page"]: while self.history.position < self.history.size: self.next_page() def after_event(self, event): """Ensure all lines on a screen have proper width (:attr:`columns`). Extra characters are truncated, missing characters are filled with whitespace. :param str event: event name, for example ``"linefeed"``. """ if event in ["prev_page", "next_page"]: for line in self.buffer.values(): for x in line: if x > self.columns: line.pop(x) # If we're at the bottom of the history buffer and `DECTCEM` # mode is set -- show the cursor. self.cursor.hidden = not ( self.history.position == self.history.size and mo.DECTCEM in self.mode ) def _reset_history(self): self.history.top.clear() self.history.bottom.clear() self.history = self.history._replace(position=self.history.size) def reset(self): """Overloaded to reset screen history state: history position is reset to bottom of both queues; queues themselves are emptied. """ super(HistoryScreen, self).reset() self._reset_history() def erase_in_display(self, how=0): """Overloaded to reset history state.""" super(HistoryScreen, self).erase_in_display(how) if how == 3: self._reset_history() def index(self): """Overloaded to update top history with the removed lines.""" top, bottom = self.margins or Margins(0, self.lines - 1) if self.cursor.y == bottom: self.history.top.append(self.buffer[top]) super(HistoryScreen, self).index() def reverse_index(self): """Overloaded to update bottom history with the removed lines.""" top, bottom = self.margins or Margins(0, self.lines - 1) if self.cursor.y == top: self.history.bottom.append(self.buffer[bottom]) super(HistoryScreen, self).reverse_index() def prev_page(self): """Move the screen page up through the history buffer. Page size is defined by ``history.ratio``, so for instance ``ratio = .5`` means that half the screen is restored from history on page switch. """ if self.history.position > self.lines and self.history.top: mid = min(len(self.history.top), int(math.ceil(self.lines * self.history.ratio))) self.history.bottom.extendleft( self.buffer[y] for y in range(self.lines - 1, self.lines - mid - 1, -1)) self.history = self.history \ ._replace(position=self.history.position - mid) for y in range(self.lines - 1, mid - 1, -1): self.buffer[y] = self.buffer[y - mid] for y in range(mid - 1, -1, -1): self.buffer[y] = self.history.top.pop() self.dirty = set(range(self.lines)) def next_page(self): """Move the screen page down through the history buffer.""" if self.history.position < self.history.size and self.history.bottom: mid = min(len(self.history.bottom), int(math.ceil(self.lines * self.history.ratio))) self.history.top.extend(self.buffer[y] for y in range(mid)) self.history = self.history \ ._replace(position=self.history.position + mid) for y in range(self.lines - mid): self.buffer[y] = self.buffer[y + mid] for y in range(self.lines - mid, self.lines): self.buffer[y] = self.history.bottom.popleft() self.dirty = set(range(self.lines)) class DebugEvent(namedtuple("Event", "name args kwargs")): """Event dispatched to :class:`~pyte.screens.DebugScreen`. .. warning:: This is developer API with no backward compatibility guarantees. Use at your own risk! """ @staticmethod def from_string(line): return DebugEvent(*json.loads(line)) def __str__(self): return json.dumps(self) def __call__(self, screen): """Execute this event on a given ``screen``.""" return getattr(screen, self.name)(*self.args, **self.kwargs) class DebugScreen(object): r"""A screen which dumps a subset of the received events to a file. >>> import io >>> with io.StringIO() as buf: ... stream = Stream(DebugScreen(to=buf)) ... stream.feed("\x1b[1;24r\x1b[4l\x1b[24;1H\x1b[0;10m") ... print(buf.getvalue()) ... ... # doctest: +NORMALIZE_WHITESPACE ["set_margins", [1, 24], {}] ["reset_mode", [4], {}] ["cursor_position", [24, 1], {}] ["select_graphic_rendition", [0, 10], {}] :param file to: a file-like object to write debug information to. :param list only: a list of events you want to debug (empty by default, which means -- debug all events). .. warning:: This is developer API with no backward compatibility guarantees. Use at your own risk! """ def __init__(self, to=sys.stderr, only=()): self.to = to self.only = only def only_wrapper(self, attr): def wrapper(*args, **kwargs): self.to.write(str(DebugEvent(attr, args, kwargs))) self.to.write(str(os.linesep)) return wrapper def __getattribute__(self, attr): if attr not in Stream.events: return super(DebugScreen, self).__getattribute__(attr) elif not self.only or attr in self.only: return self.only_wrapper(attr) else: return lambda *args, **kwargs: None pyte-0.8.0/pyte/__main__.py0000644f2us0000000135213117620156017175 0ustar s.lebedev00000000000000# -*- coding: utf-8 -*- """ pyte ~~~~ Command-line tool for "disassembling" escape and CSI sequences:: $ echo -e "\e[Jfoo" | python -m pyte ERASE_IN_DISPLAY 0 DRAW f DRAW o DRAW o LINEFEED $ python -m pyte foo DRAW f DRAW o DRAW o :copyright: (c) 2011-2012 by Selectel. :copyright: (c) 2012-2017 by pyte authors and contributors, see AUTHORS for details. :license: LGPL, see LICENSE for more details. """ from __future__ import unicode_literals if __name__ == "__main__": import sys import pyte if len(sys.argv) == 1: pyte.dis(sys.stdin.read()) else: pyte.dis("".join(sys.argv[1:]))